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.

67199 lines
2.1MB

  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 51
  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 && ! defined (__INTEL_COMPILER)
  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(a) a
  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. JUCE_ALIGN(8)
  1805. /** The raw value that this class operates on.
  1806. This is exposed publically in case you need to manipulate it directly
  1807. for performance reasons.
  1808. */
  1809. volatile Type value;
  1810. private:
  1811. static inline Type castFrom32Bit (int32 value) throw() { return *(Type*) &value; }
  1812. static inline Type castFrom64Bit (int64 value) throw() { return *(Type*) &value; }
  1813. static inline int32 castTo32Bit (Type value) throw() { return *(int32*) &value; }
  1814. static inline int64 castTo64Bit (Type value) throw() { return *(int64*) &value; }
  1815. Type operator++ (int); // better to just use pre-increment with atomics..
  1816. Type operator-- (int);
  1817. };
  1818. /*
  1819. The following code is in the header so that the atomics can be inlined where possible...
  1820. */
  1821. #if (JUCE_IOS && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  1822. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  1823. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  1824. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1825. #define JUCE_MAC_ATOMICS_VOLATILE
  1826. #else
  1827. #define JUCE_MAC_ATOMICS_VOLATILE volatile
  1828. #endif
  1829. #if JUCE_PPC || JUCE_IOS
  1830. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  1831. template <typename Type> static Type OSAtomicAdd64Barrier (Type b, JUCE_MAC_ATOMICS_VOLATILE Type* a) throw() { jassertfalse; return *a += b; }
  1832. template <typename Type> static Type OSAtomicIncrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) throw() { jassertfalse; return ++*a; }
  1833. template <typename Type> static Type OSAtomicDecrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) throw() { jassertfalse; return --*a; }
  1834. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, JUCE_MAC_ATOMICS_VOLATILE Type* value) throw()
  1835. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  1836. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1837. #endif
  1838. #elif JUCE_ANDROID
  1839. #define JUCE_ATOMICS_ANDROID 1 // Android atomic functions
  1840. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1841. #elif JUCE_GCC
  1842. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  1843. #if JUCE_IOS
  1844. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1 // (on the iphone, the 64-bit ops will compile but not link)
  1845. #endif
  1846. #else
  1847. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  1848. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  1849. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  1850. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  1851. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  1852. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  1853. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  1854. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  1855. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  1856. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  1857. #define juce_MemoryBarrier _ReadWriteBarrier
  1858. #else
  1859. // (these are defined in juce_win32_Threads.cpp)
  1860. long juce_InterlockedExchange (volatile long* a, long b) throw();
  1861. long juce_InterlockedIncrement (volatile long* a) throw();
  1862. long juce_InterlockedDecrement (volatile long* a) throw();
  1863. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw();
  1864. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw();
  1865. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) throw();
  1866. inline void juce_MemoryBarrier() throw() { long x = 0; juce_InterlockedIncrement (&x); }
  1867. #endif
  1868. #if JUCE_64BIT
  1869. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  1870. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  1871. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  1872. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  1873. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  1874. #else
  1875. // None of these atomics are available in a 32-bit Windows build!!
  1876. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a += b; return old; }
  1877. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a = b; return old; }
  1878. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) throw() { jassertfalse; return ++*a; }
  1879. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) throw() { jassertfalse; return --*a; }
  1880. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1881. #endif
  1882. #endif
  1883. #if JUCE_MSVC
  1884. #pragma warning (push)
  1885. #pragma warning (disable: 4311) // (truncation warning)
  1886. #endif
  1887. template <typename Type>
  1888. inline Type Atomic<Type>::get() const throw()
  1889. {
  1890. #if JUCE_ATOMICS_MAC
  1891. return sizeof (Type) == 4 ? castFrom32Bit ((int32) OSAtomicAdd32Barrier ((int32_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value))
  1892. : castFrom64Bit ((int64) OSAtomicAdd64Barrier ((int64_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value));
  1893. #elif JUCE_ATOMICS_WINDOWS
  1894. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchangeAdd ((volatile long*) &value, (long) 0))
  1895. : castFrom64Bit ((int64) juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0));
  1896. #elif JUCE_ATOMICS_ANDROID
  1897. return value;
  1898. #elif JUCE_ATOMICS_GCC
  1899. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_add_and_fetch ((volatile int32*) &value, 0))
  1900. : castFrom64Bit ((int64) __sync_add_and_fetch ((volatile int64*) &value, 0));
  1901. #endif
  1902. }
  1903. template <typename Type>
  1904. inline Type Atomic<Type>::exchange (const Type newValue) throw()
  1905. {
  1906. #if JUCE_ATOMICS_ANDROID
  1907. return castFrom32Bit (__atomic_swap (castTo32Bit (newValue), (volatile int*) &value));
  1908. #elif JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  1909. Type currentVal = value;
  1910. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  1911. return currentVal;
  1912. #elif JUCE_ATOMICS_WINDOWS
  1913. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue)))
  1914. : castFrom64Bit ((int64) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue)));
  1915. #endif
  1916. }
  1917. template <typename Type>
  1918. inline Type Atomic<Type>::operator+= (const Type amountToAdd) throw()
  1919. {
  1920. #if JUCE_ATOMICS_MAC
  1921. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32Barrier ((int32_t) castTo32Bit (amountToAdd), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1922. : (Type) OSAtomicAdd64Barrier ((int64_t) amountToAdd, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1923. #elif JUCE_ATOMICS_WINDOWS
  1924. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  1925. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  1926. #elif JUCE_ATOMICS_ANDROID
  1927. for (;;)
  1928. {
  1929. const Type oldValue (value);
  1930. const Type newValue (castFrom32Bit (castTo32Bit (oldValue) + castTo32Bit (amountToAdd)));
  1931. if (compareAndSetBool (newValue, oldValue))
  1932. return newValue;
  1933. }
  1934. #elif JUCE_ATOMICS_GCC
  1935. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  1936. #endif
  1937. }
  1938. template <typename Type>
  1939. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) throw()
  1940. {
  1941. return operator+= (juce_negate (amountToSubtract));
  1942. }
  1943. template <typename Type>
  1944. inline Type Atomic<Type>::operator++() throw()
  1945. {
  1946. #if JUCE_ATOMICS_MAC
  1947. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1948. : (Type) OSAtomicIncrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1949. #elif JUCE_ATOMICS_WINDOWS
  1950. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  1951. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  1952. #elif JUCE_ATOMICS_ANDROID
  1953. return (Type) (__atomic_inc ((volatile int*) &value) + 1);
  1954. #elif JUCE_ATOMICS_GCC
  1955. return (Type) __sync_add_and_fetch (&value, 1);
  1956. #endif
  1957. }
  1958. template <typename Type>
  1959. inline Type Atomic<Type>::operator--() throw()
  1960. {
  1961. #if JUCE_ATOMICS_MAC
  1962. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1963. : (Type) OSAtomicDecrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1964. #elif JUCE_ATOMICS_WINDOWS
  1965. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  1966. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  1967. #elif JUCE_ATOMICS_ANDROID
  1968. return (Type) (__atomic_dec ((volatile int*) &value) - 1);
  1969. #elif JUCE_ATOMICS_GCC
  1970. return (Type) __sync_add_and_fetch (&value, -1);
  1971. #endif
  1972. }
  1973. template <typename Type>
  1974. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) throw()
  1975. {
  1976. #if JUCE_ATOMICS_MAC
  1977. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) castTo32Bit (valueToCompare), (int32_t) castTo32Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1978. : OSAtomicCompareAndSwap64Barrier ((int64_t) castTo64Bit (valueToCompare), (int64_t) castTo64Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1979. #elif JUCE_ATOMICS_WINDOWS
  1980. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  1981. #elif JUCE_ATOMICS_ANDROID
  1982. return __atomic_cmpxchg (castTo32Bit (valueToCompare), castTo32Bit (newValue), (volatile int*) &value) == 0;
  1983. #elif JUCE_ATOMICS_GCC
  1984. return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))
  1985. : __sync_bool_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue));
  1986. #endif
  1987. }
  1988. template <typename Type>
  1989. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) throw()
  1990. {
  1991. #if JUCE_ATOMICS_MAC || JUCE_ATOMICS_ANDROID
  1992. for (;;) // Annoying workaround for only having a bool CAS operation..
  1993. {
  1994. if (compareAndSetBool (newValue, valueToCompare))
  1995. return valueToCompare;
  1996. const Type result = value;
  1997. if (result != valueToCompare)
  1998. return result;
  1999. }
  2000. #elif JUCE_ATOMICS_WINDOWS
  2001. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare)))
  2002. : castFrom64Bit ((int64) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare)));
  2003. #elif JUCE_ATOMICS_GCC
  2004. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_val_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)))
  2005. : castFrom64Bit ((int64) __sync_val_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)));
  2006. #endif
  2007. }
  2008. template <typename Type>
  2009. inline void Atomic<Type>::memoryBarrier() throw()
  2010. {
  2011. #if JUCE_ATOMICS_MAC
  2012. OSMemoryBarrier();
  2013. #elif JUCE_ATOMICS_GCC
  2014. __sync_synchronize();
  2015. #elif JUCE_ATOMICS_WINDOWS
  2016. juce_MemoryBarrier();
  2017. #endif
  2018. }
  2019. #if JUCE_MSVC
  2020. #pragma warning (pop)
  2021. #endif
  2022. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2023. /*** End of inlined file: juce_Atomic.h ***/
  2024. /*** Start of inlined file: juce_CharPointer_UTF8.h ***/
  2025. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2026. #define __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2027. /**
  2028. Wraps a pointer to a null-terminated UTF-8 character string, and provides
  2029. various methods to operate on the data.
  2030. @see CharPointer_UTF16, CharPointer_UTF32
  2031. */
  2032. class CharPointer_UTF8
  2033. {
  2034. public:
  2035. typedef char CharType;
  2036. inline explicit CharPointer_UTF8 (const CharType* const rawPointer) throw()
  2037. : data (const_cast <CharType*> (rawPointer))
  2038. {
  2039. }
  2040. inline CharPointer_UTF8 (const CharPointer_UTF8& other) throw()
  2041. : data (other.data)
  2042. {
  2043. }
  2044. inline CharPointer_UTF8& operator= (const CharPointer_UTF8& other) throw()
  2045. {
  2046. data = other.data;
  2047. return *this;
  2048. }
  2049. inline CharPointer_UTF8& operator= (const CharType* text) throw()
  2050. {
  2051. data = const_cast <CharType*> (text);
  2052. return *this;
  2053. }
  2054. /** This is a pointer comparison, it doesn't compare the actual text. */
  2055. inline bool operator== (const CharPointer_UTF8& other) const throw() { return data == other.data; }
  2056. inline bool operator!= (const CharPointer_UTF8& other) const throw() { return data != other.data; }
  2057. inline bool operator<= (const CharPointer_UTF8& other) const throw() { return data <= other.data; }
  2058. inline bool operator< (const CharPointer_UTF8& other) const throw() { return data < other.data; }
  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. /** Returns the address that this pointer is pointing to. */
  2062. inline CharType* getAddress() const throw() { return data; }
  2063. /** Returns the address that this pointer is pointing to. */
  2064. inline operator const CharType*() const throw() { return data; }
  2065. /** Returns true if this pointer is pointing to a null character. */
  2066. inline bool isEmpty() const throw() { return *data == 0; }
  2067. /** Returns the unicode character that this pointer is pointing to. */
  2068. juce_wchar operator*() const throw()
  2069. {
  2070. const signed char byte = (signed char) *data;
  2071. if (byte >= 0)
  2072. return byte;
  2073. uint32 n = (uint32) (uint8) byte;
  2074. uint32 mask = 0x7f;
  2075. uint32 bit = 0x40;
  2076. size_t numExtraValues = 0;
  2077. while ((n & bit) != 0 && bit > 0x10)
  2078. {
  2079. mask >>= 1;
  2080. ++numExtraValues;
  2081. bit >>= 1;
  2082. }
  2083. n &= mask;
  2084. for (size_t i = 1; i <= numExtraValues; ++i)
  2085. {
  2086. const juce_wchar nextByte = data [i];
  2087. if ((nextByte & 0xc0) != 0x80)
  2088. break;
  2089. n <<= 6;
  2090. n |= (nextByte & 0x3f);
  2091. }
  2092. return (juce_wchar) n;
  2093. }
  2094. /** Moves this pointer along to the next character in the string. */
  2095. CharPointer_UTF8& operator++() throw()
  2096. {
  2097. const signed char n = (signed char) *data++;
  2098. if (n < 0)
  2099. {
  2100. juce_wchar bit = 0x40;
  2101. while ((n & bit) != 0 && bit > 0x8)
  2102. {
  2103. ++data;
  2104. bit >>= 1;
  2105. }
  2106. }
  2107. return *this;
  2108. }
  2109. /** Moves this pointer back to the previous character in the string. */
  2110. CharPointer_UTF8& operator--() throw()
  2111. {
  2112. const char n = *--data;
  2113. if ((n & 0xc0) == 0xc0)
  2114. {
  2115. int count = 3;
  2116. do
  2117. {
  2118. --data;
  2119. }
  2120. while ((*data & 0xc0) == 0xc0 && --count >= 0);
  2121. }
  2122. return *this;
  2123. }
  2124. /** Returns the character that this pointer is currently pointing to, and then
  2125. advances the pointer to point to the next character. */
  2126. juce_wchar getAndAdvance() throw()
  2127. {
  2128. const signed char byte = (signed char) *data++;
  2129. if (byte >= 0)
  2130. return byte;
  2131. uint32 n = (uint32) (uint8) byte;
  2132. uint32 mask = 0x7f;
  2133. uint32 bit = 0x40;
  2134. int numExtraValues = 0;
  2135. while ((n & bit) != 0 && bit > 0x8)
  2136. {
  2137. mask >>= 1;
  2138. ++numExtraValues;
  2139. bit >>= 1;
  2140. }
  2141. n &= mask;
  2142. while (--numExtraValues >= 0)
  2143. {
  2144. const uint32 nextByte = (uint32) (uint8) *data++;
  2145. if ((nextByte & 0xc0) != 0x80)
  2146. break;
  2147. n <<= 6;
  2148. n |= (nextByte & 0x3f);
  2149. }
  2150. return (juce_wchar) n;
  2151. }
  2152. /** Moves this pointer along to the next character in the string. */
  2153. CharPointer_UTF8 operator++ (int) throw()
  2154. {
  2155. CharPointer_UTF8 temp (*this);
  2156. ++*this;
  2157. return temp;
  2158. }
  2159. /** Moves this pointer forwards by the specified number of characters. */
  2160. void operator+= (int numToSkip) throw()
  2161. {
  2162. if (numToSkip < 0)
  2163. {
  2164. while (++numToSkip <= 0)
  2165. --*this;
  2166. }
  2167. else
  2168. {
  2169. while (--numToSkip >= 0)
  2170. ++*this;
  2171. }
  2172. }
  2173. /** Moves this pointer backwards by the specified number of characters. */
  2174. void operator-= (int numToSkip) throw()
  2175. {
  2176. operator+= (-numToSkip);
  2177. }
  2178. /** Returns the character at a given character index from the start of the string. */
  2179. juce_wchar operator[] (int characterIndex) const throw()
  2180. {
  2181. CharPointer_UTF8 p (*this);
  2182. p += characterIndex;
  2183. return *p;
  2184. }
  2185. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2186. CharPointer_UTF8 operator+ (int numToSkip) const throw()
  2187. {
  2188. CharPointer_UTF8 p (*this);
  2189. p += numToSkip;
  2190. return p;
  2191. }
  2192. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2193. CharPointer_UTF8 operator- (int numToSkip) const throw()
  2194. {
  2195. CharPointer_UTF8 p (*this);
  2196. p += -numToSkip;
  2197. return p;
  2198. }
  2199. /** Returns the number of characters in this string. */
  2200. size_t length() const throw()
  2201. {
  2202. const CharType* d = data;
  2203. size_t count = 0;
  2204. for (;;)
  2205. {
  2206. const uint32 n = (uint32) (uint8) *d++;
  2207. if ((n & 0x80) != 0)
  2208. {
  2209. uint32 bit = 0x40;
  2210. while ((n & bit) != 0)
  2211. {
  2212. ++d;
  2213. bit >>= 1;
  2214. if (bit == 0)
  2215. break; // illegal utf-8 sequence
  2216. }
  2217. }
  2218. else if (n == 0)
  2219. break;
  2220. ++count;
  2221. }
  2222. return count;
  2223. }
  2224. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2225. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  2226. {
  2227. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2228. }
  2229. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2230. size_t lengthUpTo (const CharPointer_UTF8& end) const throw()
  2231. {
  2232. return CharacterFunctions::lengthUpTo (*this, end);
  2233. }
  2234. /** Returns the number of bytes that are used to represent this string.
  2235. This includes the terminating null character.
  2236. */
  2237. size_t sizeInBytes() const throw()
  2238. {
  2239. return strlen (data) + 1;
  2240. }
  2241. /** Returns the number of bytes that would be needed to represent the given
  2242. unicode character in this encoding format.
  2243. */
  2244. static size_t getBytesRequiredFor (const juce_wchar charToWrite) throw()
  2245. {
  2246. size_t num = 1;
  2247. const uint32 c = (uint32) charToWrite;
  2248. if (c >= 0x80)
  2249. {
  2250. ++num;
  2251. if (c >= 0x800)
  2252. {
  2253. ++num;
  2254. if (c >= 0x10000)
  2255. ++num;
  2256. }
  2257. }
  2258. return num;
  2259. }
  2260. /** Returns the number of bytes that would be needed to represent the given
  2261. string in this encoding format.
  2262. The value returned does NOT include the terminating null character.
  2263. */
  2264. template <class CharPointer>
  2265. static size_t getBytesRequiredFor (CharPointer text) throw()
  2266. {
  2267. size_t count = 0;
  2268. juce_wchar n;
  2269. while ((n = text.getAndAdvance()) != 0)
  2270. count += getBytesRequiredFor (n);
  2271. return count;
  2272. }
  2273. /** Returns a pointer to the null character that terminates this string. */
  2274. CharPointer_UTF8 findTerminatingNull() const throw()
  2275. {
  2276. return CharPointer_UTF8 (data + strlen (data));
  2277. }
  2278. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2279. void write (const juce_wchar charToWrite) throw()
  2280. {
  2281. const uint32 c = (uint32) charToWrite;
  2282. if (c >= 0x80)
  2283. {
  2284. int numExtraBytes = 1;
  2285. if (c >= 0x800)
  2286. {
  2287. ++numExtraBytes;
  2288. if (c >= 0x10000)
  2289. ++numExtraBytes;
  2290. }
  2291. *data++ = (CharType) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  2292. while (--numExtraBytes >= 0)
  2293. *data++ = (CharType) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  2294. }
  2295. else
  2296. {
  2297. *data++ = (CharType) c;
  2298. }
  2299. }
  2300. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2301. inline void writeNull() const throw()
  2302. {
  2303. *data = 0;
  2304. }
  2305. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2306. template <typename CharPointer>
  2307. void writeAll (const CharPointer& src) throw()
  2308. {
  2309. CharacterFunctions::copyAll (*this, src);
  2310. }
  2311. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2312. void writeAll (const CharPointer_UTF8& src) throw()
  2313. {
  2314. const CharType* s = src.data;
  2315. while ((*data = *s) != 0)
  2316. {
  2317. ++data;
  2318. ++s;
  2319. }
  2320. }
  2321. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2322. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2323. to the destination buffer before stopping.
  2324. */
  2325. template <typename CharPointer>
  2326. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  2327. {
  2328. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2329. }
  2330. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2331. The maxChars parameter specifies the maximum number of characters that can be
  2332. written to the destination buffer before stopping (including the terminating null).
  2333. */
  2334. template <typename CharPointer>
  2335. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  2336. {
  2337. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2338. }
  2339. /** Compares this string with another one. */
  2340. template <typename CharPointer>
  2341. int compare (const CharPointer& other) const throw()
  2342. {
  2343. return CharacterFunctions::compare (*this, other);
  2344. }
  2345. /** Compares this string with another one, up to a specified number of characters. */
  2346. template <typename CharPointer>
  2347. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  2348. {
  2349. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2350. }
  2351. /** Compares this string with another one. */
  2352. template <typename CharPointer>
  2353. int compareIgnoreCase (const CharPointer& other) const throw()
  2354. {
  2355. return CharacterFunctions::compareIgnoreCase (*this, other);
  2356. }
  2357. /** Compares this string with another one. */
  2358. int compareIgnoreCase (const CharPointer_UTF8& other) const throw()
  2359. {
  2360. #if JUCE_WINDOWS
  2361. return stricmp (data, other.data);
  2362. #else
  2363. return strcasecmp (data, other.data);
  2364. #endif
  2365. }
  2366. /** Compares this string with another one, up to a specified number of characters. */
  2367. template <typename CharPointer>
  2368. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  2369. {
  2370. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2371. }
  2372. /** Compares this string with another one, up to a specified number of characters. */
  2373. int compareIgnoreCaseUpTo (const CharPointer_UTF8& other, const int maxChars) const throw()
  2374. {
  2375. #if JUCE_WINDOWS
  2376. return strnicmp (data, other.data, maxChars);
  2377. #else
  2378. return strncasecmp (data, other.data, maxChars);
  2379. #endif
  2380. }
  2381. /** Returns the character index of a substring, or -1 if it isn't found. */
  2382. template <typename CharPointer>
  2383. int indexOf (const CharPointer& stringToFind) const throw()
  2384. {
  2385. return CharacterFunctions::indexOf (*this, stringToFind);
  2386. }
  2387. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2388. int indexOf (const juce_wchar charToFind) const throw()
  2389. {
  2390. return CharacterFunctions::indexOfChar (*this, charToFind);
  2391. }
  2392. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2393. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  2394. {
  2395. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2396. : CharacterFunctions::indexOfChar (*this, charToFind);
  2397. }
  2398. /** Returns true if the first character of this string is whitespace. */
  2399. bool isWhitespace() const throw() { return *data == ' ' || (*data <= 13 && *data >= 9); }
  2400. /** Returns true if the first character of this string is a digit. */
  2401. bool isDigit() const throw() { return *data >= '0' && *data <= '9'; }
  2402. /** Returns true if the first character of this string is a letter. */
  2403. bool isLetter() const throw() { return CharacterFunctions::isLetter (operator*()) != 0; }
  2404. /** Returns true if the first character of this string is a letter or digit. */
  2405. bool isLetterOrDigit() const throw() { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2406. /** Returns true if the first character of this string is upper-case. */
  2407. bool isUpperCase() const throw() { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2408. /** Returns true if the first character of this string is lower-case. */
  2409. bool isLowerCase() const throw() { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2410. /** Returns an upper-case version of the first character of this string. */
  2411. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (operator*()); }
  2412. /** Returns a lower-case version of the first character of this string. */
  2413. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (operator*()); }
  2414. /** Parses this string as a 32-bit integer. */
  2415. int getIntValue32() const throw() { return atoi (data); }
  2416. /** Parses this string as a 64-bit integer. */
  2417. int64 getIntValue64() const throw()
  2418. {
  2419. #if JUCE_LINUX || JUCE_ANDROID
  2420. return atoll (data);
  2421. #elif JUCE_WINDOWS
  2422. return _atoi64 (data);
  2423. #else
  2424. return CharacterFunctions::getIntValue <int64, CharPointer_UTF8> (*this);
  2425. #endif
  2426. }
  2427. /** Parses this string as a floating point double. */
  2428. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  2429. /** Returns the first non-whitespace character in the string. */
  2430. CharPointer_UTF8 findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  2431. /** Returns true if the given unicode character can be represented in this encoding. */
  2432. static bool canRepresent (juce_wchar character) throw()
  2433. {
  2434. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  2435. }
  2436. /** Returns true if this data contains a valid string in this encoding. */
  2437. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2438. {
  2439. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2440. {
  2441. const signed char byte = (signed char) *dataToTest;
  2442. if (byte < 0)
  2443. {
  2444. uint32 n = (uint32) (uint8) byte;
  2445. uint32 mask = 0x7f;
  2446. uint32 bit = 0x40;
  2447. int numExtraValues = 0;
  2448. while ((n & bit) != 0)
  2449. {
  2450. if (bit <= 0x10)
  2451. return false;
  2452. mask >>= 1;
  2453. ++numExtraValues;
  2454. bit >>= 1;
  2455. }
  2456. n &= mask;
  2457. while (--numExtraValues >= 0)
  2458. {
  2459. const uint32 nextByte = (uint32) (uint8) *dataToTest++;
  2460. if ((nextByte & 0xc0) != 0x80)
  2461. return false;
  2462. }
  2463. }
  2464. }
  2465. return true;
  2466. }
  2467. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2468. CharPointer_UTF8 atomicSwap (const CharPointer_UTF8& newValue)
  2469. {
  2470. return CharPointer_UTF8 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2471. }
  2472. /** These values are the byte-order-mark (BOM) values for a UTF-8 stream. */
  2473. enum
  2474. {
  2475. byteOrderMark1 = 0xef,
  2476. byteOrderMark2 = 0xbb,
  2477. byteOrderMark3 = 0xbf
  2478. };
  2479. private:
  2480. CharType* data;
  2481. };
  2482. #endif // __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2483. /*** End of inlined file: juce_CharPointer_UTF8.h ***/
  2484. /*** Start of inlined file: juce_CharPointer_UTF16.h ***/
  2485. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2486. #define __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2487. /**
  2488. Wraps a pointer to a null-terminated UTF-16 character string, and provides
  2489. various methods to operate on the data.
  2490. @see CharPointer_UTF8, CharPointer_UTF32
  2491. */
  2492. class CharPointer_UTF16
  2493. {
  2494. public:
  2495. #if JUCE_NATIVE_WCHAR_IS_UTF16
  2496. typedef wchar_t CharType;
  2497. #else
  2498. typedef int16 CharType;
  2499. #endif
  2500. inline explicit CharPointer_UTF16 (const CharType* const rawPointer) throw()
  2501. : data (const_cast <CharType*> (rawPointer))
  2502. {
  2503. }
  2504. inline CharPointer_UTF16 (const CharPointer_UTF16& other) throw()
  2505. : data (other.data)
  2506. {
  2507. }
  2508. inline CharPointer_UTF16& operator= (const CharPointer_UTF16& other) throw()
  2509. {
  2510. data = other.data;
  2511. return *this;
  2512. }
  2513. inline CharPointer_UTF16& operator= (const CharType* text) throw()
  2514. {
  2515. data = const_cast <CharType*> (text);
  2516. return *this;
  2517. }
  2518. /** This is a pointer comparison, it doesn't compare the actual text. */
  2519. inline bool operator== (const CharPointer_UTF16& other) const throw() { return data == other.data; }
  2520. inline bool operator!= (const CharPointer_UTF16& other) const throw() { return data != other.data; }
  2521. inline bool operator<= (const CharPointer_UTF16& other) const throw() { return data <= other.data; }
  2522. inline bool operator< (const CharPointer_UTF16& other) const throw() { return data < other.data; }
  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. /** Returns the address that this pointer is pointing to. */
  2526. inline CharType* getAddress() const throw() { return data; }
  2527. /** Returns the address that this pointer is pointing to. */
  2528. inline operator const CharType*() const throw() { return data; }
  2529. /** Returns true if this pointer is pointing to a null character. */
  2530. inline bool isEmpty() const throw() { return *data == 0; }
  2531. /** Returns the unicode character that this pointer is pointing to. */
  2532. juce_wchar operator*() const throw()
  2533. {
  2534. uint32 n = (uint32) (uint16) *data;
  2535. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) data[1]) >= 0xdc00)
  2536. n = 0x10000 + (((n - 0xd800) << 10) | (((uint32) (uint16) data[1]) - 0xdc00));
  2537. return (juce_wchar) n;
  2538. }
  2539. /** Moves this pointer along to the next character in the string. */
  2540. CharPointer_UTF16& operator++() throw()
  2541. {
  2542. const juce_wchar n = *data++;
  2543. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2544. ++data;
  2545. return *this;
  2546. }
  2547. /** Moves this pointer back to the previous character in the string. */
  2548. CharPointer_UTF16& operator--() throw()
  2549. {
  2550. const juce_wchar n = *--data;
  2551. if (n >= 0xdc00 && n <= 0xdfff)
  2552. --data;
  2553. return *this;
  2554. }
  2555. /** Returns the character that this pointer is currently pointing to, and then
  2556. advances the pointer to point to the next character. */
  2557. juce_wchar getAndAdvance() throw()
  2558. {
  2559. uint32 n = (uint32) (uint16) *data++;
  2560. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2561. n = 0x10000 + ((((n - 0xd800) << 10) | (((uint32) (uint16) *data++) - 0xdc00)));
  2562. return (juce_wchar) n;
  2563. }
  2564. /** Moves this pointer along to the next character in the string. */
  2565. CharPointer_UTF16 operator++ (int) throw()
  2566. {
  2567. CharPointer_UTF16 temp (*this);
  2568. ++*this;
  2569. return temp;
  2570. }
  2571. /** Moves this pointer forwards by the specified number of characters. */
  2572. void operator+= (int numToSkip) throw()
  2573. {
  2574. if (numToSkip < 0)
  2575. {
  2576. while (++numToSkip <= 0)
  2577. --*this;
  2578. }
  2579. else
  2580. {
  2581. while (--numToSkip >= 0)
  2582. ++*this;
  2583. }
  2584. }
  2585. /** Moves this pointer backwards by the specified number of characters. */
  2586. void operator-= (int numToSkip) throw()
  2587. {
  2588. operator+= (-numToSkip);
  2589. }
  2590. /** Returns the character at a given character index from the start of the string. */
  2591. juce_wchar operator[] (const int characterIndex) const throw()
  2592. {
  2593. CharPointer_UTF16 p (*this);
  2594. p += characterIndex;
  2595. return *p;
  2596. }
  2597. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2598. CharPointer_UTF16 operator+ (const int numToSkip) const throw()
  2599. {
  2600. CharPointer_UTF16 p (*this);
  2601. p += numToSkip;
  2602. return p;
  2603. }
  2604. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2605. CharPointer_UTF16 operator- (const int numToSkip) const throw()
  2606. {
  2607. CharPointer_UTF16 p (*this);
  2608. p += -numToSkip;
  2609. return p;
  2610. }
  2611. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2612. void write (juce_wchar charToWrite) throw()
  2613. {
  2614. if (charToWrite >= 0x10000)
  2615. {
  2616. charToWrite -= 0x10000;
  2617. *data++ = (CharType) (0xd800 + (charToWrite >> 10));
  2618. *data++ = (CharType) (0xdc00 + (charToWrite & 0x3ff));
  2619. }
  2620. else
  2621. {
  2622. *data++ = (CharType) charToWrite;
  2623. }
  2624. }
  2625. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2626. inline void writeNull() const throw()
  2627. {
  2628. *data = 0;
  2629. }
  2630. /** Returns the number of characters in this string. */
  2631. size_t length() const throw()
  2632. {
  2633. const CharType* d = data;
  2634. size_t count = 0;
  2635. for (;;)
  2636. {
  2637. const int n = *d++;
  2638. if (n >= 0xd800 && n <= 0xdfff)
  2639. {
  2640. if (*d++ == 0)
  2641. break;
  2642. }
  2643. else if (n == 0)
  2644. break;
  2645. ++count;
  2646. }
  2647. return count;
  2648. }
  2649. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2650. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  2651. {
  2652. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2653. }
  2654. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2655. size_t lengthUpTo (const CharPointer_UTF16& end) const throw()
  2656. {
  2657. return CharacterFunctions::lengthUpTo (*this, end);
  2658. }
  2659. /** Returns the number of bytes that are used to represent this string.
  2660. This includes the terminating null character.
  2661. */
  2662. size_t sizeInBytes() const throw()
  2663. {
  2664. return sizeof (CharType) * (findNullIndex (data) + 1);
  2665. }
  2666. /** Returns the number of bytes that would be needed to represent the given
  2667. unicode character in this encoding format.
  2668. */
  2669. static size_t getBytesRequiredFor (const juce_wchar charToWrite) throw()
  2670. {
  2671. return (charToWrite >= 0x10000) ? (sizeof (CharType) * 2) : sizeof (CharType);
  2672. }
  2673. /** Returns the number of bytes that would be needed to represent the given
  2674. string in this encoding format.
  2675. The value returned does NOT include the terminating null character.
  2676. */
  2677. template <class CharPointer>
  2678. static size_t getBytesRequiredFor (CharPointer text) throw()
  2679. {
  2680. size_t count = 0;
  2681. juce_wchar n;
  2682. while ((n = text.getAndAdvance()) != 0)
  2683. count += getBytesRequiredFor (n);
  2684. return count;
  2685. }
  2686. /** Returns a pointer to the null character that terminates this string. */
  2687. CharPointer_UTF16 findTerminatingNull() const throw()
  2688. {
  2689. const CharType* t = data;
  2690. while (*t != 0)
  2691. ++t;
  2692. return CharPointer_UTF16 (t);
  2693. }
  2694. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2695. template <typename CharPointer>
  2696. void writeAll (const CharPointer& src) throw()
  2697. {
  2698. CharacterFunctions::copyAll (*this, src);
  2699. }
  2700. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2701. void writeAll (const CharPointer_UTF16& src) throw()
  2702. {
  2703. const CharType* s = src.data;
  2704. while ((*data = *s) != 0)
  2705. {
  2706. ++data;
  2707. ++s;
  2708. }
  2709. }
  2710. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2711. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2712. to the destination buffer before stopping.
  2713. */
  2714. template <typename CharPointer>
  2715. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  2716. {
  2717. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2718. }
  2719. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2720. The maxChars parameter specifies the maximum number of characters that can be
  2721. written to the destination buffer before stopping (including the terminating null).
  2722. */
  2723. template <typename CharPointer>
  2724. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  2725. {
  2726. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2727. }
  2728. /** Compares this string with another one. */
  2729. template <typename CharPointer>
  2730. int compare (const CharPointer& other) const throw()
  2731. {
  2732. return CharacterFunctions::compare (*this, other);
  2733. }
  2734. /** Compares this string with another one, up to a specified number of characters. */
  2735. template <typename CharPointer>
  2736. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  2737. {
  2738. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2739. }
  2740. /** Compares this string with another one. */
  2741. template <typename CharPointer>
  2742. int compareIgnoreCase (const CharPointer& other) const throw()
  2743. {
  2744. return CharacterFunctions::compareIgnoreCase (*this, other);
  2745. }
  2746. /** Compares this string with another one, up to a specified number of characters. */
  2747. template <typename CharPointer>
  2748. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  2749. {
  2750. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2751. }
  2752. #if JUCE_WINDOWS && ! DOXYGEN
  2753. int compareIgnoreCase (const CharPointer_UTF16& other) const throw()
  2754. {
  2755. return _wcsicmp (data, other.data);
  2756. }
  2757. int compareIgnoreCaseUpTo (const CharPointer_UTF16& other, int maxChars) const throw()
  2758. {
  2759. return _wcsnicmp (data, other.data, maxChars);
  2760. }
  2761. int indexOf (const CharPointer_UTF16& stringToFind) const throw()
  2762. {
  2763. const CharType* const t = wcsstr (data, stringToFind.getAddress());
  2764. return t == 0 ? -1 : (int) (t - data);
  2765. }
  2766. #endif
  2767. /** Returns the character index of a substring, or -1 if it isn't found. */
  2768. template <typename CharPointer>
  2769. int indexOf (const CharPointer& stringToFind) const throw()
  2770. {
  2771. return CharacterFunctions::indexOf (*this, stringToFind);
  2772. }
  2773. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2774. int indexOf (const juce_wchar charToFind) const throw()
  2775. {
  2776. return CharacterFunctions::indexOfChar (*this, charToFind);
  2777. }
  2778. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2779. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  2780. {
  2781. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2782. : CharacterFunctions::indexOfChar (*this, charToFind);
  2783. }
  2784. /** Returns true if the first character of this string is whitespace. */
  2785. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (operator*()) != 0; }
  2786. /** Returns true if the first character of this string is a digit. */
  2787. bool isDigit() const throw() { return CharacterFunctions::isDigit (operator*()) != 0; }
  2788. /** Returns true if the first character of this string is a letter. */
  2789. bool isLetter() const throw() { return CharacterFunctions::isLetter (operator*()) != 0; }
  2790. /** Returns true if the first character of this string is a letter or digit. */
  2791. bool isLetterOrDigit() const throw() { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2792. /** Returns true if the first character of this string is upper-case. */
  2793. bool isUpperCase() const throw() { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2794. /** Returns true if the first character of this string is lower-case. */
  2795. bool isLowerCase() const throw() { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2796. /** Returns an upper-case version of the first character of this string. */
  2797. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (operator*()); }
  2798. /** Returns a lower-case version of the first character of this string. */
  2799. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (operator*()); }
  2800. /** Parses this string as a 32-bit integer. */
  2801. int getIntValue32() const throw()
  2802. {
  2803. #if JUCE_WINDOWS
  2804. return _wtoi (data);
  2805. #else
  2806. return CharacterFunctions::getIntValue <int, CharPointer_UTF16> (*this);
  2807. #endif
  2808. }
  2809. /** Parses this string as a 64-bit integer. */
  2810. int64 getIntValue64() const throw()
  2811. {
  2812. #if JUCE_WINDOWS
  2813. return _wtoi64 (data);
  2814. #else
  2815. return CharacterFunctions::getIntValue <int64, CharPointer_UTF16> (*this);
  2816. #endif
  2817. }
  2818. /** Parses this string as a floating point double. */
  2819. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  2820. /** Returns the first non-whitespace character in the string. */
  2821. CharPointer_UTF16 findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  2822. /** Returns true if the given unicode character can be represented in this encoding. */
  2823. static bool canRepresent (juce_wchar character) throw()
  2824. {
  2825. return ((unsigned int) character) < (unsigned int) 0x10ffff
  2826. && (((unsigned int) character) < 0xd800 || ((unsigned int) character) > 0xdfff);
  2827. }
  2828. /** Returns true if this data contains a valid string in this encoding. */
  2829. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2830. {
  2831. maxBytesToRead /= sizeof (CharType);
  2832. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2833. {
  2834. const uint32 n = (uint32) (uint16) *dataToTest++;
  2835. if (n >= 0xd800)
  2836. {
  2837. if (n > 0x10ffff)
  2838. return false;
  2839. if (n <= 0xdfff)
  2840. {
  2841. if (n > 0xdc00)
  2842. return false;
  2843. const uint32 nextChar = (uint32) (uint16) *dataToTest++;
  2844. if (nextChar < 0xdc00 || nextChar > 0xdfff)
  2845. return false;
  2846. }
  2847. }
  2848. }
  2849. return true;
  2850. }
  2851. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2852. CharPointer_UTF16 atomicSwap (const CharPointer_UTF16& newValue)
  2853. {
  2854. return CharPointer_UTF16 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2855. }
  2856. /** These values are the byte-order-mark (BOM) values for a UTF-16 stream. */
  2857. enum
  2858. {
  2859. byteOrderMarkBE1 = 0xfe,
  2860. byteOrderMarkBE2 = 0xff,
  2861. byteOrderMarkLE1 = 0xff,
  2862. byteOrderMarkLE2 = 0xfe
  2863. };
  2864. private:
  2865. CharType* data;
  2866. static int findNullIndex (const CharType* const t) throw()
  2867. {
  2868. int n = 0;
  2869. while (t[n] != 0)
  2870. ++n;
  2871. return n;
  2872. }
  2873. };
  2874. #endif // __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2875. /*** End of inlined file: juce_CharPointer_UTF16.h ***/
  2876. /*** Start of inlined file: juce_CharPointer_UTF32.h ***/
  2877. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2878. #define __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2879. /**
  2880. Wraps a pointer to a null-terminated UTF-32 character string, and provides
  2881. various methods to operate on the data.
  2882. @see CharPointer_UTF8, CharPointer_UTF16
  2883. */
  2884. class CharPointer_UTF32
  2885. {
  2886. public:
  2887. typedef juce_wchar CharType;
  2888. inline explicit CharPointer_UTF32 (const CharType* const rawPointer) throw()
  2889. : data (const_cast <CharType*> (rawPointer))
  2890. {
  2891. }
  2892. inline CharPointer_UTF32 (const CharPointer_UTF32& other) throw()
  2893. : data (other.data)
  2894. {
  2895. }
  2896. inline CharPointer_UTF32& operator= (const CharPointer_UTF32& other) throw()
  2897. {
  2898. data = other.data;
  2899. return *this;
  2900. }
  2901. inline CharPointer_UTF32& operator= (const CharType* text) throw()
  2902. {
  2903. data = const_cast <CharType*> (text);
  2904. return *this;
  2905. }
  2906. /** This is a pointer comparison, it doesn't compare the actual text. */
  2907. inline bool operator== (const CharPointer_UTF32& other) const throw() { return data == other.data; }
  2908. inline bool operator!= (const CharPointer_UTF32& other) const throw() { return data != other.data; }
  2909. inline bool operator<= (const CharPointer_UTF32& other) const throw() { return data <= other.data; }
  2910. inline bool operator< (const CharPointer_UTF32& other) const throw() { return data < other.data; }
  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. /** Returns the address that this pointer is pointing to. */
  2914. inline CharType* getAddress() const throw() { return data; }
  2915. /** Returns the address that this pointer is pointing to. */
  2916. inline operator const CharType*() const throw() { return data; }
  2917. /** Returns true if this pointer is pointing to a null character. */
  2918. inline bool isEmpty() const throw() { return *data == 0; }
  2919. /** Returns the unicode character that this pointer is pointing to. */
  2920. inline juce_wchar operator*() const throw() { return *data; }
  2921. /** Moves this pointer along to the next character in the string. */
  2922. inline CharPointer_UTF32& operator++() throw()
  2923. {
  2924. ++data;
  2925. return *this;
  2926. }
  2927. /** Moves this pointer to the previous character in the string. */
  2928. inline CharPointer_UTF32& operator--() throw()
  2929. {
  2930. --data;
  2931. return *this;
  2932. }
  2933. /** Returns the character that this pointer is currently pointing to, and then
  2934. advances the pointer to point to the next character. */
  2935. inline juce_wchar getAndAdvance() throw() { return *data++; }
  2936. /** Moves this pointer along to the next character in the string. */
  2937. CharPointer_UTF32 operator++ (int) throw()
  2938. {
  2939. CharPointer_UTF32 temp (*this);
  2940. ++data;
  2941. return temp;
  2942. }
  2943. /** Moves this pointer forwards by the specified number of characters. */
  2944. inline void operator+= (const int numToSkip) throw()
  2945. {
  2946. data += numToSkip;
  2947. }
  2948. inline void operator-= (const int numToSkip) throw()
  2949. {
  2950. data -= numToSkip;
  2951. }
  2952. /** Returns the character at a given character index from the start of the string. */
  2953. inline juce_wchar& operator[] (const int characterIndex) const throw()
  2954. {
  2955. return data [characterIndex];
  2956. }
  2957. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2958. CharPointer_UTF32 operator+ (const int numToSkip) const throw()
  2959. {
  2960. return CharPointer_UTF32 (data + numToSkip);
  2961. }
  2962. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2963. CharPointer_UTF32 operator- (const int numToSkip) const throw()
  2964. {
  2965. return CharPointer_UTF32 (data - numToSkip);
  2966. }
  2967. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2968. inline void write (const juce_wchar charToWrite) throw()
  2969. {
  2970. *data++ = charToWrite;
  2971. }
  2972. inline void replaceChar (const juce_wchar newChar) throw()
  2973. {
  2974. *data = newChar;
  2975. }
  2976. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2977. inline void writeNull() const throw()
  2978. {
  2979. *data = 0;
  2980. }
  2981. /** Returns the number of characters in this string. */
  2982. size_t length() const throw()
  2983. {
  2984. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  2985. return wcslen (data);
  2986. #else
  2987. size_t n = 0;
  2988. while (data[n] != 0)
  2989. ++n;
  2990. return n;
  2991. #endif
  2992. }
  2993. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2994. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  2995. {
  2996. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2997. }
  2998. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2999. size_t lengthUpTo (const CharPointer_UTF32& end) const throw()
  3000. {
  3001. return CharacterFunctions::lengthUpTo (*this, end);
  3002. }
  3003. /** Returns the number of bytes that are used to represent this string.
  3004. This includes the terminating null character.
  3005. */
  3006. size_t sizeInBytes() const throw()
  3007. {
  3008. return sizeof (CharType) * (length() + 1);
  3009. }
  3010. /** Returns the number of bytes that would be needed to represent the given
  3011. unicode character in this encoding format.
  3012. */
  3013. static inline size_t getBytesRequiredFor (const juce_wchar) throw()
  3014. {
  3015. return sizeof (CharType);
  3016. }
  3017. /** Returns the number of bytes that would be needed to represent the given
  3018. string in this encoding format.
  3019. The value returned does NOT include the terminating null character.
  3020. */
  3021. template <class CharPointer>
  3022. static size_t getBytesRequiredFor (const CharPointer& text) throw()
  3023. {
  3024. return sizeof (CharType) * text.length();
  3025. }
  3026. /** Returns a pointer to the null character that terminates this string. */
  3027. CharPointer_UTF32 findTerminatingNull() const throw()
  3028. {
  3029. return CharPointer_UTF32 (data + length());
  3030. }
  3031. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3032. template <typename CharPointer>
  3033. void writeAll (const CharPointer& src) throw()
  3034. {
  3035. CharacterFunctions::copyAll (*this, src);
  3036. }
  3037. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3038. void writeAll (const CharPointer_UTF32& src) throw()
  3039. {
  3040. const CharType* s = src.data;
  3041. while ((*data = *s) != 0)
  3042. {
  3043. ++data;
  3044. ++s;
  3045. }
  3046. }
  3047. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3048. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3049. to the destination buffer before stopping.
  3050. */
  3051. template <typename CharPointer>
  3052. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  3053. {
  3054. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3055. }
  3056. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3057. The maxChars parameter specifies the maximum number of characters that can be
  3058. written to the destination buffer before stopping (including the terminating null).
  3059. */
  3060. template <typename CharPointer>
  3061. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  3062. {
  3063. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3064. }
  3065. /** Compares this string with another one. */
  3066. template <typename CharPointer>
  3067. int compare (const CharPointer& other) const throw()
  3068. {
  3069. return CharacterFunctions::compare (*this, other);
  3070. }
  3071. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  3072. /** Compares this string with another one. */
  3073. int compare (const CharPointer_UTF32& other) const throw()
  3074. {
  3075. return wcscmp (data, other.data);
  3076. }
  3077. #endif
  3078. /** Compares this string with another one, up to a specified number of characters. */
  3079. template <typename CharPointer>
  3080. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  3081. {
  3082. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3083. }
  3084. /** Compares this string with another one. */
  3085. template <typename CharPointer>
  3086. int compareIgnoreCase (const CharPointer& other) const
  3087. {
  3088. return CharacterFunctions::compareIgnoreCase (*this, other);
  3089. }
  3090. /** Compares this string with another one, up to a specified number of characters. */
  3091. template <typename CharPointer>
  3092. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  3093. {
  3094. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3095. }
  3096. /** Returns the character index of a substring, or -1 if it isn't found. */
  3097. template <typename CharPointer>
  3098. int indexOf (const CharPointer& stringToFind) const throw()
  3099. {
  3100. return CharacterFunctions::indexOf (*this, stringToFind);
  3101. }
  3102. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3103. int indexOf (const juce_wchar charToFind) const throw()
  3104. {
  3105. int i = 0;
  3106. while (data[i] != 0)
  3107. {
  3108. if (data[i] == charToFind)
  3109. return i;
  3110. ++i;
  3111. }
  3112. return -1;
  3113. }
  3114. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3115. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  3116. {
  3117. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3118. : CharacterFunctions::indexOfChar (*this, charToFind);
  3119. }
  3120. /** Returns true if the first character of this string is whitespace. */
  3121. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3122. /** Returns true if the first character of this string is a digit. */
  3123. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3124. /** Returns true if the first character of this string is a letter. */
  3125. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3126. /** Returns true if the first character of this string is a letter or digit. */
  3127. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3128. /** Returns true if the first character of this string is upper-case. */
  3129. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3130. /** Returns true if the first character of this string is lower-case. */
  3131. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3132. /** Returns an upper-case version of the first character of this string. */
  3133. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (*data); }
  3134. /** Returns a lower-case version of the first character of this string. */
  3135. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (*data); }
  3136. /** Parses this string as a 32-bit integer. */
  3137. int getIntValue32() const throw() { return CharacterFunctions::getIntValue <int, CharPointer_UTF32> (*this); }
  3138. /** Parses this string as a 64-bit integer. */
  3139. int64 getIntValue64() const throw() { return CharacterFunctions::getIntValue <int64, CharPointer_UTF32> (*this); }
  3140. /** Parses this string as a floating point double. */
  3141. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  3142. /** Returns the first non-whitespace character in the string. */
  3143. CharPointer_UTF32 findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  3144. /** Returns true if the given unicode character can be represented in this encoding. */
  3145. static bool canRepresent (juce_wchar character) throw()
  3146. {
  3147. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  3148. }
  3149. /** Returns true if this data contains a valid string in this encoding. */
  3150. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3151. {
  3152. maxBytesToRead /= sizeof (CharType);
  3153. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  3154. if (! canRepresent (*dataToTest++))
  3155. return false;
  3156. return true;
  3157. }
  3158. /** Atomically swaps this pointer for a new value, returning the previous value. */
  3159. CharPointer_UTF32 atomicSwap (const CharPointer_UTF32& newValue)
  3160. {
  3161. return CharPointer_UTF32 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  3162. }
  3163. private:
  3164. CharType* data;
  3165. };
  3166. #endif // __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  3167. /*** End of inlined file: juce_CharPointer_UTF32.h ***/
  3168. /*** Start of inlined file: juce_CharPointer_ASCII.h ***/
  3169. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3170. #define __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3171. /**
  3172. Wraps a pointer to a null-terminated ASCII character string, and provides
  3173. various methods to operate on the data.
  3174. A valid ASCII string is assumed to not contain any characters above 127.
  3175. @see CharPointer_UTF8, CharPointer_UTF16, CharPointer_UTF32
  3176. */
  3177. class CharPointer_ASCII
  3178. {
  3179. public:
  3180. typedef char CharType;
  3181. inline explicit CharPointer_ASCII (const CharType* const rawPointer) throw()
  3182. : data (const_cast <CharType*> (rawPointer))
  3183. {
  3184. }
  3185. inline CharPointer_ASCII (const CharPointer_ASCII& other) throw()
  3186. : data (other.data)
  3187. {
  3188. }
  3189. inline CharPointer_ASCII& operator= (const CharPointer_ASCII& other) throw()
  3190. {
  3191. data = other.data;
  3192. return *this;
  3193. }
  3194. inline CharPointer_ASCII& operator= (const CharType* text) throw()
  3195. {
  3196. data = const_cast <CharType*> (text);
  3197. return *this;
  3198. }
  3199. /** This is a pointer comparison, it doesn't compare the actual text. */
  3200. inline bool operator== (const CharPointer_ASCII& other) const throw() { return data == other.data; }
  3201. inline bool operator!= (const CharPointer_ASCII& other) const throw() { return data != other.data; }
  3202. inline bool operator<= (const CharPointer_ASCII& other) const throw() { return data <= other.data; }
  3203. inline bool operator< (const CharPointer_ASCII& other) const throw() { return data < other.data; }
  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. /** Returns the address that this pointer is pointing to. */
  3207. inline CharType* getAddress() const throw() { return data; }
  3208. /** Returns the address that this pointer is pointing to. */
  3209. inline operator const CharType*() const throw() { return data; }
  3210. /** Returns true if this pointer is pointing to a null character. */
  3211. inline bool isEmpty() const throw() { return *data == 0; }
  3212. /** Returns the unicode character that this pointer is pointing to. */
  3213. inline juce_wchar operator*() const throw() { return *data; }
  3214. /** Moves this pointer along to the next character in the string. */
  3215. inline CharPointer_ASCII& operator++() throw()
  3216. {
  3217. ++data;
  3218. return *this;
  3219. }
  3220. /** Moves this pointer to the previous character in the string. */
  3221. inline CharPointer_ASCII& operator--() throw()
  3222. {
  3223. --data;
  3224. return *this;
  3225. }
  3226. /** Returns the character that this pointer is currently pointing to, and then
  3227. advances the pointer to point to the next character. */
  3228. inline juce_wchar getAndAdvance() throw() { return *data++; }
  3229. /** Moves this pointer along to the next character in the string. */
  3230. CharPointer_ASCII operator++ (int) throw()
  3231. {
  3232. CharPointer_ASCII temp (*this);
  3233. ++data;
  3234. return temp;
  3235. }
  3236. /** Moves this pointer forwards by the specified number of characters. */
  3237. inline void operator+= (const int numToSkip) throw()
  3238. {
  3239. data += numToSkip;
  3240. }
  3241. inline void operator-= (const int numToSkip) throw()
  3242. {
  3243. data -= numToSkip;
  3244. }
  3245. /** Returns the character at a given character index from the start of the string. */
  3246. inline juce_wchar operator[] (const int characterIndex) const throw()
  3247. {
  3248. return (juce_wchar) (unsigned char) data [characterIndex];
  3249. }
  3250. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  3251. CharPointer_ASCII operator+ (const int numToSkip) const throw()
  3252. {
  3253. return CharPointer_ASCII (data + numToSkip);
  3254. }
  3255. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  3256. CharPointer_ASCII operator- (const int numToSkip) const throw()
  3257. {
  3258. return CharPointer_ASCII (data - numToSkip);
  3259. }
  3260. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  3261. inline void write (const juce_wchar charToWrite) throw()
  3262. {
  3263. *data++ = (char) charToWrite;
  3264. }
  3265. inline void replaceChar (const juce_wchar newChar) throw()
  3266. {
  3267. *data = (char) newChar;
  3268. }
  3269. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  3270. inline void writeNull() const throw()
  3271. {
  3272. *data = 0;
  3273. }
  3274. /** Returns the number of characters in this string. */
  3275. size_t length() const throw()
  3276. {
  3277. return (size_t) strlen (data);
  3278. }
  3279. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  3280. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  3281. {
  3282. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  3283. }
  3284. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  3285. size_t lengthUpTo (const CharPointer_ASCII& end) const throw()
  3286. {
  3287. return CharacterFunctions::lengthUpTo (*this, end);
  3288. }
  3289. /** Returns the number of bytes that are used to represent this string.
  3290. This includes the terminating null character.
  3291. */
  3292. size_t sizeInBytes() const throw()
  3293. {
  3294. return length() + 1;
  3295. }
  3296. /** Returns the number of bytes that would be needed to represent the given
  3297. unicode character in this encoding format.
  3298. */
  3299. static inline size_t getBytesRequiredFor (const juce_wchar) throw()
  3300. {
  3301. return 1;
  3302. }
  3303. /** Returns the number of bytes that would be needed to represent the given
  3304. string in this encoding format.
  3305. The value returned does NOT include the terminating null character.
  3306. */
  3307. template <class CharPointer>
  3308. static size_t getBytesRequiredFor (const CharPointer& text) throw()
  3309. {
  3310. return text.length();
  3311. }
  3312. /** Returns a pointer to the null character that terminates this string. */
  3313. CharPointer_ASCII findTerminatingNull() const throw()
  3314. {
  3315. return CharPointer_ASCII (data + length());
  3316. }
  3317. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3318. template <typename CharPointer>
  3319. void writeAll (const CharPointer& src) throw()
  3320. {
  3321. CharacterFunctions::copyAll (*this, src);
  3322. }
  3323. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3324. void writeAll (const CharPointer_ASCII& src) throw()
  3325. {
  3326. strcpy (data, src.data);
  3327. }
  3328. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3329. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3330. to the destination buffer before stopping.
  3331. */
  3332. template <typename CharPointer>
  3333. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  3334. {
  3335. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3336. }
  3337. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3338. The maxChars parameter specifies the maximum number of characters that can be
  3339. written to the destination buffer before stopping (including the terminating null).
  3340. */
  3341. template <typename CharPointer>
  3342. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  3343. {
  3344. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3345. }
  3346. /** Compares this string with another one. */
  3347. template <typename CharPointer>
  3348. int compare (const CharPointer& other) const throw()
  3349. {
  3350. return CharacterFunctions::compare (*this, other);
  3351. }
  3352. /** Compares this string with another one. */
  3353. int compare (const CharPointer_ASCII& other) const throw()
  3354. {
  3355. return strcmp (data, other.data);
  3356. }
  3357. /** Compares this string with another one, up to a specified number of characters. */
  3358. template <typename CharPointer>
  3359. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  3360. {
  3361. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3362. }
  3363. /** Compares this string with another one, up to a specified number of characters. */
  3364. int compareUpTo (const CharPointer_ASCII& other, const int maxChars) const throw()
  3365. {
  3366. return strncmp (data, other.data, (size_t) maxChars);
  3367. }
  3368. /** Compares this string with another one. */
  3369. template <typename CharPointer>
  3370. int compareIgnoreCase (const CharPointer& other) const
  3371. {
  3372. return CharacterFunctions::compareIgnoreCase (*this, other);
  3373. }
  3374. int compareIgnoreCase (const CharPointer_ASCII& other) const
  3375. {
  3376. #if JUCE_WINDOWS
  3377. return stricmp (data, other.data);
  3378. #else
  3379. return strcasecmp (data, other.data);
  3380. #endif
  3381. }
  3382. /** Compares this string with another one, up to a specified number of characters. */
  3383. template <typename CharPointer>
  3384. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  3385. {
  3386. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3387. }
  3388. /** Returns the character index of a substring, or -1 if it isn't found. */
  3389. template <typename CharPointer>
  3390. int indexOf (const CharPointer& stringToFind) const throw()
  3391. {
  3392. return CharacterFunctions::indexOf (*this, stringToFind);
  3393. }
  3394. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3395. int indexOf (const juce_wchar charToFind) const throw()
  3396. {
  3397. int i = 0;
  3398. while (data[i] != 0)
  3399. {
  3400. if (data[i] == (char) charToFind)
  3401. return i;
  3402. ++i;
  3403. }
  3404. return -1;
  3405. }
  3406. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3407. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  3408. {
  3409. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3410. : CharacterFunctions::indexOfChar (*this, charToFind);
  3411. }
  3412. /** Returns true if the first character of this string is whitespace. */
  3413. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3414. /** Returns true if the first character of this string is a digit. */
  3415. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3416. /** Returns true if the first character of this string is a letter. */
  3417. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3418. /** Returns true if the first character of this string is a letter or digit. */
  3419. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3420. /** Returns true if the first character of this string is upper-case. */
  3421. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3422. /** Returns true if the first character of this string is lower-case. */
  3423. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3424. /** Returns an upper-case version of the first character of this string. */
  3425. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (*data); }
  3426. /** Returns a lower-case version of the first character of this string. */
  3427. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (*data); }
  3428. /** Parses this string as a 32-bit integer. */
  3429. int getIntValue32() const throw() { return atoi (data); }
  3430. /** Parses this string as a 64-bit integer. */
  3431. int64 getIntValue64() const throw()
  3432. {
  3433. #if JUCE_LINUX || JUCE_ANDROID
  3434. return atoll (data);
  3435. #elif JUCE_WINDOWS
  3436. return _atoi64 (data);
  3437. #else
  3438. return CharacterFunctions::getIntValue <int64, CharPointer_ASCII> (*this);
  3439. #endif
  3440. }
  3441. /** Parses this string as a floating point double. */
  3442. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  3443. /** Returns the first non-whitespace character in the string. */
  3444. CharPointer_ASCII findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  3445. /** Returns true if the given unicode character can be represented in this encoding. */
  3446. static bool canRepresent (juce_wchar character) throw()
  3447. {
  3448. return ((unsigned int) character) < (unsigned int) 128;
  3449. }
  3450. /** Returns true if this data contains a valid string in this encoding. */
  3451. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3452. {
  3453. while (--maxBytesToRead >= 0)
  3454. {
  3455. if (((signed char) *dataToTest) <= 0)
  3456. return *dataToTest == 0;
  3457. ++dataToTest;
  3458. }
  3459. return true;
  3460. }
  3461. private:
  3462. CharType* data;
  3463. };
  3464. #endif // __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3465. /*** End of inlined file: juce_CharPointer_ASCII.h ***/
  3466. #if JUCE_MSVC
  3467. #pragma warning (pop)
  3468. #endif
  3469. class OutputStream;
  3470. /**
  3471. The JUCE String class!
  3472. Using a reference-counted internal representation, these strings are fast
  3473. and efficient, and there are methods to do just about any operation you'll ever
  3474. dream of.
  3475. @see StringArray, StringPairArray
  3476. */
  3477. class JUCE_API String
  3478. {
  3479. public:
  3480. /** Creates an empty string.
  3481. @see empty
  3482. */
  3483. String() throw();
  3484. /** Creates a copy of another string. */
  3485. String (const String& other) throw();
  3486. /** Creates a string from a zero-terminated ascii text string.
  3487. The string passed-in must not contain any characters with a value above 127, because
  3488. these can't be converted to unicode without knowing the original encoding that was
  3489. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3490. assertion.
  3491. To create strings with extended characters from UTF-8, you should explicitly call
  3492. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3493. use UTF-8 with escape characters in your source code to represent extended characters,
  3494. because there's no other way to represent unicode strings in a way that isn't dependent
  3495. on the compiler, source code editor and platform.
  3496. */
  3497. String (const char* text);
  3498. /** Creates a string from a string of 8-bit ascii characters.
  3499. The string passed-in must not contain any characters with a value above 127, because
  3500. these can't be converted to unicode without knowing the original encoding that was
  3501. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3502. assertion.
  3503. To create strings with extended characters from UTF-8, you should explicitly call
  3504. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3505. use UTF-8 with escape characters in your source code to represent extended characters,
  3506. because there's no other way to represent unicode strings in a way that isn't dependent
  3507. on the compiler, source code editor and platform.
  3508. This will use up the the first maxChars characters of the string (or less if the string
  3509. is actually shorter).
  3510. */
  3511. String (const char* text, size_t maxChars);
  3512. /** Creates a string from a whcar_t character string.
  3513. Depending on the platform, this may be treated as either UTF-32 or UTF-16.
  3514. */
  3515. String (const wchar_t* text);
  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, size_t maxChars);
  3520. /** Creates a string from a UTF-8 character string */
  3521. String (const CharPointer_UTF8& text);
  3522. /** Creates a string from a UTF-8 character string */
  3523. String (const CharPointer_UTF8& text, size_t maxChars);
  3524. /** Creates a string from a UTF-8 character string */
  3525. String (const CharPointer_UTF8& start, const CharPointer_UTF8& end);
  3526. /** Creates a string from a UTF-16 character string */
  3527. String (const CharPointer_UTF16& text);
  3528. /** Creates a string from a UTF-16 character string */
  3529. String (const CharPointer_UTF16& text, size_t maxChars);
  3530. /** Creates a string from a UTF-16 character string */
  3531. String (const CharPointer_UTF16& start, const CharPointer_UTF16& end);
  3532. /** Creates a string from a UTF-32 character string */
  3533. String (const CharPointer_UTF32& text);
  3534. /** Creates a string from a UTF-32 character string */
  3535. String (const CharPointer_UTF32& text, size_t maxChars);
  3536. /** Creates a string from a UTF-32 character string */
  3537. String (const CharPointer_UTF32& start, const CharPointer_UTF32& end);
  3538. /** Creates a string from an ASCII character string */
  3539. String (const CharPointer_ASCII& text);
  3540. /** Creates a string from a single character. */
  3541. static const String charToString (juce_wchar character);
  3542. /** Destructor. */
  3543. ~String() throw();
  3544. /** This is an empty string that can be used whenever one is needed.
  3545. It's better to use this than String() because it explains what's going on
  3546. and is more efficient.
  3547. */
  3548. static const String empty;
  3549. /** This is the character encoding type used internally to store the string.
  3550. By setting the value of JUCE_STRING_UTF_TYPE to 8, 16, or 32, you can change the
  3551. internal storage format of the String class. UTF-8 uses the least space (if your strings
  3552. contain few extended characters), but call operator[] involves iterating the string to find
  3553. the required index. UTF-32 provides instant random access to its characters, but uses 4 bytes
  3554. per character to store them. UTF-16 uses more space than UTF-8 and is also slow to index,
  3555. but is the native wchar_t format used in Windows.
  3556. It doesn't matter too much which format you pick, because the toUTF8(), toUTF16() and
  3557. toUTF32() methods let you access the string's content in any of the other formats.
  3558. */
  3559. #if (JUCE_STRING_UTF_TYPE == 32)
  3560. typedef CharPointer_UTF32 CharPointerType;
  3561. #elif (JUCE_STRING_UTF_TYPE == 16)
  3562. typedef CharPointer_UTF16 CharPointerType;
  3563. #elif (JUCE_STRING_UTF_TYPE == 8)
  3564. typedef CharPointer_UTF8 CharPointerType;
  3565. #else
  3566. #error "You must set the value of JUCE_STRING_UTF_TYPE to be either 8, 16, or 32!"
  3567. #endif
  3568. /** Generates a probably-unique 32-bit hashcode from this string. */
  3569. int hashCode() const throw();
  3570. /** Generates a probably-unique 64-bit hashcode from this string. */
  3571. int64 hashCode64() const throw();
  3572. /** Returns the number of characters in the string. */
  3573. int length() const throw();
  3574. // Assignment and concatenation operators..
  3575. /** Replaces this string's contents with another string. */
  3576. String& operator= (const String& other) throw();
  3577. /** Appends another string at the end of this one. */
  3578. String& operator+= (const String& stringToAppend);
  3579. /** Appends another string at the end of this one. */
  3580. String& operator+= (const char* textToAppend);
  3581. /** Appends another string at the end of this one. */
  3582. String& operator+= (const wchar_t* textToAppend);
  3583. /** Appends a decimal number at the end of this string. */
  3584. String& operator+= (int numberToAppend);
  3585. /** Appends a character at the end of this string. */
  3586. String& operator+= (char characterToAppend);
  3587. /** Appends a character at the end of this string. */
  3588. String& operator+= (wchar_t characterToAppend);
  3589. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  3590. /** Appends a character at the end of this string. */
  3591. String& operator+= (juce_wchar characterToAppend);
  3592. #endif
  3593. /** Appends a string to the end of this one.
  3594. @param textToAppend the string to add
  3595. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3596. */
  3597. void append (const String& textToAppend, size_t maxCharsToTake);
  3598. /** Appends a string to the end of this one.
  3599. @param textToAppend the string to add
  3600. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3601. */
  3602. template <class CharPointer>
  3603. void appendCharPointer (const CharPointer& textToAppend, size_t maxCharsToTake)
  3604. {
  3605. if (textToAppend.getAddress() != 0)
  3606. {
  3607. size_t extraBytesNeeded = 0;
  3608. size_t numChars = 0;
  3609. for (CharPointer t (textToAppend); numChars < maxCharsToTake && ! t.isEmpty();)
  3610. {
  3611. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3612. ++numChars;
  3613. }
  3614. if (numChars > 0)
  3615. {
  3616. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3617. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3618. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeWithCharLimit (textToAppend, (int) (numChars + 1));
  3619. }
  3620. }
  3621. }
  3622. /** Appends a string to the end of this one.
  3623. @param textToAppend the string to add
  3624. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3625. */
  3626. template <class CharPointer>
  3627. void appendCharPointer (const CharPointer& textToAppend)
  3628. {
  3629. if (textToAppend.getAddress() != 0)
  3630. {
  3631. size_t extraBytesNeeded = 0;
  3632. for (CharPointer t (textToAppend); ! t.isEmpty();)
  3633. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3634. if (extraBytesNeeded > 0)
  3635. {
  3636. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3637. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3638. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeAll (textToAppend);
  3639. }
  3640. }
  3641. }
  3642. // Comparison methods..
  3643. /** Returns true if the string contains no characters.
  3644. Note that there's also an isNotEmpty() method to help write readable code.
  3645. @see containsNonWhitespaceChars()
  3646. */
  3647. inline bool isEmpty() const throw() { return text[0] == 0; }
  3648. /** Returns true if the string contains at least one character.
  3649. Note that there's also an isEmpty() method to help write readable code.
  3650. @see containsNonWhitespaceChars()
  3651. */
  3652. inline bool isNotEmpty() const throw() { return text[0] != 0; }
  3653. /** Case-insensitive comparison with another string. */
  3654. bool equalsIgnoreCase (const String& other) const throw();
  3655. /** Case-insensitive comparison with another string. */
  3656. bool equalsIgnoreCase (const wchar_t* other) const throw();
  3657. /** Case-insensitive comparison with another string. */
  3658. bool equalsIgnoreCase (const char* other) const throw();
  3659. /** Case-sensitive comparison with another string.
  3660. @returns 0 if the two strings are identical; negative if this string comes before
  3661. the other one alphabetically, or positive if it comes after it.
  3662. */
  3663. int compare (const String& other) const throw();
  3664. /** Case-sensitive comparison with another string.
  3665. @returns 0 if the two strings are identical; negative if this string comes before
  3666. the other one alphabetically, or positive if it comes after it.
  3667. */
  3668. int compare (const char* other) const throw();
  3669. /** Case-sensitive comparison with another string.
  3670. @returns 0 if the two strings are identical; negative if this string comes before
  3671. the other one alphabetically, or positive if it comes after it.
  3672. */
  3673. int compare (const wchar_t* other) const throw();
  3674. /** Case-insensitive comparison with another string.
  3675. @returns 0 if the two strings are identical; negative if this string comes before
  3676. the other one alphabetically, or positive if it comes after it.
  3677. */
  3678. int compareIgnoreCase (const String& other) const throw();
  3679. /** Lexicographic comparison with another string.
  3680. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  3681. characters, making it good for sorting human-readable strings.
  3682. @returns 0 if the two strings are identical; negative if this string comes before
  3683. the other one alphabetically, or positive if it comes after it.
  3684. */
  3685. int compareLexicographically (const String& other) const throw();
  3686. /** Tests whether the string begins with another string.
  3687. If the parameter is an empty string, this will always return true.
  3688. Uses a case-sensitive comparison.
  3689. */
  3690. bool startsWith (const String& text) const throw();
  3691. /** Tests whether the string begins with a particular character.
  3692. If the character is 0, this will always return false.
  3693. Uses a case-sensitive comparison.
  3694. */
  3695. bool startsWithChar (juce_wchar character) const throw();
  3696. /** Tests whether the string begins with another string.
  3697. If the parameter is an empty string, this will always return true.
  3698. Uses a case-insensitive comparison.
  3699. */
  3700. bool startsWithIgnoreCase (const String& text) const throw();
  3701. /** Tests whether the string ends with another string.
  3702. If the parameter is an empty string, this will always return true.
  3703. Uses a case-sensitive comparison.
  3704. */
  3705. bool endsWith (const String& text) const throw();
  3706. /** Tests whether the string ends with a particular character.
  3707. If the character is 0, this will always return false.
  3708. Uses a case-sensitive comparison.
  3709. */
  3710. bool endsWithChar (juce_wchar character) const throw();
  3711. /** Tests whether the string ends with another string.
  3712. If the parameter is an empty string, this will always return true.
  3713. Uses a case-insensitive comparison.
  3714. */
  3715. bool endsWithIgnoreCase (const String& text) const throw();
  3716. /** Tests whether the string contains another substring.
  3717. If the parameter is an empty string, this will always return true.
  3718. Uses a case-sensitive comparison.
  3719. */
  3720. bool contains (const String& text) const throw();
  3721. /** Tests whether the string contains a particular character.
  3722. Uses a case-sensitive comparison.
  3723. */
  3724. bool containsChar (juce_wchar character) const throw();
  3725. /** Tests whether the string contains another substring.
  3726. Uses a case-insensitive comparison.
  3727. */
  3728. bool containsIgnoreCase (const String& text) const throw();
  3729. /** Tests whether the string contains another substring as a distict word.
  3730. @returns true if the string contains this word, surrounded by
  3731. non-alphanumeric characters
  3732. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3733. */
  3734. bool containsWholeWord (const String& wordToLookFor) const throw();
  3735. /** Tests whether the string contains another substring as a distict word.
  3736. @returns true if the string contains this word, surrounded by
  3737. non-alphanumeric characters
  3738. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3739. */
  3740. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  3741. /** Finds an instance of another substring if it exists as a distict word.
  3742. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3743. then this will return the index of the start of the substring. If it isn't
  3744. found, then it will return -1
  3745. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3746. */
  3747. int indexOfWholeWord (const String& wordToLookFor) const throw();
  3748. /** Finds an instance of another substring if it exists as a distict word.
  3749. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3750. then this will return the index of the start of the substring. If it isn't
  3751. found, then it will return -1
  3752. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3753. */
  3754. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  3755. /** Looks for any of a set of characters in the string.
  3756. Uses a case-sensitive comparison.
  3757. @returns true if the string contains any of the characters from
  3758. the string that is passed in.
  3759. */
  3760. bool containsAnyOf (const String& charactersItMightContain) const throw();
  3761. /** Looks for a set of characters in the string.
  3762. Uses a case-sensitive comparison.
  3763. @returns Returns false if any of the characters in this string do not occur in
  3764. the parameter string. If this string is empty, the return value will
  3765. always be true.
  3766. */
  3767. bool containsOnly (const String& charactersItMightContain) const throw();
  3768. /** Returns true if this string contains any non-whitespace characters.
  3769. This will return false if the string contains only whitespace characters, or
  3770. if it's empty.
  3771. It is equivalent to calling "myString.trim().isNotEmpty()".
  3772. */
  3773. bool containsNonWhitespaceChars() const throw();
  3774. /** Returns true if the string matches this simple wildcard expression.
  3775. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  3776. This isn't a full-blown regex though! The only wildcard characters supported
  3777. are "*" and "?". It's mainly intended for filename pattern matching.
  3778. */
  3779. bool matchesWildcard (const String& wildcard, bool ignoreCase) const throw();
  3780. // Substring location methods..
  3781. /** Searches for a character inside this string.
  3782. Uses a case-sensitive comparison.
  3783. @returns the index of the first occurrence of the character in this
  3784. string, or -1 if it's not found.
  3785. */
  3786. int indexOfChar (juce_wchar characterToLookFor) const throw();
  3787. /** Searches for a character inside this string.
  3788. Uses a case-sensitive comparison.
  3789. @param startIndex the index from which the search should proceed
  3790. @param characterToLookFor the character to look for
  3791. @returns the index of the first occurrence of the character in this
  3792. string, or -1 if it's not found.
  3793. */
  3794. int indexOfChar (int startIndex, juce_wchar characterToLookFor) const throw();
  3795. /** Returns the index of the first character that matches one of the characters
  3796. passed-in to this method.
  3797. This scans the string, beginning from the startIndex supplied, and if it finds
  3798. a character that appears in the string charactersToLookFor, it returns its index.
  3799. If none of these characters are found, it returns -1.
  3800. If ignoreCase is true, the comparison will be case-insensitive.
  3801. @see indexOfChar, lastIndexOfAnyOf
  3802. */
  3803. int indexOfAnyOf (const String& charactersToLookFor,
  3804. int startIndex = 0,
  3805. bool ignoreCase = false) const throw();
  3806. /** Searches for a substring within this string.
  3807. Uses a case-sensitive comparison.
  3808. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3809. If textToLookFor is an empty string, this will always return 0.
  3810. */
  3811. int indexOf (const String& textToLookFor) const throw();
  3812. /** Searches for a substring within this string.
  3813. Uses a case-sensitive comparison.
  3814. @param startIndex the index from which the search should proceed
  3815. @param textToLookFor the string to search for
  3816. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3817. If textToLookFor is an empty string, this will always return -1.
  3818. */
  3819. int indexOf (int startIndex, const String& textToLookFor) const throw();
  3820. /** Searches for a substring within this string.
  3821. Uses a case-insensitive comparison.
  3822. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3823. If textToLookFor is an empty string, this will always return 0.
  3824. */
  3825. int indexOfIgnoreCase (const String& textToLookFor) const throw();
  3826. /** Searches for a substring within this string.
  3827. Uses a case-insensitive comparison.
  3828. @param startIndex the index from which the search should proceed
  3829. @param textToLookFor the string to search for
  3830. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3831. If textToLookFor is an empty string, this will always return -1.
  3832. */
  3833. int indexOfIgnoreCase (int startIndex, const String& textToLookFor) const throw();
  3834. /** Searches for a character inside this string (working backwards from the end of the string).
  3835. Uses a case-sensitive comparison.
  3836. @returns the index of the last occurrence of the character in this string, or -1 if it's not found.
  3837. */
  3838. int lastIndexOfChar (juce_wchar character) const throw();
  3839. /** Searches for a substring inside this string (working backwards from the end of the string).
  3840. Uses a case-sensitive comparison.
  3841. @returns the index of the start of the last occurrence of the substring within this string,
  3842. or -1 if it's not found. If textToLookFor is an empty string, this will always return -1.
  3843. */
  3844. int lastIndexOf (const String& textToLookFor) const throw();
  3845. /** Searches for a substring inside this string (working backwards from the end of the string).
  3846. Uses a case-insensitive comparison.
  3847. @returns the index of the start of the last occurrence of the substring within this string, or -1
  3848. if it's not found. If textToLookFor is an empty string, this will always return -1.
  3849. */
  3850. int lastIndexOfIgnoreCase (const String& textToLookFor) const throw();
  3851. /** Returns the index of the last character in this string that matches one of the
  3852. characters passed-in to this method.
  3853. This scans the string backwards, starting from its end, and if it finds
  3854. a character that appears in the string charactersToLookFor, it returns its index.
  3855. If none of these characters are found, it returns -1.
  3856. If ignoreCase is true, the comparison will be case-insensitive.
  3857. @see lastIndexOf, indexOfAnyOf
  3858. */
  3859. int lastIndexOfAnyOf (const String& charactersToLookFor,
  3860. bool ignoreCase = false) const throw();
  3861. // Substring extraction and manipulation methods..
  3862. /** Returns the character at this index in the string.
  3863. In a release build, no checks are made to see if the index is within a valid range, so be
  3864. careful! In a debug build, the index is checked and an assertion fires if it's out-of-range.
  3865. Also beware that depending on the encoding format that the string is using internally, this
  3866. method may execute in either O(1) or O(n) time, so be careful when using it in your algorithms.
  3867. If you're scanning through a string to inspect its characters, you should never use this operator
  3868. for random access, it's far more efficient to call getCharPointer() to return a pointer, and
  3869. then to use that to iterate the string.
  3870. @see getCharPointer
  3871. */
  3872. const juce_wchar operator[] (int index) const throw();
  3873. /** Returns the final character of the string.
  3874. If the string is empty this will return 0.
  3875. */
  3876. juce_wchar getLastCharacter() const throw();
  3877. /** Returns a subsection of the string.
  3878. If the range specified is beyond the limits of the string, as much as
  3879. possible is returned.
  3880. @param startIndex the index of the start of the substring needed
  3881. @param endIndex all characters from startIndex up to (but not including)
  3882. this index are returned
  3883. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  3884. */
  3885. const String substring (int startIndex, int endIndex) const;
  3886. /** Returns a section of the string, starting from a given position.
  3887. @param startIndex the first character to include. If this is beyond the end
  3888. of the string, an empty string is returned. If it is zero or
  3889. less, the whole string is returned.
  3890. @returns the substring from startIndex up to the end of the string
  3891. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  3892. */
  3893. const String substring (int startIndex) const;
  3894. /** Returns a version of this string with a number of characters removed
  3895. from the end.
  3896. @param numberToDrop the number of characters to drop from the end of the
  3897. string. If this is greater than the length of the string,
  3898. an empty string will be returned. If zero or less, the
  3899. original string will be returned.
  3900. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  3901. */
  3902. const String dropLastCharacters (int numberToDrop) const;
  3903. /** Returns a number of characters from the end of the string.
  3904. This returns the last numCharacters characters from the end of the string. If the
  3905. string is shorter than numCharacters, the whole string is returned.
  3906. @see substring, dropLastCharacters, getLastCharacter
  3907. */
  3908. const String getLastCharacters (int numCharacters) const;
  3909. /** Returns a section of the string starting from a given substring.
  3910. This will search for the first occurrence of the given substring, and
  3911. return the section of the string starting from the point where this is
  3912. found (optionally not including the substring itself).
  3913. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  3914. fromFirstOccurrenceOf ("34", false) would return "56".
  3915. If the substring isn't found, the method will return an empty string.
  3916. If ignoreCase is true, the comparison will be case-insensitive.
  3917. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  3918. */
  3919. const String fromFirstOccurrenceOf (const String& substringToStartFrom,
  3920. bool includeSubStringInResult,
  3921. bool ignoreCase) const;
  3922. /** Returns a section of the string starting from the last occurrence of a given substring.
  3923. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  3924. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  3925. return the whole of the original string.
  3926. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  3927. */
  3928. const String fromLastOccurrenceOf (const String& substringToFind,
  3929. bool includeSubStringInResult,
  3930. bool ignoreCase) const;
  3931. /** Returns the start of this string, up to the first occurrence of a substring.
  3932. This will search for the first occurrence of a given substring, and then
  3933. return a copy of the string, up to the position of this substring,
  3934. optionally including or excluding the substring itself in the result.
  3935. e.g. for the string "123456", upTo ("34", false) would return "12", and
  3936. upTo ("34", true) would return "1234".
  3937. If the substring isn't found, this will return the whole of the original string.
  3938. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  3939. */
  3940. const String upToFirstOccurrenceOf (const String& substringToEndWith,
  3941. bool includeSubStringInResult,
  3942. bool ignoreCase) const;
  3943. /** Returns the start of this string, up to the last occurrence of a substring.
  3944. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  3945. If the substring isn't found, this will return the whole of the original string.
  3946. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  3947. */
  3948. const String upToLastOccurrenceOf (const String& substringToFind,
  3949. bool includeSubStringInResult,
  3950. bool ignoreCase) const;
  3951. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  3952. const String trim() const;
  3953. /** Returns a copy of this string with any whitespace characters removed from the start. */
  3954. const String trimStart() const;
  3955. /** Returns a copy of this string with any whitespace characters removed from the end. */
  3956. const String trimEnd() const;
  3957. /** Returns a copy of this string, having removed a specified set of characters from its start.
  3958. Characters are removed from the start of the string until it finds one that is not in the
  3959. specified set, and then it stops.
  3960. @param charactersToTrim the set of characters to remove.
  3961. @see trim, trimStart, trimCharactersAtEnd
  3962. */
  3963. const String trimCharactersAtStart (const String& charactersToTrim) const;
  3964. /** Returns a copy of this string, having removed a specified set of characters from its end.
  3965. Characters are removed from the end of the string until it finds one that is not in the
  3966. specified set, and then it stops.
  3967. @param charactersToTrim the set of characters to remove.
  3968. @see trim, trimEnd, trimCharactersAtStart
  3969. */
  3970. const String trimCharactersAtEnd (const String& charactersToTrim) const;
  3971. /** Returns an upper-case version of this string. */
  3972. const String toUpperCase() const;
  3973. /** Returns an lower-case version of this string. */
  3974. const String toLowerCase() const;
  3975. /** Replaces a sub-section of the string with another string.
  3976. This will return a copy of this string, with a set of characters
  3977. from startIndex to startIndex + numCharsToReplace removed, and with
  3978. a new string inserted in their place.
  3979. Note that this is a const method, and won't alter the string itself.
  3980. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  3981. it will be constrained to a valid range.
  3982. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  3983. characters will be taken out.
  3984. @param stringToInsert the new string to insert at startIndex after the characters have been
  3985. removed.
  3986. */
  3987. const String replaceSection (int startIndex,
  3988. int numCharactersToReplace,
  3989. const String& stringToInsert) const;
  3990. /** Replaces all occurrences of a substring with another string.
  3991. Returns a copy of this string, with any occurrences of stringToReplace
  3992. swapped for stringToInsertInstead.
  3993. Note that this is a const method, and won't alter the string itself.
  3994. */
  3995. const String replace (const String& stringToReplace,
  3996. const String& stringToInsertInstead,
  3997. bool ignoreCase = false) const;
  3998. /** Returns a string with all occurrences of a character replaced with a different one. */
  3999. const String replaceCharacter (juce_wchar characterToReplace,
  4000. juce_wchar characterToInsertInstead) const;
  4001. /** Replaces a set of characters with another set.
  4002. Returns a string in which each character from charactersToReplace has been replaced
  4003. by the character at the equivalent position in newCharacters (so the two strings
  4004. passed in must be the same length).
  4005. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  4006. Note that this is a const method, and won't affect the string itself.
  4007. */
  4008. const String replaceCharacters (const String& charactersToReplace,
  4009. const String& charactersToInsertInstead) const;
  4010. /** Returns a version of this string that only retains a fixed set of characters.
  4011. This will return a copy of this string, omitting any characters which are not
  4012. found in the string passed-in.
  4013. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  4014. Note that this is a const method, and won't alter the string itself.
  4015. */
  4016. const String retainCharacters (const String& charactersToRetain) const;
  4017. /** Returns a version of this string with a set of characters removed.
  4018. This will return a copy of this string, omitting any characters which are
  4019. found in the string passed-in.
  4020. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  4021. Note that this is a const method, and won't alter the string itself.
  4022. */
  4023. const String removeCharacters (const String& charactersToRemove) const;
  4024. /** Returns a section from the start of the string that only contains a certain set of characters.
  4025. This returns the leftmost section of the string, up to (and not including) the
  4026. first character that doesn't appear in the string passed in.
  4027. */
  4028. const String initialSectionContainingOnly (const String& permittedCharacters) const;
  4029. /** Returns a section from the start of the string that only contains a certain set of characters.
  4030. This returns the leftmost section of the string, up to (and not including) the
  4031. first character that occurs in the string passed in. (If none of the specified
  4032. characters are found in the string, the return value will just be the original string).
  4033. */
  4034. const String initialSectionNotContaining (const String& charactersToStopAt) const;
  4035. /** Checks whether the string might be in quotation marks.
  4036. @returns true if the string begins with a quote character (either a double or single quote).
  4037. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  4038. @see unquoted, quoted
  4039. */
  4040. bool isQuotedString() const;
  4041. /** Removes quotation marks from around the string, (if there are any).
  4042. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  4043. at the ends of the string are not affected. If there aren't any quotes, the original string
  4044. is returned.
  4045. Note that this is a const method, and won't alter the string itself.
  4046. @see isQuotedString, quoted
  4047. */
  4048. const String unquoted() const;
  4049. /** Adds quotation marks around a string.
  4050. This will return a copy of the string with a quote at the start and end, (but won't
  4051. add the quote if there's already one there, so it's safe to call this on strings that
  4052. may already have quotes around them).
  4053. Note that this is a const method, and won't alter the string itself.
  4054. @param quoteCharacter the character to add at the start and end
  4055. @see isQuotedString, unquoted
  4056. */
  4057. const String quoted (juce_wchar quoteCharacter = '"') const;
  4058. /** Creates a string which is a version of a string repeated and joined together.
  4059. @param stringToRepeat the string to repeat
  4060. @param numberOfTimesToRepeat how many times to repeat it
  4061. */
  4062. static const String repeatedString (const String& stringToRepeat,
  4063. int numberOfTimesToRepeat);
  4064. /** Returns a copy of this string with the specified character repeatedly added to its
  4065. beginning until the total length is at least the minimum length specified.
  4066. */
  4067. const String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  4068. /** Returns a copy of this string with the specified character repeatedly added to its
  4069. end until the total length is at least the minimum length specified.
  4070. */
  4071. const String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  4072. /** Creates a string from data in an unknown format.
  4073. This looks at some binary data and tries to guess whether it's Unicode
  4074. or 8-bit characters, then returns a string that represents it correctly.
  4075. Should be able to handle Unicode endianness correctly, by looking at
  4076. the first two bytes.
  4077. */
  4078. static const String createStringFromData (const void* data, int size);
  4079. /** Creates a String from a printf-style parameter list.
  4080. I don't like this method. I don't use it myself, and I recommend avoiding it and
  4081. using the operator<< methods or pretty much anything else instead. It's only provided
  4082. here because of the popular unrest that was stirred-up when I tried to remove it...
  4083. If you're really determined to use it, at least make sure that you never, ever,
  4084. pass any String objects to it as parameters. And bear in mind that internally, depending
  4085. on the platform, it may be using wchar_t or char character types, so that even string
  4086. literals can't be safely used as parameters if you're writing portable code.
  4087. */
  4088. static const String formatted (const String formatString, ... );
  4089. // Numeric conversions..
  4090. /** Creates a string containing this signed 32-bit integer as a decimal number.
  4091. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4092. */
  4093. explicit String (int decimalInteger);
  4094. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  4095. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4096. */
  4097. explicit String (unsigned int decimalInteger);
  4098. /** Creates a string containing this signed 16-bit integer as a decimal number.
  4099. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4100. */
  4101. explicit String (short decimalInteger);
  4102. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  4103. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4104. */
  4105. explicit String (unsigned short decimalInteger);
  4106. /** Creates a string containing this signed 64-bit integer as a decimal number.
  4107. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4108. */
  4109. explicit String (int64 largeIntegerValue);
  4110. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  4111. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4112. */
  4113. explicit String (uint64 largeIntegerValue);
  4114. /** Creates a string representing this floating-point number.
  4115. @param floatValue the value to convert to a string
  4116. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4117. decimal places, and will not use exponent notation. If 0 or
  4118. less, it will use exponent notation if necessary.
  4119. @see getDoubleValue, getIntValue
  4120. */
  4121. explicit String (float floatValue,
  4122. int numberOfDecimalPlaces = 0);
  4123. /** Creates a string representing this floating-point number.
  4124. @param doubleValue the value to convert to a string
  4125. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4126. decimal places, and will not use exponent notation. If 0 or
  4127. less, it will use exponent notation if necessary.
  4128. @see getFloatValue, getIntValue
  4129. */
  4130. explicit String (double doubleValue,
  4131. int numberOfDecimalPlaces = 0);
  4132. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  4133. @returns the value of the string as a 32 bit signed base-10 integer.
  4134. @see getTrailingIntValue, getHexValue32, getHexValue64
  4135. */
  4136. int getIntValue() const throw();
  4137. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  4138. @returns the value of the string as a 64 bit signed base-10 integer.
  4139. */
  4140. int64 getLargeIntValue() const throw();
  4141. /** Parses a decimal number from the end of the string.
  4142. This will look for a value at the end of the string.
  4143. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  4144. Negative numbers are not handled, so "xyz-5" returns 5.
  4145. @see getIntValue
  4146. */
  4147. int getTrailingIntValue() const throw();
  4148. /** Parses this string as a floating point number.
  4149. @returns the value of the string as a 32-bit floating point value.
  4150. @see getDoubleValue
  4151. */
  4152. float getFloatValue() const throw();
  4153. /** Parses this string as a floating point number.
  4154. @returns the value of the string as a 64-bit floating point value.
  4155. @see getFloatValue
  4156. */
  4157. double getDoubleValue() const throw();
  4158. /** Parses the string as a hexadecimal number.
  4159. Non-hexadecimal characters in the string are ignored.
  4160. If the string contains too many characters, then the lowest significant
  4161. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  4162. @returns a 32-bit number which is the value of the string in hex.
  4163. */
  4164. int getHexValue32() const throw();
  4165. /** Parses the string as a hexadecimal number.
  4166. Non-hexadecimal characters in the string are ignored.
  4167. If the string contains too many characters, then the lowest significant
  4168. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  4169. @returns a 64-bit number which is the value of the string in hex.
  4170. */
  4171. int64 getHexValue64() const throw();
  4172. /** Creates a string representing this 32-bit value in hexadecimal. */
  4173. static const String toHexString (int number);
  4174. /** Creates a string representing this 64-bit value in hexadecimal. */
  4175. static const String toHexString (int64 number);
  4176. /** Creates a string representing this 16-bit value in hexadecimal. */
  4177. static const String toHexString (short number);
  4178. /** Creates a string containing a hex dump of a block of binary data.
  4179. @param data the binary data to use as input
  4180. @param size how many bytes of data to use
  4181. @param groupSize how many bytes are grouped together before inserting a
  4182. space into the output. e.g. group size 0 has no spaces,
  4183. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  4184. like "bea1 c2ff".
  4185. */
  4186. static const String toHexString (const unsigned char* data,
  4187. int size,
  4188. int groupSize = 1);
  4189. /** Returns the character pointer currently being used to store this string.
  4190. Because it returns a reference to the string's internal data, the pointer
  4191. that is returned must not be stored anywhere, as it can be deleted whenever the
  4192. string changes.
  4193. */
  4194. inline const CharPointerType& getCharPointer() const throw() { return text; }
  4195. /** Returns a pointer to a UTF-8 version of this string.
  4196. Because it returns a reference to the string's internal data, the pointer
  4197. that is returned must not be stored anywhere, as it can be deleted whenever the
  4198. string changes.
  4199. To find out how many bytes you need to store this string as UTF-8, you can call
  4200. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4201. @see getCharPointer, toUTF16, toUTF32
  4202. */
  4203. const CharPointer_UTF8 toUTF8() const;
  4204. /** Returns a pointer to a UTF-32 version of this string.
  4205. Because it returns a reference to the string's internal data, the pointer
  4206. that is returned must not be stored anywhere, as it can be deleted whenever the
  4207. string changes.
  4208. To find out how many bytes you need to store this string as UTF-16, you can call
  4209. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4210. @see getCharPointer, toUTF8, toUTF32
  4211. */
  4212. CharPointer_UTF16 toUTF16() const;
  4213. /** Returns a pointer to a UTF-32 version of this string.
  4214. Because it returns a reference to the string's internal data, the pointer
  4215. that is returned must not be stored anywhere, as it can be deleted whenever the
  4216. string changes.
  4217. @see getCharPointer, toUTF8, toUTF16
  4218. */
  4219. CharPointer_UTF32 toUTF32() const;
  4220. /** Returns a pointer to a wchar_t version of this string.
  4221. Because it returns a reference to the string's internal data, the pointer
  4222. that is returned must not be stored anywhere, as it can be deleted whenever the
  4223. string changes.
  4224. Bear in mind that the wchar_t type is different on different platforms, so on
  4225. Windows, this will be equivalent to calling toUTF16(), on unix it'll be the same
  4226. as calling toUTF32(), etc.
  4227. @see getCharPointer, toUTF8, toUTF16, toUTF32
  4228. */
  4229. const wchar_t* toWideCharPointer() const;
  4230. /** Creates a String from a UTF-8 encoded buffer.
  4231. If the size is < 0, it'll keep reading until it hits a zero.
  4232. */
  4233. static const String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  4234. /** Returns the number of bytes required to represent this string as UTF8.
  4235. The number returned does NOT include the trailing zero.
  4236. @see toUTF8, copyToUTF8
  4237. */
  4238. int getNumBytesAsUTF8() const throw();
  4239. /** Copies the string to a buffer as UTF-8 characters.
  4240. Returns the number of bytes copied to the buffer, including the terminating null
  4241. character.
  4242. To find out how many bytes you need to store this string as UTF-8, you can call
  4243. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4244. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4245. returns the number of bytes required (including the terminating null character).
  4246. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4247. put in as many as it can while still allowing for a terminating null char at the
  4248. end, and will return the number of bytes that were actually used.
  4249. @see CharPointer_UTF8::writeWithDestByteLimit
  4250. */
  4251. int copyToUTF8 (CharPointer_UTF8::CharType* destBuffer, int maxBufferSizeBytes) const throw();
  4252. /** Copies the string to a buffer as UTF-16 characters.
  4253. Returns the number of bytes copied to the buffer, including the terminating null
  4254. character.
  4255. To find out how many bytes you need to store this string as UTF-16, you can call
  4256. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4257. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4258. returns the number of bytes required (including the terminating null character).
  4259. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4260. put in as many as it can while still allowing for a terminating null char at the
  4261. end, and will return the number of bytes that were actually used.
  4262. @see CharPointer_UTF16::writeWithDestByteLimit
  4263. */
  4264. int copyToUTF16 (CharPointer_UTF16::CharType* destBuffer, int maxBufferSizeBytes) const throw();
  4265. /** Copies the string to a buffer as UTF-16 characters.
  4266. Returns the number of bytes copied to the buffer, including the terminating null
  4267. character.
  4268. To find out how many bytes you need to store this string as UTF-32, you can call
  4269. CharPointer_UTF32::getBytesRequiredFor (myString.getCharPointer())
  4270. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4271. returns the number of bytes required (including the terminating null character).
  4272. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4273. put in as many as it can while still allowing for a terminating null char at the
  4274. end, and will return the number of bytes that were actually used.
  4275. @see CharPointer_UTF32::writeWithDestByteLimit
  4276. */
  4277. int copyToUTF32 (CharPointer_UTF32::CharType* destBuffer, int maxBufferSizeBytes) const throw();
  4278. /** Increases the string's internally allocated storage.
  4279. Although the string's contents won't be affected by this call, it will
  4280. increase the amount of memory allocated internally for the string to grow into.
  4281. If you're about to make a large number of calls to methods such
  4282. as += or <<, it's more efficient to preallocate enough extra space
  4283. beforehand, so that these methods won't have to keep resizing the string
  4284. to append the extra characters.
  4285. @param numBytesNeeded the number of bytes to allocate storage for. If this
  4286. value is less than the currently allocated size, it will
  4287. have no effect.
  4288. */
  4289. void preallocateBytes (size_t numBytesNeeded);
  4290. /** Swaps the contents of this string with another one.
  4291. This is a very fast operation, as no allocation or copying needs to be done.
  4292. */
  4293. void swapWith (String& other) throw();
  4294. /** A helper class to improve performance when concatenating many large strings
  4295. together.
  4296. Because appending one string to another involves measuring the length of
  4297. both strings, repeatedly doing this for many long strings will become
  4298. an exponentially slow operation. This class uses some internal state to
  4299. avoid that, so that each append operation only needs to measure the length
  4300. of the appended string.
  4301. */
  4302. class JUCE_API Concatenator
  4303. {
  4304. public:
  4305. Concatenator (String& stringToAppendTo);
  4306. ~Concatenator();
  4307. void append (const String& s);
  4308. private:
  4309. String& result;
  4310. int nextIndex;
  4311. JUCE_DECLARE_NON_COPYABLE (Concatenator);
  4312. };
  4313. private:
  4314. CharPointerType text;
  4315. struct PreallocationBytes
  4316. {
  4317. explicit PreallocationBytes (size_t);
  4318. size_t numBytes;
  4319. };
  4320. explicit String (const PreallocationBytes&); // This constructor preallocates a certain amount of memory
  4321. void appendFixedLength (const char* text, int numExtraChars);
  4322. size_t getByteOffsetOfEnd() const throw();
  4323. JUCE_DEPRECATED (String (const String& stringToCopy, size_t charsToAllocate));
  4324. // This private cast operator should prevent strings being accidentally cast
  4325. // to bools (this is possible because the compiler can add an implicit cast
  4326. // via a const char*)
  4327. operator bool() const throw() { return false; }
  4328. };
  4329. /** Concatenates two strings. */
  4330. JUCE_API const String JUCE_CALLTYPE operator+ (const char* string1, const String& string2);
  4331. /** Concatenates two strings. */
  4332. JUCE_API const String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2);
  4333. /** Concatenates two strings. */
  4334. JUCE_API const String JUCE_CALLTYPE operator+ (char string1, const String& string2);
  4335. /** Concatenates two strings. */
  4336. JUCE_API const String JUCE_CALLTYPE operator+ (wchar_t string1, const String& string2);
  4337. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4338. /** Concatenates two strings. */
  4339. JUCE_API const String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2);
  4340. #endif
  4341. /** Concatenates two strings. */
  4342. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2);
  4343. /** Concatenates two strings. */
  4344. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* string2);
  4345. /** Concatenates two strings. */
  4346. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2);
  4347. /** Concatenates two strings. */
  4348. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, char characterToAppend);
  4349. /** Concatenates two strings. */
  4350. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, wchar_t characterToAppend);
  4351. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4352. /** Concatenates two strings. */
  4353. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend);
  4354. #endif
  4355. /** Appends a character at the end of a string. */
  4356. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend);
  4357. /** Appends a character at the end of a string. */
  4358. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, wchar_t characterToAppend);
  4359. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4360. /** Appends a character at the end of a string. */
  4361. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend);
  4362. #endif
  4363. /** Appends a string to the end of the first one. */
  4364. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* string2);
  4365. /** Appends a string to the end of the first one. */
  4366. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const wchar_t* string2);
  4367. /** Appends a string to the end of the first one. */
  4368. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2);
  4369. /** Appends a decimal number at the end of a string. */
  4370. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, short number);
  4371. /** Appends a decimal number at the end of a string. */
  4372. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, int number);
  4373. /** Appends a decimal number at the end of a string. */
  4374. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, long number);
  4375. /** Appends a decimal number at the end of a string. */
  4376. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, float number);
  4377. /** Appends a decimal number at the end of a string. */
  4378. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, double number);
  4379. /** Case-sensitive comparison of two strings. */
  4380. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw();
  4381. /** Case-sensitive comparison of two strings. */
  4382. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw();
  4383. /** Case-sensitive comparison of two strings. */
  4384. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const wchar_t* string2) throw();
  4385. /** Case-sensitive comparison of two strings. */
  4386. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF8& string2) throw();
  4387. /** Case-sensitive comparison of two strings. */
  4388. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF16& string2) throw();
  4389. /** Case-sensitive comparison of two strings. */
  4390. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF32& string2) throw();
  4391. /** Case-sensitive comparison of two strings. */
  4392. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw();
  4393. /** Case-sensitive comparison of two strings. */
  4394. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw();
  4395. /** Case-sensitive comparison of two strings. */
  4396. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const wchar_t* string2) throw();
  4397. /** Case-sensitive comparison of two strings. */
  4398. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8& string2) throw();
  4399. /** Case-sensitive comparison of two strings. */
  4400. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16& string2) throw();
  4401. /** Case-sensitive comparison of two strings. */
  4402. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32& string2) throw();
  4403. /** Case-sensitive comparison of two strings. */
  4404. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw();
  4405. /** Case-sensitive comparison of two strings. */
  4406. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw();
  4407. /** Case-sensitive comparison of two strings. */
  4408. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw();
  4409. /** Case-sensitive comparison of two strings. */
  4410. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw();
  4411. /** This streaming override allows you to pass a juce String directly into std output streams.
  4412. This is very handy for writing strings to std::cout, std::cerr, etc.
  4413. */
  4414. template <class charT, class traits>
  4415. std::basic_ostream <charT, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <charT, traits>& stream, const String& stringToWrite)
  4416. {
  4417. return stream << stringToWrite.toUTF8().getAddress();
  4418. }
  4419. /** Writes a string to an OutputStream as UTF8. */
  4420. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text);
  4421. #endif // __JUCE_STRING_JUCEHEADER__
  4422. /*** End of inlined file: juce_String.h ***/
  4423. /**
  4424. Acts as an application-wide logging class.
  4425. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  4426. method and this will then be used by all calls to writeToLog.
  4427. The logger class also contains methods for writing messages to the debugger's
  4428. output stream.
  4429. @see FileLogger
  4430. */
  4431. class JUCE_API Logger
  4432. {
  4433. public:
  4434. /** Destructor. */
  4435. virtual ~Logger();
  4436. /** Sets the current logging class to use.
  4437. Note that the object passed in won't be deleted when no longer needed.
  4438. A null pointer can be passed-in to disable any logging.
  4439. If deleteOldLogger is set to true, the existing logger will be
  4440. deleted (if there is one).
  4441. */
  4442. static void JUCE_CALLTYPE setCurrentLogger (Logger* newLogger,
  4443. bool deleteOldLogger = false);
  4444. /** Writes a string to the current logger.
  4445. This will pass the string to the logger's logMessage() method if a logger
  4446. has been set.
  4447. @see logMessage
  4448. */
  4449. static void JUCE_CALLTYPE writeToLog (const String& message);
  4450. /** Writes a message to the standard error stream.
  4451. This can be called directly, or by using the DBG() macro in
  4452. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  4453. */
  4454. static void JUCE_CALLTYPE outputDebugString (const String& text);
  4455. protected:
  4456. Logger();
  4457. /** This is overloaded by subclasses to implement custom logging behaviour.
  4458. @see setCurrentLogger
  4459. */
  4460. virtual void logMessage (const String& message) = 0;
  4461. private:
  4462. static Logger* currentLogger;
  4463. };
  4464. #endif // __JUCE_LOGGER_JUCEHEADER__
  4465. /*** End of inlined file: juce_Logger.h ***/
  4466. /*** Start of inlined file: juce_LeakedObjectDetector.h ***/
  4467. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4468. #define __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4469. /**
  4470. Embedding an instance of this class inside another class can be used as a low-overhead
  4471. way of detecting leaked instances.
  4472. This class keeps an internal static count of the number of instances that are
  4473. active, so that when the app is shutdown and the static destructors are called,
  4474. it can check whether there are any left-over instances that may have been leaked.
  4475. To use it, use the JUCE_LEAK_DETECTOR macro as a simple way to put one in your
  4476. class declaration. Have a look through the juce codebase for examples, it's used
  4477. in most of the classes.
  4478. */
  4479. template <class OwnerClass>
  4480. class LeakedObjectDetector
  4481. {
  4482. public:
  4483. LeakedObjectDetector() throw() { ++(getCounter().numObjects); }
  4484. LeakedObjectDetector (const LeakedObjectDetector&) throw() { ++(getCounter().numObjects); }
  4485. ~LeakedObjectDetector()
  4486. {
  4487. if (--(getCounter().numObjects) < 0)
  4488. {
  4489. DBG ("*** Dangling pointer deletion! Class: " << getLeakedObjectClassName());
  4490. /** If you hit this, then you've managed to delete more instances of this class than you've
  4491. created.. That indicates that you're deleting some dangling pointers.
  4492. Note that although this assertion will have been triggered during a destructor, it might
  4493. not be this particular deletion that's at fault - the incorrect one may have happened
  4494. at an earlier point in the program, and simply not been detected until now.
  4495. Most errors like this are caused by using old-fashioned, non-RAII techniques for
  4496. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4497. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4498. */
  4499. jassertfalse;
  4500. }
  4501. }
  4502. private:
  4503. class LeakCounter
  4504. {
  4505. public:
  4506. LeakCounter() throw() {}
  4507. ~LeakCounter()
  4508. {
  4509. if (numObjects.value > 0)
  4510. {
  4511. DBG ("*** Leaked objects detected: " << numObjects.value << " instance(s) of class " << getLeakedObjectClassName());
  4512. /** If you hit this, then you've leaked one or more objects of the type specified by
  4513. the 'OwnerClass' template parameter - the name should have been printed by the line above.
  4514. If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for
  4515. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4516. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4517. */
  4518. jassertfalse;
  4519. }
  4520. }
  4521. Atomic<int> numObjects;
  4522. };
  4523. static const char* getLeakedObjectClassName()
  4524. {
  4525. return OwnerClass::getLeakedObjectClassName();
  4526. }
  4527. static LeakCounter& getCounter() throw()
  4528. {
  4529. static LeakCounter counter;
  4530. return counter;
  4531. }
  4532. };
  4533. #if DOXYGEN || ! defined (JUCE_LEAK_DETECTOR)
  4534. #if (DOXYGEN || JUCE_CHECK_MEMORY_LEAKS)
  4535. /** This macro lets you embed a leak-detecting object inside a class.
  4536. To use it, simply declare a JUCE_LEAK_DETECTOR(YourClassName) inside a private section
  4537. of the class declaration. E.g.
  4538. @code
  4539. class MyClass
  4540. {
  4541. public:
  4542. MyClass();
  4543. void blahBlah();
  4544. private:
  4545. JUCE_LEAK_DETECTOR (MyClass);
  4546. };@endcode
  4547. @see JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR, LeakedObjectDetector
  4548. */
  4549. #define JUCE_LEAK_DETECTOR(OwnerClass) \
  4550. friend class JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass>; \
  4551. static const char* getLeakedObjectClassName() throw() { return #OwnerClass; } \
  4552. JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass> JUCE_JOIN_MACRO (leakDetector, __LINE__);
  4553. #else
  4554. #define JUCE_LEAK_DETECTOR(OwnerClass)
  4555. #endif
  4556. #endif
  4557. #endif // __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4558. /*** End of inlined file: juce_LeakedObjectDetector.h ***/
  4559. END_JUCE_NAMESPACE
  4560. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  4561. /*** End of inlined file: juce_StandardHeader.h ***/
  4562. BEGIN_JUCE_NAMESPACE
  4563. #if JUCE_MSVC
  4564. // this is set explicitly in case the app is using a different packing size.
  4565. #pragma pack (push, 8)
  4566. #pragma warning (push)
  4567. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  4568. #ifdef __INTEL_COMPILER
  4569. #pragma warning (disable: 1125)
  4570. #endif
  4571. #endif
  4572. // this is where all the class header files get brought in..
  4573. /*** Start of inlined file: juce_core_includes.h ***/
  4574. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4575. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4576. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4577. /*** Start of inlined file: juce_AbstractFifo.h ***/
  4578. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4579. #define __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4580. /**
  4581. Encapsulates the logic required to implement a lock-free FIFO.
  4582. This class handles the logic needed when building a single-reader, single-writer FIFO.
  4583. It doesn't actually hold any data itself, but your FIFO class can use one of these to manage
  4584. its position and status when reading or writing to it.
  4585. To use it, you can call prepareToWrite() to determine the position within your own buffer that
  4586. an incoming block of data should be stored, and prepareToRead() to find out when the next
  4587. outgoing block should be read from.
  4588. e.g.
  4589. @code
  4590. class MyFifo
  4591. {
  4592. public:
  4593. MyFifo() : abstractFifo (1024)
  4594. {
  4595. }
  4596. void addToFifo (const int* someData, int numItems)
  4597. {
  4598. int start1, size1, start2, size2;
  4599. prepareToWrite (numItems, start1, size1, start2, size2);
  4600. if (size1 > 0)
  4601. copySomeData (myBuffer + start1, someData, size1);
  4602. if (size2 > 0)
  4603. copySomeData (myBuffer + start2, someData + size1, size2);
  4604. finishedWrite (size1 + size2);
  4605. }
  4606. void readFromFifo (int* someData, int numItems)
  4607. {
  4608. int start1, size1, start2, size2;
  4609. prepareToRead (numSamples, start1, size1, start2, size2);
  4610. if (size1 > 0)
  4611. copySomeData (someData, myBuffer + start1, size1);
  4612. if (size2 > 0)
  4613. copySomeData (someData + size1, myBuffer + start2, size2);
  4614. finishedRead (size1 + size2);
  4615. }
  4616. private:
  4617. AbstractFifo abstractFifo;
  4618. int myBuffer [1024];
  4619. };
  4620. @endcode
  4621. */
  4622. class JUCE_API AbstractFifo
  4623. {
  4624. public:
  4625. /** Creates a FIFO to manage a buffer with the specified capacity. */
  4626. AbstractFifo (int capacity) throw();
  4627. /** Destructor */
  4628. ~AbstractFifo();
  4629. /** Returns the total size of the buffer being managed. */
  4630. int getTotalSize() const throw();
  4631. /** Returns the number of items that can currently be added to the buffer without it overflowing. */
  4632. int getFreeSpace() const throw();
  4633. /** Returns the number of items that can currently be read from the buffer. */
  4634. int getNumReady() const throw();
  4635. /** Clears the buffer positions, so that it appears empty. */
  4636. void reset() throw();
  4637. /** Changes the buffer's total size.
  4638. Note that this isn't thread-safe, so don't call it if there's any danger that it
  4639. might overlap with a call to any other method in this class!
  4640. */
  4641. void setTotalSize (int newSize) throw();
  4642. /** Returns the location within the buffer at which an incoming block of data should be written.
  4643. Because the section of data that you want to add to the buffer may overlap the end
  4644. and wrap around to the start, two blocks within your buffer are returned, and you
  4645. should copy your data into the first one, with any remaining data spilling over into
  4646. the second.
  4647. If the number of items you ask for is too large to fit within the buffer's free space, then
  4648. blockSize1 + blockSize2 may add up to a lower value than numToWrite. If this happens, you
  4649. may decide to keep waiting and re-trying the method until there's enough space available.
  4650. After calling this method, if you choose to write your data into the blocks returned, you
  4651. must call finishedWrite() to tell the FIFO how much data you actually added.
  4652. e.g.
  4653. @code
  4654. void addToFifo (const int* someData, int numItems)
  4655. {
  4656. int start1, size1, start2, size2;
  4657. prepareToWrite (numItems, start1, size1, start2, size2);
  4658. if (size1 > 0)
  4659. copySomeData (myBuffer + start1, someData, size1);
  4660. if (size2 > 0)
  4661. copySomeData (myBuffer + start2, someData + size1, size2);
  4662. finishedWrite (size1 + size2);
  4663. }
  4664. @endcode
  4665. @param numToWrite indicates how many items you'd like to add to the buffer
  4666. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4667. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4668. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4669. the first block should be written
  4670. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4671. @see finishedWrite
  4672. */
  4673. void prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw();
  4674. /** Called after reading from the FIFO, to indicate that this many items have been added.
  4675. @see prepareToWrite
  4676. */
  4677. void finishedWrite (int numWritten) throw();
  4678. /** Returns the location within the buffer from which the next block of data should be read.
  4679. Because the section of data that you want to read from the buffer may overlap the end
  4680. and wrap around to the start, two blocks within your buffer are returned, and you
  4681. should read from both of them.
  4682. If the number of items you ask for is greater than the amount of data available, then
  4683. blockSize1 + blockSize2 may add up to a lower value than numWanted. If this happens, you
  4684. may decide to keep waiting and re-trying the method until there's enough data available.
  4685. After calling this method, if you choose to read the data, you must call finishedRead() to
  4686. tell the FIFO how much data you have consumed.
  4687. e.g.
  4688. @code
  4689. void readFromFifo (int* someData, int numItems)
  4690. {
  4691. int start1, size1, start2, size2;
  4692. prepareToRead (numSamples, start1, size1, start2, size2);
  4693. if (size1 > 0)
  4694. copySomeData (someData, myBuffer + start1, size1);
  4695. if (size2 > 0)
  4696. copySomeData (someData + size1, myBuffer + start2, size2);
  4697. finishedRead (size1 + size2);
  4698. }
  4699. @endcode
  4700. @param numWanted indicates how many items you'd like to add to the buffer
  4701. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4702. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4703. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4704. the first block should be written
  4705. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4706. @see finishedRead
  4707. */
  4708. void prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw();
  4709. /** Called after reading from the FIFO, to indicate that this many items have now been consumed.
  4710. @see prepareToRead
  4711. */
  4712. void finishedRead (int numRead) throw();
  4713. private:
  4714. int bufferSize;
  4715. Atomic <int> validStart, validEnd;
  4716. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AbstractFifo);
  4717. };
  4718. #endif // __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4719. /*** End of inlined file: juce_AbstractFifo.h ***/
  4720. #endif
  4721. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4722. /*** Start of inlined file: juce_Array.h ***/
  4723. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4724. #define __JUCE_ARRAY_JUCEHEADER__
  4725. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  4726. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4727. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4728. /*** Start of inlined file: juce_HeapBlock.h ***/
  4729. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  4730. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  4731. /**
  4732. Very simple container class to hold a pointer to some data on the heap.
  4733. When you need to allocate some heap storage for something, always try to use
  4734. this class instead of allocating the memory directly using malloc/free.
  4735. A HeapBlock<char> object can be treated in pretty much exactly the same way
  4736. as an char*, but as long as you allocate it on the stack or as a class member,
  4737. it's almost impossible for it to leak memory.
  4738. It also makes your code much more concise and readable than doing the same thing
  4739. using direct allocations,
  4740. E.g. instead of this:
  4741. @code
  4742. int* temp = (int*) malloc (1024 * sizeof (int));
  4743. memcpy (temp, xyz, 1024 * sizeof (int));
  4744. free (temp);
  4745. temp = (int*) calloc (2048 * sizeof (int));
  4746. temp[0] = 1234;
  4747. memcpy (foobar, temp, 2048 * sizeof (int));
  4748. free (temp);
  4749. @endcode
  4750. ..you could just write this:
  4751. @code
  4752. HeapBlock <int> temp (1024);
  4753. memcpy (temp, xyz, 1024 * sizeof (int));
  4754. temp.calloc (2048);
  4755. temp[0] = 1234;
  4756. memcpy (foobar, temp, 2048 * sizeof (int));
  4757. @endcode
  4758. The class is extremely lightweight, containing only a pointer to the
  4759. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  4760. as their less object-oriented counterparts. Despite adding safety, you probably
  4761. won't sacrifice any performance by using this in place of normal pointers.
  4762. @see Array, OwnedArray, MemoryBlock
  4763. */
  4764. template <class ElementType>
  4765. class HeapBlock
  4766. {
  4767. public:
  4768. /** Creates a HeapBlock which is initially just a null pointer.
  4769. After creation, you can resize the array using the malloc(), calloc(),
  4770. or realloc() methods.
  4771. */
  4772. HeapBlock() throw() : data (0)
  4773. {
  4774. }
  4775. /** Creates a HeapBlock containing a number of elements.
  4776. The contents of the block are undefined, as it will have been created by a
  4777. malloc call.
  4778. If you want an array of zero values, you can use the calloc() method instead.
  4779. */
  4780. explicit HeapBlock (const size_t numElements)
  4781. : data (static_cast <ElementType*> (::malloc (numElements * sizeof (ElementType))))
  4782. {
  4783. }
  4784. /** Destructor.
  4785. This will free the data, if any has been allocated.
  4786. */
  4787. ~HeapBlock()
  4788. {
  4789. ::free (data);
  4790. }
  4791. /** Returns a raw pointer to the allocated data.
  4792. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4793. freed by calling the free() method.
  4794. */
  4795. inline operator ElementType*() const throw() { return data; }
  4796. /** Returns a raw pointer to the allocated data.
  4797. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4798. freed by calling the free() method.
  4799. */
  4800. inline ElementType* getData() const throw() { return data; }
  4801. /** Returns a void pointer to the allocated data.
  4802. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4803. freed by calling the free() method.
  4804. */
  4805. inline operator void*() const throw() { return static_cast <void*> (data); }
  4806. /** Returns a void pointer to the allocated data.
  4807. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4808. freed by calling the free() method.
  4809. */
  4810. inline operator const void*() const throw() { return static_cast <const void*> (data); }
  4811. /** Lets you use indirect calls to the first element in the array.
  4812. Obviously this will cause problems if the array hasn't been initialised, because it'll
  4813. be referencing a null pointer.
  4814. */
  4815. inline ElementType* operator->() const throw() { return data; }
  4816. /** Returns a reference to one of the data elements.
  4817. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  4818. has no idea of the size it currently has allocated.
  4819. */
  4820. template <typename IndexType>
  4821. inline ElementType& operator[] (IndexType index) const throw() { return data [index]; }
  4822. /** Returns a pointer to a data element at an offset from the start of the array.
  4823. This is the same as doing pointer arithmetic on the raw pointer itself.
  4824. */
  4825. template <typename IndexType>
  4826. inline ElementType* operator+ (IndexType index) const throw() { return data + index; }
  4827. /** Compares the pointer with another pointer.
  4828. This can be handy for checking whether this is a null pointer.
  4829. */
  4830. inline bool operator== (const ElementType* const otherPointer) const throw() { return otherPointer == data; }
  4831. /** Compares the pointer with another pointer.
  4832. This can be handy for checking whether this is a null pointer.
  4833. */
  4834. inline bool operator!= (const ElementType* const otherPointer) const throw() { return otherPointer != data; }
  4835. /** Allocates a specified amount of memory.
  4836. This uses the normal malloc to allocate an amount of memory for this object.
  4837. Any previously allocated memory will be freed by this method.
  4838. The number of bytes allocated will be (newNumElements * elementSize). Normally
  4839. you wouldn't need to specify the second parameter, but it can be handy if you need
  4840. to allocate a size in bytes rather than in terms of the number of elements.
  4841. The data that is allocated will be freed when this object is deleted, or when you
  4842. call free() or any of the allocation methods.
  4843. */
  4844. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4845. {
  4846. ::free (data);
  4847. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4848. }
  4849. /** Allocates a specified amount of memory and clears it.
  4850. This does the same job as the malloc() method, but clears the memory that it allocates.
  4851. */
  4852. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4853. {
  4854. ::free (data);
  4855. data = static_cast <ElementType*> (::calloc (newNumElements, elementSize));
  4856. }
  4857. /** Allocates a specified amount of memory and optionally clears it.
  4858. This does the same job as either malloc() or calloc(), depending on the
  4859. initialiseToZero parameter.
  4860. */
  4861. void allocate (const size_t newNumElements, const bool initialiseToZero)
  4862. {
  4863. ::free (data);
  4864. if (initialiseToZero)
  4865. data = static_cast <ElementType*> (::calloc (newNumElements, sizeof (ElementType)));
  4866. else
  4867. data = static_cast <ElementType*> (::malloc (newNumElements * sizeof (ElementType)));
  4868. }
  4869. /** Re-allocates a specified amount of memory.
  4870. The semantics of this method are the same as malloc() and calloc(), but it
  4871. uses realloc() to keep as much of the existing data as possible.
  4872. */
  4873. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4874. {
  4875. if (data == 0)
  4876. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4877. else
  4878. data = static_cast <ElementType*> (::realloc (data, newNumElements * elementSize));
  4879. }
  4880. /** Frees any currently-allocated data.
  4881. This will free the data and reset this object to be a null pointer.
  4882. */
  4883. void free()
  4884. {
  4885. ::free (data);
  4886. data = 0;
  4887. }
  4888. /** Swaps this object's data with the data of another HeapBlock.
  4889. The two objects simply exchange their data pointers.
  4890. */
  4891. void swapWith (HeapBlock <ElementType>& other) throw()
  4892. {
  4893. swapVariables (data, other.data);
  4894. }
  4895. /** This fills the block with zeros, up to the number of elements specified.
  4896. Since the block has no way of knowing its own size, you must make sure that the number of
  4897. elements you specify doesn't exceed the allocated size.
  4898. */
  4899. void clear (size_t numElements) throw()
  4900. {
  4901. zeromem (data, sizeof (ElementType) * numElements);
  4902. }
  4903. private:
  4904. ElementType* data;
  4905. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HeapBlock);
  4906. };
  4907. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  4908. /*** End of inlined file: juce_HeapBlock.h ***/
  4909. /**
  4910. Implements some basic array storage allocation functions.
  4911. This class isn't really for public use - it's used by the other
  4912. array classes, but might come in handy for some purposes.
  4913. It inherits from a critical section class to allow the arrays to use
  4914. the "empty base class optimisation" pattern to reduce their footprint.
  4915. @see Array, OwnedArray, ReferenceCountedArray
  4916. */
  4917. template <class ElementType, class TypeOfCriticalSectionToUse>
  4918. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  4919. {
  4920. public:
  4921. /** Creates an empty array. */
  4922. ArrayAllocationBase() throw()
  4923. : numAllocated (0)
  4924. {
  4925. }
  4926. /** Destructor. */
  4927. ~ArrayAllocationBase()
  4928. {
  4929. }
  4930. /** Changes the amount of storage allocated.
  4931. This will retain any data currently held in the array, and either add or
  4932. remove extra space at the end.
  4933. @param numElements the number of elements that are needed
  4934. */
  4935. void setAllocatedSize (const int numElements)
  4936. {
  4937. if (numAllocated != numElements)
  4938. {
  4939. if (numElements > 0)
  4940. elements.realloc (numElements);
  4941. else
  4942. elements.free();
  4943. numAllocated = numElements;
  4944. }
  4945. }
  4946. /** Increases the amount of storage allocated if it is less than a given amount.
  4947. This will retain any data currently held in the array, but will add
  4948. extra space at the end to make sure there it's at least as big as the size
  4949. passed in. If it's already bigger, no action is taken.
  4950. @param minNumElements the minimum number of elements that are needed
  4951. */
  4952. void ensureAllocatedSize (const int minNumElements)
  4953. {
  4954. if (minNumElements > numAllocated)
  4955. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  4956. }
  4957. /** Minimises the amount of storage allocated so that it's no more than
  4958. the given number of elements.
  4959. */
  4960. void shrinkToNoMoreThan (const int maxNumElements)
  4961. {
  4962. if (maxNumElements < numAllocated)
  4963. setAllocatedSize (maxNumElements);
  4964. }
  4965. /** Swap the contents of two objects. */
  4966. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  4967. {
  4968. elements.swapWith (other.elements);
  4969. swapVariables (numAllocated, other.numAllocated);
  4970. }
  4971. HeapBlock <ElementType> elements;
  4972. int numAllocated;
  4973. private:
  4974. JUCE_DECLARE_NON_COPYABLE (ArrayAllocationBase);
  4975. };
  4976. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4977. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  4978. /*** Start of inlined file: juce_ElementComparator.h ***/
  4979. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4980. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4981. /**
  4982. Sorts a range of elements in an array.
  4983. The comparator object that is passed-in must define a public method with the following
  4984. signature:
  4985. @code
  4986. int compareElements (ElementType first, ElementType second);
  4987. @endcode
  4988. ..and this method must return:
  4989. - a value of < 0 if the first comes before the second
  4990. - a value of 0 if the two objects are equivalent
  4991. - a value of > 0 if the second comes before the first
  4992. To improve performance, the compareElements() method can be declared as static or const.
  4993. @param comparator an object which defines a compareElements() method
  4994. @param array the array to sort
  4995. @param firstElement the index of the first element of the range to be sorted
  4996. @param lastElement the index of the last element in the range that needs
  4997. sorting (this is inclusive)
  4998. @param retainOrderOfEquivalentItems if true, the order of items that the
  4999. comparator deems the same will be maintained - this will be
  5000. a slower algorithm than if they are allowed to be moved around.
  5001. @see sortArrayRetainingOrder
  5002. */
  5003. template <class ElementType, class ElementComparator>
  5004. static void sortArray (ElementComparator& comparator,
  5005. ElementType* const array,
  5006. int firstElement,
  5007. int lastElement,
  5008. const bool retainOrderOfEquivalentItems)
  5009. {
  5010. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5011. // avoids getting warning messages about the parameter being unused
  5012. if (lastElement > firstElement)
  5013. {
  5014. if (retainOrderOfEquivalentItems)
  5015. {
  5016. for (int i = firstElement; i < lastElement; ++i)
  5017. {
  5018. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  5019. {
  5020. swapVariables (array[i], array[i + 1]);
  5021. if (i > firstElement)
  5022. i -= 2;
  5023. }
  5024. }
  5025. }
  5026. else
  5027. {
  5028. int fromStack[30], toStack[30];
  5029. int stackIndex = 0;
  5030. for (;;)
  5031. {
  5032. const int size = (lastElement - firstElement) + 1;
  5033. if (size <= 8)
  5034. {
  5035. int j = lastElement;
  5036. int maxIndex;
  5037. while (j > firstElement)
  5038. {
  5039. maxIndex = firstElement;
  5040. for (int k = firstElement + 1; k <= j; ++k)
  5041. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  5042. maxIndex = k;
  5043. swapVariables (array[j], array[maxIndex]);
  5044. --j;
  5045. }
  5046. }
  5047. else
  5048. {
  5049. const int mid = firstElement + (size >> 1);
  5050. swapVariables (array[mid], array[firstElement]);
  5051. int i = firstElement;
  5052. int j = lastElement + 1;
  5053. for (;;)
  5054. {
  5055. while (++i <= lastElement
  5056. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  5057. {}
  5058. while (--j > firstElement
  5059. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  5060. {}
  5061. if (j < i)
  5062. break;
  5063. swapVariables (array[i], array[j]);
  5064. }
  5065. swapVariables (array[j], array[firstElement]);
  5066. if (j - 1 - firstElement >= lastElement - i)
  5067. {
  5068. if (firstElement + 1 < j)
  5069. {
  5070. fromStack [stackIndex] = firstElement;
  5071. toStack [stackIndex] = j - 1;
  5072. ++stackIndex;
  5073. }
  5074. if (i < lastElement)
  5075. {
  5076. firstElement = i;
  5077. continue;
  5078. }
  5079. }
  5080. else
  5081. {
  5082. if (i < lastElement)
  5083. {
  5084. fromStack [stackIndex] = i;
  5085. toStack [stackIndex] = lastElement;
  5086. ++stackIndex;
  5087. }
  5088. if (firstElement + 1 < j)
  5089. {
  5090. lastElement = j - 1;
  5091. continue;
  5092. }
  5093. }
  5094. }
  5095. if (--stackIndex < 0)
  5096. break;
  5097. jassert (stackIndex < numElementsInArray (fromStack));
  5098. firstElement = fromStack [stackIndex];
  5099. lastElement = toStack [stackIndex];
  5100. }
  5101. }
  5102. }
  5103. }
  5104. /**
  5105. Searches a sorted array of elements, looking for the index at which a specified value
  5106. should be inserted for it to be in the correct order.
  5107. The comparator object that is passed-in must define a public method with the following
  5108. signature:
  5109. @code
  5110. int compareElements (ElementType first, ElementType second);
  5111. @endcode
  5112. ..and this method must return:
  5113. - a value of < 0 if the first comes before the second
  5114. - a value of 0 if the two objects are equivalent
  5115. - a value of > 0 if the second comes before the first
  5116. To improve performance, the compareElements() method can be declared as static or const.
  5117. @param comparator an object which defines a compareElements() method
  5118. @param array the array to search
  5119. @param newElement the value that is going to be inserted
  5120. @param firstElement the index of the first element to search
  5121. @param lastElement the index of the last element in the range (this is non-inclusive)
  5122. */
  5123. template <class ElementType, class ElementComparator>
  5124. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  5125. ElementType* const array,
  5126. const ElementType newElement,
  5127. int firstElement,
  5128. int lastElement)
  5129. {
  5130. jassert (firstElement <= lastElement);
  5131. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5132. // avoids getting warning messages about the parameter being unused
  5133. while (firstElement < lastElement)
  5134. {
  5135. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  5136. {
  5137. ++firstElement;
  5138. break;
  5139. }
  5140. else
  5141. {
  5142. const int halfway = (firstElement + lastElement) >> 1;
  5143. if (halfway == firstElement)
  5144. {
  5145. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5146. ++firstElement;
  5147. break;
  5148. }
  5149. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5150. {
  5151. firstElement = halfway;
  5152. }
  5153. else
  5154. {
  5155. lastElement = halfway;
  5156. }
  5157. }
  5158. }
  5159. return firstElement;
  5160. }
  5161. /**
  5162. A simple ElementComparator class that can be used to sort an array of
  5163. objects that support the '<' operator.
  5164. This will work for primitive types and objects that implement operator<().
  5165. Example: @code
  5166. Array <int> myArray;
  5167. DefaultElementComparator<int> sorter;
  5168. myArray.sort (sorter);
  5169. @endcode
  5170. @see ElementComparator
  5171. */
  5172. template <class ElementType>
  5173. class DefaultElementComparator
  5174. {
  5175. private:
  5176. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5177. public:
  5178. static int compareElements (ParameterType first, ParameterType second)
  5179. {
  5180. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  5181. }
  5182. };
  5183. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5184. /*** End of inlined file: juce_ElementComparator.h ***/
  5185. /*** Start of inlined file: juce_CriticalSection.h ***/
  5186. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  5187. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  5188. #ifndef DOXYGEN
  5189. class ScopedLock;
  5190. class ScopedUnlock;
  5191. #endif
  5192. /**
  5193. Prevents multiple threads from accessing shared objects at the same time.
  5194. @see ScopedLock, Thread, InterProcessLock
  5195. */
  5196. class JUCE_API CriticalSection
  5197. {
  5198. public:
  5199. /**
  5200. Creates a CriticalSection object
  5201. */
  5202. CriticalSection() throw();
  5203. /** Destroys a CriticalSection object.
  5204. If the critical section is deleted whilst locked, its subsequent behaviour
  5205. is unpredictable.
  5206. */
  5207. ~CriticalSection() throw();
  5208. /** Locks this critical section.
  5209. If the lock is currently held by another thread, this will wait until it
  5210. becomes free.
  5211. If the lock is already held by the caller thread, the method returns immediately.
  5212. @see exit, ScopedLock
  5213. */
  5214. void enter() const throw();
  5215. /** Attempts to lock this critical section without blocking.
  5216. This method behaves identically to CriticalSection::enter, except that the caller thread
  5217. does not wait if the lock is currently held by another thread but returns false immediately.
  5218. @returns false if the lock is currently held by another thread, true otherwise.
  5219. @see enter
  5220. */
  5221. bool tryEnter() const throw();
  5222. /** Releases the lock.
  5223. If the caller thread hasn't got the lock, this can have unpredictable results.
  5224. If the enter() method has been called multiple times by the thread, each
  5225. call must be matched by a call to exit() before other threads will be allowed
  5226. to take over the lock.
  5227. @see enter, ScopedLock
  5228. */
  5229. void exit() const throw();
  5230. /** Provides the type of scoped lock to use with this type of critical section object. */
  5231. typedef ScopedLock ScopedLockType;
  5232. /** Provides the type of scoped unlocker to use with this type of critical section object. */
  5233. typedef ScopedUnlock ScopedUnlockType;
  5234. private:
  5235. #if JUCE_WINDOWS
  5236. #if JUCE_64BIT
  5237. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  5238. // block of memory here that's big enough to be used internally as a windows critical
  5239. // section object.
  5240. uint8 internal [44];
  5241. #else
  5242. uint8 internal [24];
  5243. #endif
  5244. #else
  5245. mutable pthread_mutex_t internal;
  5246. #endif
  5247. JUCE_DECLARE_NON_COPYABLE (CriticalSection);
  5248. };
  5249. /**
  5250. A class that can be used in place of a real CriticalSection object.
  5251. This is currently used by some templated classes, and should get
  5252. optimised out by the compiler.
  5253. @see Array, OwnedArray, ReferenceCountedArray
  5254. */
  5255. class JUCE_API DummyCriticalSection
  5256. {
  5257. public:
  5258. inline DummyCriticalSection() throw() {}
  5259. inline ~DummyCriticalSection() throw() {}
  5260. inline void enter() const throw() {}
  5261. inline void exit() const throw() {}
  5262. /** A dummy scoped-lock type to use with a dummy critical section. */
  5263. struct ScopedLockType
  5264. {
  5265. ScopedLockType (const DummyCriticalSection&) throw() {}
  5266. };
  5267. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  5268. typedef ScopedLockType ScopedUnlockType;
  5269. private:
  5270. JUCE_DECLARE_NON_COPYABLE (DummyCriticalSection);
  5271. };
  5272. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  5273. /*** End of inlined file: juce_CriticalSection.h ***/
  5274. /**
  5275. Holds a resizable array of primitive or copy-by-value objects.
  5276. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  5277. The Array class can be used to hold simple, non-polymorphic objects as well as primitive types - to
  5278. do so, the class must fulfil these requirements:
  5279. - it must have a copy constructor and assignment operator
  5280. - it must be able to be relocated in memory by a memcpy without this causing any problems - so
  5281. objects whose functionality relies on external pointers or references to themselves can be used.
  5282. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  5283. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  5284. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  5285. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  5286. specialised class StringArray, which provides more useful functions.
  5287. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  5288. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  5289. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  5290. */
  5291. template <typename ElementType,
  5292. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  5293. class Array
  5294. {
  5295. private:
  5296. #if JUCE_VC8_OR_EARLIER
  5297. typedef const ElementType& ParameterType;
  5298. #else
  5299. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5300. #endif
  5301. public:
  5302. /** Creates an empty array. */
  5303. Array() throw()
  5304. : numUsed (0)
  5305. {
  5306. }
  5307. /** Creates a copy of another array.
  5308. @param other the array to copy
  5309. */
  5310. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  5311. {
  5312. const ScopedLockType lock (other.getLock());
  5313. numUsed = other.numUsed;
  5314. data.setAllocatedSize (other.numUsed);
  5315. for (int i = 0; i < numUsed; ++i)
  5316. new (data.elements + i) ElementType (other.data.elements[i]);
  5317. }
  5318. /** Initalises from a null-terminated C array of values.
  5319. @param values the array to copy from
  5320. */
  5321. template <typename TypeToCreateFrom>
  5322. explicit Array (const TypeToCreateFrom* values)
  5323. : numUsed (0)
  5324. {
  5325. while (*values != TypeToCreateFrom())
  5326. add (*values++);
  5327. }
  5328. /** Initalises from a C array of values.
  5329. @param values the array to copy from
  5330. @param numValues the number of values in the array
  5331. */
  5332. template <typename TypeToCreateFrom>
  5333. Array (const TypeToCreateFrom* values, int numValues)
  5334. : numUsed (numValues)
  5335. {
  5336. data.setAllocatedSize (numValues);
  5337. for (int i = 0; i < numValues; ++i)
  5338. new (data.elements + i) ElementType (values[i]);
  5339. }
  5340. /** Destructor. */
  5341. ~Array()
  5342. {
  5343. for (int i = 0; i < numUsed; ++i)
  5344. data.elements[i].~ElementType();
  5345. }
  5346. /** Copies another array.
  5347. @param other the array to copy
  5348. */
  5349. Array& operator= (const Array& other)
  5350. {
  5351. if (this != &other)
  5352. {
  5353. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  5354. swapWithArray (otherCopy);
  5355. }
  5356. return *this;
  5357. }
  5358. /** Compares this array to another one.
  5359. Two arrays are considered equal if they both contain the same set of
  5360. elements, in the same order.
  5361. @param other the other array to compare with
  5362. */
  5363. template <class OtherArrayType>
  5364. bool operator== (const OtherArrayType& other) const
  5365. {
  5366. const ScopedLockType lock (getLock());
  5367. if (numUsed != other.numUsed)
  5368. return false;
  5369. for (int i = numUsed; --i >= 0;)
  5370. if (! (data.elements [i] == other.data.elements [i]))
  5371. return false;
  5372. return true;
  5373. }
  5374. /** Compares this array to another one.
  5375. Two arrays are considered equal if they both contain the same set of
  5376. elements, in the same order.
  5377. @param other the other array to compare with
  5378. */
  5379. template <class OtherArrayType>
  5380. bool operator!= (const OtherArrayType& other) const
  5381. {
  5382. return ! operator== (other);
  5383. }
  5384. /** Removes all elements from the array.
  5385. This will remove all the elements, and free any storage that the array is
  5386. using. To clear the array without freeing the storage, use the clearQuick()
  5387. method instead.
  5388. @see clearQuick
  5389. */
  5390. void clear()
  5391. {
  5392. const ScopedLockType lock (getLock());
  5393. for (int i = 0; i < numUsed; ++i)
  5394. data.elements[i].~ElementType();
  5395. data.setAllocatedSize (0);
  5396. numUsed = 0;
  5397. }
  5398. /** Removes all elements from the array without freeing the array's allocated storage.
  5399. @see clear
  5400. */
  5401. void clearQuick()
  5402. {
  5403. const ScopedLockType lock (getLock());
  5404. for (int i = 0; i < numUsed; ++i)
  5405. data.elements[i].~ElementType();
  5406. numUsed = 0;
  5407. }
  5408. /** Returns the current number of elements in the array.
  5409. */
  5410. inline int size() const throw()
  5411. {
  5412. return numUsed;
  5413. }
  5414. /** Returns one of the elements in the array.
  5415. If the index passed in is beyond the range of valid elements, this
  5416. will return zero.
  5417. If you're certain that the index will always be a valid element, you
  5418. can call getUnchecked() instead, which is faster.
  5419. @param index the index of the element being requested (0 is the first element in the array)
  5420. @see getUnchecked, getFirst, getLast
  5421. */
  5422. inline ElementType operator[] (const int index) const
  5423. {
  5424. const ScopedLockType lock (getLock());
  5425. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  5426. : ElementType();
  5427. }
  5428. /** Returns one of the elements in the array, without checking the index passed in.
  5429. Unlike the operator[] method, this will try to return an element without
  5430. checking that the index is within the bounds of the array, so should only
  5431. be used when you're confident that it will always be a valid index.
  5432. @param index the index of the element being requested (0 is the first element in the array)
  5433. @see operator[], getFirst, getLast
  5434. */
  5435. inline const ElementType getUnchecked (const int index) const
  5436. {
  5437. const ScopedLockType lock (getLock());
  5438. jassert (isPositiveAndBelow (index, numUsed));
  5439. return data.elements [index];
  5440. }
  5441. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  5442. This is like getUnchecked, but returns a direct reference to the element, so that
  5443. you can alter it directly. Obviously this can be dangerous, so only use it when
  5444. absolutely necessary.
  5445. @param index the index of the element being requested (0 is the first element in the array)
  5446. @see operator[], getFirst, getLast
  5447. */
  5448. inline ElementType& getReference (const int index) const throw()
  5449. {
  5450. const ScopedLockType lock (getLock());
  5451. jassert (isPositiveAndBelow (index, numUsed));
  5452. return data.elements [index];
  5453. }
  5454. /** Returns the first element in the array, or 0 if the array is empty.
  5455. @see operator[], getUnchecked, getLast
  5456. */
  5457. inline ElementType getFirst() const
  5458. {
  5459. const ScopedLockType lock (getLock());
  5460. return (numUsed > 0) ? data.elements [0]
  5461. : ElementType();
  5462. }
  5463. /** Returns the last element in the array, or 0 if the array is empty.
  5464. @see operator[], getUnchecked, getFirst
  5465. */
  5466. inline ElementType getLast() const
  5467. {
  5468. const ScopedLockType lock (getLock());
  5469. return (numUsed > 0) ? data.elements [numUsed - 1]
  5470. : ElementType();
  5471. }
  5472. /** Returns a pointer to the actual array data.
  5473. This pointer will only be valid until the next time a non-const method
  5474. is called on the array.
  5475. */
  5476. inline ElementType* getRawDataPointer() throw()
  5477. {
  5478. return data.elements;
  5479. }
  5480. /** Finds the index of the first element which matches the value passed in.
  5481. This will search the array for the given object, and return the index
  5482. of its first occurrence. If the object isn't found, the method will return -1.
  5483. @param elementToLookFor the value or object to look for
  5484. @returns the index of the object, or -1 if it's not found
  5485. */
  5486. int indexOf (ParameterType elementToLookFor) const
  5487. {
  5488. const ScopedLockType lock (getLock());
  5489. const ElementType* e = data.elements.getData();
  5490. const ElementType* const end = e + numUsed;
  5491. for (; e != end; ++e)
  5492. if (elementToLookFor == *e)
  5493. return static_cast <int> (e - data.elements.getData());
  5494. return -1;
  5495. }
  5496. /** Returns true if the array contains at least one occurrence of an object.
  5497. @param elementToLookFor the value or object to look for
  5498. @returns true if the item is found
  5499. */
  5500. bool contains (ParameterType elementToLookFor) const
  5501. {
  5502. const ScopedLockType lock (getLock());
  5503. const ElementType* e = data.elements.getData();
  5504. const ElementType* const end = e + numUsed;
  5505. for (; e != end; ++e)
  5506. if (elementToLookFor == *e)
  5507. return true;
  5508. return false;
  5509. }
  5510. /** Appends a new element at the end of the array.
  5511. @param newElement the new object to add to the array
  5512. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  5513. */
  5514. void add (ParameterType newElement)
  5515. {
  5516. const ScopedLockType lock (getLock());
  5517. data.ensureAllocatedSize (numUsed + 1);
  5518. new (data.elements + numUsed++) ElementType (newElement);
  5519. }
  5520. /** Inserts a new element into the array at a given position.
  5521. If the index is less than 0 or greater than the size of the array, the
  5522. element will be added to the end of the array.
  5523. Otherwise, it will be inserted into the array, moving all the later elements
  5524. along to make room.
  5525. @param indexToInsertAt the index at which the new element should be
  5526. inserted (pass in -1 to add it to the end)
  5527. @param newElement the new object to add to the array
  5528. @see add, addSorted, addUsingDefaultSort, set
  5529. */
  5530. void insert (int indexToInsertAt, ParameterType newElement)
  5531. {
  5532. const ScopedLockType lock (getLock());
  5533. data.ensureAllocatedSize (numUsed + 1);
  5534. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5535. {
  5536. ElementType* const insertPos = data.elements + indexToInsertAt;
  5537. const int numberToMove = numUsed - indexToInsertAt;
  5538. if (numberToMove > 0)
  5539. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  5540. new (insertPos) ElementType (newElement);
  5541. ++numUsed;
  5542. }
  5543. else
  5544. {
  5545. new (data.elements + numUsed++) ElementType (newElement);
  5546. }
  5547. }
  5548. /** Inserts multiple copies of an element into the array at a given position.
  5549. If the index is less than 0 or greater than the size of the array, the
  5550. element will be added to the end of the array.
  5551. Otherwise, it will be inserted into the array, moving all the later elements
  5552. along to make room.
  5553. @param indexToInsertAt the index at which the new element should be inserted
  5554. @param newElement the new object to add to the array
  5555. @param numberOfTimesToInsertIt how many copies of the value to insert
  5556. @see insert, add, addSorted, set
  5557. */
  5558. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  5559. int numberOfTimesToInsertIt)
  5560. {
  5561. if (numberOfTimesToInsertIt > 0)
  5562. {
  5563. const ScopedLockType lock (getLock());
  5564. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  5565. ElementType* insertPos;
  5566. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5567. {
  5568. insertPos = data.elements + indexToInsertAt;
  5569. const int numberToMove = numUsed - indexToInsertAt;
  5570. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  5571. }
  5572. else
  5573. {
  5574. insertPos = data.elements + numUsed;
  5575. }
  5576. numUsed += numberOfTimesToInsertIt;
  5577. while (--numberOfTimesToInsertIt >= 0)
  5578. new (insertPos++) ElementType (newElement);
  5579. }
  5580. }
  5581. /** Inserts an array of values into this array at a given position.
  5582. If the index is less than 0 or greater than the size of the array, the
  5583. new elements will be added to the end of the array.
  5584. Otherwise, they will be inserted into the array, moving all the later elements
  5585. along to make room.
  5586. @param indexToInsertAt the index at which the first new element should be inserted
  5587. @param newElements the new values to add to the array
  5588. @param numberOfElements how many items are in the array
  5589. @see insert, add, addSorted, set
  5590. */
  5591. void insertArray (int indexToInsertAt,
  5592. const ElementType* newElements,
  5593. int numberOfElements)
  5594. {
  5595. if (numberOfElements > 0)
  5596. {
  5597. const ScopedLockType lock (getLock());
  5598. data.ensureAllocatedSize (numUsed + numberOfElements);
  5599. ElementType* insertPos;
  5600. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5601. {
  5602. insertPos = data.elements + indexToInsertAt;
  5603. const int numberToMove = numUsed - indexToInsertAt;
  5604. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  5605. }
  5606. else
  5607. {
  5608. insertPos = data.elements + numUsed;
  5609. }
  5610. numUsed += numberOfElements;
  5611. while (--numberOfElements >= 0)
  5612. new (insertPos++) ElementType (*newElements++);
  5613. }
  5614. }
  5615. /** Appends a new element at the end of the array as long as the array doesn't
  5616. already contain it.
  5617. If the array already contains an element that matches the one passed in, nothing
  5618. will be done.
  5619. @param newElement the new object to add to the array
  5620. */
  5621. void addIfNotAlreadyThere (ParameterType newElement)
  5622. {
  5623. const ScopedLockType lock (getLock());
  5624. if (! contains (newElement))
  5625. add (newElement);
  5626. }
  5627. /** Replaces an element with a new value.
  5628. If the index is less than zero, this method does nothing.
  5629. If the index is beyond the end of the array, the item is added to the end of the array.
  5630. @param indexToChange the index whose value you want to change
  5631. @param newValue the new value to set for this index.
  5632. @see add, insert
  5633. */
  5634. void set (const int indexToChange, ParameterType newValue)
  5635. {
  5636. jassert (indexToChange >= 0);
  5637. const ScopedLockType lock (getLock());
  5638. if (isPositiveAndBelow (indexToChange, numUsed))
  5639. {
  5640. data.elements [indexToChange] = newValue;
  5641. }
  5642. else if (indexToChange >= 0)
  5643. {
  5644. data.ensureAllocatedSize (numUsed + 1);
  5645. new (data.elements + numUsed++) ElementType (newValue);
  5646. }
  5647. }
  5648. /** Replaces an element with a new value without doing any bounds-checking.
  5649. This just sets a value directly in the array's internal storage, so you'd
  5650. better make sure it's in range!
  5651. @param indexToChange the index whose value you want to change
  5652. @param newValue the new value to set for this index.
  5653. @see set, getUnchecked
  5654. */
  5655. void setUnchecked (const int indexToChange, ParameterType newValue)
  5656. {
  5657. const ScopedLockType lock (getLock());
  5658. jassert (isPositiveAndBelow (indexToChange, numUsed));
  5659. data.elements [indexToChange] = newValue;
  5660. }
  5661. /** Adds elements from an array to the end of this array.
  5662. @param elementsToAdd the array of elements to add
  5663. @param numElementsToAdd how many elements are in this other array
  5664. @see add
  5665. */
  5666. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  5667. {
  5668. const ScopedLockType lock (getLock());
  5669. if (numElementsToAdd > 0)
  5670. {
  5671. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5672. while (--numElementsToAdd >= 0)
  5673. {
  5674. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  5675. ++numUsed;
  5676. }
  5677. }
  5678. }
  5679. /** This swaps the contents of this array with those of another array.
  5680. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5681. because it just swaps their internal pointers.
  5682. */
  5683. void swapWithArray (Array& otherArray) throw()
  5684. {
  5685. const ScopedLockType lock1 (getLock());
  5686. const ScopedLockType lock2 (otherArray.getLock());
  5687. data.swapWith (otherArray.data);
  5688. swapVariables (numUsed, otherArray.numUsed);
  5689. }
  5690. /** Adds elements from another array to the end of this array.
  5691. @param arrayToAddFrom the array from which to copy the elements
  5692. @param startIndex the first element of the other array to start copying from
  5693. @param numElementsToAdd how many elements to add from the other array. If this
  5694. value is negative or greater than the number of available elements,
  5695. all available elements will be copied.
  5696. @see add
  5697. */
  5698. template <class OtherArrayType>
  5699. void addArray (const OtherArrayType& arrayToAddFrom,
  5700. int startIndex = 0,
  5701. int numElementsToAdd = -1)
  5702. {
  5703. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5704. {
  5705. const ScopedLockType lock2 (getLock());
  5706. if (startIndex < 0)
  5707. {
  5708. jassertfalse;
  5709. startIndex = 0;
  5710. }
  5711. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5712. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5713. while (--numElementsToAdd >= 0)
  5714. add (arrayToAddFrom.getUnchecked (startIndex++));
  5715. }
  5716. }
  5717. /** Inserts a new element into the array, assuming that the array is sorted.
  5718. This will use a comparator to find the position at which the new element
  5719. should go. If the array isn't sorted, the behaviour of this
  5720. method will be unpredictable.
  5721. @param comparator the comparator to use to compare the elements - see the sort()
  5722. method for details about the form this object should take
  5723. @param newElement the new element to insert to the array
  5724. @see addUsingDefaultSort, add, sort
  5725. */
  5726. template <class ElementComparator>
  5727. void addSorted (ElementComparator& comparator, ParameterType newElement)
  5728. {
  5729. const ScopedLockType lock (getLock());
  5730. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed), newElement);
  5731. }
  5732. /** Inserts a new element into the array, assuming that the array is sorted.
  5733. This will use the DefaultElementComparator class for sorting, so your ElementType
  5734. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  5735. method will be unpredictable.
  5736. @param newElement the new element to insert to the array
  5737. @see addSorted, sort
  5738. */
  5739. void addUsingDefaultSort (ParameterType newElement)
  5740. {
  5741. DefaultElementComparator <ElementType> comparator;
  5742. addSorted (comparator, newElement);
  5743. }
  5744. /** Finds the index of an element in the array, assuming that the array is sorted.
  5745. This will use a comparator to do a binary-chop to find the index of the given
  5746. element, if it exists. If the array isn't sorted, the behaviour of this
  5747. method will be unpredictable.
  5748. @param comparator the comparator to use to compare the elements - see the sort()
  5749. method for details about the form this object should take
  5750. @param elementToLookFor the element to search for
  5751. @returns the index of the element, or -1 if it's not found
  5752. @see addSorted, sort
  5753. */
  5754. template <class ElementComparator>
  5755. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  5756. {
  5757. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5758. // avoids getting warning messages about the parameter being unused
  5759. const ScopedLockType lock (getLock());
  5760. int start = 0;
  5761. int end = numUsed;
  5762. for (;;)
  5763. {
  5764. if (start >= end)
  5765. {
  5766. return -1;
  5767. }
  5768. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  5769. {
  5770. return start;
  5771. }
  5772. else
  5773. {
  5774. const int halfway = (start + end) >> 1;
  5775. if (halfway == start)
  5776. return -1;
  5777. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  5778. start = halfway;
  5779. else
  5780. end = halfway;
  5781. }
  5782. }
  5783. }
  5784. /** Removes an element from the array.
  5785. This will remove the element at a given index, and move back
  5786. all the subsequent elements to close the gap.
  5787. If the index passed in is out-of-range, nothing will happen.
  5788. @param indexToRemove the index of the element to remove
  5789. @returns the element that has been removed
  5790. @see removeValue, removeRange
  5791. */
  5792. ElementType remove (const int indexToRemove)
  5793. {
  5794. const ScopedLockType lock (getLock());
  5795. if (isPositiveAndBelow (indexToRemove, numUsed))
  5796. {
  5797. --numUsed;
  5798. ElementType* const e = data.elements + indexToRemove;
  5799. ElementType removed (*e);
  5800. e->~ElementType();
  5801. const int numberToShift = numUsed - indexToRemove;
  5802. if (numberToShift > 0)
  5803. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  5804. if ((numUsed << 1) < data.numAllocated)
  5805. minimiseStorageOverheads();
  5806. return removed;
  5807. }
  5808. else
  5809. {
  5810. return ElementType();
  5811. }
  5812. }
  5813. /** Removes an item from the array.
  5814. This will remove the first occurrence of the given element from the array.
  5815. If the item isn't found, no action is taken.
  5816. @param valueToRemove the object to try to remove
  5817. @see remove, removeRange
  5818. */
  5819. void removeValue (ParameterType valueToRemove)
  5820. {
  5821. const ScopedLockType lock (getLock());
  5822. ElementType* const e = data.elements;
  5823. for (int i = 0; i < numUsed; ++i)
  5824. {
  5825. if (valueToRemove == e[i])
  5826. {
  5827. remove (i);
  5828. break;
  5829. }
  5830. }
  5831. }
  5832. /** Removes a range of elements from the array.
  5833. This will remove a set of elements, starting from the given index,
  5834. and move subsequent elements down to close the gap.
  5835. If the range extends beyond the bounds of the array, it will
  5836. be safely clipped to the size of the array.
  5837. @param startIndex the index of the first element to remove
  5838. @param numberToRemove how many elements should be removed
  5839. @see remove, removeValue
  5840. */
  5841. void removeRange (int startIndex, int numberToRemove)
  5842. {
  5843. const ScopedLockType lock (getLock());
  5844. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  5845. startIndex = jlimit (0, numUsed, startIndex);
  5846. if (endIndex > startIndex)
  5847. {
  5848. ElementType* const e = data.elements + startIndex;
  5849. numberToRemove = endIndex - startIndex;
  5850. for (int i = 0; i < numberToRemove; ++i)
  5851. e[i].~ElementType();
  5852. const int numToShift = numUsed - endIndex;
  5853. if (numToShift > 0)
  5854. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  5855. numUsed -= numberToRemove;
  5856. if ((numUsed << 1) < data.numAllocated)
  5857. minimiseStorageOverheads();
  5858. }
  5859. }
  5860. /** Removes the last n elements from the array.
  5861. @param howManyToRemove how many elements to remove from the end of the array
  5862. @see remove, removeValue, removeRange
  5863. */
  5864. void removeLast (int howManyToRemove = 1)
  5865. {
  5866. const ScopedLockType lock (getLock());
  5867. if (howManyToRemove > numUsed)
  5868. howManyToRemove = numUsed;
  5869. for (int i = 1; i <= howManyToRemove; ++i)
  5870. data.elements [numUsed - i].~ElementType();
  5871. numUsed -= howManyToRemove;
  5872. if ((numUsed << 1) < data.numAllocated)
  5873. minimiseStorageOverheads();
  5874. }
  5875. /** Removes any elements which are also in another array.
  5876. @param otherArray the other array in which to look for elements to remove
  5877. @see removeValuesNotIn, remove, removeValue, removeRange
  5878. */
  5879. template <class OtherArrayType>
  5880. void removeValuesIn (const OtherArrayType& otherArray)
  5881. {
  5882. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  5883. const ScopedLockType lock2 (getLock());
  5884. if (this == &otherArray)
  5885. {
  5886. clear();
  5887. }
  5888. else
  5889. {
  5890. if (otherArray.size() > 0)
  5891. {
  5892. for (int i = numUsed; --i >= 0;)
  5893. if (otherArray.contains (data.elements [i]))
  5894. remove (i);
  5895. }
  5896. }
  5897. }
  5898. /** Removes any elements which are not found in another array.
  5899. Only elements which occur in this other array will be retained.
  5900. @param otherArray the array in which to look for elements NOT to remove
  5901. @see removeValuesIn, remove, removeValue, removeRange
  5902. */
  5903. template <class OtherArrayType>
  5904. void removeValuesNotIn (const OtherArrayType& otherArray)
  5905. {
  5906. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  5907. const ScopedLockType lock2 (getLock());
  5908. if (this != &otherArray)
  5909. {
  5910. if (otherArray.size() <= 0)
  5911. {
  5912. clear();
  5913. }
  5914. else
  5915. {
  5916. for (int i = numUsed; --i >= 0;)
  5917. if (! otherArray.contains (data.elements [i]))
  5918. remove (i);
  5919. }
  5920. }
  5921. }
  5922. /** Swaps over two elements in the array.
  5923. This swaps over the elements found at the two indexes passed in.
  5924. If either index is out-of-range, this method will do nothing.
  5925. @param index1 index of one of the elements to swap
  5926. @param index2 index of the other element to swap
  5927. */
  5928. void swap (const int index1,
  5929. const int index2)
  5930. {
  5931. const ScopedLockType lock (getLock());
  5932. if (isPositiveAndBelow (index1, numUsed)
  5933. && isPositiveAndBelow (index2, numUsed))
  5934. {
  5935. swapVariables (data.elements [index1],
  5936. data.elements [index2]);
  5937. }
  5938. }
  5939. /** Moves one of the values to a different position.
  5940. This will move the value to a specified index, shuffling along
  5941. any intervening elements as required.
  5942. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5943. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5944. @param currentIndex the index of the value to be moved. If this isn't a
  5945. valid index, then nothing will be done
  5946. @param newIndex the index at which you'd like this value to end up. If this
  5947. is less than zero, the value will be moved to the end
  5948. of the array
  5949. */
  5950. void move (const int currentIndex, int newIndex) throw()
  5951. {
  5952. if (currentIndex != newIndex)
  5953. {
  5954. const ScopedLockType lock (getLock());
  5955. if (isPositiveAndBelow (currentIndex, numUsed))
  5956. {
  5957. if (! isPositiveAndBelow (newIndex, numUsed))
  5958. newIndex = numUsed - 1;
  5959. char tempCopy [sizeof (ElementType)];
  5960. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  5961. if (newIndex > currentIndex)
  5962. {
  5963. memmove (data.elements + currentIndex,
  5964. data.elements + currentIndex + 1,
  5965. (newIndex - currentIndex) * sizeof (ElementType));
  5966. }
  5967. else
  5968. {
  5969. memmove (data.elements + newIndex + 1,
  5970. data.elements + newIndex,
  5971. (currentIndex - newIndex) * sizeof (ElementType));
  5972. }
  5973. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  5974. }
  5975. }
  5976. }
  5977. /** Reduces the amount of storage being used by the array.
  5978. Arrays typically allocate slightly more storage than they need, and after
  5979. removing elements, they may have quite a lot of unused space allocated.
  5980. This method will reduce the amount of allocated storage to a minimum.
  5981. */
  5982. void minimiseStorageOverheads()
  5983. {
  5984. const ScopedLockType lock (getLock());
  5985. data.shrinkToNoMoreThan (numUsed);
  5986. }
  5987. /** Increases the array's internal storage to hold a minimum number of elements.
  5988. Calling this before adding a large known number of elements means that
  5989. the array won't have to keep dynamically resizing itself as the elements
  5990. are added, and it'll therefore be more efficient.
  5991. */
  5992. void ensureStorageAllocated (const int minNumElements)
  5993. {
  5994. const ScopedLockType lock (getLock());
  5995. data.ensureAllocatedSize (minNumElements);
  5996. }
  5997. /** Sorts the elements in the array.
  5998. This will use a comparator object to sort the elements into order. The object
  5999. passed must have a method of the form:
  6000. @code
  6001. int compareElements (ElementType first, ElementType second);
  6002. @endcode
  6003. ..and this method must return:
  6004. - a value of < 0 if the first comes before the second
  6005. - a value of 0 if the two objects are equivalent
  6006. - a value of > 0 if the second comes before the first
  6007. To improve performance, the compareElements() method can be declared as static or const.
  6008. @param comparator the comparator to use for comparing elements.
  6009. @param retainOrderOfEquivalentItems if this is true, then items
  6010. which the comparator says are equivalent will be
  6011. kept in the order in which they currently appear
  6012. in the array. This is slower to perform, but may
  6013. be important in some cases. If it's false, a faster
  6014. algorithm is used, but equivalent elements may be
  6015. rearranged.
  6016. @see addSorted, indexOfSorted, sortArray
  6017. */
  6018. template <class ElementComparator>
  6019. void sort (ElementComparator& comparator,
  6020. const bool retainOrderOfEquivalentItems = false) const
  6021. {
  6022. const ScopedLockType lock (getLock());
  6023. (void) comparator; // if you pass in an object with a static compareElements() method, this
  6024. // avoids getting warning messages about the parameter being unused
  6025. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  6026. }
  6027. /** Returns the CriticalSection that locks this array.
  6028. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  6029. an object of ScopedLockType as an RAII lock for it.
  6030. */
  6031. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  6032. /** Returns the type of scoped lock to use for locking this array */
  6033. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  6034. private:
  6035. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  6036. int numUsed;
  6037. };
  6038. #endif // __JUCE_ARRAY_JUCEHEADER__
  6039. /*** End of inlined file: juce_Array.h ***/
  6040. #endif
  6041. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  6042. #endif
  6043. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6044. /*** Start of inlined file: juce_DynamicObject.h ***/
  6045. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6046. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6047. /*** Start of inlined file: juce_NamedValueSet.h ***/
  6048. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  6049. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  6050. /*** Start of inlined file: juce_Variant.h ***/
  6051. #ifndef __JUCE_VARIANT_JUCEHEADER__
  6052. #define __JUCE_VARIANT_JUCEHEADER__
  6053. /*** Start of inlined file: juce_Identifier.h ***/
  6054. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  6055. #define __JUCE_IDENTIFIER_JUCEHEADER__
  6056. /*** Start of inlined file: juce_StringPool.h ***/
  6057. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  6058. #define __JUCE_STRINGPOOL_JUCEHEADER__
  6059. /**
  6060. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  6061. comparison speed when dealing with many duplicate strings.
  6062. When you add a string to a pool using getPooledString, it'll return a character
  6063. array containing the same string. This array is owned by the pool, and the same array
  6064. is returned every time a matching string is asked for. This means that it's trivial to
  6065. compare two pooled strings for equality, as you can simply compare their pointers. It
  6066. also cuts down on storage if you're using many copies of the same string.
  6067. */
  6068. class JUCE_API StringPool
  6069. {
  6070. public:
  6071. /** Creates an empty pool. */
  6072. StringPool() throw();
  6073. /** Destructor */
  6074. ~StringPool();
  6075. /** Returns a pointer to a copy of the string that is passed in.
  6076. The pool will always return the same pointer when asked for a string that matches it.
  6077. The pool will own all the pointers that it returns, deleting them when the pool itself
  6078. is deleted.
  6079. */
  6080. const String::CharPointerType getPooledString (const String& original);
  6081. /** Returns a pointer to a copy of the string that is passed in.
  6082. The pool will always return the same pointer when asked for a string that matches it.
  6083. The pool will own all the pointers that it returns, deleting them when the pool itself
  6084. is deleted.
  6085. */
  6086. const String::CharPointerType getPooledString (const char* original);
  6087. /** Returns a pointer to a copy of the string that is passed in.
  6088. The pool will always return the same pointer when asked for a string that matches it.
  6089. The pool will own all the pointers that it returns, deleting them when the pool itself
  6090. is deleted.
  6091. */
  6092. const String::CharPointerType getPooledString (const wchar_t* original);
  6093. /** Returns the number of strings in the pool. */
  6094. int size() const throw();
  6095. /** Returns one of the strings in the pool, by index. */
  6096. const String::CharPointerType operator[] (int index) const throw();
  6097. private:
  6098. Array <String> strings;
  6099. };
  6100. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  6101. /*** End of inlined file: juce_StringPool.h ***/
  6102. /**
  6103. Represents a string identifier, designed for accessing properties by name.
  6104. Identifier objects are very light and fast to copy, but slower to initialise
  6105. from a string, so it's much faster to keep a static identifier object to refer
  6106. to frequently-used names, rather than constructing them each time you need it.
  6107. @see NamedPropertySet, ValueTree
  6108. */
  6109. class JUCE_API Identifier
  6110. {
  6111. public:
  6112. /** Creates a null identifier. */
  6113. Identifier() throw();
  6114. /** Creates an identifier with a specified name.
  6115. Because this name may need to be used in contexts such as script variables or XML
  6116. tags, it must only contain ascii letters and digits, or the underscore character.
  6117. */
  6118. Identifier (const char* name);
  6119. /** Creates an identifier with a specified name.
  6120. Because this name may need to be used in contexts such as script variables or XML
  6121. tags, it must only contain ascii letters and digits, or the underscore character.
  6122. */
  6123. Identifier (const String& name);
  6124. /** Creates a copy of another identifier. */
  6125. Identifier (const Identifier& other) throw();
  6126. /** Creates a copy of another identifier. */
  6127. Identifier& operator= (const Identifier& other) throw();
  6128. /** Destructor */
  6129. ~Identifier();
  6130. /** Compares two identifiers. This is a very fast operation. */
  6131. inline bool operator== (const Identifier& other) const throw() { return name == other.name; }
  6132. /** Compares two identifiers. This is a very fast operation. */
  6133. inline bool operator!= (const Identifier& other) const throw() { return name != other.name; }
  6134. /** Returns this identifier as a string. */
  6135. const String toString() const { return name; }
  6136. /** Returns this identifier's raw string pointer. */
  6137. operator const String::CharPointerType() const throw() { return name; }
  6138. private:
  6139. String::CharPointerType name;
  6140. static StringPool& getPool();
  6141. };
  6142. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  6143. /*** End of inlined file: juce_Identifier.h ***/
  6144. /*** Start of inlined file: juce_OutputStream.h ***/
  6145. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6146. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6147. /*** Start of inlined file: juce_NewLine.h ***/
  6148. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  6149. #define __JUCE_NEWLINE_JUCEHEADER__
  6150. /** This class is used for represent a new-line character sequence.
  6151. To write a new-line to a stream, you can use the predefined 'newLine' variable, e.g.
  6152. @code
  6153. myOutputStream << "Hello World" << newLine << newLine;
  6154. @endcode
  6155. The exact character sequence that will be used for the new-line can be set and
  6156. retrieved with OutputStream::setNewLineString() and OutputStream::getNewLineString().
  6157. */
  6158. class JUCE_API NewLine
  6159. {
  6160. public:
  6161. /** Returns the default new-line sequence that the library uses.
  6162. @see OutputStream::setNewLineString()
  6163. */
  6164. static const char* getDefault() throw() { return "\r\n"; }
  6165. /** Returns the default new-line sequence that the library uses.
  6166. @see getDefault()
  6167. */
  6168. operator const String() const { return getDefault(); }
  6169. };
  6170. /** An predefined object representing a new-line, which can be written to a string or stream.
  6171. To write a new-line to a stream, you can use the predefined 'newLine' variable like this:
  6172. @code
  6173. myOutputStream << "Hello World" << newLine << newLine;
  6174. @endcode
  6175. */
  6176. extern NewLine newLine;
  6177. /** Writes a new-line sequence to a string.
  6178. You can use the predefined object 'newLine' to invoke this, e.g.
  6179. @code
  6180. myString << "Hello World" << newLine << newLine;
  6181. @endcode
  6182. */
  6183. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&);
  6184. #endif // __JUCE_NEWLINE_JUCEHEADER__
  6185. /*** End of inlined file: juce_NewLine.h ***/
  6186. /*** Start of inlined file: juce_InputStream.h ***/
  6187. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6188. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6189. /*** Start of inlined file: juce_MemoryBlock.h ***/
  6190. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  6191. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  6192. /**
  6193. A class to hold a resizable block of raw data.
  6194. */
  6195. class JUCE_API MemoryBlock
  6196. {
  6197. public:
  6198. /** Create an uninitialised block with 0 size. */
  6199. MemoryBlock() throw();
  6200. /** Creates a memory block with a given initial size.
  6201. @param initialSize the size of block to create
  6202. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  6203. */
  6204. MemoryBlock (const size_t initialSize,
  6205. bool initialiseToZero = false);
  6206. /** Creates a copy of another memory block. */
  6207. MemoryBlock (const MemoryBlock& other);
  6208. /** Creates a memory block using a copy of a block of data.
  6209. @param dataToInitialiseFrom some data to copy into this block
  6210. @param sizeInBytes how much space to use
  6211. */
  6212. MemoryBlock (const void* dataToInitialiseFrom, size_t sizeInBytes);
  6213. /** Destructor. */
  6214. ~MemoryBlock() throw();
  6215. /** Copies another memory block onto this one.
  6216. This block will be resized and copied to exactly match the other one.
  6217. */
  6218. MemoryBlock& operator= (const MemoryBlock& other);
  6219. /** Compares two memory blocks.
  6220. @returns true only if the two blocks are the same size and have identical contents.
  6221. */
  6222. bool operator== (const MemoryBlock& other) const throw();
  6223. /** Compares two memory blocks.
  6224. @returns true if the two blocks are different sizes or have different contents.
  6225. */
  6226. bool operator!= (const MemoryBlock& other) const throw();
  6227. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  6228. */
  6229. bool matches (const void* data, size_t dataSize) const throw();
  6230. /** Returns a void pointer to the data.
  6231. Note that the pointer returned will probably become invalid when the
  6232. block is resized.
  6233. */
  6234. void* getData() const throw() { return data; }
  6235. /** Returns a byte from the memory block.
  6236. This returns a reference, so you can also use it to set a byte.
  6237. */
  6238. template <typename Type>
  6239. char& operator[] (const Type offset) const throw() { return data [offset]; }
  6240. /** Returns the block's current allocated size, in bytes. */
  6241. size_t getSize() const throw() { return size; }
  6242. /** Resizes the memory block.
  6243. This will try to keep as much of the block's current content as it can,
  6244. and can optionally be made to clear any new space that gets allocated at
  6245. the end of the block.
  6246. @param newSize the new desired size for the block
  6247. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  6248. whether to clear the new section or just leave it
  6249. uninitialised
  6250. @see ensureSize
  6251. */
  6252. void setSize (const size_t newSize,
  6253. bool initialiseNewSpaceToZero = false);
  6254. /** Increases the block's size only if it's smaller than a given size.
  6255. @param minimumSize if the block is already bigger than this size, no action
  6256. will be taken; otherwise it will be increased to this size
  6257. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  6258. whether to clear the new section or just leave it
  6259. uninitialised
  6260. @see setSize
  6261. */
  6262. void ensureSize (const size_t minimumSize,
  6263. bool initialiseNewSpaceToZero = false);
  6264. /** Fills the entire memory block with a repeated byte value.
  6265. This is handy for clearing a block of memory to zero.
  6266. */
  6267. void fillWith (uint8 valueToUse) throw();
  6268. /** Adds another block of data to the end of this one.
  6269. This block's size will be increased accordingly.
  6270. */
  6271. void append (const void* data, size_t numBytes);
  6272. /** Exchanges the contents of this and another memory block.
  6273. No actual copying is required for this, so it's very fast.
  6274. */
  6275. void swapWith (MemoryBlock& other) throw();
  6276. /** Copies data into this MemoryBlock from a memory address.
  6277. @param srcData the memory location of the data to copy into this block
  6278. @param destinationOffset the offset in this block at which the data being copied should begin
  6279. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  6280. it will be clipped so not to do anything nasty)
  6281. */
  6282. void copyFrom (const void* srcData,
  6283. int destinationOffset,
  6284. size_t numBytes) throw();
  6285. /** Copies data from this MemoryBlock to a memory address.
  6286. @param destData the memory location to write to
  6287. @param sourceOffset the offset within this block from which the copied data will be read
  6288. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  6289. zeros will be used for that portion of the data)
  6290. */
  6291. void copyTo (void* destData,
  6292. int sourceOffset,
  6293. size_t numBytes) const throw();
  6294. /** Chops out a section of the block.
  6295. This will remove a section of the memory block and close the gap around it,
  6296. shifting any subsequent data downwards and reducing the size of the block.
  6297. If the range specified goes beyond the size of the block, it will be clipped.
  6298. */
  6299. void removeSection (size_t startByte, size_t numBytesToRemove);
  6300. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  6301. characters in the system's default encoding. */
  6302. const String toString() const;
  6303. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  6304. The block will be resized to the number of valid bytes read from the string.
  6305. Non-hex characters in the string will be ignored.
  6306. @see String::toHexString()
  6307. */
  6308. void loadFromHexString (const String& sourceHexString);
  6309. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  6310. void setBitRange (size_t bitRangeStart,
  6311. size_t numBits,
  6312. int binaryNumberToApply) throw();
  6313. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  6314. int getBitRange (size_t bitRangeStart,
  6315. size_t numBitsToRead) const throw();
  6316. /** Returns a string of characters that represent the binary contents of this block.
  6317. Uses a 64-bit encoding system to allow binary data to be turned into a string
  6318. of simple non-extended characters, e.g. for storage in XML.
  6319. @see fromBase64Encoding
  6320. */
  6321. const String toBase64Encoding() const;
  6322. /** Takes a string of encoded characters and turns it into binary data.
  6323. The string passed in must have been created by to64BitEncoding(), and this
  6324. block will be resized to recreate the original data block.
  6325. @see toBase64Encoding
  6326. */
  6327. bool fromBase64Encoding (const String& encodedString);
  6328. private:
  6329. HeapBlock <char> data;
  6330. size_t size;
  6331. static const char* const encodingTable;
  6332. JUCE_LEAK_DETECTOR (MemoryBlock);
  6333. };
  6334. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  6335. /*** End of inlined file: juce_MemoryBlock.h ***/
  6336. /** The base class for streams that read data.
  6337. Input and output streams are used throughout the library - subclasses can override
  6338. some or all of the virtual functions to implement their behaviour.
  6339. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6340. */
  6341. class JUCE_API InputStream
  6342. {
  6343. public:
  6344. /** Destructor. */
  6345. virtual ~InputStream() {}
  6346. /** Returns the total number of bytes available for reading in this stream.
  6347. Note that this is the number of bytes available from the start of the
  6348. stream, not from the current position.
  6349. If the size of the stream isn't actually known, this may return -1.
  6350. */
  6351. virtual int64 getTotalLength() = 0;
  6352. /** Returns true if the stream has no more data to read. */
  6353. virtual bool isExhausted() = 0;
  6354. /** Reads a set of bytes from the stream into a memory buffer.
  6355. This is the only read method that subclasses actually need to implement, as the
  6356. InputStream base class implements the other read methods in terms of this one (although
  6357. it's often more efficient for subclasses to implement them directly).
  6358. @param destBuffer the destination buffer for the data
  6359. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6360. memory block passed in is big enough to contain this
  6361. many bytes.
  6362. @returns the actual number of bytes that were read, which may be less than
  6363. maxBytesToRead if the stream is exhausted before it gets that far
  6364. */
  6365. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  6366. /** Reads a byte from the stream.
  6367. If the stream is exhausted, this will return zero.
  6368. @see OutputStream::writeByte
  6369. */
  6370. virtual char readByte();
  6371. /** Reads a boolean from the stream.
  6372. The bool is encoded as a single byte - 1 for true, 0 for false.
  6373. If the stream is exhausted, this will return false.
  6374. @see OutputStream::writeBool
  6375. */
  6376. virtual bool readBool();
  6377. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6378. If the next two bytes read are byte1 and byte2, this returns
  6379. (byte1 | (byte2 << 8)).
  6380. If the stream is exhausted partway through reading the bytes, this will return zero.
  6381. @see OutputStream::writeShort, readShortBigEndian
  6382. */
  6383. virtual short readShort();
  6384. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6385. If the next two bytes read are byte1 and byte2, this returns
  6386. (byte2 | (byte1 << 8)).
  6387. If the stream is exhausted partway through reading the bytes, this will return zero.
  6388. @see OutputStream::writeShortBigEndian, readShort
  6389. */
  6390. virtual short readShortBigEndian();
  6391. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6392. If the next four bytes are byte1 to byte4, this returns
  6393. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6394. If the stream is exhausted partway through reading the bytes, this will return zero.
  6395. @see OutputStream::writeInt, readIntBigEndian
  6396. */
  6397. virtual int readInt();
  6398. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6399. If the next four bytes are byte1 to byte4, this returns
  6400. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6401. If the stream is exhausted partway through reading the bytes, this will return zero.
  6402. @see OutputStream::writeIntBigEndian, readInt
  6403. */
  6404. virtual int readIntBigEndian();
  6405. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6406. If the next eight bytes are byte1 to byte8, this returns
  6407. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6408. If the stream is exhausted partway through reading the bytes, this will return zero.
  6409. @see OutputStream::writeInt64, readInt64BigEndian
  6410. */
  6411. virtual int64 readInt64();
  6412. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6413. If the next eight bytes are byte1 to byte8, this returns
  6414. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6415. If the stream is exhausted partway through reading the bytes, this will return zero.
  6416. @see OutputStream::writeInt64BigEndian, readInt64
  6417. */
  6418. virtual int64 readInt64BigEndian();
  6419. /** Reads four bytes as a 32-bit floating point value.
  6420. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6421. If the stream is exhausted partway through reading the bytes, this will return zero.
  6422. @see OutputStream::writeFloat, readDouble
  6423. */
  6424. virtual float readFloat();
  6425. /** Reads four bytes as a 32-bit floating point value.
  6426. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6427. If the stream is exhausted partway through reading the bytes, this will return zero.
  6428. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6429. */
  6430. virtual float readFloatBigEndian();
  6431. /** Reads eight bytes as a 64-bit floating point value.
  6432. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6433. If the stream is exhausted partway through reading the bytes, this will return zero.
  6434. @see OutputStream::writeDouble, readFloat
  6435. */
  6436. virtual double readDouble();
  6437. /** Reads eight bytes as a 64-bit floating point value.
  6438. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6439. If the stream is exhausted partway through reading the bytes, this will return zero.
  6440. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6441. */
  6442. virtual double readDoubleBigEndian();
  6443. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6444. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6445. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6446. @see OutputStream::writeCompressedInt()
  6447. */
  6448. virtual int readCompressedInt();
  6449. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  6450. This will read up to the next "\n" or "\r\n" or end-of-stream.
  6451. After this call, the stream's position will be left pointing to the next character
  6452. following the line-feed, but the linefeeds aren't included in the string that
  6453. is returned.
  6454. */
  6455. virtual const String readNextLine();
  6456. /** Reads a zero-terminated UTF8 string from the stream.
  6457. This will read characters from the stream until it hits a zero character or
  6458. end-of-stream.
  6459. @see OutputStream::writeString, readEntireStreamAsString
  6460. */
  6461. virtual const String readString();
  6462. /** Tries to read the whole stream and turn it into a string.
  6463. This will read from the stream's current position until the end-of-stream, and
  6464. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6465. */
  6466. virtual const String readEntireStreamAsString();
  6467. /** Reads from the stream and appends the data to a MemoryBlock.
  6468. @param destBlock the block to append the data onto
  6469. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6470. of bytes that will be read - if it's negative, data
  6471. will be read until the stream is exhausted.
  6472. @returns the number of bytes that were added to the memory block
  6473. */
  6474. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6475. int maxNumBytesToRead = -1);
  6476. /** Returns the offset of the next byte that will be read from the stream.
  6477. @see setPosition
  6478. */
  6479. virtual int64 getPosition() = 0;
  6480. /** Tries to move the current read position of the stream.
  6481. The position is an absolute number of bytes from the stream's start.
  6482. Some streams might not be able to do this, in which case they should do
  6483. nothing and return false. Others might be able to manage it by resetting
  6484. themselves and skipping to the correct position, although this is
  6485. obviously a bit slow.
  6486. @returns true if the stream manages to reposition itself correctly
  6487. @see getPosition
  6488. */
  6489. virtual bool setPosition (int64 newPosition) = 0;
  6490. /** Reads and discards a number of bytes from the stream.
  6491. Some input streams might implement this efficiently, but the base
  6492. class will just keep reading data until the requisite number of bytes
  6493. have been done.
  6494. */
  6495. virtual void skipNextBytes (int64 numBytesToSkip);
  6496. protected:
  6497. InputStream() throw() {}
  6498. private:
  6499. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InputStream);
  6500. };
  6501. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6502. /*** End of inlined file: juce_InputStream.h ***/
  6503. class File;
  6504. /**
  6505. The base class for streams that write data to some kind of destination.
  6506. Input and output streams are used throughout the library - subclasses can override
  6507. some or all of the virtual functions to implement their behaviour.
  6508. @see InputStream, MemoryOutputStream, FileOutputStream
  6509. */
  6510. class JUCE_API OutputStream
  6511. {
  6512. protected:
  6513. OutputStream();
  6514. public:
  6515. /** Destructor.
  6516. Some subclasses might want to do things like call flush() during their
  6517. destructors.
  6518. */
  6519. virtual ~OutputStream();
  6520. /** If the stream is using a buffer, this will ensure it gets written
  6521. out to the destination. */
  6522. virtual void flush() = 0;
  6523. /** Tries to move the stream's output position.
  6524. Not all streams will be able to seek to a new position - this will return
  6525. false if it fails to work.
  6526. @see getPosition
  6527. */
  6528. virtual bool setPosition (int64 newPosition) = 0;
  6529. /** Returns the stream's current position.
  6530. @see setPosition
  6531. */
  6532. virtual int64 getPosition() = 0;
  6533. /** Writes a block of data to the stream.
  6534. When creating a subclass of OutputStream, this is the only write method
  6535. that needs to be overloaded - the base class has methods for writing other
  6536. types of data which use this to do the work.
  6537. @returns false if the write operation fails for some reason
  6538. */
  6539. virtual bool write (const void* dataToWrite,
  6540. int howManyBytes) = 0;
  6541. /** Writes a single byte to the stream.
  6542. @see InputStream::readByte
  6543. */
  6544. virtual void writeByte (char byte);
  6545. /** Writes a boolean to the stream as a single byte.
  6546. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  6547. @see InputStream::readBool
  6548. */
  6549. virtual void writeBool (bool boolValue);
  6550. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6551. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6552. @see InputStream::readShort
  6553. */
  6554. virtual void writeShort (short value);
  6555. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6556. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6557. @see InputStream::readShortBigEndian
  6558. */
  6559. virtual void writeShortBigEndian (short value);
  6560. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6561. @see InputStream::readInt
  6562. */
  6563. virtual void writeInt (int value);
  6564. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6565. @see InputStream::readIntBigEndian
  6566. */
  6567. virtual void writeIntBigEndian (int value);
  6568. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6569. @see InputStream::readInt64
  6570. */
  6571. virtual void writeInt64 (int64 value);
  6572. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6573. @see InputStream::readInt64BigEndian
  6574. */
  6575. virtual void writeInt64BigEndian (int64 value);
  6576. /** Writes a 32-bit floating point value to the stream in a binary format.
  6577. The binary 32-bit encoding of the float is written as a little-endian int.
  6578. @see InputStream::readFloat
  6579. */
  6580. virtual void writeFloat (float value);
  6581. /** Writes a 32-bit floating point value to the stream in a binary format.
  6582. The binary 32-bit encoding of the float is written as a big-endian int.
  6583. @see InputStream::readFloatBigEndian
  6584. */
  6585. virtual void writeFloatBigEndian (float value);
  6586. /** Writes a 64-bit floating point value to the stream in a binary format.
  6587. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6588. @see InputStream::readDouble
  6589. */
  6590. virtual void writeDouble (double value);
  6591. /** Writes a 64-bit floating point value to the stream in a binary format.
  6592. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6593. @see InputStream::readDoubleBigEndian
  6594. */
  6595. virtual void writeDoubleBigEndian (double value);
  6596. /** Writes a byte to the output stream a given number of times. */
  6597. virtual void writeRepeatedByte (uint8 byte, int numTimesToRepeat);
  6598. /** Writes a condensed binary encoding of a 32-bit integer.
  6599. If you're storing a lot of integers which are unlikely to have very large values,
  6600. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6601. under 0xffff only 3 bytes, etc.
  6602. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6603. @see InputStream::readCompressedInt
  6604. */
  6605. virtual void writeCompressedInt (int value);
  6606. /** Stores a string in the stream in a binary format.
  6607. This isn't the method to use if you're trying to append text to the end of a
  6608. text-file! It's intended for storing a string so that it can be retrieved later
  6609. by InputStream::readString().
  6610. It writes the string to the stream as UTF8, including the null termination character.
  6611. For appending text to a file, instead use writeText, or operator<<
  6612. @see InputStream::readString, writeText, operator<<
  6613. */
  6614. virtual void writeString (const String& text);
  6615. /** Writes a string of text to the stream.
  6616. It can either write the text as UTF-8 or UTF-16, and can also add the UTF-16 byte-order-mark
  6617. bytes (0xff, 0xfe) to indicate the endianness (these should only be used at the start
  6618. of a file).
  6619. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6620. */
  6621. virtual void writeText (const String& text,
  6622. bool asUTF16,
  6623. bool writeUTF16ByteOrderMark);
  6624. /** Reads data from an input stream and writes it to this stream.
  6625. @param source the stream to read from
  6626. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6627. less than zero, it will keep reading until the input
  6628. is exhausted)
  6629. */
  6630. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  6631. /** Sets the string that will be written to the stream when the writeNewLine()
  6632. method is called.
  6633. By default this will be set the the value of NewLine::getDefault().
  6634. */
  6635. void setNewLineString (const String& newLineString);
  6636. /** Returns the current new-line string that was set by setNewLineString(). */
  6637. const String& getNewLineString() const throw() { return newLineString; }
  6638. private:
  6639. String newLineString;
  6640. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OutputStream);
  6641. };
  6642. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6643. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  6644. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6645. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  6646. /** Writes a character to a stream. */
  6647. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  6648. /** Writes a null-terminated text string to a stream. */
  6649. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  6650. /** Writes a block of data from a MemoryBlock to a stream. */
  6651. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  6652. /** Writes the contents of a file to a stream. */
  6653. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  6654. /** Writes a new-line to a stream.
  6655. You can use the predefined symbol 'newLine' to invoke this, e.g.
  6656. @code
  6657. myOutputStream << "Hello World" << newLine << newLine;
  6658. @endcode
  6659. @see OutputStream::setNewLineString
  6660. */
  6661. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&);
  6662. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6663. /*** End of inlined file: juce_OutputStream.h ***/
  6664. #ifndef DOXYGEN
  6665. class DynamicObject;
  6666. #endif
  6667. /**
  6668. A variant class, that can be used to hold a range of primitive values.
  6669. A var object can hold a range of simple primitive values, strings, or
  6670. a reference-counted pointer to a DynamicObject. The var class is intended
  6671. to act like the values used in dynamic scripting languages.
  6672. @see DynamicObject
  6673. */
  6674. class JUCE_API var
  6675. {
  6676. public:
  6677. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  6678. typedef Identifier identifier;
  6679. /** Creates a void variant. */
  6680. var() throw();
  6681. /** Destructor. */
  6682. ~var() throw();
  6683. /** A static var object that can be used where you need an empty variant object. */
  6684. static const var null;
  6685. var (const var& valueToCopy);
  6686. var (int value) throw();
  6687. var (int64 value) throw();
  6688. var (bool value) throw();
  6689. var (double value) throw();
  6690. var (const char* value);
  6691. var (const wchar_t* value);
  6692. var (const String& value);
  6693. var (DynamicObject* object);
  6694. var (MethodFunction method) throw();
  6695. var& operator= (const var& valueToCopy);
  6696. var& operator= (int value);
  6697. var& operator= (int64 value);
  6698. var& operator= (bool value);
  6699. var& operator= (double value);
  6700. var& operator= (const char* value);
  6701. var& operator= (const wchar_t* value);
  6702. var& operator= (const String& value);
  6703. var& operator= (DynamicObject* object);
  6704. var& operator= (MethodFunction method);
  6705. void swapWith (var& other) throw();
  6706. operator int() const;
  6707. operator int64() const;
  6708. operator bool() const;
  6709. operator float() const;
  6710. operator double() const;
  6711. operator const String() const;
  6712. const String toString() const;
  6713. DynamicObject* getObject() const;
  6714. bool isVoid() const throw();
  6715. bool isInt() const throw();
  6716. bool isInt64() const throw();
  6717. bool isBool() const throw();
  6718. bool isDouble() const throw();
  6719. bool isString() const throw();
  6720. bool isObject() const throw();
  6721. bool isMethod() const throw();
  6722. /** Writes a binary representation of this value to a stream.
  6723. The data can be read back later using readFromStream().
  6724. */
  6725. void writeToStream (OutputStream& output) const;
  6726. /** Reads back a stored binary representation of a value.
  6727. The data in the stream must have been written using writeToStream(), or this
  6728. will have unpredictable results.
  6729. */
  6730. static const var readFromStream (InputStream& input);
  6731. /** If this variant is an object, this returns one of its properties. */
  6732. const var operator[] (const Identifier& propertyName) const;
  6733. /** If this variant is an object, this invokes one of its methods with no arguments. */
  6734. const var call (const Identifier& method) const;
  6735. /** If this variant is an object, this invokes one of its methods with one argument. */
  6736. const var call (const Identifier& method, const var& arg1) const;
  6737. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  6738. const var call (const Identifier& method, const var& arg1, const var& arg2) const;
  6739. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  6740. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  6741. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  6742. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  6743. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  6744. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  6745. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  6746. const var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  6747. /** If this variant is a method pointer, this invokes it on a target object. */
  6748. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  6749. /** Returns true if this var has the same value as the one supplied. */
  6750. bool equals (const var& other) const throw();
  6751. /** Returns true if this var has the same value and type as the one supplied.
  6752. This differs from equals() because e.g. "0" and 0 will be considered different.
  6753. */
  6754. bool equalsWithSameType (const var& other) const throw();
  6755. private:
  6756. class VariantType;
  6757. friend class VariantType;
  6758. class VariantType_Void;
  6759. friend class VariantType_Void;
  6760. class VariantType_Int;
  6761. friend class VariantType_Int;
  6762. class VariantType_Int64;
  6763. friend class VariantType_Int64;
  6764. class VariantType_Double;
  6765. friend class VariantType_Double;
  6766. class VariantType_Float;
  6767. friend class VariantType_Float;
  6768. class VariantType_Bool;
  6769. friend class VariantType_Bool;
  6770. class VariantType_String;
  6771. friend class VariantType_String;
  6772. class VariantType_Object;
  6773. friend class VariantType_Object;
  6774. class VariantType_Method;
  6775. friend class VariantType_Method;
  6776. union ValueUnion
  6777. {
  6778. int intValue;
  6779. int64 int64Value;
  6780. bool boolValue;
  6781. double doubleValue;
  6782. String* stringValue;
  6783. DynamicObject* objectValue;
  6784. MethodFunction methodValue;
  6785. };
  6786. const VariantType* type;
  6787. ValueUnion value;
  6788. };
  6789. bool operator== (const var& v1, const var& v2) throw();
  6790. bool operator!= (const var& v1, const var& v2) throw();
  6791. bool operator== (const var& v1, const String& v2) throw();
  6792. bool operator!= (const var& v1, const String& v2) throw();
  6793. #endif // __JUCE_VARIANT_JUCEHEADER__
  6794. /*** End of inlined file: juce_Variant.h ***/
  6795. /*** Start of inlined file: juce_LinkedListPointer.h ***/
  6796. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  6797. #define __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  6798. /**
  6799. Helps to manipulate singly-linked lists of objects.
  6800. For objects that are designed to contain a pointer to the subsequent item in the
  6801. list, this class contains methods to deal with the list. To use it, the ObjectType
  6802. class that it points to must contain a LinkedListPointer called nextListItem, e.g.
  6803. @code
  6804. struct MyObject
  6805. {
  6806. int x, y, z;
  6807. // A linkable object must contain a member with this name and type, which must be
  6808. // accessible by the LinkedListPointer class. (This doesn't mean it has to be public -
  6809. // you could make your class a friend of a LinkedListPointer<MyObject> instead).
  6810. LinkedListPointer<MyObject> nextListItem;
  6811. };
  6812. LinkedListPointer<MyObject> myList;
  6813. myList.append (new MyObject());
  6814. myList.append (new MyObject());
  6815. int numItems = myList.size(); // returns 2
  6816. MyObject* lastInList = myList.getLast();
  6817. @endcode
  6818. */
  6819. template <class ObjectType>
  6820. class LinkedListPointer
  6821. {
  6822. public:
  6823. /** Creates a null pointer to an empty list. */
  6824. LinkedListPointer() throw()
  6825. : item (0)
  6826. {
  6827. }
  6828. /** Creates a pointer to a list whose head is the item provided. */
  6829. explicit LinkedListPointer (ObjectType* const headItem) throw()
  6830. : item (headItem)
  6831. {
  6832. }
  6833. /** Sets this pointer to point to a new list. */
  6834. LinkedListPointer& operator= (ObjectType* const newItem) throw()
  6835. {
  6836. item = newItem;
  6837. return *this;
  6838. }
  6839. /** Returns the item which this pointer points to. */
  6840. inline operator ObjectType*() const throw()
  6841. {
  6842. return item;
  6843. }
  6844. /** Returns the item which this pointer points to. */
  6845. inline ObjectType* get() const throw()
  6846. {
  6847. return item;
  6848. }
  6849. /** Returns the last item in the list which this pointer points to.
  6850. This will iterate the list and return the last item found. Obviously the speed
  6851. of this operation will be proportional to the size of the list. If the list is
  6852. empty the return value will be this object.
  6853. If you're planning on appending a number of items to your list, it's much more
  6854. efficient to use the Appender class than to repeatedly call getLast() to find the end.
  6855. */
  6856. LinkedListPointer& getLast() throw()
  6857. {
  6858. LinkedListPointer* l = this;
  6859. while (l->item != 0)
  6860. l = &(l->item->nextListItem);
  6861. return *l;
  6862. }
  6863. /** Returns the number of items in the list.
  6864. Obviously with a simple linked list, getting the size involves iterating the list, so
  6865. this can be a lengthy operation - be careful when using this method in your code.
  6866. */
  6867. int size() const throw()
  6868. {
  6869. int total = 0;
  6870. for (ObjectType* i = item; i != 0; i = i->nextListItem)
  6871. ++total;
  6872. return total;
  6873. }
  6874. /** Returns the item at a given index in the list.
  6875. Since the only way to find an item is to iterate the list, this operation can obviously
  6876. be slow, depending on its size, so you should be careful when using this in algorithms.
  6877. */
  6878. LinkedListPointer& operator[] (int index) throw()
  6879. {
  6880. LinkedListPointer* l = this;
  6881. while (--index >= 0 && l->item != 0)
  6882. l = &(l->item->nextListItem);
  6883. return *l;
  6884. }
  6885. /** Returns the item at a given index in the list.
  6886. Since the only way to find an item is to iterate the list, this operation can obviously
  6887. be slow, depending on its size, so you should be careful when using this in algorithms.
  6888. */
  6889. const LinkedListPointer& operator[] (int index) const throw()
  6890. {
  6891. const LinkedListPointer* l = this;
  6892. while (--index >= 0 && l->item != 0)
  6893. l = &(l->item->nextListItem);
  6894. return *l;
  6895. }
  6896. /** Returns true if the list contains the given item. */
  6897. bool contains (const ObjectType* const itemToLookFor) const throw()
  6898. {
  6899. for (ObjectType* i = item; i != 0; i = i->nextListItem)
  6900. if (itemToLookFor == i)
  6901. return true;
  6902. return false;
  6903. }
  6904. /** Inserts an item into the list, placing it before the item that this pointer
  6905. currently points to.
  6906. */
  6907. void insertNext (ObjectType* const newItem)
  6908. {
  6909. jassert (newItem != 0);
  6910. jassert (newItem->nextListItem == 0);
  6911. newItem->nextListItem = item;
  6912. item = newItem;
  6913. }
  6914. /** Inserts an item at a numeric index in the list.
  6915. Obviously this will involve iterating the list to find the item at the given index,
  6916. so be careful about the impact this may have on execution time.
  6917. */
  6918. void insertAtIndex (int index, ObjectType* newItem)
  6919. {
  6920. jassert (newItem != 0);
  6921. LinkedListPointer* l = this;
  6922. while (index != 0 && l->item != 0)
  6923. {
  6924. l = &(l->item->nextListItem);
  6925. --index;
  6926. }
  6927. l->insertNext (newItem);
  6928. }
  6929. /** Replaces the object that this pointer points to, appending the rest of the list to
  6930. the new object, and returning the old one.
  6931. */
  6932. ObjectType* replaceNext (ObjectType* const newItem) throw()
  6933. {
  6934. jassert (newItem != 0);
  6935. jassert (newItem->nextListItem == 0);
  6936. ObjectType* const oldItem = item;
  6937. item = newItem;
  6938. item->nextListItem = oldItem->nextListItem.item;
  6939. oldItem->nextListItem = (ObjectType*) 0;
  6940. return oldItem;
  6941. }
  6942. /** Adds an item to the end of the list.
  6943. This operation involves iterating the whole list, so can be slow - if you need to
  6944. append a number of items to your list, it's much more efficient to use the Appender
  6945. class than to repeatedly call append().
  6946. */
  6947. void append (ObjectType* const newItem)
  6948. {
  6949. getLast().item = newItem;
  6950. }
  6951. /** Creates copies of all the items in another list and adds them to this one.
  6952. This will use the ObjectType's copy constructor to try to create copies of each
  6953. item in the other list, and appends them to this list.
  6954. */
  6955. void addCopyOfList (const LinkedListPointer& other)
  6956. {
  6957. LinkedListPointer* insertPoint = this;
  6958. for (ObjectType* i = other.item; i != 0; i = i->nextListItem)
  6959. {
  6960. insertPoint->insertNext (new ObjectType (*i));
  6961. insertPoint = &(insertPoint->item->nextListItem);
  6962. }
  6963. }
  6964. /** Removes the head item from the list.
  6965. This won't delete the object that is removed, but returns it, so the caller can
  6966. delete it if necessary.
  6967. */
  6968. ObjectType* removeNext() throw()
  6969. {
  6970. ObjectType* const oldItem = item;
  6971. if (oldItem != 0)
  6972. {
  6973. item = oldItem->nextListItem;
  6974. oldItem->nextListItem = (ObjectType*) 0;
  6975. }
  6976. return oldItem;
  6977. }
  6978. /** Removes a specific item from the list.
  6979. Note that this will not delete the item, it simply unlinks it from the list.
  6980. */
  6981. void remove (ObjectType* const itemToRemove)
  6982. {
  6983. LinkedListPointer* const l = findPointerTo (itemToRemove);
  6984. if (l != 0)
  6985. l->removeNext();
  6986. }
  6987. /** Iterates the list, calling the delete operator on all of its elements and
  6988. leaving this pointer empty.
  6989. */
  6990. void deleteAll()
  6991. {
  6992. while (item != 0)
  6993. {
  6994. ObjectType* const oldItem = item;
  6995. item = oldItem->nextListItem;
  6996. delete oldItem;
  6997. }
  6998. }
  6999. /** Finds a pointer to a given item.
  7000. If the item is found in the list, this returns the pointer that points to it. If
  7001. the item isn't found, this returns null.
  7002. */
  7003. LinkedListPointer* findPointerTo (ObjectType* const itemToLookFor) throw()
  7004. {
  7005. LinkedListPointer* l = this;
  7006. while (l->item != 0)
  7007. {
  7008. if (l->item == itemToLookFor)
  7009. return l;
  7010. l = &(l->item->nextListItem);
  7011. }
  7012. return 0;
  7013. }
  7014. /** Copies the items in the list to an array.
  7015. The destArray must contain enough elements to hold the entire list - no checks are
  7016. made for this!
  7017. */
  7018. void copyToArray (ObjectType** destArray) const throw()
  7019. {
  7020. jassert (destArray != 0);
  7021. for (ObjectType* i = item; i != 0; i = i->nextListItem)
  7022. *destArray++ = i;
  7023. }
  7024. /**
  7025. Allows efficient repeated insertions into a list.
  7026. You can create an Appender object which points to the last element in your
  7027. list, and then repeatedly call Appender::append() to add items to the end
  7028. of the list in O(1) time.
  7029. */
  7030. class Appender
  7031. {
  7032. public:
  7033. /** Creates an appender which will add items to the given list.
  7034. */
  7035. Appender (LinkedListPointer& endOfListPointer) throw()
  7036. : endOfList (&endOfListPointer)
  7037. {
  7038. // This can only be used to add to the end of a list.
  7039. jassert (endOfListPointer.item == 0);
  7040. }
  7041. /** Appends an item to the list. */
  7042. void append (ObjectType* const newItem) throw()
  7043. {
  7044. *endOfList = newItem;
  7045. endOfList = &(newItem->nextListItem);
  7046. }
  7047. private:
  7048. LinkedListPointer* endOfList;
  7049. JUCE_DECLARE_NON_COPYABLE (Appender);
  7050. };
  7051. private:
  7052. ObjectType* item;
  7053. JUCE_DECLARE_NON_COPYABLE (LinkedListPointer);
  7054. };
  7055. #endif // __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7056. /*** End of inlined file: juce_LinkedListPointer.h ***/
  7057. class XmlElement;
  7058. /** Holds a set of named var objects.
  7059. This can be used as a basic structure to hold a set of var object, which can
  7060. be retrieved by using their identifier.
  7061. */
  7062. class JUCE_API NamedValueSet
  7063. {
  7064. public:
  7065. /** Creates an empty set. */
  7066. NamedValueSet() throw();
  7067. /** Creates a copy of another set. */
  7068. NamedValueSet (const NamedValueSet& other);
  7069. /** Replaces this set with a copy of another set. */
  7070. NamedValueSet& operator= (const NamedValueSet& other);
  7071. /** Destructor. */
  7072. ~NamedValueSet();
  7073. bool operator== (const NamedValueSet& other) const;
  7074. bool operator!= (const NamedValueSet& other) const;
  7075. /** Returns the total number of values that the set contains. */
  7076. int size() const throw();
  7077. /** Returns the value of a named item.
  7078. If the name isn't found, this will return a void variant.
  7079. @see getProperty
  7080. */
  7081. const var& operator[] (const Identifier& name) const;
  7082. /** Tries to return the named value, but if no such value is found, this will
  7083. instead return the supplied default value.
  7084. */
  7085. const var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  7086. /** Changes or adds a named value.
  7087. @returns true if a value was changed or added; false if the
  7088. value was already set the the value passed-in.
  7089. */
  7090. bool set (const Identifier& name, const var& newValue);
  7091. /** Returns true if the set contains an item with the specified name. */
  7092. bool contains (const Identifier& name) const;
  7093. /** Removes a value from the set.
  7094. @returns true if a value was removed; false if there was no value
  7095. with the name that was given.
  7096. */
  7097. bool remove (const Identifier& name);
  7098. /** Returns the name of the value at a given index.
  7099. The index must be between 0 and size() - 1.
  7100. */
  7101. const Identifier getName (int index) const;
  7102. /** Returns the value of the item at a given index.
  7103. The index must be between 0 and size() - 1.
  7104. */
  7105. const var getValueAt (int index) const;
  7106. /** Removes all values. */
  7107. void clear();
  7108. /** Returns a pointer to the var that holds a named value, or null if there is
  7109. no value with this name.
  7110. Do not use this method unless you really need access to the internal var object
  7111. for some reason - for normal reading and writing always prefer operator[]() and set().
  7112. */
  7113. var* getVarPointer (const Identifier& name) const;
  7114. /** Sets properties to the values of all of an XML element's attributes. */
  7115. void setFromXmlAttributes (const XmlElement& xml);
  7116. /** Sets attributes in an XML element corresponding to each of this object's
  7117. properties.
  7118. */
  7119. void copyToXmlAttributes (XmlElement& xml) const;
  7120. private:
  7121. class NamedValue
  7122. {
  7123. public:
  7124. NamedValue() throw();
  7125. NamedValue (const NamedValue&);
  7126. NamedValue (const Identifier& name, const var& value);
  7127. NamedValue& operator= (const NamedValue&);
  7128. bool operator== (const NamedValue& other) const throw();
  7129. LinkedListPointer<NamedValue> nextListItem;
  7130. Identifier name;
  7131. var value;
  7132. private:
  7133. JUCE_LEAK_DETECTOR (NamedValue);
  7134. };
  7135. friend class LinkedListPointer<NamedValue>;
  7136. LinkedListPointer<NamedValue> values;
  7137. };
  7138. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  7139. /*** End of inlined file: juce_NamedValueSet.h ***/
  7140. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  7141. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7142. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7143. /**
  7144. Adds reference-counting to an object.
  7145. To add reference-counting to a class, derive it from this class, and
  7146. use the ReferenceCountedObjectPtr class to point to it.
  7147. e.g. @code
  7148. class MyClass : public ReferenceCountedObject
  7149. {
  7150. void foo();
  7151. // This is a neat way of declaring a typedef for a pointer class,
  7152. // rather than typing out the full templated name each time..
  7153. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7154. };
  7155. MyClass::Ptr p = new MyClass();
  7156. MyClass::Ptr p2 = p;
  7157. p = 0;
  7158. p2->foo();
  7159. @endcode
  7160. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7161. careful not to delete the object manually.
  7162. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  7163. */
  7164. class JUCE_API ReferenceCountedObject
  7165. {
  7166. public:
  7167. /** Increments the object's reference count.
  7168. This is done automatically by the smart pointer, but is public just
  7169. in case it's needed for nefarious purposes.
  7170. */
  7171. inline void incReferenceCount() throw()
  7172. {
  7173. ++refCount;
  7174. }
  7175. /** Decreases the object's reference count.
  7176. If the count gets to zero, the object will be deleted.
  7177. */
  7178. inline void decReferenceCount() throw()
  7179. {
  7180. jassert (getReferenceCount() > 0);
  7181. if (--refCount == 0)
  7182. delete this;
  7183. }
  7184. /** Returns the object's current reference count. */
  7185. inline int getReferenceCount() const throw()
  7186. {
  7187. return refCount.get();
  7188. }
  7189. protected:
  7190. /** Creates the reference-counted object (with an initial ref count of zero). */
  7191. ReferenceCountedObject()
  7192. {
  7193. }
  7194. /** Destructor. */
  7195. virtual ~ReferenceCountedObject()
  7196. {
  7197. // it's dangerous to delete an object that's still referenced by something else!
  7198. jassert (getReferenceCount() == 0);
  7199. }
  7200. private:
  7201. Atomic <int> refCount;
  7202. };
  7203. /**
  7204. A smart-pointer class which points to a reference-counted object.
  7205. The template parameter specifies the class of the object you want to point to - the easiest
  7206. way to make a class reference-countable is to simply make it inherit from ReferenceCountedObject,
  7207. but if you need to, you could roll your own reference-countable class by implementing a pair of
  7208. mathods called incReferenceCount() and decReferenceCount().
  7209. When using this class, you'll probably want to create a typedef to abbreviate the full
  7210. templated name - e.g.
  7211. @code typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;@endcode
  7212. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7213. */
  7214. template <class ReferenceCountedObjectClass>
  7215. class ReferenceCountedObjectPtr
  7216. {
  7217. public:
  7218. /** Creates a pointer to a null object. */
  7219. inline ReferenceCountedObjectPtr() throw()
  7220. : referencedObject (0)
  7221. {
  7222. }
  7223. /** Creates a pointer to an object.
  7224. This will increment the object's reference-count if it is non-null.
  7225. */
  7226. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  7227. : referencedObject (refCountedObject)
  7228. {
  7229. if (refCountedObject != 0)
  7230. refCountedObject->incReferenceCount();
  7231. }
  7232. /** Copies another pointer.
  7233. This will increment the object's reference-count (if it is non-null).
  7234. */
  7235. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  7236. : referencedObject (other.referencedObject)
  7237. {
  7238. if (referencedObject != 0)
  7239. referencedObject->incReferenceCount();
  7240. }
  7241. /** Changes this pointer to point at a different object.
  7242. The reference count of the old object is decremented, and it might be
  7243. deleted if it hits zero. The new object's count is incremented.
  7244. */
  7245. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7246. {
  7247. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7248. if (newObject != referencedObject)
  7249. {
  7250. if (newObject != 0)
  7251. newObject->incReferenceCount();
  7252. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7253. referencedObject = newObject;
  7254. if (oldObject != 0)
  7255. oldObject->decReferenceCount();
  7256. }
  7257. return *this;
  7258. }
  7259. /** Changes this pointer to point at a different object.
  7260. The reference count of the old object is decremented, and it might be
  7261. deleted if it hits zero. The new object's count is incremented.
  7262. */
  7263. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7264. {
  7265. if (referencedObject != newObject)
  7266. {
  7267. if (newObject != 0)
  7268. newObject->incReferenceCount();
  7269. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7270. referencedObject = newObject;
  7271. if (oldObject != 0)
  7272. oldObject->decReferenceCount();
  7273. }
  7274. return *this;
  7275. }
  7276. /** Destructor.
  7277. This will decrement the object's reference-count, and may delete it if it
  7278. gets to zero.
  7279. */
  7280. inline ~ReferenceCountedObjectPtr()
  7281. {
  7282. if (referencedObject != 0)
  7283. referencedObject->decReferenceCount();
  7284. }
  7285. /** Returns the object that this pointer references.
  7286. The pointer returned may be zero, of course.
  7287. */
  7288. inline operator ReferenceCountedObjectClass*() const throw()
  7289. {
  7290. return referencedObject;
  7291. }
  7292. // the -> operator is called on the referenced object
  7293. inline ReferenceCountedObjectClass* operator->() const throw()
  7294. {
  7295. return referencedObject;
  7296. }
  7297. /** Returns the object that this pointer references.
  7298. The pointer returned may be zero, of course.
  7299. */
  7300. inline ReferenceCountedObjectClass* getObject() const throw()
  7301. {
  7302. return referencedObject;
  7303. }
  7304. private:
  7305. ReferenceCountedObjectClass* referencedObject;
  7306. };
  7307. /** Compares two ReferenceCountedObjectPointers. */
  7308. template <class ReferenceCountedObjectClass>
  7309. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectClass* const object2) throw()
  7310. {
  7311. return object1.getObject() == object2;
  7312. }
  7313. /** Compares two ReferenceCountedObjectPointers. */
  7314. template <class ReferenceCountedObjectClass>
  7315. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7316. {
  7317. return object1.getObject() == object2.getObject();
  7318. }
  7319. /** Compares two ReferenceCountedObjectPointers. */
  7320. template <class ReferenceCountedObjectClass>
  7321. bool operator== (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7322. {
  7323. return object1 == object2.getObject();
  7324. }
  7325. /** Compares two ReferenceCountedObjectPointers. */
  7326. template <class ReferenceCountedObjectClass>
  7327. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectClass* object2) throw()
  7328. {
  7329. return object1.getObject() != object2;
  7330. }
  7331. /** Compares two ReferenceCountedObjectPointers. */
  7332. template <class ReferenceCountedObjectClass>
  7333. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7334. {
  7335. return object1.getObject() != object2.getObject();
  7336. }
  7337. /** Compares two ReferenceCountedObjectPointers. */
  7338. template <class ReferenceCountedObjectClass>
  7339. bool operator!= (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7340. {
  7341. return object1 != object2.getObject();
  7342. }
  7343. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7344. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  7345. /**
  7346. Represents a dynamically implemented object.
  7347. This class is primarily intended for wrapping scripting language objects,
  7348. but could be used for other purposes.
  7349. An instance of a DynamicObject can be used to store named properties, and
  7350. by subclassing hasMethod() and invokeMethod(), you can give your object
  7351. methods.
  7352. */
  7353. class JUCE_API DynamicObject : public ReferenceCountedObject
  7354. {
  7355. public:
  7356. DynamicObject();
  7357. /** Destructor. */
  7358. virtual ~DynamicObject();
  7359. /** Returns true if the object has a property with this name.
  7360. Note that if the property is actually a method, this will return false.
  7361. */
  7362. virtual bool hasProperty (const Identifier& propertyName) const;
  7363. /** Returns a named property.
  7364. This returns a void if no such property exists.
  7365. */
  7366. virtual const var getProperty (const Identifier& propertyName) const;
  7367. /** Sets a named property. */
  7368. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  7369. /** Removes a named property. */
  7370. virtual void removeProperty (const Identifier& propertyName);
  7371. /** Checks whether this object has the specified method.
  7372. The default implementation of this just checks whether there's a property
  7373. with this name that's actually a method, but this can be overridden for
  7374. building objects with dynamic invocation.
  7375. */
  7376. virtual bool hasMethod (const Identifier& methodName) const;
  7377. /** Invokes a named method on this object.
  7378. The default implementation looks up the named property, and if it's a method
  7379. call, then it invokes it.
  7380. This method is virtual to allow more dynamic invocation to used for objects
  7381. where the methods may not already be set as properies.
  7382. */
  7383. virtual const var invokeMethod (const Identifier& methodName,
  7384. const var* parameters,
  7385. int numParameters);
  7386. /** Sets up a method.
  7387. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  7388. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  7389. the code easier to read,
  7390. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  7391. @code
  7392. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  7393. @endcode
  7394. */
  7395. void setMethod (const Identifier& methodName,
  7396. var::MethodFunction methodFunction);
  7397. /** Removes all properties and methods from the object. */
  7398. void clear();
  7399. private:
  7400. NamedValueSet properties;
  7401. JUCE_LEAK_DETECTOR (DynamicObject);
  7402. };
  7403. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  7404. /*** End of inlined file: juce_DynamicObject.h ***/
  7405. #endif
  7406. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  7407. #endif
  7408. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7409. #endif
  7410. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  7411. #endif
  7412. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  7413. /*** Start of inlined file: juce_OwnedArray.h ***/
  7414. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  7415. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  7416. /** An array designed for holding objects.
  7417. This holds a list of pointers to objects, and will automatically
  7418. delete the objects when they are removed from the array, or when the
  7419. array is itself deleted.
  7420. Declare it in the form: OwnedArray<MyObjectClass>
  7421. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  7422. After adding objects, they are 'owned' by the array and will be deleted when
  7423. removed or replaced.
  7424. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7425. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7426. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  7427. */
  7428. template <class ObjectClass,
  7429. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7430. class OwnedArray
  7431. {
  7432. public:
  7433. /** Creates an empty array. */
  7434. OwnedArray() throw()
  7435. : numUsed (0)
  7436. {
  7437. }
  7438. /** Deletes the array and also deletes any objects inside it.
  7439. To get rid of the array without deleting its objects, use its
  7440. clear (false) method before deleting it.
  7441. */
  7442. ~OwnedArray()
  7443. {
  7444. clear (true);
  7445. }
  7446. /** Clears the array, optionally deleting the objects inside it first. */
  7447. void clear (const bool deleteObjects = true)
  7448. {
  7449. const ScopedLockType lock (getLock());
  7450. if (deleteObjects)
  7451. {
  7452. while (numUsed > 0)
  7453. delete data.elements [--numUsed];
  7454. }
  7455. data.setAllocatedSize (0);
  7456. numUsed = 0;
  7457. }
  7458. /** Returns the number of items currently in the array.
  7459. @see operator[]
  7460. */
  7461. inline int size() const throw()
  7462. {
  7463. return numUsed;
  7464. }
  7465. /** Returns a pointer to the object at this index in the array.
  7466. If the index is out-of-range, this will return a null pointer, (and
  7467. it could be null anyway, because it's ok for the array to hold null
  7468. pointers as well as objects).
  7469. @see getUnchecked
  7470. */
  7471. inline ObjectClass* operator[] (const int index) const throw()
  7472. {
  7473. const ScopedLockType lock (getLock());
  7474. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  7475. : static_cast <ObjectClass*> (0);
  7476. }
  7477. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7478. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7479. it can be used when you're sure the index if always going to be legal.
  7480. */
  7481. inline ObjectClass* getUnchecked (const int index) const throw()
  7482. {
  7483. const ScopedLockType lock (getLock());
  7484. jassert (isPositiveAndBelow (index, numUsed));
  7485. return data.elements [index];
  7486. }
  7487. /** Returns a pointer to the first object in the array.
  7488. This will return a null pointer if the array's empty.
  7489. @see getLast
  7490. */
  7491. inline ObjectClass* getFirst() const throw()
  7492. {
  7493. const ScopedLockType lock (getLock());
  7494. return numUsed > 0 ? data.elements [0]
  7495. : static_cast <ObjectClass*> (0);
  7496. }
  7497. /** Returns a pointer to the last object in the array.
  7498. This will return a null pointer if the array's empty.
  7499. @see getFirst
  7500. */
  7501. inline ObjectClass* getLast() const throw()
  7502. {
  7503. const ScopedLockType lock (getLock());
  7504. return numUsed > 0 ? data.elements [numUsed - 1]
  7505. : static_cast <ObjectClass*> (0);
  7506. }
  7507. /** Returns a pointer to the actual array data.
  7508. This pointer will only be valid until the next time a non-const method
  7509. is called on the array.
  7510. */
  7511. inline ObjectClass** getRawDataPointer() throw()
  7512. {
  7513. return data.elements;
  7514. }
  7515. /** Finds the index of an object which might be in the array.
  7516. @param objectToLookFor the object to look for
  7517. @returns the index at which the object was found, or -1 if it's not found
  7518. */
  7519. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7520. {
  7521. const ScopedLockType lock (getLock());
  7522. ObjectClass* const* e = data.elements.getData();
  7523. ObjectClass* const* const end = e + numUsed;
  7524. for (; e != end; ++e)
  7525. if (objectToLookFor == *e)
  7526. return static_cast <int> (e - data.elements.getData());
  7527. return -1;
  7528. }
  7529. /** Returns true if the array contains a specified object.
  7530. @param objectToLookFor the object to look for
  7531. @returns true if the object is in the array
  7532. */
  7533. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7534. {
  7535. const ScopedLockType lock (getLock());
  7536. ObjectClass* const* e = data.elements.getData();
  7537. ObjectClass* const* const end = e + numUsed;
  7538. for (; e != end; ++e)
  7539. if (objectToLookFor == *e)
  7540. return true;
  7541. return false;
  7542. }
  7543. /** Appends a new object to the end of the array.
  7544. Note that the this object will be deleted by the OwnedArray when it
  7545. is removed, so be careful not to delete it somewhere else.
  7546. Also be careful not to add the same object to the array more than once,
  7547. as this will obviously cause deletion of dangling pointers.
  7548. @param newObject the new object to add to the array
  7549. @see set, insert, addIfNotAlreadyThere, addSorted
  7550. */
  7551. void add (const ObjectClass* const newObject) throw()
  7552. {
  7553. const ScopedLockType lock (getLock());
  7554. data.ensureAllocatedSize (numUsed + 1);
  7555. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7556. }
  7557. /** Inserts a new object into the array at the given index.
  7558. Note that the this object will be deleted by the OwnedArray when it
  7559. is removed, so be careful not to delete it somewhere else.
  7560. If the index is less than 0 or greater than the size of the array, the
  7561. element will be added to the end of the array.
  7562. Otherwise, it will be inserted into the array, moving all the later elements
  7563. along to make room.
  7564. Be careful not to add the same object to the array more than once,
  7565. as this will obviously cause deletion of dangling pointers.
  7566. @param indexToInsertAt the index at which the new element should be inserted
  7567. @param newObject the new object to add to the array
  7568. @see add, addSorted, addIfNotAlreadyThere, set
  7569. */
  7570. void insert (int indexToInsertAt,
  7571. const ObjectClass* const newObject) throw()
  7572. {
  7573. if (indexToInsertAt >= 0)
  7574. {
  7575. const ScopedLockType lock (getLock());
  7576. if (indexToInsertAt > numUsed)
  7577. indexToInsertAt = numUsed;
  7578. data.ensureAllocatedSize (numUsed + 1);
  7579. ObjectClass** const e = data.elements + indexToInsertAt;
  7580. const int numToMove = numUsed - indexToInsertAt;
  7581. if (numToMove > 0)
  7582. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7583. *e = const_cast <ObjectClass*> (newObject);
  7584. ++numUsed;
  7585. }
  7586. else
  7587. {
  7588. add (newObject);
  7589. }
  7590. }
  7591. /** Appends a new object at the end of the array as long as the array doesn't
  7592. already contain it.
  7593. If the array already contains a matching object, nothing will be done.
  7594. @param newObject the new object to add to the array
  7595. */
  7596. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  7597. {
  7598. const ScopedLockType lock (getLock());
  7599. if (! contains (newObject))
  7600. add (newObject);
  7601. }
  7602. /** Replaces an object in the array with a different one.
  7603. If the index is less than zero, this method does nothing.
  7604. If the index is beyond the end of the array, the new object is added to the end of the array.
  7605. Be careful not to add the same object to the array more than once,
  7606. as this will obviously cause deletion of dangling pointers.
  7607. @param indexToChange the index whose value you want to change
  7608. @param newObject the new value to set for this index.
  7609. @param deleteOldElement whether to delete the object that's being replaced with the new one
  7610. @see add, insert, remove
  7611. */
  7612. void set (const int indexToChange,
  7613. const ObjectClass* const newObject,
  7614. const bool deleteOldElement = true)
  7615. {
  7616. if (indexToChange >= 0)
  7617. {
  7618. ObjectClass* toDelete = 0;
  7619. {
  7620. const ScopedLockType lock (getLock());
  7621. if (indexToChange < numUsed)
  7622. {
  7623. if (deleteOldElement)
  7624. {
  7625. toDelete = data.elements [indexToChange];
  7626. if (toDelete == newObject)
  7627. toDelete = 0;
  7628. }
  7629. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  7630. }
  7631. else
  7632. {
  7633. data.ensureAllocatedSize (numUsed + 1);
  7634. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7635. }
  7636. }
  7637. delete toDelete; // don't want to use a ScopedPointer here because if the
  7638. // object has a private destructor, both OwnedArray and
  7639. // ScopedPointer would need to be friend classes..
  7640. }
  7641. else
  7642. {
  7643. jassertfalse; // you're trying to set an object at a negative index, which doesn't have
  7644. // any effect - but since the object is not being added, it may be leaking..
  7645. }
  7646. }
  7647. /** Adds elements from another array to the end of this array.
  7648. @param arrayToAddFrom the array from which to copy the elements
  7649. @param startIndex the first element of the other array to start copying from
  7650. @param numElementsToAdd how many elements to add from the other array. If this
  7651. value is negative or greater than the number of available elements,
  7652. all available elements will be copied.
  7653. @see add
  7654. */
  7655. template <class OtherArrayType>
  7656. void addArray (const OtherArrayType& arrayToAddFrom,
  7657. int startIndex = 0,
  7658. int numElementsToAdd = -1)
  7659. {
  7660. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7661. const ScopedLockType lock2 (getLock());
  7662. if (startIndex < 0)
  7663. {
  7664. jassertfalse;
  7665. startIndex = 0;
  7666. }
  7667. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7668. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7669. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7670. while (--numElementsToAdd >= 0)
  7671. {
  7672. data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++);
  7673. ++numUsed;
  7674. }
  7675. }
  7676. /** Adds copies of the elements in another array to the end of this array.
  7677. The other array must be either an OwnedArray of a compatible type of object, or an Array
  7678. containing pointers to the same kind of object. The objects involved must provide
  7679. a copy constructor, and this will be used to create new copies of each element, and
  7680. add them to this array.
  7681. @param arrayToAddFrom the array from which to copy the elements
  7682. @param startIndex the first element of the other array to start copying from
  7683. @param numElementsToAdd how many elements to add from the other array. If this
  7684. value is negative or greater than the number of available elements,
  7685. all available elements will be copied.
  7686. @see add
  7687. */
  7688. template <class OtherArrayType>
  7689. void addCopiesOf (const OtherArrayType& arrayToAddFrom,
  7690. int startIndex = 0,
  7691. int numElementsToAdd = -1)
  7692. {
  7693. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7694. const ScopedLockType lock2 (getLock());
  7695. if (startIndex < 0)
  7696. {
  7697. jassertfalse;
  7698. startIndex = 0;
  7699. }
  7700. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7701. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7702. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7703. while (--numElementsToAdd >= 0)
  7704. {
  7705. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  7706. ++numUsed;
  7707. }
  7708. }
  7709. /** Inserts a new object into the array assuming that the array is sorted.
  7710. This will use a comparator to find the position at which the new object
  7711. should go. If the array isn't sorted, the behaviour of this
  7712. method will be unpredictable.
  7713. @param comparator the comparator to use to compare the elements - see the sort method
  7714. for details about this object's structure
  7715. @param newObject the new object to insert to the array
  7716. @see add, sort, indexOfSorted
  7717. */
  7718. template <class ElementComparator>
  7719. void addSorted (ElementComparator& comparator,
  7720. ObjectClass* const newObject) throw()
  7721. {
  7722. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7723. // avoids getting warning messages about the parameter being unused
  7724. const ScopedLockType lock (getLock());
  7725. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  7726. }
  7727. /** Finds the index of an object in the array, assuming that the array is sorted.
  7728. This will use a comparator to do a binary-chop to find the index of the given
  7729. element, if it exists. If the array isn't sorted, the behaviour of this
  7730. method will be unpredictable.
  7731. @param comparator the comparator to use to compare the elements - see the sort()
  7732. method for details about the form this object should take
  7733. @param objectToLookFor the object to search for
  7734. @returns the index of the element, or -1 if it's not found
  7735. @see addSorted, sort
  7736. */
  7737. template <class ElementComparator>
  7738. int indexOfSorted (ElementComparator& comparator,
  7739. const ObjectClass* const objectToLookFor) const throw()
  7740. {
  7741. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7742. // avoids getting warning messages about the parameter being unused
  7743. const ScopedLockType lock (getLock());
  7744. int start = 0;
  7745. int end = numUsed;
  7746. for (;;)
  7747. {
  7748. if (start >= end)
  7749. {
  7750. return -1;
  7751. }
  7752. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  7753. {
  7754. return start;
  7755. }
  7756. else
  7757. {
  7758. const int halfway = (start + end) >> 1;
  7759. if (halfway == start)
  7760. return -1;
  7761. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  7762. start = halfway;
  7763. else
  7764. end = halfway;
  7765. }
  7766. }
  7767. }
  7768. /** Removes an object from the array.
  7769. This will remove the object at a given index (optionally also
  7770. deleting it) and move back all the subsequent objects to close the gap.
  7771. If the index passed in is out-of-range, nothing will happen.
  7772. @param indexToRemove the index of the element to remove
  7773. @param deleteObject whether to delete the object that is removed
  7774. @see removeObject, removeRange
  7775. */
  7776. void remove (const int indexToRemove,
  7777. const bool deleteObject = true)
  7778. {
  7779. ObjectClass* toDelete = 0;
  7780. {
  7781. const ScopedLockType lock (getLock());
  7782. if (isPositiveAndBelow (indexToRemove, numUsed))
  7783. {
  7784. ObjectClass** const e = data.elements + indexToRemove;
  7785. if (deleteObject)
  7786. toDelete = *e;
  7787. --numUsed;
  7788. const int numToShift = numUsed - indexToRemove;
  7789. if (numToShift > 0)
  7790. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  7791. }
  7792. }
  7793. delete toDelete; // don't want to use a ScopedPointer here because if the
  7794. // object has a private destructor, both OwnedArray and
  7795. // ScopedPointer would need to be friend classes..
  7796. if ((numUsed << 1) < data.numAllocated)
  7797. minimiseStorageOverheads();
  7798. }
  7799. /** Removes and returns an object from the array without deleting it.
  7800. This will remove the object at a given index and return it, moving back all
  7801. the subsequent objects to close the gap. If the index passed in is out-of-range,
  7802. nothing will happen.
  7803. @param indexToRemove the index of the element to remove
  7804. @see remove, removeObject, removeRange
  7805. */
  7806. ObjectClass* removeAndReturn (const int indexToRemove)
  7807. {
  7808. ObjectClass* removedItem = 0;
  7809. const ScopedLockType lock (getLock());
  7810. if (isPositiveAndBelow (indexToRemove, numUsed))
  7811. {
  7812. ObjectClass** const e = data.elements + indexToRemove;
  7813. removedItem = *e;
  7814. --numUsed;
  7815. const int numToShift = numUsed - indexToRemove;
  7816. if (numToShift > 0)
  7817. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  7818. if ((numUsed << 1) < data.numAllocated)
  7819. minimiseStorageOverheads();
  7820. }
  7821. return removedItem;
  7822. }
  7823. /** Removes a specified object from the array.
  7824. If the item isn't found, no action is taken.
  7825. @param objectToRemove the object to try to remove
  7826. @param deleteObject whether to delete the object (if it's found)
  7827. @see remove, removeRange
  7828. */
  7829. void removeObject (const ObjectClass* const objectToRemove,
  7830. const bool deleteObject = true)
  7831. {
  7832. const ScopedLockType lock (getLock());
  7833. ObjectClass** const e = data.elements.getData();
  7834. for (int i = 0; i < numUsed; ++i)
  7835. {
  7836. if (objectToRemove == e[i])
  7837. {
  7838. remove (i, deleteObject);
  7839. break;
  7840. }
  7841. }
  7842. }
  7843. /** Removes a range of objects from the array.
  7844. This will remove a set of objects, starting from the given index,
  7845. and move any subsequent elements down to close the gap.
  7846. If the range extends beyond the bounds of the array, it will
  7847. be safely clipped to the size of the array.
  7848. @param startIndex the index of the first object to remove
  7849. @param numberToRemove how many objects should be removed
  7850. @param deleteObjects whether to delete the objects that get removed
  7851. @see remove, removeObject
  7852. */
  7853. void removeRange (int startIndex,
  7854. const int numberToRemove,
  7855. const bool deleteObjects = true)
  7856. {
  7857. const ScopedLockType lock (getLock());
  7858. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  7859. startIndex = jlimit (0, numUsed, startIndex);
  7860. if (endIndex > startIndex)
  7861. {
  7862. if (deleteObjects)
  7863. {
  7864. for (int i = startIndex; i < endIndex; ++i)
  7865. {
  7866. delete data.elements [i];
  7867. data.elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  7868. }
  7869. }
  7870. const int rangeSize = endIndex - startIndex;
  7871. ObjectClass** e = data.elements + startIndex;
  7872. int numToShift = numUsed - endIndex;
  7873. numUsed -= rangeSize;
  7874. while (--numToShift >= 0)
  7875. {
  7876. *e = e [rangeSize];
  7877. ++e;
  7878. }
  7879. if ((numUsed << 1) < data.numAllocated)
  7880. minimiseStorageOverheads();
  7881. }
  7882. }
  7883. /** Removes the last n objects from the array.
  7884. @param howManyToRemove how many objects to remove from the end of the array
  7885. @param deleteObjects whether to also delete the objects that are removed
  7886. @see remove, removeObject, removeRange
  7887. */
  7888. void removeLast (int howManyToRemove = 1,
  7889. const bool deleteObjects = true)
  7890. {
  7891. const ScopedLockType lock (getLock());
  7892. if (howManyToRemove >= numUsed)
  7893. clear (deleteObjects);
  7894. else
  7895. removeRange (numUsed - howManyToRemove, howManyToRemove, deleteObjects);
  7896. }
  7897. /** Swaps a pair of objects in the array.
  7898. If either of the indexes passed in is out-of-range, nothing will happen,
  7899. otherwise the two objects at these positions will be exchanged.
  7900. */
  7901. void swap (const int index1,
  7902. const int index2) throw()
  7903. {
  7904. const ScopedLockType lock (getLock());
  7905. if (isPositiveAndBelow (index1, numUsed)
  7906. && isPositiveAndBelow (index2, numUsed))
  7907. {
  7908. swapVariables (data.elements [index1],
  7909. data.elements [index2]);
  7910. }
  7911. }
  7912. /** Moves one of the objects to a different position.
  7913. This will move the object to a specified index, shuffling along
  7914. any intervening elements as required.
  7915. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  7916. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  7917. @param currentIndex the index of the object to be moved. If this isn't a
  7918. valid index, then nothing will be done
  7919. @param newIndex the index at which you'd like this object to end up. If this
  7920. is less than zero, it will be moved to the end of the array
  7921. */
  7922. void move (const int currentIndex,
  7923. int newIndex) throw()
  7924. {
  7925. if (currentIndex != newIndex)
  7926. {
  7927. const ScopedLockType lock (getLock());
  7928. if (isPositiveAndBelow (currentIndex, numUsed))
  7929. {
  7930. if (! isPositiveAndBelow (newIndex, numUsed))
  7931. newIndex = numUsed - 1;
  7932. ObjectClass* const value = data.elements [currentIndex];
  7933. if (newIndex > currentIndex)
  7934. {
  7935. memmove (data.elements + currentIndex,
  7936. data.elements + currentIndex + 1,
  7937. (newIndex - currentIndex) * sizeof (ObjectClass*));
  7938. }
  7939. else
  7940. {
  7941. memmove (data.elements + newIndex + 1,
  7942. data.elements + newIndex,
  7943. (currentIndex - newIndex) * sizeof (ObjectClass*));
  7944. }
  7945. data.elements [newIndex] = value;
  7946. }
  7947. }
  7948. }
  7949. /** This swaps the contents of this array with those of another array.
  7950. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  7951. because it just swaps their internal pointers.
  7952. */
  7953. void swapWithArray (OwnedArray& otherArray) throw()
  7954. {
  7955. const ScopedLockType lock1 (getLock());
  7956. const ScopedLockType lock2 (otherArray.getLock());
  7957. data.swapWith (otherArray.data);
  7958. swapVariables (numUsed, otherArray.numUsed);
  7959. }
  7960. /** Reduces the amount of storage being used by the array.
  7961. Arrays typically allocate slightly more storage than they need, and after
  7962. removing elements, they may have quite a lot of unused space allocated.
  7963. This method will reduce the amount of allocated storage to a minimum.
  7964. */
  7965. void minimiseStorageOverheads() throw()
  7966. {
  7967. const ScopedLockType lock (getLock());
  7968. data.shrinkToNoMoreThan (numUsed);
  7969. }
  7970. /** Increases the array's internal storage to hold a minimum number of elements.
  7971. Calling this before adding a large known number of elements means that
  7972. the array won't have to keep dynamically resizing itself as the elements
  7973. are added, and it'll therefore be more efficient.
  7974. */
  7975. void ensureStorageAllocated (const int minNumElements) throw()
  7976. {
  7977. const ScopedLockType lock (getLock());
  7978. data.ensureAllocatedSize (minNumElements);
  7979. }
  7980. /** Sorts the elements in the array.
  7981. This will use a comparator object to sort the elements into order. The object
  7982. passed must have a method of the form:
  7983. @code
  7984. int compareElements (ElementType first, ElementType second);
  7985. @endcode
  7986. ..and this method must return:
  7987. - a value of < 0 if the first comes before the second
  7988. - a value of 0 if the two objects are equivalent
  7989. - a value of > 0 if the second comes before the first
  7990. To improve performance, the compareElements() method can be declared as static or const.
  7991. @param comparator the comparator to use for comparing elements.
  7992. @param retainOrderOfEquivalentItems if this is true, then items
  7993. which the comparator says are equivalent will be
  7994. kept in the order in which they currently appear
  7995. in the array. This is slower to perform, but may
  7996. be important in some cases. If it's false, a faster
  7997. algorithm is used, but equivalent elements may be
  7998. rearranged.
  7999. @see sortArray, indexOfSorted
  8000. */
  8001. template <class ElementComparator>
  8002. void sort (ElementComparator& comparator,
  8003. const bool retainOrderOfEquivalentItems = false) const throw()
  8004. {
  8005. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8006. // avoids getting warning messages about the parameter being unused
  8007. const ScopedLockType lock (getLock());
  8008. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  8009. }
  8010. /** Returns the CriticalSection that locks this array.
  8011. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8012. an object of ScopedLockType as an RAII lock for it.
  8013. */
  8014. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  8015. /** Returns the type of scoped lock to use for locking this array */
  8016. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8017. private:
  8018. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  8019. int numUsed;
  8020. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OwnedArray);
  8021. };
  8022. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  8023. /*** End of inlined file: juce_OwnedArray.h ***/
  8024. #endif
  8025. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8026. /*** Start of inlined file: juce_PropertySet.h ***/
  8027. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8028. #define __JUCE_PROPERTYSET_JUCEHEADER__
  8029. /*** Start of inlined file: juce_StringPairArray.h ***/
  8030. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8031. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8032. /*** Start of inlined file: juce_StringArray.h ***/
  8033. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  8034. #define __JUCE_STRINGARRAY_JUCEHEADER__
  8035. /**
  8036. A special array for holding a list of strings.
  8037. @see String, StringPairArray
  8038. */
  8039. class JUCE_API StringArray
  8040. {
  8041. public:
  8042. /** Creates an empty string array */
  8043. StringArray() throw();
  8044. /** Creates a copy of another string array */
  8045. StringArray (const StringArray& other);
  8046. /** Creates an array containing a single string. */
  8047. explicit StringArray (const String& firstValue);
  8048. /** Creates a copy of an array of string literals.
  8049. @param strings an array of strings to add. Null pointers in the array will be
  8050. treated as empty strings
  8051. @param numberOfStrings how many items there are in the array
  8052. */
  8053. StringArray (const char* const* strings, int numberOfStrings);
  8054. /** Creates a copy of a null-terminated array of string literals.
  8055. Each item from the array passed-in is added, until it encounters a null pointer,
  8056. at which point it stops.
  8057. */
  8058. explicit StringArray (const char* const* strings);
  8059. /** Creates a copy of a null-terminated array of string literals.
  8060. Each item from the array passed-in is added, until it encounters a null pointer,
  8061. at which point it stops.
  8062. */
  8063. explicit StringArray (const wchar_t* const* strings);
  8064. /** Creates a copy of an array of string literals.
  8065. @param strings an array of strings to add. Null pointers in the array will be
  8066. treated as empty strings
  8067. @param numberOfStrings how many items there are in the array
  8068. */
  8069. StringArray (const wchar_t* const* strings, int numberOfStrings);
  8070. /** Destructor. */
  8071. ~StringArray();
  8072. /** Copies the contents of another string array into this one */
  8073. StringArray& operator= (const StringArray& other);
  8074. /** Compares two arrays.
  8075. Comparisons are case-sensitive.
  8076. @returns true only if the other array contains exactly the same strings in the same order
  8077. */
  8078. bool operator== (const StringArray& other) const throw();
  8079. /** Compares two arrays.
  8080. Comparisons are case-sensitive.
  8081. @returns false if the other array contains exactly the same strings in the same order
  8082. */
  8083. bool operator!= (const StringArray& other) const throw();
  8084. /** Returns the number of strings in the array */
  8085. inline int size() const throw() { return strings.size(); };
  8086. /** Returns one of the strings from the array.
  8087. If the index is out-of-range, an empty string is returned.
  8088. Obviously the reference returned shouldn't be stored for later use, as the
  8089. string it refers to may disappear when the array changes.
  8090. */
  8091. const String& operator[] (int index) const throw();
  8092. /** Returns a reference to one of the strings in the array.
  8093. This lets you modify a string in-place in the array, but you must be sure that
  8094. the index is in-range.
  8095. */
  8096. String& getReference (int index) throw();
  8097. /** Searches for a string in the array.
  8098. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8099. @returns true if the string is found inside the array
  8100. */
  8101. bool contains (const String& stringToLookFor,
  8102. bool ignoreCase = false) const;
  8103. /** Searches for a string in the array.
  8104. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8105. @param stringToLookFor the string to try to find
  8106. @param ignoreCase whether the comparison should be case-insensitive
  8107. @param startIndex the first index to start searching from
  8108. @returns the index of the first occurrence of the string in this array,
  8109. or -1 if it isn't found.
  8110. */
  8111. int indexOf (const String& stringToLookFor,
  8112. bool ignoreCase = false,
  8113. int startIndex = 0) const;
  8114. /** Appends a string at the end of the array. */
  8115. void add (const String& stringToAdd);
  8116. /** Inserts a string into the array.
  8117. This will insert a string into the array at the given index, moving
  8118. up the other elements to make room for it.
  8119. If the index is less than zero or greater than the size of the array,
  8120. the new string will be added to the end of the array.
  8121. */
  8122. void insert (int index, const String& stringToAdd);
  8123. /** Adds a string to the array as long as it's not already in there.
  8124. The search can optionally be case-insensitive.
  8125. */
  8126. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  8127. /** Replaces one of the strings in the array with another one.
  8128. If the index is higher than the array's size, the new string will be
  8129. added to the end of the array; if it's less than zero nothing happens.
  8130. */
  8131. void set (int index, const String& newString);
  8132. /** Appends some strings from another array to the end of this one.
  8133. @param other the array to add
  8134. @param startIndex the first element of the other array to add
  8135. @param numElementsToAdd the maximum number of elements to add (if this is
  8136. less than zero, they are all added)
  8137. */
  8138. void addArray (const StringArray& other,
  8139. int startIndex = 0,
  8140. int numElementsToAdd = -1);
  8141. /** Breaks up a string into tokens and adds them to this array.
  8142. This will tokenise the given string using whitespace characters as the
  8143. token delimiters, and will add these tokens to the end of the array.
  8144. @returns the number of tokens added
  8145. */
  8146. int addTokens (const String& stringToTokenise,
  8147. bool preserveQuotedStrings);
  8148. /** Breaks up a string into tokens and adds them to this array.
  8149. This will tokenise the given string (using the string passed in to define the
  8150. token delimiters), and will add these tokens to the end of the array.
  8151. @param stringToTokenise the string to tokenise
  8152. @param breakCharacters a string of characters, any of which will be considered
  8153. to be a token delimiter.
  8154. @param quoteCharacters if this string isn't empty, it defines a set of characters
  8155. which are treated as quotes. Any text occurring
  8156. between quotes is not broken up into tokens.
  8157. @returns the number of tokens added
  8158. */
  8159. int addTokens (const String& stringToTokenise,
  8160. const String& breakCharacters,
  8161. const String& quoteCharacters);
  8162. /** Breaks up a string into lines and adds them to this array.
  8163. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  8164. to the array. Line-break characters are omitted from the strings that are added to
  8165. the array.
  8166. */
  8167. int addLines (const String& stringToBreakUp);
  8168. /** Removes all elements from the array. */
  8169. void clear();
  8170. /** Removes a string from the array.
  8171. If the index is out-of-range, no action will be taken.
  8172. */
  8173. void remove (int index);
  8174. /** Finds a string in the array and removes it.
  8175. This will remove the first occurrence of the given string from the array. The
  8176. comparison may be case-insensitive depending on the ignoreCase parameter.
  8177. */
  8178. void removeString (const String& stringToRemove,
  8179. bool ignoreCase = false);
  8180. /** Removes a range of elements from the array.
  8181. This will remove a set of elements, starting from the given index,
  8182. and move subsequent elements down to close the gap.
  8183. If the range extends beyond the bounds of the array, it will
  8184. be safely clipped to the size of the array.
  8185. @param startIndex the index of the first element to remove
  8186. @param numberToRemove how many elements should be removed
  8187. */
  8188. void removeRange (int startIndex, int numberToRemove);
  8189. /** Removes any duplicated elements from the array.
  8190. If any string appears in the array more than once, only the first occurrence of
  8191. it will be retained.
  8192. @param ignoreCase whether to use a case-insensitive comparison
  8193. */
  8194. void removeDuplicates (bool ignoreCase);
  8195. /** Removes empty strings from the array.
  8196. @param removeWhitespaceStrings if true, strings that only contain whitespace
  8197. characters will also be removed
  8198. */
  8199. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  8200. /** Moves one of the strings to a different position.
  8201. This will move the string to a specified index, shuffling along
  8202. any intervening elements as required.
  8203. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8204. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8205. @param currentIndex the index of the value to be moved. If this isn't a
  8206. valid index, then nothing will be done
  8207. @param newIndex the index at which you'd like this value to end up. If this
  8208. is less than zero, the value will be moved to the end
  8209. of the array
  8210. */
  8211. void move (int currentIndex, int newIndex) throw();
  8212. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  8213. void trim();
  8214. /** Adds numbers to the strings in the array, to make each string unique.
  8215. This will add numbers to the ends of groups of similar strings.
  8216. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  8217. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  8218. @param appendNumberToFirstInstance whether the first of a group of similar strings
  8219. also has a number appended to it.
  8220. @param preNumberString when adding a number, this string is added before the number.
  8221. If you pass 0, a default string will be used, which adds
  8222. brackets around the number.
  8223. @param postNumberString this string is appended after any numbers that are added.
  8224. If you pass 0, a default string will be used, which adds
  8225. brackets around the number.
  8226. */
  8227. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  8228. bool appendNumberToFirstInstance,
  8229. CharPointer_UTF8 preNumberString = CharPointer_UTF8 (0),
  8230. CharPointer_UTF8 postNumberString = CharPointer_UTF8 (0));
  8231. /** Joins the strings in the array together into one string.
  8232. This will join a range of elements from the array into a string, separating
  8233. them with a given string.
  8234. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  8235. @param separatorString the string to insert between all the strings
  8236. @param startIndex the first element to join
  8237. @param numberOfElements how many elements to join together. If this is less
  8238. than zero, all available elements will be used.
  8239. */
  8240. const String joinIntoString (const String& separatorString,
  8241. int startIndex = 0,
  8242. int numberOfElements = -1) const;
  8243. /** Sorts the array into alphabetical order.
  8244. @param ignoreCase if true, the comparisons used will be case-sensitive.
  8245. */
  8246. void sort (bool ignoreCase);
  8247. /** Reduces the amount of storage being used by the array.
  8248. Arrays typically allocate slightly more storage than they need, and after
  8249. removing elements, they may have quite a lot of unused space allocated.
  8250. This method will reduce the amount of allocated storage to a minimum.
  8251. */
  8252. void minimiseStorageOverheads();
  8253. private:
  8254. Array <String> strings;
  8255. JUCE_LEAK_DETECTOR (StringArray);
  8256. };
  8257. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  8258. /*** End of inlined file: juce_StringArray.h ***/
  8259. /**
  8260. A container for holding a set of strings which are keyed by another string.
  8261. @see StringArray
  8262. */
  8263. class JUCE_API StringPairArray
  8264. {
  8265. public:
  8266. /** Creates an empty array */
  8267. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  8268. /** Creates a copy of another array */
  8269. StringPairArray (const StringPairArray& other);
  8270. /** Destructor. */
  8271. ~StringPairArray();
  8272. /** Copies the contents of another string array into this one */
  8273. StringPairArray& operator= (const StringPairArray& other);
  8274. /** Compares two arrays.
  8275. Comparisons are case-sensitive.
  8276. @returns true only if the other array contains exactly the same strings with the same keys
  8277. */
  8278. bool operator== (const StringPairArray& other) const;
  8279. /** Compares two arrays.
  8280. Comparisons are case-sensitive.
  8281. @returns false if the other array contains exactly the same strings with the same keys
  8282. */
  8283. bool operator!= (const StringPairArray& other) const;
  8284. /** Finds the value corresponding to a key string.
  8285. If no such key is found, this will just return an empty string. To check whether
  8286. a given key actually exists (because it might actually be paired with an empty string), use
  8287. the getAllKeys() method to obtain a list.
  8288. Obviously the reference returned shouldn't be stored for later use, as the
  8289. string it refers to may disappear when the array changes.
  8290. @see getValue
  8291. */
  8292. const String& operator[] (const String& key) const;
  8293. /** Finds the value corresponding to a key string.
  8294. If no such key is found, this will just return the value provided as a default.
  8295. @see operator[]
  8296. */
  8297. const String getValue (const String& key, const String& defaultReturnValue) const;
  8298. /** Returns a list of all keys in the array. */
  8299. const StringArray& getAllKeys() const throw() { return keys; }
  8300. /** Returns a list of all values in the array. */
  8301. const StringArray& getAllValues() const throw() { return values; }
  8302. /** Returns the number of strings in the array */
  8303. inline int size() const throw() { return keys.size(); };
  8304. /** Adds or amends a key/value pair.
  8305. If a value already exists with this key, its value will be overwritten,
  8306. otherwise the key/value pair will be added to the array.
  8307. */
  8308. void set (const String& key, const String& value);
  8309. /** Adds the items from another array to this one.
  8310. This is equivalent to using set() to add each of the pairs from the other array.
  8311. */
  8312. void addArray (const StringPairArray& other);
  8313. /** Removes all elements from the array. */
  8314. void clear();
  8315. /** Removes a string from the array based on its key.
  8316. If the key isn't found, nothing will happen.
  8317. */
  8318. void remove (const String& key);
  8319. /** Removes a string from the array based on its index.
  8320. If the index is out-of-range, no action will be taken.
  8321. */
  8322. void remove (int index);
  8323. /** Indicates whether to use a case-insensitive search when looking up a key string.
  8324. */
  8325. void setIgnoresCase (bool shouldIgnoreCase);
  8326. /** Returns a descriptive string containing the items.
  8327. This is handy for dumping the contents of an array.
  8328. */
  8329. const String getDescription() const;
  8330. /** Reduces the amount of storage being used by the array.
  8331. Arrays typically allocate slightly more storage than they need, and after
  8332. removing elements, they may have quite a lot of unused space allocated.
  8333. This method will reduce the amount of allocated storage to a minimum.
  8334. */
  8335. void minimiseStorageOverheads();
  8336. private:
  8337. StringArray keys, values;
  8338. bool ignoreCase;
  8339. JUCE_LEAK_DETECTOR (StringPairArray);
  8340. };
  8341. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8342. /*** End of inlined file: juce_StringPairArray.h ***/
  8343. /*** Start of inlined file: juce_XmlElement.h ***/
  8344. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  8345. #define __JUCE_XMLELEMENT_JUCEHEADER__
  8346. /*** Start of inlined file: juce_File.h ***/
  8347. #ifndef __JUCE_FILE_JUCEHEADER__
  8348. #define __JUCE_FILE_JUCEHEADER__
  8349. /*** Start of inlined file: juce_Time.h ***/
  8350. #ifndef __JUCE_TIME_JUCEHEADER__
  8351. #define __JUCE_TIME_JUCEHEADER__
  8352. /*** Start of inlined file: juce_RelativeTime.h ***/
  8353. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  8354. #define __JUCE_RELATIVETIME_JUCEHEADER__
  8355. /** A relative measure of time.
  8356. The time is stored as a number of seconds, at double-precision floating
  8357. point accuracy, and may be positive or negative.
  8358. If you need an absolute time, (i.e. a date + time), see the Time class.
  8359. */
  8360. class JUCE_API RelativeTime
  8361. {
  8362. public:
  8363. /** Creates a RelativeTime.
  8364. @param seconds the number of seconds, which may be +ve or -ve.
  8365. @see milliseconds, minutes, hours, days, weeks
  8366. */
  8367. explicit RelativeTime (double seconds = 0.0) throw();
  8368. /** Copies another relative time. */
  8369. RelativeTime (const RelativeTime& other) throw();
  8370. /** Copies another relative time. */
  8371. RelativeTime& operator= (const RelativeTime& other) throw();
  8372. /** Destructor. */
  8373. ~RelativeTime() throw();
  8374. /** Creates a new RelativeTime object representing a number of milliseconds.
  8375. @see minutes, hours, days, weeks
  8376. */
  8377. static const RelativeTime milliseconds (int milliseconds) throw();
  8378. /** Creates a new RelativeTime object representing a number of milliseconds.
  8379. @see minutes, hours, days, weeks
  8380. */
  8381. static const RelativeTime milliseconds (int64 milliseconds) throw();
  8382. /** Creates a new RelativeTime object representing a number of minutes.
  8383. @see milliseconds, hours, days, weeks
  8384. */
  8385. static const RelativeTime minutes (double numberOfMinutes) throw();
  8386. /** Creates a new RelativeTime object representing a number of hours.
  8387. @see milliseconds, minutes, days, weeks
  8388. */
  8389. static const RelativeTime hours (double numberOfHours) throw();
  8390. /** Creates a new RelativeTime object representing a number of days.
  8391. @see milliseconds, minutes, hours, weeks
  8392. */
  8393. static const RelativeTime days (double numberOfDays) throw();
  8394. /** Creates a new RelativeTime object representing a number of weeks.
  8395. @see milliseconds, minutes, hours, days
  8396. */
  8397. static const RelativeTime weeks (double numberOfWeeks) throw();
  8398. /** Returns the number of milliseconds this time represents.
  8399. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  8400. */
  8401. int64 inMilliseconds() const throw();
  8402. /** Returns the number of seconds this time represents.
  8403. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  8404. */
  8405. double inSeconds() const throw() { return seconds; }
  8406. /** Returns the number of minutes this time represents.
  8407. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  8408. */
  8409. double inMinutes() const throw();
  8410. /** Returns the number of hours this time represents.
  8411. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  8412. */
  8413. double inHours() const throw();
  8414. /** Returns the number of days this time represents.
  8415. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  8416. */
  8417. double inDays() const throw();
  8418. /** Returns the number of weeks this time represents.
  8419. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  8420. */
  8421. double inWeeks() const throw();
  8422. /** Returns a readable textual description of the time.
  8423. The exact format of the string returned will depend on
  8424. the magnitude of the time - e.g.
  8425. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  8426. so that only the two most significant units are printed.
  8427. The returnValueForZeroTime value is the result that is returned if the
  8428. length is zero. Depending on your application you might want to use this
  8429. to return something more relevant like "empty" or "0 secs", etc.
  8430. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  8431. */
  8432. const String getDescription (const String& returnValueForZeroTime = "0") const;
  8433. /** Adds another RelativeTime to this one. */
  8434. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  8435. /** Subtracts another RelativeTime from this one. */
  8436. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  8437. /** Adds a number of seconds to this time. */
  8438. const RelativeTime& operator+= (double secondsToAdd) throw();
  8439. /** Subtracts a number of seconds from this time. */
  8440. const RelativeTime& operator-= (double secondsToSubtract) throw();
  8441. private:
  8442. double seconds;
  8443. };
  8444. /** Compares two RelativeTimes. */
  8445. bool operator== (const RelativeTime& t1, const RelativeTime& t2) throw();
  8446. /** Compares two RelativeTimes. */
  8447. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) throw();
  8448. /** Compares two RelativeTimes. */
  8449. bool operator> (const RelativeTime& t1, const RelativeTime& t2) throw();
  8450. /** Compares two RelativeTimes. */
  8451. bool operator< (const RelativeTime& t1, const RelativeTime& t2) throw();
  8452. /** Compares two RelativeTimes. */
  8453. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) throw();
  8454. /** Compares two RelativeTimes. */
  8455. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) throw();
  8456. /** Adds two RelativeTimes together. */
  8457. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) throw();
  8458. /** Subtracts two RelativeTimes. */
  8459. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) throw();
  8460. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  8461. /*** End of inlined file: juce_RelativeTime.h ***/
  8462. /**
  8463. Holds an absolute date and time.
  8464. Internally, the time is stored at millisecond precision.
  8465. @see RelativeTime
  8466. */
  8467. class JUCE_API Time
  8468. {
  8469. public:
  8470. /** Creates a Time object.
  8471. This default constructor creates a time of 1st January 1970, (which is
  8472. represented internally as 0ms).
  8473. To create a time object representing the current time, use getCurrentTime().
  8474. @see getCurrentTime
  8475. */
  8476. Time() throw();
  8477. /** Creates a time based on a number of milliseconds.
  8478. The internal millisecond count is set to 0 (1st January 1970). To create a
  8479. time object set to the current time, use getCurrentTime().
  8480. @param millisecondsSinceEpoch the number of milliseconds since the unix
  8481. 'epoch' (midnight Jan 1st 1970).
  8482. @see getCurrentTime, currentTimeMillis
  8483. */
  8484. explicit Time (int64 millisecondsSinceEpoch) throw();
  8485. /** Creates a time from a set of date components.
  8486. The timezone is assumed to be whatever the system is using as its locale.
  8487. @param year the year, in 4-digit format, e.g. 2004
  8488. @param month the month, in the range 0 to 11
  8489. @param day the day of the month, in the range 1 to 31
  8490. @param hours hours in 24-hour clock format, 0 to 23
  8491. @param minutes minutes 0 to 59
  8492. @param seconds seconds 0 to 59
  8493. @param milliseconds milliseconds 0 to 999
  8494. @param useLocalTime if true, encode using the current machine's local time; if
  8495. false, it will always work in GMT.
  8496. */
  8497. Time (int year,
  8498. int month,
  8499. int day,
  8500. int hours,
  8501. int minutes,
  8502. int seconds = 0,
  8503. int milliseconds = 0,
  8504. bool useLocalTime = true) throw();
  8505. /** Creates a copy of another Time object. */
  8506. Time (const Time& other) throw();
  8507. /** Destructor. */
  8508. ~Time() throw();
  8509. /** Copies this time from another one. */
  8510. Time& operator= (const Time& other) throw();
  8511. /** Returns a Time object that is set to the current system time.
  8512. @see currentTimeMillis
  8513. */
  8514. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  8515. /** Returns the time as a number of milliseconds.
  8516. @returns the number of milliseconds this Time object represents, since
  8517. midnight jan 1st 1970.
  8518. @see getMilliseconds
  8519. */
  8520. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  8521. /** Returns the year.
  8522. A 4-digit format is used, e.g. 2004.
  8523. */
  8524. int getYear() const throw();
  8525. /** Returns the number of the month.
  8526. The value returned is in the range 0 to 11.
  8527. @see getMonthName
  8528. */
  8529. int getMonth() const throw();
  8530. /** Returns the name of the month.
  8531. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  8532. it'll return the long form, e.g. "January"
  8533. @see getMonth
  8534. */
  8535. const String getMonthName (bool threeLetterVersion) const;
  8536. /** Returns the day of the month.
  8537. The value returned is in the range 1 to 31.
  8538. */
  8539. int getDayOfMonth() const throw();
  8540. /** Returns the number of the day of the week.
  8541. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  8542. */
  8543. int getDayOfWeek() const throw();
  8544. /** Returns the name of the weekday.
  8545. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  8546. false, it'll return the full version, e.g. "Tuesday".
  8547. */
  8548. const String getWeekdayName (bool threeLetterVersion) const;
  8549. /** Returns the number of hours since midnight.
  8550. This is in 24-hour clock format, in the range 0 to 23.
  8551. @see getHoursInAmPmFormat, isAfternoon
  8552. */
  8553. int getHours() const throw();
  8554. /** Returns true if the time is in the afternoon.
  8555. So it returns true for "PM", false for "AM".
  8556. @see getHoursInAmPmFormat, getHours
  8557. */
  8558. bool isAfternoon() const throw();
  8559. /** Returns the hours in 12-hour clock format.
  8560. This will return a value 1 to 12 - use isAfternoon() to find out
  8561. whether this is in the afternoon or morning.
  8562. @see getHours, isAfternoon
  8563. */
  8564. int getHoursInAmPmFormat() const throw();
  8565. /** Returns the number of minutes, 0 to 59. */
  8566. int getMinutes() const throw();
  8567. /** Returns the number of seconds, 0 to 59. */
  8568. int getSeconds() const throw();
  8569. /** Returns the number of milliseconds, 0 to 999.
  8570. Unlike toMilliseconds(), this just returns the position within the
  8571. current second rather than the total number since the epoch.
  8572. @see toMilliseconds
  8573. */
  8574. int getMilliseconds() const throw();
  8575. /** Returns true if the local timezone uses a daylight saving correction. */
  8576. bool isDaylightSavingTime() const throw();
  8577. /** Returns a 3-character string to indicate the local timezone. */
  8578. const String getTimeZone() const throw();
  8579. /** Quick way of getting a string version of a date and time.
  8580. For a more powerful way of formatting the date and time, see the formatted() method.
  8581. @param includeDate whether to include the date in the string
  8582. @param includeTime whether to include the time in the string
  8583. @param includeSeconds if the time is being included, this provides an option not to include
  8584. the seconds in it
  8585. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  8586. hour notation.
  8587. @see formatted
  8588. */
  8589. const String toString (bool includeDate,
  8590. bool includeTime,
  8591. bool includeSeconds = true,
  8592. bool use24HourClock = false) const throw();
  8593. /** Converts this date/time to a string with a user-defined format.
  8594. This uses the C strftime() function to format this time as a string. To save you
  8595. looking it up, these are the escape codes that strftime uses (other codes might
  8596. work on some platforms and not others, but these are the common ones):
  8597. %a is replaced by the locale's abbreviated weekday name.
  8598. %A is replaced by the locale's full weekday name.
  8599. %b is replaced by the locale's abbreviated month name.
  8600. %B is replaced by the locale's full month name.
  8601. %c is replaced by the locale's appropriate date and time representation.
  8602. %d is replaced by the day of the month as a decimal number [01,31].
  8603. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  8604. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  8605. %j is replaced by the day of the year as a decimal number [001,366].
  8606. %m is replaced by the month as a decimal number [01,12].
  8607. %M is replaced by the minute as a decimal number [00,59].
  8608. %p is replaced by the locale's equivalent of either a.m. or p.m.
  8609. %S is replaced by the second as a decimal number [00,61].
  8610. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  8611. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  8612. %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.
  8613. %x is replaced by the locale's appropriate date representation.
  8614. %X is replaced by the locale's appropriate time representation.
  8615. %y is replaced by the year without century as a decimal number [00,99].
  8616. %Y is replaced by the year with century as a decimal number.
  8617. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  8618. %% is replaced by %.
  8619. @see toString
  8620. */
  8621. const String formatted (const String& format) const;
  8622. /** Adds a RelativeTime to this time. */
  8623. Time& operator+= (const RelativeTime& delta);
  8624. /** Subtracts a RelativeTime from this time. */
  8625. Time& operator-= (const RelativeTime& delta);
  8626. /** Tries to set the computer's clock.
  8627. @returns true if this succeeds, although depending on the system, the
  8628. application might not have sufficient privileges to do this.
  8629. */
  8630. bool setSystemTimeToThisTime() const;
  8631. /** Returns the name of a day of the week.
  8632. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  8633. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  8634. false, it'll return the full version, e.g. "Tuesday".
  8635. */
  8636. static const String getWeekdayName (int dayNumber,
  8637. bool threeLetterVersion);
  8638. /** Returns the name of one of the months.
  8639. @param monthNumber the month, 0 to 11
  8640. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  8641. it'll return the long form, e.g. "January"
  8642. */
  8643. static const String getMonthName (int monthNumber,
  8644. bool threeLetterVersion);
  8645. // Static methods for getting system timers directly..
  8646. /** Returns the current system time.
  8647. Returns the number of milliseconds since midnight jan 1st 1970.
  8648. Should be accurate to within a few millisecs, depending on platform,
  8649. hardware, etc.
  8650. */
  8651. static int64 currentTimeMillis() throw();
  8652. /** Returns the number of millisecs since a fixed event (usually system startup).
  8653. This returns a monotonically increasing value which it unaffected by changes to the
  8654. system clock. It should be accurate to within a few millisecs, depending on platform,
  8655. hardware, etc.
  8656. @see getApproximateMillisecondCounter
  8657. */
  8658. static uint32 getMillisecondCounter() throw();
  8659. /** Returns the number of millisecs since a fixed event (usually system startup).
  8660. This has the same function as getMillisecondCounter(), but returns a more accurate
  8661. value, using a higher-resolution timer if one is available.
  8662. @see getMillisecondCounter
  8663. */
  8664. static double getMillisecondCounterHiRes() throw();
  8665. /** Waits until the getMillisecondCounter() reaches a given value.
  8666. This will make the thread sleep as efficiently as it can while it's waiting.
  8667. */
  8668. static void waitForMillisecondCounter (uint32 targetTime) throw();
  8669. /** Less-accurate but faster version of getMillisecondCounter().
  8670. This will return the last value that getMillisecondCounter() returned, so doesn't
  8671. need to make a system call, but is less accurate - it shouldn't be more than
  8672. 100ms away from the correct time, though, so is still accurate enough for a
  8673. lot of purposes.
  8674. @see getMillisecondCounter
  8675. */
  8676. static uint32 getApproximateMillisecondCounter() throw();
  8677. // High-resolution timers..
  8678. /** Returns the current high-resolution counter's tick-count.
  8679. This is a similar idea to getMillisecondCounter(), but with a higher
  8680. resolution.
  8681. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  8682. secondsToHighResolutionTicks
  8683. */
  8684. static int64 getHighResolutionTicks() throw();
  8685. /** Returns the resolution of the high-resolution counter in ticks per second.
  8686. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  8687. secondsToHighResolutionTicks
  8688. */
  8689. static int64 getHighResolutionTicksPerSecond() throw();
  8690. /** Converts a number of high-resolution ticks into seconds.
  8691. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  8692. secondsToHighResolutionTicks
  8693. */
  8694. static double highResolutionTicksToSeconds (int64 ticks) throw();
  8695. /** Converts a number seconds into high-resolution ticks.
  8696. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  8697. highResolutionTicksToSeconds
  8698. */
  8699. static int64 secondsToHighResolutionTicks (double seconds) throw();
  8700. private:
  8701. int64 millisSinceEpoch;
  8702. };
  8703. /** Adds a RelativeTime to a Time. */
  8704. JUCE_API const Time operator+ (const Time& time, const RelativeTime& delta);
  8705. /** Adds a RelativeTime to a Time. */
  8706. JUCE_API const Time operator+ (const RelativeTime& delta, const Time& time);
  8707. /** Subtracts a RelativeTime from a Time. */
  8708. JUCE_API const Time operator- (const Time& time, const RelativeTime& delta);
  8709. /** Returns the relative time difference between two times. */
  8710. JUCE_API const RelativeTime operator- (const Time& time1, const Time& time2);
  8711. /** Compares two Time objects. */
  8712. JUCE_API bool operator== (const Time& time1, const Time& time2);
  8713. /** Compares two Time objects. */
  8714. JUCE_API bool operator!= (const Time& time1, const Time& time2);
  8715. /** Compares two Time objects. */
  8716. JUCE_API bool operator< (const Time& time1, const Time& time2);
  8717. /** Compares two Time objects. */
  8718. JUCE_API bool operator<= (const Time& time1, const Time& time2);
  8719. /** Compares two Time objects. */
  8720. JUCE_API bool operator> (const Time& time1, const Time& time2);
  8721. /** Compares two Time objects. */
  8722. JUCE_API bool operator>= (const Time& time1, const Time& time2);
  8723. #endif // __JUCE_TIME_JUCEHEADER__
  8724. /*** End of inlined file: juce_Time.h ***/
  8725. /*** Start of inlined file: juce_ScopedPointer.h ***/
  8726. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8727. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8728. /**
  8729. This class holds a pointer which is automatically deleted when this object goes
  8730. out of scope.
  8731. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  8732. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  8733. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  8734. created objects.
  8735. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  8736. to an object. If you use the assignment operator to assign a different object to a
  8737. ScopedPointer, the old one will be automatically deleted.
  8738. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  8739. object to which it points during its lifetime. This means that making a copy of a const
  8740. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  8741. old one.
  8742. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  8743. can use the release() method.
  8744. */
  8745. template <class ObjectType>
  8746. class ScopedPointer
  8747. {
  8748. public:
  8749. /** Creates a ScopedPointer containing a null pointer. */
  8750. inline ScopedPointer() throw() : object (0)
  8751. {
  8752. }
  8753. /** Creates a ScopedPointer that owns the specified object. */
  8754. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) throw()
  8755. : object (objectToTakePossessionOf)
  8756. {
  8757. }
  8758. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  8759. Because a pointer can only belong to one ScopedPointer, this transfers
  8760. the pointer from the other object to this one, and the other object is reset to
  8761. be a null pointer.
  8762. */
  8763. ScopedPointer (ScopedPointer& objectToTransferFrom) throw()
  8764. : object (objectToTransferFrom.object)
  8765. {
  8766. objectToTransferFrom.object = 0;
  8767. }
  8768. /** Destructor.
  8769. This will delete the object that this ScopedPointer currently refers to.
  8770. */
  8771. inline ~ScopedPointer() { delete object; }
  8772. /** Changes this ScopedPointer to point to a new object.
  8773. Because a pointer can only belong to one ScopedPointer, this transfers
  8774. the pointer from the other object to this one, and the other object is reset to
  8775. be a null pointer.
  8776. If this ScopedPointer already points to an object, that object
  8777. will first be deleted.
  8778. */
  8779. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  8780. {
  8781. if (this != objectToTransferFrom.getAddress())
  8782. {
  8783. // Two ScopedPointers should never be able to refer to the same object - if
  8784. // this happens, you must have done something dodgy!
  8785. jassert (object == 0 || object != objectToTransferFrom.object);
  8786. ObjectType* const oldObject = object;
  8787. object = objectToTransferFrom.object;
  8788. objectToTransferFrom.object = 0;
  8789. delete oldObject;
  8790. }
  8791. return *this;
  8792. }
  8793. /** Changes this ScopedPointer to point to a new object.
  8794. If this ScopedPointer already points to an object, that object
  8795. will first be deleted.
  8796. The pointer that you pass is may be null.
  8797. */
  8798. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  8799. {
  8800. if (object != newObjectToTakePossessionOf)
  8801. {
  8802. ObjectType* const oldObject = object;
  8803. object = newObjectToTakePossessionOf;
  8804. delete oldObject;
  8805. }
  8806. return *this;
  8807. }
  8808. /** Returns the object that this ScopedPointer refers to. */
  8809. inline operator ObjectType*() const throw() { return object; }
  8810. /** Returns the object that this ScopedPointer refers to. */
  8811. inline ObjectType& operator*() const throw() { return *object; }
  8812. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  8813. inline ObjectType* operator->() const throw() { return object; }
  8814. /** Removes the current object from this ScopedPointer without deleting it.
  8815. This will return the current object, and set the ScopedPointer to a null pointer.
  8816. */
  8817. ObjectType* release() throw() { ObjectType* const o = object; object = 0; return o; }
  8818. /** Swaps this object with that of another ScopedPointer.
  8819. The two objects simply exchange their pointers.
  8820. */
  8821. void swapWith (ScopedPointer <ObjectType>& other) throw()
  8822. {
  8823. // Two ScopedPointers should never be able to refer to the same object - if
  8824. // this happens, you must have done something dodgy!
  8825. jassert (object != other.object);
  8826. swapVariables (object, other.object);
  8827. }
  8828. private:
  8829. ObjectType* object;
  8830. // (Required as an alternative to the overloaded & operator).
  8831. const ScopedPointer* getAddress() const throw() { return this; }
  8832. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  8833. /* This is private to stop people accidentally copying a const ScopedPointer (the compiler
  8834. would let you do so by implicitly casting the source to its raw object pointer).
  8835. A side effect of this is that you may hit a puzzling compiler error when you write something
  8836. like this:
  8837. ScopedPointer<MyClass> m = new MyClass(); // Compile error: copy constructor is private.
  8838. Even though the compiler would normally ignore the assignment here, it can't do so when the
  8839. copy constructor is private. It's very easy to fis though - just write it like this:
  8840. ScopedPointer<MyClass> m (new MyClass()); // Compiles OK
  8841. It's good practice to always use the latter form when writing your object declarations anyway,
  8842. rather than writing them as assignments and assuming (or hoping) that the compiler will be
  8843. smart enough to replace your construction + assignment with a single constructor.
  8844. */
  8845. ScopedPointer (const ScopedPointer&);
  8846. #endif
  8847. };
  8848. /** Compares a ScopedPointer with another pointer.
  8849. This can be handy for checking whether this is a null pointer.
  8850. */
  8851. template <class ObjectType>
  8852. bool operator== (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) throw()
  8853. {
  8854. return static_cast <ObjectType*> (pointer1) == pointer2;
  8855. }
  8856. /** Compares a ScopedPointer with another pointer.
  8857. This can be handy for checking whether this is a null pointer.
  8858. */
  8859. template <class ObjectType>
  8860. bool operator!= (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) throw()
  8861. {
  8862. return static_cast <ObjectType*> (pointer1) != pointer2;
  8863. }
  8864. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8865. /*** End of inlined file: juce_ScopedPointer.h ***/
  8866. class FileInputStream;
  8867. class FileOutputStream;
  8868. /**
  8869. Represents a local file or directory.
  8870. This class encapsulates the absolute pathname of a file or directory, and
  8871. has methods for finding out about the file and changing its properties.
  8872. To read or write to the file, there are methods for returning an input or
  8873. output stream.
  8874. @see FileInputStream, FileOutputStream
  8875. */
  8876. class JUCE_API File
  8877. {
  8878. public:
  8879. /** Creates an (invalid) file object.
  8880. The file is initially set to an empty path, so getFullPath() will return
  8881. an empty string, and comparing the file to File::nonexistent will return
  8882. true.
  8883. You can use its operator= method to point it at a proper file.
  8884. */
  8885. File() {}
  8886. /** Creates a file from an absolute path.
  8887. If the path supplied is a relative path, it is taken to be relative
  8888. to the current working directory (see File::getCurrentWorkingDirectory()),
  8889. but this isn't a recommended way of creating a file, because you
  8890. never know what the CWD is going to be.
  8891. On the Mac/Linux, the path can include "~" notation for referring to
  8892. user home directories.
  8893. */
  8894. File (const String& path);
  8895. /** Creates a copy of another file object. */
  8896. File (const File& other);
  8897. /** Destructor. */
  8898. ~File() {}
  8899. /** Sets the file based on an absolute pathname.
  8900. If the path supplied is a relative path, it is taken to be relative
  8901. to the current working directory (see File::getCurrentWorkingDirectory()),
  8902. but this isn't a recommended way of creating a file, because you
  8903. never know what the CWD is going to be.
  8904. On the Mac/Linux, the path can include "~" notation for referring to
  8905. user home directories.
  8906. */
  8907. File& operator= (const String& newFilePath);
  8908. /** Copies from another file object. */
  8909. File& operator= (const File& otherFile);
  8910. /** This static constant is used for referring to an 'invalid' file. */
  8911. static const File nonexistent;
  8912. /** Checks whether the file actually exists.
  8913. @returns true if the file exists, either as a file or a directory.
  8914. @see existsAsFile, isDirectory
  8915. */
  8916. bool exists() const;
  8917. /** Checks whether the file exists and is a file rather than a directory.
  8918. @returns true only if this is a real file, false if it's a directory
  8919. or doesn't exist
  8920. @see exists, isDirectory
  8921. */
  8922. bool existsAsFile() const;
  8923. /** Checks whether the file is a directory that exists.
  8924. @returns true only if the file is a directory which actually exists, so
  8925. false if it's a file or doesn't exist at all
  8926. @see exists, existsAsFile
  8927. */
  8928. bool isDirectory() const;
  8929. /** Returns the size of the file in bytes.
  8930. @returns the number of bytes in the file, or 0 if it doesn't exist.
  8931. */
  8932. int64 getSize() const;
  8933. /** Utility function to convert a file size in bytes to a neat string description.
  8934. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  8935. 2000000 would produce "2 MB", etc.
  8936. */
  8937. static const String descriptionOfSizeInBytes (int64 bytes);
  8938. /** Returns the complete, absolute path of this file.
  8939. This includes the filename and all its parent folders. On Windows it'll
  8940. also include the drive letter prefix; on Mac or Linux it'll be a complete
  8941. path starting from the root folder.
  8942. If you just want the file's name, you should use getFileName() or
  8943. getFileNameWithoutExtension().
  8944. @see getFileName, getRelativePathFrom
  8945. */
  8946. const String& getFullPathName() const throw() { return fullPath; }
  8947. /** Returns the last section of the pathname.
  8948. Returns just the final part of the path - e.g. if the whole path
  8949. is "/moose/fish/foo.txt" this will return "foo.txt".
  8950. For a directory, it returns the final part of the path - e.g. for the
  8951. directory "/moose/fish" it'll return "fish".
  8952. If the filename begins with a dot, it'll return the whole filename, e.g. for
  8953. "/moose/.fish", it'll return ".fish"
  8954. @see getFullPathName, getFileNameWithoutExtension
  8955. */
  8956. const String getFileName() const;
  8957. /** Creates a relative path that refers to a file relatively to a given directory.
  8958. e.g. File ("/moose/foo.txt").getRelativePathFrom (File ("/moose/fish/haddock"))
  8959. would return "../../foo.txt".
  8960. If it's not possible to navigate from one file to the other, an absolute
  8961. path is returned. If the paths are invalid, an empty string may also be
  8962. returned.
  8963. @param directoryToBeRelativeTo the directory which the resultant string will
  8964. be relative to. If this is actually a file rather than
  8965. a directory, its parent directory will be used instead.
  8966. If it doesn't exist, it's assumed to be a directory.
  8967. @see getChildFile, isAbsolutePath
  8968. */
  8969. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  8970. /** Returns the file's extension.
  8971. Returns the file extension of this file, also including the dot.
  8972. e.g. "/moose/fish/foo.txt" would return ".txt"
  8973. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  8974. */
  8975. const String getFileExtension() const;
  8976. /** Checks whether the file has a given extension.
  8977. @param extensionToTest the extension to look for - it doesn't matter whether or
  8978. not this string has a dot at the start, so ".wav" and "wav"
  8979. will have the same effect. The comparison used is
  8980. case-insensitve. To compare with multiple extensions, this
  8981. parameter can contain multiple strings, separated by semi-colons -
  8982. so, for example: hasFileExtension (".jpeg;png;gif") would return
  8983. true if the file has any of those three extensions.
  8984. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  8985. */
  8986. bool hasFileExtension (const String& extensionToTest) const;
  8987. /** Returns a version of this file with a different file extension.
  8988. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  8989. @param newExtension the new extension, either with or without a dot at the start (this
  8990. doesn't make any difference). To get remove a file's extension altogether,
  8991. pass an empty string into this function.
  8992. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  8993. */
  8994. const File withFileExtension (const String& newExtension) const;
  8995. /** Returns the last part of the filename, without its file extension.
  8996. e.g. for "/moose/fish/foo.txt" this will return "foo".
  8997. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  8998. */
  8999. const String getFileNameWithoutExtension() const;
  9000. /** Returns a 32-bit hash-code that identifies this file.
  9001. This is based on the filename. Obviously it's possible, although unlikely, that
  9002. two files will have the same hash-code.
  9003. */
  9004. int hashCode() const;
  9005. /** Returns a 64-bit hash-code that identifies this file.
  9006. This is based on the filename. Obviously it's possible, although unlikely, that
  9007. two files will have the same hash-code.
  9008. */
  9009. int64 hashCode64() const;
  9010. /** Returns a file based on a relative path.
  9011. This will find a child file or directory of the current object.
  9012. e.g.
  9013. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  9014. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  9015. If the string is actually an absolute path, it will be treated as such, e.g.
  9016. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  9017. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  9018. */
  9019. const File getChildFile (String relativePath) const;
  9020. /** Returns a file which is in the same directory as this one.
  9021. This is equivalent to getParentDirectory().getChildFile (name).
  9022. @see getChildFile, getParentDirectory
  9023. */
  9024. const File getSiblingFile (const String& siblingFileName) const;
  9025. /** Returns the directory that contains this file or directory.
  9026. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  9027. */
  9028. const File getParentDirectory() const;
  9029. /** Checks whether a file is somewhere inside a directory.
  9030. Returns true if this file is somewhere inside a subdirectory of the directory
  9031. that is passed in. Neither file actually has to exist, because the function
  9032. just checks the paths for similarities.
  9033. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  9034. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  9035. */
  9036. bool isAChildOf (const File& potentialParentDirectory) const;
  9037. /** Chooses a filename relative to this one that doesn't already exist.
  9038. If this file is a directory, this will return a child file of this
  9039. directory that doesn't exist, by adding numbers to a prefix and suffix until
  9040. it finds one that isn't already there.
  9041. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  9042. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  9043. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  9044. @param prefix the string to use for the filename before the number
  9045. @param suffix the string to add to the filename after the number
  9046. @param putNumbersInBrackets if true, this will create filenames in the
  9047. format "prefix(number)suffix", if false, it will leave the
  9048. brackets out.
  9049. */
  9050. const File getNonexistentChildFile (const String& prefix,
  9051. const String& suffix,
  9052. bool putNumbersInBrackets = true) const;
  9053. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  9054. If this file doesn't exist, this will just return itself, otherwise it
  9055. will return an appropriate sibling that doesn't exist, e.g. if a file
  9056. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  9057. @param putNumbersInBrackets whether to add brackets around the numbers that
  9058. get appended to the new filename.
  9059. */
  9060. const File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  9061. /** Compares the pathnames for two files. */
  9062. bool operator== (const File& otherFile) const;
  9063. /** Compares the pathnames for two files. */
  9064. bool operator!= (const File& otherFile) const;
  9065. /** Compares the pathnames for two files. */
  9066. bool operator< (const File& otherFile) const;
  9067. /** Compares the pathnames for two files. */
  9068. bool operator> (const File& otherFile) const;
  9069. /** Checks whether a file can be created or written to.
  9070. @returns true if it's possible to create and write to this file. If the file
  9071. doesn't already exist, this will check its parent directory to
  9072. see if writing is allowed.
  9073. @see setReadOnly
  9074. */
  9075. bool hasWriteAccess() const;
  9076. /** Changes the write-permission of a file or directory.
  9077. @param shouldBeReadOnly whether to add or remove write-permission
  9078. @param applyRecursively if the file is a directory and this is true, it will
  9079. recurse through all the subfolders changing the permissions
  9080. of all files
  9081. @returns true if it manages to change the file's permissions.
  9082. @see hasWriteAccess
  9083. */
  9084. bool setReadOnly (bool shouldBeReadOnly,
  9085. bool applyRecursively = false) const;
  9086. /** Returns true if this file is a hidden or system file.
  9087. The criteria for deciding whether a file is hidden are platform-dependent.
  9088. */
  9089. bool isHidden() const;
  9090. /** If this file is a link, this returns the file that it points to.
  9091. If this file isn't actually link, it'll just return itself.
  9092. */
  9093. const File getLinkedTarget() const;
  9094. /** Returns the last modification time of this file.
  9095. @returns the time, or an invalid time if the file doesn't exist.
  9096. @see setLastModificationTime, getLastAccessTime, getCreationTime
  9097. */
  9098. const Time getLastModificationTime() const;
  9099. /** Returns the last time this file was accessed.
  9100. @returns the time, or an invalid time if the file doesn't exist.
  9101. @see setLastAccessTime, getLastModificationTime, getCreationTime
  9102. */
  9103. const Time getLastAccessTime() const;
  9104. /** Returns the time that this file was created.
  9105. @returns the time, or an invalid time if the file doesn't exist.
  9106. @see getLastModificationTime, getLastAccessTime
  9107. */
  9108. const Time getCreationTime() const;
  9109. /** Changes the modification time for this file.
  9110. @param newTime the time to apply to the file
  9111. @returns true if it manages to change the file's time.
  9112. @see getLastModificationTime, setLastAccessTime, setCreationTime
  9113. */
  9114. bool setLastModificationTime (const Time& newTime) const;
  9115. /** Changes the last-access time for this file.
  9116. @param newTime the time to apply to the file
  9117. @returns true if it manages to change the file's time.
  9118. @see getLastAccessTime, setLastModificationTime, setCreationTime
  9119. */
  9120. bool setLastAccessTime (const Time& newTime) const;
  9121. /** Changes the creation date for this file.
  9122. @param newTime the time to apply to the file
  9123. @returns true if it manages to change the file's time.
  9124. @see getCreationTime, setLastModificationTime, setLastAccessTime
  9125. */
  9126. bool setCreationTime (const Time& newTime) const;
  9127. /** If possible, this will try to create a version string for the given file.
  9128. The OS may be able to look at the file and give a version for it - e.g. with
  9129. executables, bundles, dlls, etc. If no version is available, this will
  9130. return an empty string.
  9131. */
  9132. const String getVersion() const;
  9133. /** Creates an empty file if it doesn't already exist.
  9134. If the file that this object refers to doesn't exist, this will create a file
  9135. of zero size.
  9136. If it already exists or is a directory, this method will do nothing.
  9137. @returns true if the file has been created (or if it already existed).
  9138. @see createDirectory
  9139. */
  9140. bool create() const;
  9141. /** Creates a new directory for this filename.
  9142. This will try to create the file as a directory, and fill also create
  9143. any parent directories it needs in order to complete the operation.
  9144. @returns true if the directory has been created successfully, (or if it
  9145. already existed beforehand).
  9146. @see create
  9147. */
  9148. bool createDirectory() const;
  9149. /** Deletes a file.
  9150. If this file is actually a directory, it may not be deleted correctly if it
  9151. contains files. See deleteRecursively() as a better way of deleting directories.
  9152. @returns true if the file has been successfully deleted (or if it didn't exist to
  9153. begin with).
  9154. @see deleteRecursively
  9155. */
  9156. bool deleteFile() const;
  9157. /** Deletes a file or directory and all its subdirectories.
  9158. If this file is a directory, this will try to delete it and all its subfolders. If
  9159. it's just a file, it will just try to delete the file.
  9160. @returns true if the file and all its subfolders have been successfully deleted
  9161. (or if it didn't exist to begin with).
  9162. @see deleteFile
  9163. */
  9164. bool deleteRecursively() const;
  9165. /** Moves this file or folder to the trash.
  9166. @returns true if the operation succeeded. It could fail if the trash is full, or
  9167. if the file is write-protected, so you should check the return value
  9168. and act appropriately.
  9169. */
  9170. bool moveToTrash() const;
  9171. /** Moves or renames a file.
  9172. Tries to move a file to a different location.
  9173. If the target file already exists, this will attempt to delete it first, and
  9174. will fail if this can't be done.
  9175. Note that the destination file isn't the directory to put it in, it's the actual
  9176. filename that you want the new file to have.
  9177. @returns true if the operation succeeds
  9178. */
  9179. bool moveFileTo (const File& targetLocation) const;
  9180. /** Copies a file.
  9181. Tries to copy a file to a different location.
  9182. If the target file already exists, this will attempt to delete it first, and
  9183. will fail if this can't be done.
  9184. @returns true if the operation succeeds
  9185. */
  9186. bool copyFileTo (const File& targetLocation) const;
  9187. /** Copies a directory.
  9188. Tries to copy an entire directory, recursively.
  9189. If this file isn't a directory or if any target files can't be created, this
  9190. will return false.
  9191. @param newDirectory the directory that this one should be copied to. Note that this
  9192. is the name of the actual directory to create, not the directory
  9193. into which the new one should be placed, so there must be enough
  9194. write privileges to create it if it doesn't exist. Any files inside
  9195. it will be overwritten by similarly named ones that are copied.
  9196. */
  9197. bool copyDirectoryTo (const File& newDirectory) const;
  9198. /** Used in file searching, to specify whether to return files, directories, or both.
  9199. */
  9200. enum TypesOfFileToFind
  9201. {
  9202. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  9203. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  9204. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  9205. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  9206. };
  9207. /** Searches inside a directory for files matching a wildcard pattern.
  9208. Assuming that this file is a directory, this method will search it
  9209. for either files or subdirectories whose names match a filename pattern.
  9210. @param results an array to which File objects will be added for the
  9211. files that the search comes up with
  9212. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9213. return files, directories, or both. If the ignoreHiddenFiles flag
  9214. is also added to this value, hidden files won't be returned
  9215. @param searchRecursively if true, all subdirectories will be recursed into to do
  9216. an exhaustive search
  9217. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9218. @returns the number of results that have been found
  9219. @see getNumberOfChildFiles, DirectoryIterator
  9220. */
  9221. int findChildFiles (Array<File>& results,
  9222. int whatToLookFor,
  9223. bool searchRecursively,
  9224. const String& wildCardPattern = "*") const;
  9225. /** Searches inside a directory and counts how many files match a wildcard pattern.
  9226. Assuming that this file is a directory, this method will search it
  9227. for either files or subdirectories whose names match a filename pattern,
  9228. and will return the number of matches found.
  9229. This isn't a recursive call, and will only search this directory, not
  9230. its children.
  9231. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9232. count files, directories, or both. If the ignoreHiddenFiles flag
  9233. is also added to this value, hidden files won't be counted
  9234. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9235. @returns the number of matches found
  9236. @see findChildFiles, DirectoryIterator
  9237. */
  9238. int getNumberOfChildFiles (int whatToLookFor,
  9239. const String& wildCardPattern = "*") const;
  9240. /** Returns true if this file is a directory that contains one or more subdirectories.
  9241. @see isDirectory, findChildFiles
  9242. */
  9243. bool containsSubDirectories() const;
  9244. /** Creates a stream to read from this file.
  9245. @returns a stream that will read from this file (initially positioned at the
  9246. start of the file), or 0 if the file can't be opened for some reason
  9247. @see createOutputStream, loadFileAsData
  9248. */
  9249. FileInputStream* createInputStream() const;
  9250. /** Creates a stream to write to this file.
  9251. If the file exists, the stream that is returned will be positioned ready for
  9252. writing at the end of the file, so you might want to use deleteFile() first
  9253. to write to an empty file.
  9254. @returns a stream that will write to this file (initially positioned at the
  9255. end of the file), or 0 if the file can't be opened for some reason
  9256. @see createInputStream, appendData, appendText
  9257. */
  9258. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  9259. /** Loads a file's contents into memory as a block of binary data.
  9260. Of course, trying to load a very large file into memory will blow up, so
  9261. it's better to check first.
  9262. @param result the data block to which the file's contents should be appended - note
  9263. that if the memory block might already contain some data, you
  9264. might want to clear it first
  9265. @returns true if the file could all be read into memory
  9266. */
  9267. bool loadFileAsData (MemoryBlock& result) const;
  9268. /** Reads a file into memory as a string.
  9269. Attempts to load the entire file as a zero-terminated string.
  9270. This makes use of InputStream::readEntireStreamAsString, which should
  9271. automatically cope with unicode/acsii file formats.
  9272. */
  9273. const String loadFileAsString() const;
  9274. /** Appends a block of binary data to the end of the file.
  9275. This will try to write the given buffer to the end of the file.
  9276. @returns false if it can't write to the file for some reason
  9277. */
  9278. bool appendData (const void* dataToAppend,
  9279. int numberOfBytes) const;
  9280. /** Replaces this file's contents with a given block of data.
  9281. This will delete the file and replace it with the given data.
  9282. A nice feature of this method is that it's safe - instead of deleting
  9283. the file first and then re-writing it, it creates a new temporary file,
  9284. writes the data to that, and then moves the new file to replace the existing
  9285. file. This means that if the power gets pulled out or something crashes,
  9286. you're a lot less likely to end up with a corrupted or unfinished file..
  9287. Returns true if the operation succeeds, or false if it fails.
  9288. @see appendText
  9289. */
  9290. bool replaceWithData (const void* dataToWrite,
  9291. int numberOfBytes) const;
  9292. /** Appends a string to the end of the file.
  9293. This will try to append a text string to the file, as either 16-bit unicode
  9294. or 8-bit characters in the default system encoding.
  9295. It can also write the 'ff fe' unicode header bytes before the text to indicate
  9296. the endianness of the file.
  9297. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  9298. @see replaceWithText
  9299. */
  9300. bool appendText (const String& textToAppend,
  9301. bool asUnicode = false,
  9302. bool writeUnicodeHeaderBytes = false) const;
  9303. /** Replaces this file's contents with a given text string.
  9304. This will delete the file and replace it with the given text.
  9305. A nice feature of this method is that it's safe - instead of deleting
  9306. the file first and then re-writing it, it creates a new temporary file,
  9307. writes the text to that, and then moves the new file to replace the existing
  9308. file. This means that if the power gets pulled out or something crashes,
  9309. you're a lot less likely to end up with an empty file..
  9310. For an explanation of the parameters here, see the appendText() method.
  9311. Returns true if the operation succeeds, or false if it fails.
  9312. @see appendText
  9313. */
  9314. bool replaceWithText (const String& textToWrite,
  9315. bool asUnicode = false,
  9316. bool writeUnicodeHeaderBytes = false) const;
  9317. /** Attempts to scan the contents of this file and compare it to another file, returning
  9318. true if this is possible and they match byte-for-byte.
  9319. */
  9320. bool hasIdenticalContentTo (const File& other) const;
  9321. /** Creates a set of files to represent each file root.
  9322. e.g. on Windows this will create files for "c:\", "d:\" etc according
  9323. to which ones are available. On the Mac/Linux, this will probably
  9324. just add a single entry for "/".
  9325. */
  9326. static void findFileSystemRoots (Array<File>& results);
  9327. /** Finds the name of the drive on which this file lives.
  9328. @returns the volume label of the drive, or an empty string if this isn't possible
  9329. */
  9330. const String getVolumeLabel() const;
  9331. /** Returns the serial number of the volume on which this file lives.
  9332. @returns the serial number, or zero if there's a problem doing this
  9333. */
  9334. int getVolumeSerialNumber() const;
  9335. /** Returns the number of bytes free on the drive that this file lives on.
  9336. @returns the number of bytes free, or 0 if there's a problem finding this out
  9337. @see getVolumeTotalSize
  9338. */
  9339. int64 getBytesFreeOnVolume() const;
  9340. /** Returns the total size of the drive that contains this file.
  9341. @returns the total number of bytes that the volume can hold
  9342. @see getBytesFreeOnVolume
  9343. */
  9344. int64 getVolumeTotalSize() const;
  9345. /** Returns true if this file is on a CD or DVD drive. */
  9346. bool isOnCDRomDrive() const;
  9347. /** Returns true if this file is on a hard disk.
  9348. This will fail if it's a network drive, but will still be true for
  9349. removable hard-disks.
  9350. */
  9351. bool isOnHardDisk() const;
  9352. /** Returns true if this file is on a removable disk drive.
  9353. This might be a usb-drive, a CD-rom, or maybe a network drive.
  9354. */
  9355. bool isOnRemovableDrive() const;
  9356. /** Launches the file as a process.
  9357. - if the file is executable, this will run it.
  9358. - if it's a document of some kind, it will launch the document with its
  9359. default viewer application.
  9360. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  9361. @see revealToUser
  9362. */
  9363. bool startAsProcess (const String& parameters = String::empty) const;
  9364. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  9365. @see startAsProcess
  9366. */
  9367. void revealToUser() const;
  9368. /** A set of types of location that can be passed to the getSpecialLocation() method.
  9369. */
  9370. enum SpecialLocationType
  9371. {
  9372. /** The user's home folder. This is the same as using File ("~"). */
  9373. userHomeDirectory,
  9374. /** The user's default documents folder. On Windows, this might be the user's
  9375. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  9376. doesn't tend to have one of these, so it might just return their home folder.
  9377. */
  9378. userDocumentsDirectory,
  9379. /** The folder that contains the user's desktop objects. */
  9380. userDesktopDirectory,
  9381. /** The folder in which applications store their persistent user-specific settings.
  9382. On Windows, this might be "\Documents and Settings\username\Application Data".
  9383. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  9384. always create your own sub-folder to put them in, to avoid making a mess.
  9385. */
  9386. userApplicationDataDirectory,
  9387. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  9388. of the computer, rather than just the current user.
  9389. On the Mac it'll be "/Library", on Windows, it could be something like
  9390. "\Documents and Settings\All Users\Application Data".
  9391. Depending on the setup, this folder may be read-only.
  9392. */
  9393. commonApplicationDataDirectory,
  9394. /** The folder that should be used for temporary files.
  9395. Always delete them when you're finished, to keep the user's computer tidy!
  9396. */
  9397. tempDirectory,
  9398. /** Returns this application's executable file.
  9399. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  9400. host app.
  9401. On the mac this will return the unix binary, not the package folder - see
  9402. currentApplicationFile for that.
  9403. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  9404. file link, invokedExecutableFile will return the name of the link.
  9405. */
  9406. currentExecutableFile,
  9407. /** Returns this application's location.
  9408. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  9409. host app.
  9410. On the mac this will return the package folder (if it's in one), not the unix binary
  9411. that's inside it - compare with currentExecutableFile.
  9412. */
  9413. currentApplicationFile,
  9414. /** Returns the file that was invoked to launch this executable.
  9415. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  9416. will return the name of the link that was used, whereas currentExecutableFile will return
  9417. the actual location of the target executable.
  9418. */
  9419. invokedExecutableFile,
  9420. /** In a plugin, this will return the path of the host executable. */
  9421. hostApplicationPath,
  9422. /** The directory in which applications normally get installed.
  9423. So on windows, this would be something like "c:\program files", on the
  9424. Mac "/Applications", or "/usr" on linux.
  9425. */
  9426. globalApplicationsDirectory,
  9427. /** The most likely place where a user might store their music files.
  9428. */
  9429. userMusicDirectory,
  9430. /** The most likely place where a user might store their movie files.
  9431. */
  9432. userMoviesDirectory,
  9433. };
  9434. /** Finds the location of a special type of file or directory, such as a home folder or
  9435. documents folder.
  9436. @see SpecialLocationType
  9437. */
  9438. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  9439. /** Returns a temporary file in the system's temp directory.
  9440. This will try to return the name of a non-existent temp file.
  9441. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  9442. */
  9443. static const File createTempFile (const String& fileNameEnding);
  9444. /** Returns the current working directory.
  9445. @see setAsCurrentWorkingDirectory
  9446. */
  9447. static const File getCurrentWorkingDirectory();
  9448. /** Sets the current working directory to be this file.
  9449. For this to work the file must point to a valid directory.
  9450. @returns true if the current directory has been changed.
  9451. @see getCurrentWorkingDirectory
  9452. */
  9453. bool setAsCurrentWorkingDirectory() const;
  9454. /** The system-specific file separator character.
  9455. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  9456. */
  9457. static const juce_wchar separator;
  9458. /** The system-specific file separator character, as a string.
  9459. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  9460. */
  9461. static const String separatorString;
  9462. /** Removes illegal characters from a filename.
  9463. This will return a copy of the given string after removing characters
  9464. that are not allowed in a legal filename, and possibly shortening the
  9465. string if it's too long.
  9466. Because this will remove slashes, don't use it on an absolute pathname.
  9467. @see createLegalPathName
  9468. */
  9469. static const String createLegalFileName (const String& fileNameToFix);
  9470. /** Removes illegal characters from a pathname.
  9471. Similar to createLegalFileName(), but this won't remove slashes, so can
  9472. be used on a complete pathname.
  9473. @see createLegalFileName
  9474. */
  9475. static const String createLegalPathName (const String& pathNameToFix);
  9476. /** Indicates whether filenames are case-sensitive on the current operating system.
  9477. */
  9478. static bool areFileNamesCaseSensitive();
  9479. /** Returns true if the string seems to be a fully-specified absolute path.
  9480. */
  9481. static bool isAbsolutePath (const String& path);
  9482. /** Creates a file that simply contains this string, without doing the sanity-checking
  9483. that the normal constructors do.
  9484. Best to avoid this unless you really know what you're doing.
  9485. */
  9486. static const File createFileWithoutCheckingPath (const String& path);
  9487. /** Adds a separator character to the end of a path if it doesn't already have one. */
  9488. static const String addTrailingSeparator (const String& path);
  9489. private:
  9490. String fullPath;
  9491. // internal way of contructing a file without checking the path
  9492. friend class DirectoryIterator;
  9493. File (const String&, int);
  9494. const String getPathUpToLastSlash() const;
  9495. void createDirectoryInternal (const String& fileName) const;
  9496. bool copyInternal (const File& dest) const;
  9497. bool moveInternal (const File& dest) const;
  9498. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  9499. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  9500. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  9501. static const String parseAbsolutePath (const String& path);
  9502. JUCE_LEAK_DETECTOR (File);
  9503. };
  9504. #endif // __JUCE_FILE_JUCEHEADER__
  9505. /*** End of inlined file: juce_File.h ***/
  9506. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  9507. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  9508. will be the name of a pointer to each child element.
  9509. E.g. @code
  9510. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  9511. forEachXmlChildElement (*myParentXml, child)
  9512. {
  9513. if (child->hasTagName ("FOO"))
  9514. doSomethingWithXmlElement (child);
  9515. }
  9516. @endcode
  9517. @see forEachXmlChildElementWithTagName
  9518. */
  9519. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  9520. \
  9521. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  9522. childElementVariableName != 0; \
  9523. childElementVariableName = childElementVariableName->getNextElement())
  9524. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  9525. which have a specified tag.
  9526. This does the same job as the forEachXmlChildElement macro, but only for those
  9527. elements that have a particular tag name.
  9528. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  9529. will be the name of a pointer to each child element. The requiredTagName is the
  9530. tag name to match.
  9531. E.g. @code
  9532. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  9533. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  9534. {
  9535. // the child object is now guaranteed to be a <MYTAG> element..
  9536. doSomethingWithMYTAGElement (child);
  9537. }
  9538. @endcode
  9539. @see forEachXmlChildElement
  9540. */
  9541. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  9542. \
  9543. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  9544. childElementVariableName != 0; \
  9545. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  9546. /** Used to build a tree of elements representing an XML document.
  9547. An XML document can be parsed into a tree of XmlElements, each of which
  9548. represents an XML tag structure, and which may itself contain other
  9549. nested elements.
  9550. An XmlElement can also be converted back into a text document, and has
  9551. lots of useful methods for manipulating its attributes and sub-elements,
  9552. so XmlElements can actually be used as a handy general-purpose data
  9553. structure.
  9554. Here's an example of parsing some elements: @code
  9555. // check we're looking at the right kind of document..
  9556. if (myElement->hasTagName ("ANIMALS"))
  9557. {
  9558. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  9559. forEachXmlChildElement (*myElement, e)
  9560. {
  9561. if (e->hasTagName ("GIRAFFE"))
  9562. {
  9563. // found a giraffe, so use some of its attributes..
  9564. String giraffeName = e->getStringAttribute ("name");
  9565. int giraffeAge = e->getIntAttribute ("age");
  9566. bool isFriendly = e->getBoolAttribute ("friendly");
  9567. }
  9568. }
  9569. }
  9570. @endcode
  9571. And here's an example of how to create an XML document from scratch: @code
  9572. // create an outer node called "ANIMALS"
  9573. XmlElement animalsList ("ANIMALS");
  9574. for (int i = 0; i < numAnimals; ++i)
  9575. {
  9576. // create an inner element..
  9577. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  9578. giraffe->setAttribute ("name", "nigel");
  9579. giraffe->setAttribute ("age", 10);
  9580. giraffe->setAttribute ("friendly", true);
  9581. // ..and add our new element to the parent node
  9582. animalsList.addChildElement (giraffe);
  9583. }
  9584. // now we can turn the whole thing into a text document..
  9585. String myXmlDoc = animalsList.createDocument (String::empty);
  9586. @endcode
  9587. @see XmlDocument
  9588. */
  9589. class JUCE_API XmlElement
  9590. {
  9591. public:
  9592. /** Creates an XmlElement with this tag name. */
  9593. explicit XmlElement (const String& tagName) throw();
  9594. /** Creates a (deep) copy of another element. */
  9595. XmlElement (const XmlElement& other);
  9596. /** Creates a (deep) copy of another element. */
  9597. XmlElement& operator= (const XmlElement& other);
  9598. /** Deleting an XmlElement will also delete all its child elements. */
  9599. ~XmlElement() throw();
  9600. /** Compares two XmlElements to see if they contain the same text and attiributes.
  9601. The elements are only considered equivalent if they contain the same attiributes
  9602. with the same values, and have the same sub-nodes.
  9603. @param other the other element to compare to
  9604. @param ignoreOrderOfAttributes if true, this means that two elements with the
  9605. same attributes in a different order will be
  9606. considered the same; if false, the attributes must
  9607. be in the same order as well
  9608. */
  9609. bool isEquivalentTo (const XmlElement* other,
  9610. bool ignoreOrderOfAttributes) const throw();
  9611. /** Returns an XML text document that represents this element.
  9612. The string returned can be parsed to recreate the same XmlElement that
  9613. was used to create it.
  9614. @param dtdToUse the DTD to add to the document
  9615. @param allOnOneLine if true, this means that the document will not contain any
  9616. linefeeds, so it'll be smaller but not very easy to read.
  9617. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  9618. document
  9619. @param encodingType the character encoding format string to put into the xml
  9620. header
  9621. @param lineWrapLength the line length that will be used before items get placed on
  9622. a new line. This isn't an absolute maximum length, it just
  9623. determines how lists of attributes get broken up
  9624. @see writeToStream, writeToFile
  9625. */
  9626. const String createDocument (const String& dtdToUse,
  9627. bool allOnOneLine = false,
  9628. bool includeXmlHeader = true,
  9629. const String& encodingType = "UTF-8",
  9630. int lineWrapLength = 60) const;
  9631. /** Writes the document to a stream as UTF-8.
  9632. @param output the stream to write to
  9633. @param dtdToUse the DTD to add to the document
  9634. @param allOnOneLine if true, this means that the document will not contain any
  9635. linefeeds, so it'll be smaller but not very easy to read.
  9636. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  9637. document
  9638. @param encodingType the character encoding format string to put into the xml
  9639. header
  9640. @param lineWrapLength the line length that will be used before items get placed on
  9641. a new line. This isn't an absolute maximum length, it just
  9642. determines how lists of attributes get broken up
  9643. @see writeToFile, createDocument
  9644. */
  9645. void writeToStream (OutputStream& output,
  9646. const String& dtdToUse,
  9647. bool allOnOneLine = false,
  9648. bool includeXmlHeader = true,
  9649. const String& encodingType = "UTF-8",
  9650. int lineWrapLength = 60) const;
  9651. /** Writes the element to a file as an XML document.
  9652. To improve safety in case something goes wrong while writing the file, this
  9653. will actually write the document to a new temporary file in the same
  9654. directory as the destination file, and if this succeeds, it will rename this
  9655. new file as the destination file (overwriting any existing file that was there).
  9656. @param destinationFile the file to write to. If this already exists, it will be
  9657. overwritten.
  9658. @param dtdToUse the DTD to add to the document
  9659. @param encodingType the character encoding format string to put into the xml
  9660. header
  9661. @param lineWrapLength the line length that will be used before items get placed on
  9662. a new line. This isn't an absolute maximum length, it just
  9663. determines how lists of attributes get broken up
  9664. @returns true if the file is written successfully; false if something goes wrong
  9665. in the process
  9666. @see createDocument
  9667. */
  9668. bool writeToFile (const File& destinationFile,
  9669. const String& dtdToUse,
  9670. const String& encodingType = "UTF-8",
  9671. int lineWrapLength = 60) const;
  9672. /** Returns this element's tag type name.
  9673. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  9674. "MOOSE".
  9675. @see hasTagName
  9676. */
  9677. inline const String& getTagName() const throw() { return tagName; }
  9678. /** Tests whether this element has a particular tag name.
  9679. @param possibleTagName the tag name you're comparing it with
  9680. @see getTagName
  9681. */
  9682. bool hasTagName (const String& possibleTagName) const throw();
  9683. /** Returns the number of XML attributes this element contains.
  9684. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  9685. return 2.
  9686. */
  9687. int getNumAttributes() const throw();
  9688. /** Returns the name of one of the elements attributes.
  9689. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  9690. getAttributeName(1) would return "antlers".
  9691. @see getAttributeValue, getStringAttribute
  9692. */
  9693. const String& getAttributeName (int attributeIndex) const throw();
  9694. /** Returns the value of one of the elements attributes.
  9695. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  9696. getAttributeName(1) would return "2".
  9697. @see getAttributeName, getStringAttribute
  9698. */
  9699. const String& getAttributeValue (int attributeIndex) const throw();
  9700. // Attribute-handling methods..
  9701. /** Checks whether the element contains an attribute with a certain name. */
  9702. bool hasAttribute (const String& attributeName) const throw();
  9703. /** Returns the value of a named attribute.
  9704. @param attributeName the name of the attribute to look up
  9705. */
  9706. const String& getStringAttribute (const String& attributeName) const throw();
  9707. /** Returns the value of a named attribute.
  9708. @param attributeName the name of the attribute to look up
  9709. @param defaultReturnValue a value to return if the element doesn't have an attribute
  9710. with this name
  9711. */
  9712. const String getStringAttribute (const String& attributeName,
  9713. const String& defaultReturnValue) const;
  9714. /** Compares the value of a named attribute with a value passed-in.
  9715. @param attributeName the name of the attribute to look up
  9716. @param stringToCompareAgainst the value to compare it with
  9717. @param ignoreCase whether the comparison should be case-insensitive
  9718. @returns true if the value of the attribute is the same as the string passed-in;
  9719. false if it's different (or if no such attribute exists)
  9720. */
  9721. bool compareAttribute (const String& attributeName,
  9722. const String& stringToCompareAgainst,
  9723. bool ignoreCase = false) const throw();
  9724. /** Returns the value of a named attribute as an integer.
  9725. This will try to find the attribute and convert it to an integer (using
  9726. the String::getIntValue() method).
  9727. @param attributeName the name of the attribute to look up
  9728. @param defaultReturnValue a value to return if the element doesn't have an attribute
  9729. with this name
  9730. @see setAttribute
  9731. */
  9732. int getIntAttribute (const String& attributeName,
  9733. int defaultReturnValue = 0) const;
  9734. /** Returns the value of a named attribute as floating-point.
  9735. This will try to find the attribute and convert it to an integer (using
  9736. the String::getDoubleValue() method).
  9737. @param attributeName the name of the attribute to look up
  9738. @param defaultReturnValue a value to return if the element doesn't have an attribute
  9739. with this name
  9740. @see setAttribute
  9741. */
  9742. double getDoubleAttribute (const String& attributeName,
  9743. double defaultReturnValue = 0.0) const;
  9744. /** Returns the value of a named attribute as a boolean.
  9745. This will try to find the attribute and interpret it as a boolean. To do this,
  9746. it'll return true if the value is "1", "true", "y", etc, or false for other
  9747. values.
  9748. @param attributeName the name of the attribute to look up
  9749. @param defaultReturnValue a value to return if the element doesn't have an attribute
  9750. with this name
  9751. */
  9752. bool getBoolAttribute (const String& attributeName,
  9753. bool defaultReturnValue = false) const;
  9754. /** Adds a named attribute to the element.
  9755. If the element already contains an attribute with this name, it's value will
  9756. be updated to the new value. If there's no such attribute yet, a new one will
  9757. be added.
  9758. Note that there are other setAttribute() methods that take integers,
  9759. doubles, etc. to make it easy to store numbers.
  9760. @param attributeName the name of the attribute to set
  9761. @param newValue the value to set it to
  9762. @see removeAttribute
  9763. */
  9764. void setAttribute (const String& attributeName,
  9765. const String& newValue);
  9766. /** Adds a named attribute to the element, setting it to an integer value.
  9767. If the element already contains an attribute with this name, it's value will
  9768. be updated to the new value. If there's no such attribute yet, a new one will
  9769. be added.
  9770. Note that there are other setAttribute() methods that take integers,
  9771. doubles, etc. to make it easy to store numbers.
  9772. @param attributeName the name of the attribute to set
  9773. @param newValue the value to set it to
  9774. */
  9775. void setAttribute (const String& attributeName,
  9776. int newValue);
  9777. /** Adds a named attribute to the element, setting it to a floating-point value.
  9778. If the element already contains an attribute with this name, it's value will
  9779. be updated to the new value. If there's no such attribute yet, a new one will
  9780. be added.
  9781. Note that there are other setAttribute() methods that take integers,
  9782. doubles, etc. to make it easy to store numbers.
  9783. @param attributeName the name of the attribute to set
  9784. @param newValue the value to set it to
  9785. */
  9786. void setAttribute (const String& attributeName,
  9787. double newValue);
  9788. /** Removes a named attribute from the element.
  9789. @param attributeName the name of the attribute to remove
  9790. @see removeAllAttributes
  9791. */
  9792. void removeAttribute (const String& attributeName) throw();
  9793. /** Removes all attributes from this element.
  9794. */
  9795. void removeAllAttributes() throw();
  9796. // Child element methods..
  9797. /** Returns the first of this element's sub-elements.
  9798. see getNextElement() for an example of how to iterate the sub-elements.
  9799. @see forEachXmlChildElement
  9800. */
  9801. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  9802. /** Returns the next of this element's siblings.
  9803. This can be used for iterating an element's sub-elements, e.g.
  9804. @code
  9805. XmlElement* child = myXmlDocument->getFirstChildElement();
  9806. while (child != 0)
  9807. {
  9808. ...do stuff with this child..
  9809. child = child->getNextElement();
  9810. }
  9811. @endcode
  9812. Note that when iterating the child elements, some of them might be
  9813. text elements as well as XML tags - use isTextElement() to work this
  9814. out.
  9815. Also, it's much easier and neater to use this method indirectly via the
  9816. forEachXmlChildElement macro.
  9817. @returns the sibling element that follows this one, or zero if this is the last
  9818. element in its parent
  9819. @see getNextElement, isTextElement, forEachXmlChildElement
  9820. */
  9821. inline XmlElement* getNextElement() const throw() { return nextListItem; }
  9822. /** Returns the next of this element's siblings which has the specified tag
  9823. name.
  9824. This is like getNextElement(), but will scan through the list until it
  9825. finds an element with the given tag name.
  9826. @see getNextElement, forEachXmlChildElementWithTagName
  9827. */
  9828. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  9829. /** Returns the number of sub-elements in this element.
  9830. @see getChildElement
  9831. */
  9832. int getNumChildElements() const throw();
  9833. /** Returns the sub-element at a certain index.
  9834. It's not very efficient to iterate the sub-elements by index - see
  9835. getNextElement() for an example of how best to iterate.
  9836. @returns the n'th child of this element, or 0 if the index is out-of-range
  9837. @see getNextElement, isTextElement, getChildByName
  9838. */
  9839. XmlElement* getChildElement (int index) const throw();
  9840. /** Returns the first sub-element with a given tag-name.
  9841. @param tagNameToLookFor the tag name of the element you want to find
  9842. @returns the first element with this tag name, or 0 if none is found
  9843. @see getNextElement, isTextElement, getChildElement
  9844. */
  9845. XmlElement* getChildByName (const String& tagNameToLookFor) const throw();
  9846. /** Appends an element to this element's list of children.
  9847. Child elements are deleted automatically when their parent is deleted, so
  9848. make sure the object that you pass in will not be deleted by anything else,
  9849. and make sure it's not already the child of another element.
  9850. @see getFirstChildElement, getNextElement, getNumChildElements,
  9851. getChildElement, removeChildElement
  9852. */
  9853. void addChildElement (XmlElement* newChildElement) throw();
  9854. /** Inserts an element into this element's list of children.
  9855. Child elements are deleted automatically when their parent is deleted, so
  9856. make sure the object that you pass in will not be deleted by anything else,
  9857. and make sure it's not already the child of another element.
  9858. @param newChildNode the element to add
  9859. @param indexToInsertAt the index at which to insert the new element - if this is
  9860. below zero, it will be added to the end of the list
  9861. @see addChildElement, insertChildElement
  9862. */
  9863. void insertChildElement (XmlElement* newChildNode,
  9864. int indexToInsertAt) throw();
  9865. /** Creates a new element with the given name and returns it, after adding it
  9866. as a child element.
  9867. This is a handy method that means that instead of writing this:
  9868. @code
  9869. XmlElement* newElement = new XmlElement ("foobar");
  9870. myParentElement->addChildElement (newElement);
  9871. @endcode
  9872. ..you could just write this:
  9873. @code
  9874. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  9875. @endcode
  9876. */
  9877. XmlElement* createNewChildElement (const String& tagName);
  9878. /** Replaces one of this element's children with another node.
  9879. If the current element passed-in isn't actually a child of this element,
  9880. this will return false and the new one won't be added. Otherwise, the
  9881. existing element will be deleted, replaced with the new one, and it
  9882. will return true.
  9883. */
  9884. bool replaceChildElement (XmlElement* currentChildElement,
  9885. XmlElement* newChildNode) throw();
  9886. /** Removes a child element.
  9887. @param childToRemove the child to look for and remove
  9888. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  9889. just remove it
  9890. */
  9891. void removeChildElement (XmlElement* childToRemove,
  9892. bool shouldDeleteTheChild) throw();
  9893. /** Deletes all the child elements in the element.
  9894. @see removeChildElement, deleteAllChildElementsWithTagName
  9895. */
  9896. void deleteAllChildElements() throw();
  9897. /** Deletes all the child elements with a given tag name.
  9898. @see removeChildElement
  9899. */
  9900. void deleteAllChildElementsWithTagName (const String& tagName) throw();
  9901. /** Returns true if the given element is a child of this one. */
  9902. bool containsChildElement (const XmlElement* possibleChild) const throw();
  9903. /** Recursively searches all sub-elements to find one that contains the specified
  9904. child element.
  9905. */
  9906. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) throw();
  9907. /** Sorts the child elements using a comparator.
  9908. This will use a comparator object to sort the elements into order. The object
  9909. passed must have a method of the form:
  9910. @code
  9911. int compareElements (const XmlElement* first, const XmlElement* second);
  9912. @endcode
  9913. ..and this method must return:
  9914. - a value of < 0 if the first comes before the second
  9915. - a value of 0 if the two objects are equivalent
  9916. - a value of > 0 if the second comes before the first
  9917. To improve performance, the compareElements() method can be declared as static or const.
  9918. @param comparator the comparator to use for comparing elements.
  9919. @param retainOrderOfEquivalentItems if this is true, then items which the comparator
  9920. says are equivalent will be kept in the order in which they
  9921. currently appear in the array. This is slower to perform, but
  9922. may be important in some cases. If it's false, a faster algorithm
  9923. is used, but equivalent elements may be rearranged.
  9924. */
  9925. template <class ElementComparator>
  9926. void sortChildElements (ElementComparator& comparator,
  9927. bool retainOrderOfEquivalentItems = false)
  9928. {
  9929. const int num = getNumChildElements();
  9930. if (num > 1)
  9931. {
  9932. HeapBlock <XmlElement*> elems (num);
  9933. getChildElementsAsArray (elems);
  9934. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  9935. reorderChildElements (elems, num);
  9936. }
  9937. }
  9938. /** Returns true if this element is a section of text.
  9939. Elements can either be an XML tag element or a secton of text, so this
  9940. is used to find out what kind of element this one is.
  9941. @see getAllText, addTextElement, deleteAllTextElements
  9942. */
  9943. bool isTextElement() const throw();
  9944. /** Returns the text for a text element.
  9945. Note that if you have an element like this:
  9946. @code<xyz>hello</xyz>@endcode
  9947. then calling getText on the "xyz" element won't return "hello", because that is
  9948. actually stored in a special text sub-element inside the xyz element. To get the
  9949. "hello" string, you could either call getText on the (unnamed) sub-element, or
  9950. use getAllSubText() to do this automatically.
  9951. Note that leading and trailing whitespace will be included in the string - to remove
  9952. if, just call String::trim() on the result.
  9953. @see isTextElement, getAllSubText, getChildElementAllSubText
  9954. */
  9955. const String& getText() const throw();
  9956. /** Sets the text in a text element.
  9957. Note that this is only a valid call if this element is a text element. If it's
  9958. not, then no action will be performed. If you're trying to add text inside a normal
  9959. element, you probably want to use addTextElement() instead.
  9960. */
  9961. void setText (const String& newText);
  9962. /** Returns all the text from this element's child nodes.
  9963. This iterates all the child elements and when it finds text elements,
  9964. it concatenates their text into a big string which it returns.
  9965. E.g. @code<xyz>hello <x>there</x> world</xyz>@endcode
  9966. if you called getAllSubText on the "xyz" element, it'd return "hello there world".
  9967. Note that leading and trailing whitespace will be included in the string - to remove
  9968. if, just call String::trim() on the result.
  9969. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  9970. */
  9971. const String getAllSubText() const;
  9972. /** Returns all the sub-text of a named child element.
  9973. If there is a child element with the given tag name, this will return
  9974. all of its sub-text (by calling getAllSubText() on it). If there is
  9975. no such child element, this will return the default string passed-in.
  9976. @see getAllSubText
  9977. */
  9978. const String getChildElementAllSubText (const String& childTagName,
  9979. const String& defaultReturnValue) const;
  9980. /** Appends a section of text to this element.
  9981. @see isTextElement, getText, getAllSubText
  9982. */
  9983. void addTextElement (const String& text);
  9984. /** Removes all the text elements from this element.
  9985. @see isTextElement, getText, getAllSubText, addTextElement
  9986. */
  9987. void deleteAllTextElements() throw();
  9988. /** Creates a text element that can be added to a parent element.
  9989. */
  9990. static XmlElement* createTextElement (const String& text);
  9991. private:
  9992. struct XmlAttributeNode
  9993. {
  9994. XmlAttributeNode (const XmlAttributeNode& other) throw();
  9995. XmlAttributeNode (const String& name, const String& value) throw();
  9996. LinkedListPointer<XmlAttributeNode> nextListItem;
  9997. String name, value;
  9998. bool hasName (const String& name) const throw();
  9999. private:
  10000. XmlAttributeNode& operator= (const XmlAttributeNode&);
  10001. };
  10002. friend class XmlDocument;
  10003. friend class LinkedListPointer<XmlAttributeNode>;
  10004. friend class LinkedListPointer <XmlElement>;
  10005. friend class LinkedListPointer <XmlElement>::Appender;
  10006. LinkedListPointer <XmlElement> nextListItem;
  10007. LinkedListPointer <XmlElement> firstChildElement;
  10008. LinkedListPointer <XmlAttributeNode> attributes;
  10009. String tagName;
  10010. XmlElement (int) throw();
  10011. void copyChildrenAndAttributesFrom (const XmlElement& other);
  10012. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  10013. void getChildElementsAsArray (XmlElement**) const throw();
  10014. void reorderChildElements (XmlElement**, int) throw();
  10015. JUCE_LEAK_DETECTOR (XmlElement);
  10016. };
  10017. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  10018. /*** End of inlined file: juce_XmlElement.h ***/
  10019. /**
  10020. A set of named property values, which can be strings, integers, floating point, etc.
  10021. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  10022. to load and save types other than strings.
  10023. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  10024. messages and saves/loads the list from a file.
  10025. */
  10026. class JUCE_API PropertySet
  10027. {
  10028. public:
  10029. /** Creates an empty PropertySet.
  10030. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  10031. case-insensitive way
  10032. */
  10033. PropertySet (bool ignoreCaseOfKeyNames = false);
  10034. /** Creates a copy of another PropertySet.
  10035. */
  10036. PropertySet (const PropertySet& other);
  10037. /** Copies another PropertySet over this one.
  10038. */
  10039. PropertySet& operator= (const PropertySet& other);
  10040. /** Destructor. */
  10041. virtual ~PropertySet();
  10042. /** Returns one of the properties as a string.
  10043. If the value isn't found in this set, then this will look for it in a fallback
  10044. property set (if you've specified one with the setFallbackPropertySet() method),
  10045. and if it can't find one there, it'll return the default value passed-in.
  10046. @param keyName the name of the property to retrieve
  10047. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10048. */
  10049. const String getValue (const String& keyName,
  10050. const String& defaultReturnValue = String::empty) const throw();
  10051. /** Returns one of the properties as an integer.
  10052. If the value isn't found in this set, then this will look for it in a fallback
  10053. property set (if you've specified one with the setFallbackPropertySet() method),
  10054. and if it can't find one there, it'll return the default value passed-in.
  10055. @param keyName the name of the property to retrieve
  10056. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10057. */
  10058. int getIntValue (const String& keyName,
  10059. const int defaultReturnValue = 0) const throw();
  10060. /** Returns one of the properties as an double.
  10061. If the value isn't found in this set, then this will look for it in a fallback
  10062. property set (if you've specified one with the setFallbackPropertySet() method),
  10063. and if it can't find one there, it'll return the default value passed-in.
  10064. @param keyName the name of the property to retrieve
  10065. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10066. */
  10067. double getDoubleValue (const String& keyName,
  10068. const double defaultReturnValue = 0.0) const throw();
  10069. /** Returns one of the properties as an boolean.
  10070. The result will be true if the string found for this key name can be parsed as a non-zero
  10071. integer.
  10072. If the value isn't found in this set, then this will look for it in a fallback
  10073. property set (if you've specified one with the setFallbackPropertySet() method),
  10074. and if it can't find one there, it'll return the default value passed-in.
  10075. @param keyName the name of the property to retrieve
  10076. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10077. */
  10078. bool getBoolValue (const String& keyName,
  10079. const bool defaultReturnValue = false) const throw();
  10080. /** Returns one of the properties as an XML element.
  10081. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  10082. key isn't found, or if the entry contains an string that isn't valid XML.
  10083. If the value isn't found in this set, then this will look for it in a fallback
  10084. property set (if you've specified one with the setFallbackPropertySet() method),
  10085. and if it can't find one there, it'll return the default value passed-in.
  10086. @param keyName the name of the property to retrieve
  10087. */
  10088. XmlElement* getXmlValue (const String& keyName) const;
  10089. /** Sets a named property.
  10090. @param keyName the name of the property to set. (This mustn't be an empty string)
  10091. @param value the new value to set it to
  10092. */
  10093. void setValue (const String& keyName, const var& value);
  10094. /** Sets a named property to an XML element.
  10095. @param keyName the name of the property to set. (This mustn't be an empty string)
  10096. @param xml the new element to set it to. If this is zero, the value will be set to
  10097. an empty string
  10098. @see getXmlValue
  10099. */
  10100. void setValue (const String& keyName, const XmlElement* xml);
  10101. /** Deletes a property.
  10102. @param keyName the name of the property to delete. (This mustn't be an empty string)
  10103. */
  10104. void removeValue (const String& keyName);
  10105. /** Returns true if the properies include the given key. */
  10106. bool containsKey (const String& keyName) const throw();
  10107. /** Removes all values. */
  10108. void clear();
  10109. /** Returns the keys/value pair array containing all the properties. */
  10110. StringPairArray& getAllProperties() throw() { return properties; }
  10111. /** Returns the lock used when reading or writing to this set */
  10112. const CriticalSection& getLock() const throw() { return lock; }
  10113. /** Returns an XML element which encapsulates all the items in this property set.
  10114. The string parameter is the tag name that should be used for the node.
  10115. @see restoreFromXml
  10116. */
  10117. XmlElement* createXml (const String& nodeName) const;
  10118. /** Reloads a set of properties that were previously stored as XML.
  10119. The node passed in must have been created by the createXml() method.
  10120. @see createXml
  10121. */
  10122. void restoreFromXml (const XmlElement& xml);
  10123. /** Sets up a second PopertySet that will be used to look up any values that aren't
  10124. set in this one.
  10125. If you set this up to be a pointer to a second property set, then whenever one
  10126. of the getValue() methods fails to find an entry in this set, it will look up that
  10127. value in the fallback set, and if it finds it, it will return that.
  10128. Make sure that you don't delete the fallback set while it's still being used by
  10129. another set! To remove the fallback set, just call this method with a null pointer.
  10130. @see getFallbackPropertySet
  10131. */
  10132. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  10133. /** Returns the fallback property set.
  10134. @see setFallbackPropertySet
  10135. */
  10136. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  10137. protected:
  10138. /** Subclasses can override this to be told when one of the properies has been changed. */
  10139. virtual void propertyChanged();
  10140. private:
  10141. StringPairArray properties;
  10142. PropertySet* fallbackProperties;
  10143. CriticalSection lock;
  10144. bool ignoreCaseOfKeys;
  10145. JUCE_LEAK_DETECTOR (PropertySet);
  10146. };
  10147. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  10148. /*** End of inlined file: juce_PropertySet.h ***/
  10149. #endif
  10150. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10151. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  10152. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10153. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10154. /**
  10155. Holds a list of objects derived from ReferenceCountedObject.
  10156. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  10157. and takes care of incrementing and decrementing their ref counts when they
  10158. are added and removed from the array.
  10159. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  10160. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  10161. @see Array, OwnedArray, StringArray
  10162. */
  10163. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  10164. class ReferenceCountedArray
  10165. {
  10166. public:
  10167. typedef ReferenceCountedObjectPtr<ObjectClass> ObjectClassPtr;
  10168. /** Creates an empty array.
  10169. @see ReferenceCountedObject, Array, OwnedArray
  10170. */
  10171. ReferenceCountedArray() throw()
  10172. : numUsed (0)
  10173. {
  10174. }
  10175. /** Creates a copy of another array */
  10176. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  10177. {
  10178. const ScopedLockType lock (other.getLock());
  10179. numUsed = other.numUsed;
  10180. data.setAllocatedSize (numUsed);
  10181. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  10182. for (int i = numUsed; --i >= 0;)
  10183. if (data.elements[i] != 0)
  10184. data.elements[i]->incReferenceCount();
  10185. }
  10186. /** Copies another array into this one.
  10187. Any existing objects in this array will first be released.
  10188. */
  10189. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  10190. {
  10191. if (this != &other)
  10192. {
  10193. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  10194. swapWithArray (otherCopy);
  10195. }
  10196. return *this;
  10197. }
  10198. /** Destructor.
  10199. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  10200. */
  10201. ~ReferenceCountedArray()
  10202. {
  10203. clear();
  10204. }
  10205. /** Removes all objects from the array.
  10206. Any objects in the array that are not referenced from elsewhere will be deleted.
  10207. */
  10208. void clear()
  10209. {
  10210. const ScopedLockType lock (getLock());
  10211. while (numUsed > 0)
  10212. if (data.elements [--numUsed] != 0)
  10213. data.elements [numUsed]->decReferenceCount();
  10214. jassert (numUsed == 0);
  10215. data.setAllocatedSize (0);
  10216. }
  10217. /** Returns the current number of objects in the array. */
  10218. inline int size() const throw()
  10219. {
  10220. return numUsed;
  10221. }
  10222. /** Returns a pointer to the object at this index in the array.
  10223. If the index is out-of-range, this will return a null pointer, (and
  10224. it could be null anyway, because it's ok for the array to hold null
  10225. pointers as well as objects).
  10226. @see getUnchecked
  10227. */
  10228. inline const ObjectClassPtr operator[] (const int index) const throw()
  10229. {
  10230. const ScopedLockType lock (getLock());
  10231. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  10232. : static_cast <ObjectClass*> (0);
  10233. }
  10234. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  10235. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  10236. it can be used when you're sure the index if always going to be legal.
  10237. */
  10238. inline const ObjectClassPtr getUnchecked (const int index) const throw()
  10239. {
  10240. const ScopedLockType lock (getLock());
  10241. jassert (isPositiveAndBelow (index, numUsed));
  10242. return data.elements [index];
  10243. }
  10244. /** Returns a pointer to the first object in the array.
  10245. This will return a null pointer if the array's empty.
  10246. @see getLast
  10247. */
  10248. inline const ObjectClassPtr getFirst() const throw()
  10249. {
  10250. const ScopedLockType lock (getLock());
  10251. return numUsed > 0 ? data.elements [0]
  10252. : static_cast <ObjectClass*> (0);
  10253. }
  10254. /** Returns a pointer to the last object in the array.
  10255. This will return a null pointer if the array's empty.
  10256. @see getFirst
  10257. */
  10258. inline const ObjectClassPtr getLast() const throw()
  10259. {
  10260. const ScopedLockType lock (getLock());
  10261. return numUsed > 0 ? data.elements [numUsed - 1]
  10262. : static_cast <ObjectClass*> (0);
  10263. }
  10264. /** Finds the index of the first occurrence of an object in the array.
  10265. @param objectToLookFor the object to look for
  10266. @returns the index at which the object was found, or -1 if it's not found
  10267. */
  10268. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  10269. {
  10270. const ScopedLockType lock (getLock());
  10271. ObjectClass** e = data.elements.getData();
  10272. ObjectClass** const end = e + numUsed;
  10273. while (e != end)
  10274. {
  10275. if (objectToLookFor == *e)
  10276. return static_cast <int> (e - data.elements.getData());
  10277. ++e;
  10278. }
  10279. return -1;
  10280. }
  10281. /** Returns true if the array contains a specified object.
  10282. @param objectToLookFor the object to look for
  10283. @returns true if the object is in the array
  10284. */
  10285. bool contains (const ObjectClass* const objectToLookFor) const throw()
  10286. {
  10287. const ScopedLockType lock (getLock());
  10288. ObjectClass** e = data.elements.getData();
  10289. ObjectClass** const end = e + numUsed;
  10290. while (e != end)
  10291. {
  10292. if (objectToLookFor == *e)
  10293. return true;
  10294. ++e;
  10295. }
  10296. return false;
  10297. }
  10298. /** Appends a new object to the end of the array.
  10299. This will increase the new object's reference count.
  10300. @param newObject the new object to add to the array
  10301. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  10302. */
  10303. void add (ObjectClass* const newObject) throw()
  10304. {
  10305. const ScopedLockType lock (getLock());
  10306. data.ensureAllocatedSize (numUsed + 1);
  10307. data.elements [numUsed++] = newObject;
  10308. if (newObject != 0)
  10309. newObject->incReferenceCount();
  10310. }
  10311. /** Inserts a new object into the array at the given index.
  10312. If the index is less than 0 or greater than the size of the array, the
  10313. element will be added to the end of the array.
  10314. Otherwise, it will be inserted into the array, moving all the later elements
  10315. along to make room.
  10316. This will increase the new object's reference count.
  10317. @param indexToInsertAt the index at which the new element should be inserted
  10318. @param newObject the new object to add to the array
  10319. @see add, addSorted, addIfNotAlreadyThere, set
  10320. */
  10321. void insert (int indexToInsertAt,
  10322. ObjectClass* const newObject) throw()
  10323. {
  10324. if (indexToInsertAt >= 0)
  10325. {
  10326. const ScopedLockType lock (getLock());
  10327. if (indexToInsertAt > numUsed)
  10328. indexToInsertAt = numUsed;
  10329. data.ensureAllocatedSize (numUsed + 1);
  10330. ObjectClass** const e = data.elements + indexToInsertAt;
  10331. const int numToMove = numUsed - indexToInsertAt;
  10332. if (numToMove > 0)
  10333. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  10334. *e = newObject;
  10335. if (newObject != 0)
  10336. newObject->incReferenceCount();
  10337. ++numUsed;
  10338. }
  10339. else
  10340. {
  10341. add (newObject);
  10342. }
  10343. }
  10344. /** Appends a new object at the end of the array as long as the array doesn't
  10345. already contain it.
  10346. If the array already contains a matching object, nothing will be done.
  10347. @param newObject the new object to add to the array
  10348. */
  10349. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  10350. {
  10351. const ScopedLockType lock (getLock());
  10352. if (! contains (newObject))
  10353. add (newObject);
  10354. }
  10355. /** Replaces an object in the array with a different one.
  10356. If the index is less than zero, this method does nothing.
  10357. If the index is beyond the end of the array, the new object is added to the end of the array.
  10358. The object being added has its reference count increased, and if it's replacing
  10359. another object, then that one has its reference count decreased, and may be deleted.
  10360. @param indexToChange the index whose value you want to change
  10361. @param newObject the new value to set for this index.
  10362. @see add, insert, remove
  10363. */
  10364. void set (const int indexToChange,
  10365. ObjectClass* const newObject)
  10366. {
  10367. if (indexToChange >= 0)
  10368. {
  10369. const ScopedLockType lock (getLock());
  10370. if (newObject != 0)
  10371. newObject->incReferenceCount();
  10372. if (indexToChange < numUsed)
  10373. {
  10374. if (data.elements [indexToChange] != 0)
  10375. data.elements [indexToChange]->decReferenceCount();
  10376. data.elements [indexToChange] = newObject;
  10377. }
  10378. else
  10379. {
  10380. data.ensureAllocatedSize (numUsed + 1);
  10381. data.elements [numUsed++] = newObject;
  10382. }
  10383. }
  10384. }
  10385. /** Adds elements from another array to the end of this array.
  10386. @param arrayToAddFrom the array from which to copy the elements
  10387. @param startIndex the first element of the other array to start copying from
  10388. @param numElementsToAdd how many elements to add from the other array. If this
  10389. value is negative or greater than the number of available elements,
  10390. all available elements will be copied.
  10391. @see add
  10392. */
  10393. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  10394. int startIndex = 0,
  10395. int numElementsToAdd = -1) throw()
  10396. {
  10397. const ScopedLockType lock1 (arrayToAddFrom.getLock());
  10398. {
  10399. const ScopedLockType lock2 (getLock());
  10400. if (startIndex < 0)
  10401. {
  10402. jassertfalse;
  10403. startIndex = 0;
  10404. }
  10405. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  10406. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  10407. if (numElementsToAdd > 0)
  10408. {
  10409. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  10410. while (--numElementsToAdd >= 0)
  10411. add (arrayToAddFrom.getUnchecked (startIndex++));
  10412. }
  10413. }
  10414. }
  10415. /** Inserts a new object into the array assuming that the array is sorted.
  10416. This will use a comparator to find the position at which the new object
  10417. should go. If the array isn't sorted, the behaviour of this
  10418. method will be unpredictable.
  10419. @param comparator the comparator object to use to compare the elements - see the
  10420. sort() method for details about this object's form
  10421. @param newObject the new object to insert to the array
  10422. @see add, sort
  10423. */
  10424. template <class ElementComparator>
  10425. void addSorted (ElementComparator& comparator,
  10426. ObjectClass* newObject) throw()
  10427. {
  10428. const ScopedLockType lock (getLock());
  10429. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  10430. }
  10431. /** Inserts or replaces an object in the array, assuming it is sorted.
  10432. This is similar to addSorted, but if a matching element already exists, then it will be
  10433. replaced by the new one, rather than the new one being added as well.
  10434. */
  10435. template <class ElementComparator>
  10436. void addOrReplaceSorted (ElementComparator& comparator,
  10437. ObjectClass* newObject) throw()
  10438. {
  10439. const ScopedLockType lock (getLock());
  10440. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  10441. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  10442. set (index - 1, newObject); // replace an existing object that matches
  10443. else
  10444. insert (index, newObject); // no match, so insert the new one
  10445. }
  10446. /** Removes an object from the array.
  10447. This will remove the object at a given index and move back all the
  10448. subsequent objects to close the gap.
  10449. If the index passed in is out-of-range, nothing will happen.
  10450. The object that is removed will have its reference count decreased,
  10451. and may be deleted if not referenced from elsewhere.
  10452. @param indexToRemove the index of the element to remove
  10453. @see removeObject, removeRange
  10454. */
  10455. void remove (const int indexToRemove)
  10456. {
  10457. const ScopedLockType lock (getLock());
  10458. if (isPositiveAndBelow (indexToRemove, numUsed))
  10459. {
  10460. ObjectClass** const e = data.elements + indexToRemove;
  10461. if (*e != 0)
  10462. (*e)->decReferenceCount();
  10463. --numUsed;
  10464. const int numberToShift = numUsed - indexToRemove;
  10465. if (numberToShift > 0)
  10466. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  10467. if ((numUsed << 1) < data.numAllocated)
  10468. minimiseStorageOverheads();
  10469. }
  10470. }
  10471. /** Removes and returns an object from the array.
  10472. This will remove the object at a given index and return it, moving back all
  10473. the subsequent objects to close the gap. If the index passed in is out-of-range,
  10474. nothing will happen and a null pointer will be returned.
  10475. @param indexToRemove the index of the element to remove
  10476. @see remove, removeObject, removeRange
  10477. */
  10478. const ObjectClassPtr removeAndReturn (const int indexToRemove)
  10479. {
  10480. ObjectClassPtr removedItem;
  10481. const ScopedLockType lock (getLock());
  10482. if (isPositiveAndBelow (indexToRemove, numUsed))
  10483. {
  10484. ObjectClass** const e = data.elements + indexToRemove;
  10485. if (*e != 0)
  10486. {
  10487. removedItem = *e;
  10488. (*e)->decReferenceCount();
  10489. }
  10490. --numUsed;
  10491. const int numberToShift = numUsed - indexToRemove;
  10492. if (numberToShift > 0)
  10493. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  10494. if ((numUsed << 1) < data.numAllocated)
  10495. minimiseStorageOverheads();
  10496. }
  10497. return removedItem;
  10498. }
  10499. /** Removes the first occurrence of a specified object from the array.
  10500. If the item isn't found, no action is taken. If it is found, it is
  10501. removed and has its reference count decreased.
  10502. @param objectToRemove the object to try to remove
  10503. @see remove, removeRange
  10504. */
  10505. void removeObject (ObjectClass* const objectToRemove)
  10506. {
  10507. const ScopedLockType lock (getLock());
  10508. remove (indexOf (objectToRemove));
  10509. }
  10510. /** Removes a range of objects from the array.
  10511. This will remove a set of objects, starting from the given index,
  10512. and move any subsequent elements down to close the gap.
  10513. If the range extends beyond the bounds of the array, it will
  10514. be safely clipped to the size of the array.
  10515. The objects that are removed will have their reference counts decreased,
  10516. and may be deleted if not referenced from elsewhere.
  10517. @param startIndex the index of the first object to remove
  10518. @param numberToRemove how many objects should be removed
  10519. @see remove, removeObject
  10520. */
  10521. void removeRange (const int startIndex,
  10522. const int numberToRemove)
  10523. {
  10524. const ScopedLockType lock (getLock());
  10525. const int start = jlimit (0, numUsed, startIndex);
  10526. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  10527. if (end > start)
  10528. {
  10529. int i;
  10530. for (i = start; i < end; ++i)
  10531. {
  10532. if (data.elements[i] != 0)
  10533. {
  10534. data.elements[i]->decReferenceCount();
  10535. data.elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  10536. }
  10537. }
  10538. const int rangeSize = end - start;
  10539. ObjectClass** e = data.elements + start;
  10540. i = numUsed - end;
  10541. numUsed -= rangeSize;
  10542. while (--i >= 0)
  10543. {
  10544. *e = e [rangeSize];
  10545. ++e;
  10546. }
  10547. if ((numUsed << 1) < data.numAllocated)
  10548. minimiseStorageOverheads();
  10549. }
  10550. }
  10551. /** Removes the last n objects from the array.
  10552. The objects that are removed will have their reference counts decreased,
  10553. and may be deleted if not referenced from elsewhere.
  10554. @param howManyToRemove how many objects to remove from the end of the array
  10555. @see remove, removeObject, removeRange
  10556. */
  10557. void removeLast (int howManyToRemove = 1)
  10558. {
  10559. const ScopedLockType lock (getLock());
  10560. if (howManyToRemove > numUsed)
  10561. howManyToRemove = numUsed;
  10562. while (--howManyToRemove >= 0)
  10563. remove (numUsed - 1);
  10564. }
  10565. /** Swaps a pair of objects in the array.
  10566. If either of the indexes passed in is out-of-range, nothing will happen,
  10567. otherwise the two objects at these positions will be exchanged.
  10568. */
  10569. void swap (const int index1,
  10570. const int index2) throw()
  10571. {
  10572. const ScopedLockType lock (getLock());
  10573. if (isPositiveAndBelow (index1, numUsed)
  10574. && isPositiveAndBelow (index2, numUsed))
  10575. {
  10576. swapVariables (data.elements [index1],
  10577. data.elements [index2]);
  10578. }
  10579. }
  10580. /** Moves one of the objects to a different position.
  10581. This will move the object to a specified index, shuffling along
  10582. any intervening elements as required.
  10583. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  10584. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  10585. @param currentIndex the index of the object to be moved. If this isn't a
  10586. valid index, then nothing will be done
  10587. @param newIndex the index at which you'd like this object to end up. If this
  10588. is less than zero, it will be moved to the end of the array
  10589. */
  10590. void move (const int currentIndex,
  10591. int newIndex) throw()
  10592. {
  10593. if (currentIndex != newIndex)
  10594. {
  10595. const ScopedLockType lock (getLock());
  10596. if (isPositiveAndBelow (currentIndex, numUsed))
  10597. {
  10598. if (! isPositiveAndBelow (newIndex, numUsed))
  10599. newIndex = numUsed - 1;
  10600. ObjectClass* const value = data.elements [currentIndex];
  10601. if (newIndex > currentIndex)
  10602. {
  10603. memmove (data.elements + currentIndex,
  10604. data.elements + currentIndex + 1,
  10605. (newIndex - currentIndex) * sizeof (ObjectClass*));
  10606. }
  10607. else
  10608. {
  10609. memmove (data.elements + newIndex + 1,
  10610. data.elements + newIndex,
  10611. (currentIndex - newIndex) * sizeof (ObjectClass*));
  10612. }
  10613. data.elements [newIndex] = value;
  10614. }
  10615. }
  10616. }
  10617. /** This swaps the contents of this array with those of another array.
  10618. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  10619. because it just swaps their internal pointers.
  10620. */
  10621. void swapWithArray (ReferenceCountedArray& otherArray) throw()
  10622. {
  10623. const ScopedLockType lock1 (getLock());
  10624. const ScopedLockType lock2 (otherArray.getLock());
  10625. data.swapWith (otherArray.data);
  10626. swapVariables (numUsed, otherArray.numUsed);
  10627. }
  10628. /** Compares this array to another one.
  10629. @returns true only if the other array contains the same objects in the same order
  10630. */
  10631. bool operator== (const ReferenceCountedArray& other) const throw()
  10632. {
  10633. const ScopedLockType lock2 (other.getLock());
  10634. const ScopedLockType lock1 (getLock());
  10635. if (numUsed != other.numUsed)
  10636. return false;
  10637. for (int i = numUsed; --i >= 0;)
  10638. if (data.elements [i] != other.data.elements [i])
  10639. return false;
  10640. return true;
  10641. }
  10642. /** Compares this array to another one.
  10643. @see operator==
  10644. */
  10645. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  10646. {
  10647. return ! operator== (other);
  10648. }
  10649. /** Sorts the elements in the array.
  10650. This will use a comparator object to sort the elements into order. The object
  10651. passed must have a method of the form:
  10652. @code
  10653. int compareElements (ElementType first, ElementType second);
  10654. @endcode
  10655. ..and this method must return:
  10656. - a value of < 0 if the first comes before the second
  10657. - a value of 0 if the two objects are equivalent
  10658. - a value of > 0 if the second comes before the first
  10659. To improve performance, the compareElements() method can be declared as static or const.
  10660. @param comparator the comparator to use for comparing elements.
  10661. @param retainOrderOfEquivalentItems if this is true, then items
  10662. which the comparator says are equivalent will be
  10663. kept in the order in which they currently appear
  10664. in the array. This is slower to perform, but may
  10665. be important in some cases. If it's false, a faster
  10666. algorithm is used, but equivalent elements may be
  10667. rearranged.
  10668. @see sortArray
  10669. */
  10670. template <class ElementComparator>
  10671. void sort (ElementComparator& comparator,
  10672. const bool retainOrderOfEquivalentItems = false) const throw()
  10673. {
  10674. (void) comparator; // if you pass in an object with a static compareElements() method, this
  10675. // avoids getting warning messages about the parameter being unused
  10676. const ScopedLockType lock (getLock());
  10677. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  10678. }
  10679. /** Reduces the amount of storage being used by the array.
  10680. Arrays typically allocate slightly more storage than they need, and after
  10681. removing elements, they may have quite a lot of unused space allocated.
  10682. This method will reduce the amount of allocated storage to a minimum.
  10683. */
  10684. void minimiseStorageOverheads() throw()
  10685. {
  10686. const ScopedLockType lock (getLock());
  10687. data.shrinkToNoMoreThan (numUsed);
  10688. }
  10689. /** Returns the CriticalSection that locks this array.
  10690. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  10691. an object of ScopedLockType as an RAII lock for it.
  10692. */
  10693. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  10694. /** Returns the type of scoped lock to use for locking this array */
  10695. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  10696. private:
  10697. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  10698. int numUsed;
  10699. };
  10700. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10701. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  10702. #endif
  10703. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  10704. /*** Start of inlined file: juce_ScopedValueSetter.h ***/
  10705. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  10706. #define __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  10707. /**
  10708. Helper class providing an RAII-based mechanism for temporarily setting and
  10709. then re-setting a value.
  10710. E.g. @code
  10711. int x = 1;
  10712. {
  10713. ScopedValueSetter setter (x, 2);
  10714. // x is now 2
  10715. }
  10716. // x is now 1 again
  10717. {
  10718. ScopedValueSetter setter (x, 3, 4);
  10719. // x is now 3
  10720. }
  10721. // x is now 4
  10722. @endcode
  10723. */
  10724. template <typename ValueType>
  10725. class ScopedValueSetter
  10726. {
  10727. public:
  10728. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  10729. given new value, and will then reset it to its original value when this object is deleted.
  10730. */
  10731. ScopedValueSetter (ValueType& valueToSet,
  10732. const ValueType& newValue)
  10733. : value (valueToSet),
  10734. originalValue (valueToSet)
  10735. {
  10736. valueToSet = newValue;
  10737. }
  10738. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  10739. given new value, and will then reset it to be valueWhenDeleted when this object is deleted.
  10740. */
  10741. ScopedValueSetter (ValueType& valueToSet,
  10742. const ValueType& newValue,
  10743. const ValueType& valueWhenDeleted)
  10744. : value (valueToSet),
  10745. originalValue (valueWhenDeleted)
  10746. {
  10747. valueToSet = newValue;
  10748. }
  10749. ~ScopedValueSetter()
  10750. {
  10751. value = originalValue;
  10752. }
  10753. private:
  10754. ValueType& value;
  10755. const ValueType originalValue;
  10756. JUCE_DECLARE_NON_COPYABLE (ScopedValueSetter);
  10757. };
  10758. #endif // __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  10759. /*** End of inlined file: juce_ScopedValueSetter.h ***/
  10760. #endif
  10761. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  10762. /*** Start of inlined file: juce_SortedSet.h ***/
  10763. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  10764. #define __JUCE_SORTEDSET_JUCEHEADER__
  10765. #if JUCE_MSVC
  10766. #pragma warning (push)
  10767. #pragma warning (disable: 4512)
  10768. #endif
  10769. /**
  10770. Holds a set of unique primitive objects, such as ints or doubles.
  10771. A set can only hold one item with a given value, so if for example it's a
  10772. set of integers, attempting to add the same integer twice will do nothing
  10773. the second time.
  10774. Internally, the list of items is kept sorted (which means that whatever
  10775. kind of primitive type is used must support the ==, <, >, <= and >= operators
  10776. to determine the order), and searching the set for known values is very fast
  10777. because it uses a binary-chop method.
  10778. Note that if you're using a class or struct as the element type, it must be
  10779. capable of being copied or moved with a straightforward memcpy, rather than
  10780. needing construction and destruction code.
  10781. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  10782. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  10783. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  10784. */
  10785. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  10786. class SortedSet
  10787. {
  10788. public:
  10789. /** Creates an empty set. */
  10790. SortedSet() throw()
  10791. : numUsed (0)
  10792. {
  10793. }
  10794. /** Creates a copy of another set.
  10795. @param other the set to copy
  10796. */
  10797. SortedSet (const SortedSet& other) throw()
  10798. {
  10799. const ScopedLockType lock (other.getLock());
  10800. numUsed = other.numUsed;
  10801. data.setAllocatedSize (other.numUsed);
  10802. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  10803. }
  10804. /** Destructor. */
  10805. ~SortedSet() throw()
  10806. {
  10807. }
  10808. /** Copies another set over this one.
  10809. @param other the set to copy
  10810. */
  10811. SortedSet& operator= (const SortedSet& other) throw()
  10812. {
  10813. if (this != &other)
  10814. {
  10815. const ScopedLockType lock1 (other.getLock());
  10816. const ScopedLockType lock2 (getLock());
  10817. data.ensureAllocatedSize (other.size());
  10818. numUsed = other.numUsed;
  10819. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  10820. minimiseStorageOverheads();
  10821. }
  10822. return *this;
  10823. }
  10824. /** Compares this set to another one.
  10825. Two sets are considered equal if they both contain the same set of
  10826. elements.
  10827. @param other the other set to compare with
  10828. */
  10829. bool operator== (const SortedSet<ElementType>& other) const throw()
  10830. {
  10831. const ScopedLockType lock (getLock());
  10832. if (numUsed != other.numUsed)
  10833. return false;
  10834. for (int i = numUsed; --i >= 0;)
  10835. if (data.elements[i] != other.data.elements[i])
  10836. return false;
  10837. return true;
  10838. }
  10839. /** Compares this set to another one.
  10840. Two sets are considered equal if they both contain the same set of
  10841. elements.
  10842. @param other the other set to compare with
  10843. */
  10844. bool operator!= (const SortedSet<ElementType>& other) const throw()
  10845. {
  10846. return ! operator== (other);
  10847. }
  10848. /** Removes all elements from the set.
  10849. This will remove all the elements, and free any storage that the set is
  10850. using. To clear it without freeing the storage, use the clearQuick()
  10851. method instead.
  10852. @see clearQuick
  10853. */
  10854. void clear() throw()
  10855. {
  10856. const ScopedLockType lock (getLock());
  10857. data.setAllocatedSize (0);
  10858. numUsed = 0;
  10859. }
  10860. /** Removes all elements from the set without freeing the array's allocated storage.
  10861. @see clear
  10862. */
  10863. void clearQuick() throw()
  10864. {
  10865. const ScopedLockType lock (getLock());
  10866. numUsed = 0;
  10867. }
  10868. /** Returns the current number of elements in the set.
  10869. */
  10870. inline int size() const throw()
  10871. {
  10872. return numUsed;
  10873. }
  10874. /** Returns one of the elements in the set.
  10875. If the index passed in is beyond the range of valid elements, this
  10876. will return zero.
  10877. If you're certain that the index will always be a valid element, you
  10878. can call getUnchecked() instead, which is faster.
  10879. @param index the index of the element being requested (0 is the first element in the set)
  10880. @see getUnchecked, getFirst, getLast
  10881. */
  10882. inline ElementType operator[] (const int index) const throw()
  10883. {
  10884. const ScopedLockType lock (getLock());
  10885. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  10886. : ElementType();
  10887. }
  10888. /** Returns one of the elements in the set, without checking the index passed in.
  10889. Unlike the operator[] method, this will try to return an element without
  10890. checking that the index is within the bounds of the set, so should only
  10891. be used when you're confident that it will always be a valid index.
  10892. @param index the index of the element being requested (0 is the first element in the set)
  10893. @see operator[], getFirst, getLast
  10894. */
  10895. inline ElementType getUnchecked (const int index) const throw()
  10896. {
  10897. const ScopedLockType lock (getLock());
  10898. jassert (isPositiveAndBelow (index, numUsed));
  10899. return data.elements [index];
  10900. }
  10901. /** Returns the first element in the set, or 0 if the set is empty.
  10902. @see operator[], getUnchecked, getLast
  10903. */
  10904. inline ElementType getFirst() const throw()
  10905. {
  10906. const ScopedLockType lock (getLock());
  10907. return numUsed > 0 ? data.elements [0] : ElementType();
  10908. }
  10909. /** Returns the last element in the set, or 0 if the set is empty.
  10910. @see operator[], getUnchecked, getFirst
  10911. */
  10912. inline ElementType getLast() const throw()
  10913. {
  10914. const ScopedLockType lock (getLock());
  10915. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  10916. }
  10917. /** Finds the index of the first element which matches the value passed in.
  10918. This will search the set for the given object, and return the index
  10919. of its first occurrence. If the object isn't found, the method will return -1.
  10920. @param elementToLookFor the value or object to look for
  10921. @returns the index of the object, or -1 if it's not found
  10922. */
  10923. int indexOf (const ElementType elementToLookFor) const throw()
  10924. {
  10925. const ScopedLockType lock (getLock());
  10926. int start = 0;
  10927. int end = numUsed;
  10928. for (;;)
  10929. {
  10930. if (start >= end)
  10931. {
  10932. return -1;
  10933. }
  10934. else if (elementToLookFor == data.elements [start])
  10935. {
  10936. return start;
  10937. }
  10938. else
  10939. {
  10940. const int halfway = (start + end) >> 1;
  10941. if (halfway == start)
  10942. return -1;
  10943. else if (elementToLookFor >= data.elements [halfway])
  10944. start = halfway;
  10945. else
  10946. end = halfway;
  10947. }
  10948. }
  10949. }
  10950. /** Returns true if the set contains at least one occurrence of an object.
  10951. @param elementToLookFor the value or object to look for
  10952. @returns true if the item is found
  10953. */
  10954. bool contains (const ElementType elementToLookFor) const throw()
  10955. {
  10956. const ScopedLockType lock (getLock());
  10957. int start = 0;
  10958. int end = numUsed;
  10959. for (;;)
  10960. {
  10961. if (start >= end)
  10962. {
  10963. return false;
  10964. }
  10965. else if (elementToLookFor == data.elements [start])
  10966. {
  10967. return true;
  10968. }
  10969. else
  10970. {
  10971. const int halfway = (start + end) >> 1;
  10972. if (halfway == start)
  10973. return false;
  10974. else if (elementToLookFor >= data.elements [halfway])
  10975. start = halfway;
  10976. else
  10977. end = halfway;
  10978. }
  10979. }
  10980. }
  10981. /** Adds a new element to the set, (as long as it's not already in there).
  10982. @param newElement the new object to add to the set
  10983. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  10984. */
  10985. void add (const ElementType newElement) throw()
  10986. {
  10987. const ScopedLockType lock (getLock());
  10988. int start = 0;
  10989. int end = numUsed;
  10990. for (;;)
  10991. {
  10992. if (start >= end)
  10993. {
  10994. jassert (start <= end);
  10995. insertInternal (start, newElement);
  10996. break;
  10997. }
  10998. else if (newElement == data.elements [start])
  10999. {
  11000. break;
  11001. }
  11002. else
  11003. {
  11004. const int halfway = (start + end) >> 1;
  11005. if (halfway == start)
  11006. {
  11007. if (newElement >= data.elements [halfway])
  11008. insertInternal (start + 1, newElement);
  11009. else
  11010. insertInternal (start, newElement);
  11011. break;
  11012. }
  11013. else if (newElement >= data.elements [halfway])
  11014. start = halfway;
  11015. else
  11016. end = halfway;
  11017. }
  11018. }
  11019. }
  11020. /** Adds elements from an array to this set.
  11021. @param elementsToAdd the array of elements to add
  11022. @param numElementsToAdd how many elements are in this other array
  11023. @see add
  11024. */
  11025. void addArray (const ElementType* elementsToAdd,
  11026. int numElementsToAdd) throw()
  11027. {
  11028. const ScopedLockType lock (getLock());
  11029. while (--numElementsToAdd >= 0)
  11030. add (*elementsToAdd++);
  11031. }
  11032. /** Adds elements from another set to this one.
  11033. @param setToAddFrom the set from which to copy the elements
  11034. @param startIndex the first element of the other set to start copying from
  11035. @param numElementsToAdd how many elements to add from the other set. If this
  11036. value is negative or greater than the number of available elements,
  11037. all available elements will be copied.
  11038. @see add
  11039. */
  11040. template <class OtherSetType>
  11041. void addSet (const OtherSetType& setToAddFrom,
  11042. int startIndex = 0,
  11043. int numElementsToAdd = -1) throw()
  11044. {
  11045. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  11046. {
  11047. const ScopedLockType lock2 (getLock());
  11048. jassert (this != &setToAddFrom);
  11049. if (this != &setToAddFrom)
  11050. {
  11051. if (startIndex < 0)
  11052. {
  11053. jassertfalse;
  11054. startIndex = 0;
  11055. }
  11056. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  11057. numElementsToAdd = setToAddFrom.size() - startIndex;
  11058. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  11059. }
  11060. }
  11061. }
  11062. /** Removes an element from the set.
  11063. This will remove the element at a given index.
  11064. If the index passed in is out-of-range, nothing will happen.
  11065. @param indexToRemove the index of the element to remove
  11066. @returns the element that has been removed
  11067. @see removeValue, removeRange
  11068. */
  11069. ElementType remove (const int indexToRemove) throw()
  11070. {
  11071. const ScopedLockType lock (getLock());
  11072. if (isPositiveAndBelow (indexToRemove, numUsed))
  11073. {
  11074. --numUsed;
  11075. ElementType* const e = data.elements + indexToRemove;
  11076. ElementType const removed = *e;
  11077. const int numberToShift = numUsed - indexToRemove;
  11078. if (numberToShift > 0)
  11079. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  11080. if ((numUsed << 1) < data.numAllocated)
  11081. minimiseStorageOverheads();
  11082. return removed;
  11083. }
  11084. return 0;
  11085. }
  11086. /** Removes an item from the set.
  11087. This will remove the given element from the set, if it's there.
  11088. @param valueToRemove the object to try to remove
  11089. @see remove, removeRange
  11090. */
  11091. void removeValue (const ElementType valueToRemove) throw()
  11092. {
  11093. const ScopedLockType lock (getLock());
  11094. remove (indexOf (valueToRemove));
  11095. }
  11096. /** Removes any elements which are also in another set.
  11097. @param otherSet the other set in which to look for elements to remove
  11098. @see removeValuesNotIn, remove, removeValue, removeRange
  11099. */
  11100. template <class OtherSetType>
  11101. void removeValuesIn (const OtherSetType& otherSet) throw()
  11102. {
  11103. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11104. const ScopedLockType lock2 (getLock());
  11105. if (this == &otherSet)
  11106. {
  11107. clear();
  11108. }
  11109. else
  11110. {
  11111. if (otherSet.size() > 0)
  11112. {
  11113. for (int i = numUsed; --i >= 0;)
  11114. if (otherSet.contains (data.elements [i]))
  11115. remove (i);
  11116. }
  11117. }
  11118. }
  11119. /** Removes any elements which are not found in another set.
  11120. Only elements which occur in this other set will be retained.
  11121. @param otherSet the set in which to look for elements NOT to remove
  11122. @see removeValuesIn, remove, removeValue, removeRange
  11123. */
  11124. template <class OtherSetType>
  11125. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  11126. {
  11127. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11128. const ScopedLockType lock2 (getLock());
  11129. if (this != &otherSet)
  11130. {
  11131. if (otherSet.size() <= 0)
  11132. {
  11133. clear();
  11134. }
  11135. else
  11136. {
  11137. for (int i = numUsed; --i >= 0;)
  11138. if (! otherSet.contains (data.elements [i]))
  11139. remove (i);
  11140. }
  11141. }
  11142. }
  11143. /** Reduces the amount of storage being used by the set.
  11144. Sets typically allocate slightly more storage than they need, and after
  11145. removing elements, they may have quite a lot of unused space allocated.
  11146. This method will reduce the amount of allocated storage to a minimum.
  11147. */
  11148. void minimiseStorageOverheads() throw()
  11149. {
  11150. const ScopedLockType lock (getLock());
  11151. data.shrinkToNoMoreThan (numUsed);
  11152. }
  11153. /** Returns the CriticalSection that locks this array.
  11154. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  11155. an object of ScopedLockType as an RAII lock for it.
  11156. */
  11157. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  11158. /** Returns the type of scoped lock to use for locking this array */
  11159. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  11160. private:
  11161. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  11162. int numUsed;
  11163. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  11164. {
  11165. data.ensureAllocatedSize (numUsed + 1);
  11166. ElementType* const insertPos = data.elements + indexToInsertAt;
  11167. const int numberToMove = numUsed - indexToInsertAt;
  11168. if (numberToMove > 0)
  11169. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  11170. *insertPos = newElement;
  11171. ++numUsed;
  11172. }
  11173. };
  11174. #if JUCE_MSVC
  11175. #pragma warning (pop)
  11176. #endif
  11177. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  11178. /*** End of inlined file: juce_SortedSet.h ***/
  11179. #endif
  11180. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11181. /*** Start of inlined file: juce_SparseSet.h ***/
  11182. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11183. #define __JUCE_SPARSESET_JUCEHEADER__
  11184. /*** Start of inlined file: juce_Range.h ***/
  11185. #ifndef __JUCE_RANGE_JUCEHEADER__
  11186. #define __JUCE_RANGE_JUCEHEADER__
  11187. /** A general-purpose range object, that simply represents any linear range with
  11188. a start and end point.
  11189. The templated parameter is expected to be a primitive integer or floating point
  11190. type, though class types could also be used if they behave in a number-like way.
  11191. */
  11192. template <typename ValueType>
  11193. class Range
  11194. {
  11195. public:
  11196. /** Constructs an empty range. */
  11197. Range() throw()
  11198. : start (ValueType()), end (ValueType())
  11199. {
  11200. }
  11201. /** Constructs a range with given start and end values. */
  11202. Range (const ValueType start_, const ValueType end_) throw()
  11203. : start (start_), end (jmax (start_, end_))
  11204. {
  11205. }
  11206. /** Constructs a copy of another range. */
  11207. Range (const Range& other) throw()
  11208. : start (other.start), end (other.end)
  11209. {
  11210. }
  11211. /** Copies another range object. */
  11212. Range& operator= (const Range& other) throw()
  11213. {
  11214. start = other.start;
  11215. end = other.end;
  11216. return *this;
  11217. }
  11218. /** Destructor. */
  11219. ~Range() throw()
  11220. {
  11221. }
  11222. /** Returns the range that lies between two positions (in either order). */
  11223. static const Range between (const ValueType position1, const ValueType position2) throw()
  11224. {
  11225. return (position1 < position2) ? Range (position1, position2)
  11226. : Range (position2, position1);
  11227. }
  11228. /** Returns a range with the specified start position and a length of zero. */
  11229. static const Range emptyRange (const ValueType start) throw()
  11230. {
  11231. return Range (start, start);
  11232. }
  11233. /** Returns the start of the range. */
  11234. inline ValueType getStart() const throw() { return start; }
  11235. /** Returns the length of the range. */
  11236. inline ValueType getLength() const throw() { return end - start; }
  11237. /** Returns the end of the range. */
  11238. inline ValueType getEnd() const throw() { return end; }
  11239. /** Returns true if the range has a length of zero. */
  11240. inline bool isEmpty() const throw() { return start == end; }
  11241. /** Changes the start position of the range, leaving the end position unchanged.
  11242. If the new start position is higher than the current end of the range, the end point
  11243. will be pushed along to equal it, leaving an empty range at the new position.
  11244. */
  11245. void setStart (const ValueType newStart) throw()
  11246. {
  11247. start = newStart;
  11248. if (end < newStart)
  11249. end = newStart;
  11250. }
  11251. /** Returns a range with the same end as this one, but a different start.
  11252. If the new start position is higher than the current end of the range, the end point
  11253. will be pushed along to equal it, returning an empty range at the new position.
  11254. */
  11255. const Range withStart (const ValueType newStart) const throw()
  11256. {
  11257. return Range (newStart, jmax (newStart, end));
  11258. }
  11259. /** Returns a range with the same length as this one, but moved to have the given start position. */
  11260. const Range movedToStartAt (const ValueType newStart) const throw()
  11261. {
  11262. return Range (newStart, end + (newStart - start));
  11263. }
  11264. /** Changes the end position of the range, leaving the start unchanged.
  11265. If the new end position is below the current start of the range, the start point
  11266. will be pushed back to equal the new end point.
  11267. */
  11268. void setEnd (const ValueType newEnd) throw()
  11269. {
  11270. end = newEnd;
  11271. if (newEnd < start)
  11272. start = newEnd;
  11273. }
  11274. /** Returns a range with the same start position as this one, but a different end.
  11275. If the new end position is below the current start of the range, the start point
  11276. will be pushed back to equal the new end point.
  11277. */
  11278. const Range withEnd (const ValueType newEnd) const throw()
  11279. {
  11280. return Range (jmin (start, newEnd), newEnd);
  11281. }
  11282. /** Returns a range with the same length as this one, but moved to have the given start position. */
  11283. const Range movedToEndAt (const ValueType newEnd) const throw()
  11284. {
  11285. return Range (start + (newEnd - end), newEnd);
  11286. }
  11287. /** Changes the length of the range.
  11288. Lengths less than zero are treated as zero.
  11289. */
  11290. void setLength (const ValueType newLength) throw()
  11291. {
  11292. end = start + jmax (ValueType(), newLength);
  11293. }
  11294. /** Returns a range with the same start as this one, but a different length.
  11295. Lengths less than zero are treated as zero.
  11296. */
  11297. const Range withLength (const ValueType newLength) const throw()
  11298. {
  11299. return Range (start, start + newLength);
  11300. }
  11301. /** Adds an amount to the start and end of the range. */
  11302. inline const Range& operator+= (const ValueType amountToAdd) throw()
  11303. {
  11304. start += amountToAdd;
  11305. end += amountToAdd;
  11306. return *this;
  11307. }
  11308. /** Subtracts an amount from the start and end of the range. */
  11309. inline const Range& operator-= (const ValueType amountToSubtract) throw()
  11310. {
  11311. start -= amountToSubtract;
  11312. end -= amountToSubtract;
  11313. return *this;
  11314. }
  11315. /** Returns a range that is equal to this one with an amount added to its
  11316. start and end.
  11317. */
  11318. const Range operator+ (const ValueType amountToAdd) const throw()
  11319. {
  11320. return Range (start + amountToAdd, end + amountToAdd);
  11321. }
  11322. /** Returns a range that is equal to this one with the specified amount
  11323. subtracted from its start and end. */
  11324. const Range operator- (const ValueType amountToSubtract) const throw()
  11325. {
  11326. return Range (start - amountToSubtract, end - amountToSubtract);
  11327. }
  11328. bool operator== (const Range& other) const throw() { return start == other.start && end == other.end; }
  11329. bool operator!= (const Range& other) const throw() { return start != other.start || end != other.end; }
  11330. /** Returns true if the given position lies inside this range. */
  11331. bool contains (const ValueType position) const throw()
  11332. {
  11333. return start <= position && position < end;
  11334. }
  11335. /** Returns the nearest value to the one supplied, which lies within the range. */
  11336. ValueType clipValue (const ValueType value) const throw()
  11337. {
  11338. return jlimit (start, end, value);
  11339. }
  11340. /** Returns true if the given range lies entirely inside this range. */
  11341. bool contains (const Range& other) const throw()
  11342. {
  11343. return start <= other.start && end >= other.end;
  11344. }
  11345. /** Returns true if the given range intersects this one. */
  11346. bool intersects (const Range& other) const throw()
  11347. {
  11348. return other.start < end && start < other.end;
  11349. }
  11350. /** Returns the range that is the intersection of the two ranges, or an empty range
  11351. with an undefined start position if they don't overlap. */
  11352. const Range getIntersectionWith (const Range& other) const throw()
  11353. {
  11354. return Range (jmax (start, other.start),
  11355. jmin (end, other.end));
  11356. }
  11357. /** Returns the smallest range that contains both this one and the other one. */
  11358. const Range getUnionWith (const Range& other) const throw()
  11359. {
  11360. return Range (jmin (start, other.start),
  11361. jmax (end, other.end));
  11362. }
  11363. /** Returns a given range, after moving it forwards or backwards to fit it
  11364. within this range.
  11365. If the supplied range has a greater length than this one, the return value
  11366. will be this range.
  11367. Otherwise, if the supplied range is smaller than this one, the return value
  11368. will be the new range, shifted forwards or backwards so that it doesn't extend
  11369. beyond this one, but keeping its original length.
  11370. */
  11371. const Range constrainRange (const Range& rangeToConstrain) const throw()
  11372. {
  11373. const ValueType otherLen = rangeToConstrain.getLength();
  11374. return getLength() <= otherLen
  11375. ? *this
  11376. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  11377. }
  11378. private:
  11379. ValueType start, end;
  11380. };
  11381. #endif // __JUCE_RANGE_JUCEHEADER__
  11382. /*** End of inlined file: juce_Range.h ***/
  11383. /**
  11384. Holds a set of primitive values, storing them as a set of ranges.
  11385. This container acts like an array, but can efficiently hold large continguous
  11386. ranges of values. It's quite a specialised class, mostly useful for things
  11387. like keeping the set of selected rows in a listbox.
  11388. The type used as a template paramter must be an integer type, such as int, short,
  11389. int64, etc.
  11390. */
  11391. template <class Type>
  11392. class SparseSet
  11393. {
  11394. public:
  11395. /** Creates a new empty set. */
  11396. SparseSet()
  11397. {
  11398. }
  11399. /** Creates a copy of another SparseSet. */
  11400. SparseSet (const SparseSet<Type>& other)
  11401. : values (other.values)
  11402. {
  11403. }
  11404. /** Clears the set. */
  11405. void clear()
  11406. {
  11407. values.clear();
  11408. }
  11409. /** Checks whether the set is empty.
  11410. This is much quicker than using (size() == 0).
  11411. */
  11412. bool isEmpty() const throw()
  11413. {
  11414. return values.size() == 0;
  11415. }
  11416. /** Returns the number of values in the set.
  11417. Because of the way the data is stored, this method can take longer if there
  11418. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  11419. are any items.
  11420. */
  11421. Type size() const
  11422. {
  11423. Type total (0);
  11424. for (int i = 0; i < values.size(); i += 2)
  11425. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  11426. return total;
  11427. }
  11428. /** Returns one of the values in the set.
  11429. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  11430. @returns the value at this index, or 0 if it's out-of-range
  11431. */
  11432. Type operator[] (Type index) const
  11433. {
  11434. for (int i = 0; i < values.size(); i += 2)
  11435. {
  11436. const Type start (values.getUnchecked (i));
  11437. const Type len (values.getUnchecked (i + 1) - start);
  11438. if (index < len)
  11439. return start + index;
  11440. index -= len;
  11441. }
  11442. return Type();
  11443. }
  11444. /** Checks whether a particular value is in the set. */
  11445. bool contains (const Type valueToLookFor) const
  11446. {
  11447. for (int i = 0; i < values.size(); ++i)
  11448. if (valueToLookFor < values.getUnchecked(i))
  11449. return (i & 1) != 0;
  11450. return false;
  11451. }
  11452. /** Returns the number of contiguous blocks of values.
  11453. @see getRange
  11454. */
  11455. int getNumRanges() const throw()
  11456. {
  11457. return values.size() >> 1;
  11458. }
  11459. /** Returns one of the contiguous ranges of values stored.
  11460. @param rangeIndex the index of the range to look up, between 0
  11461. and (getNumRanges() - 1)
  11462. @see getTotalRange
  11463. */
  11464. const Range<Type> getRange (const int rangeIndex) const
  11465. {
  11466. if (isPositiveAndBelow (rangeIndex, getNumRanges()))
  11467. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  11468. values.getUnchecked ((rangeIndex << 1) + 1));
  11469. else
  11470. return Range<Type>();
  11471. }
  11472. /** Returns the range between the lowest and highest values in the set.
  11473. @see getRange
  11474. */
  11475. const Range<Type> getTotalRange() const
  11476. {
  11477. if (values.size() > 0)
  11478. {
  11479. jassert ((values.size() & 1) == 0);
  11480. return Range<Type> (values.getUnchecked (0),
  11481. values.getUnchecked (values.size() - 1));
  11482. }
  11483. return Range<Type>();
  11484. }
  11485. /** Adds a range of contiguous values to the set.
  11486. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  11487. */
  11488. void addRange (const Range<Type>& range)
  11489. {
  11490. jassert (range.getLength() >= 0);
  11491. if (range.getLength() > 0)
  11492. {
  11493. removeRange (range);
  11494. values.addUsingDefaultSort (range.getStart());
  11495. values.addUsingDefaultSort (range.getEnd());
  11496. simplify();
  11497. }
  11498. }
  11499. /** Removes a range of values from the set.
  11500. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  11501. */
  11502. void removeRange (const Range<Type>& rangeToRemove)
  11503. {
  11504. jassert (rangeToRemove.getLength() >= 0);
  11505. if (rangeToRemove.getLength() > 0
  11506. && values.size() > 0
  11507. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  11508. && values.getUnchecked(0) < rangeToRemove.getEnd())
  11509. {
  11510. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  11511. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  11512. const bool onAtEnd = contains (lastValue);
  11513. for (int i = values.size(); --i >= 0;)
  11514. {
  11515. if (values.getUnchecked(i) <= lastValue)
  11516. {
  11517. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  11518. {
  11519. values.remove (i);
  11520. if (--i < 0)
  11521. break;
  11522. }
  11523. break;
  11524. }
  11525. }
  11526. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  11527. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  11528. simplify();
  11529. }
  11530. }
  11531. /** Does an XOR of the values in a given range. */
  11532. void invertRange (const Range<Type>& range)
  11533. {
  11534. SparseSet newItems;
  11535. newItems.addRange (range);
  11536. int i;
  11537. for (i = getNumRanges(); --i >= 0;)
  11538. newItems.removeRange (getRange (i));
  11539. removeRange (range);
  11540. for (i = newItems.getNumRanges(); --i >= 0;)
  11541. addRange (newItems.getRange(i));
  11542. }
  11543. /** Checks whether any part of a given range overlaps any part of this set. */
  11544. bool overlapsRange (const Range<Type>& range)
  11545. {
  11546. if (range.getLength() > 0)
  11547. {
  11548. for (int i = getNumRanges(); --i >= 0;)
  11549. {
  11550. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  11551. return false;
  11552. if (values.getUnchecked (i << 1) < range.getEnd())
  11553. return true;
  11554. }
  11555. }
  11556. return false;
  11557. }
  11558. /** Checks whether the whole of a given range is contained within this one. */
  11559. bool containsRange (const Range<Type>& range)
  11560. {
  11561. if (range.getLength() > 0)
  11562. {
  11563. for (int i = getNumRanges(); --i >= 0;)
  11564. {
  11565. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  11566. return false;
  11567. if (values.getUnchecked (i << 1) <= range.getStart()
  11568. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  11569. return true;
  11570. }
  11571. }
  11572. return false;
  11573. }
  11574. bool operator== (const SparseSet<Type>& other) throw()
  11575. {
  11576. return values == other.values;
  11577. }
  11578. bool operator!= (const SparseSet<Type>& other) throw()
  11579. {
  11580. return values != other.values;
  11581. }
  11582. private:
  11583. // alternating start/end values of ranges of values that are present.
  11584. Array<Type, DummyCriticalSection> values;
  11585. void simplify()
  11586. {
  11587. jassert ((values.size() & 1) == 0);
  11588. for (int i = values.size(); --i > 0;)
  11589. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  11590. values.removeRange (--i, 2);
  11591. }
  11592. };
  11593. #endif // __JUCE_SPARSESET_JUCEHEADER__
  11594. /*** End of inlined file: juce_SparseSet.h ***/
  11595. #endif
  11596. #ifndef __JUCE_VALUE_JUCEHEADER__
  11597. /*** Start of inlined file: juce_Value.h ***/
  11598. #ifndef __JUCE_VALUE_JUCEHEADER__
  11599. #define __JUCE_VALUE_JUCEHEADER__
  11600. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  11601. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  11602. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  11603. /*** Start of inlined file: juce_CallbackMessage.h ***/
  11604. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  11605. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  11606. /*** Start of inlined file: juce_Message.h ***/
  11607. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  11608. #define __JUCE_MESSAGE_JUCEHEADER__
  11609. class MessageListener;
  11610. class MessageManager;
  11611. /** The base class for objects that can be delivered to a MessageListener.
  11612. The simplest Message object contains a few integer and pointer parameters
  11613. that the user can set, and this is enough for a lot of purposes. For passing more
  11614. complex data, subclasses of Message can also be used.
  11615. @see MessageListener, MessageManager, ActionListener, ChangeListener
  11616. */
  11617. class JUCE_API Message : public ReferenceCountedObject
  11618. {
  11619. public:
  11620. /** Creates an uninitialised message.
  11621. The class's variables will also be left uninitialised.
  11622. */
  11623. Message() throw();
  11624. /** Creates a message object, filling in the member variables.
  11625. The corresponding public member variables will be set from the parameters
  11626. passed in.
  11627. */
  11628. Message (int intParameter1,
  11629. int intParameter2,
  11630. int intParameter3,
  11631. void* pointerParameter) throw();
  11632. /** Destructor. */
  11633. virtual ~Message();
  11634. // These values can be used for carrying simple data that the application needs to
  11635. // pass around. For more complex messages, just create a subclass.
  11636. int intParameter1; /**< user-defined integer value. */
  11637. int intParameter2; /**< user-defined integer value. */
  11638. int intParameter3; /**< user-defined integer value. */
  11639. void* pointerParameter; /**< user-defined pointer value. */
  11640. /** A typedef for pointers to messages. */
  11641. typedef ReferenceCountedObjectPtr <Message> Ptr;
  11642. private:
  11643. friend class MessageListener;
  11644. friend class MessageManager;
  11645. MessageListener* messageRecipient;
  11646. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Message);
  11647. };
  11648. #endif // __JUCE_MESSAGE_JUCEHEADER__
  11649. /*** End of inlined file: juce_Message.h ***/
  11650. /**
  11651. A message that calls a custom function when it gets delivered.
  11652. You can use this class to fire off actions that you want to be performed later
  11653. on the message thread.
  11654. Unlike other Message objects, these don't get sent to a MessageListener, you
  11655. just call the post() method to send them, and when they arrive, your
  11656. messageCallback() method will automatically be invoked.
  11657. Always create an instance of a CallbackMessage on the heap, as it will be
  11658. deleted automatically after the message has been delivered.
  11659. @see MessageListener, MessageManager, ActionListener, ChangeListener
  11660. */
  11661. class JUCE_API CallbackMessage : public Message
  11662. {
  11663. public:
  11664. CallbackMessage() throw();
  11665. /** Destructor. */
  11666. ~CallbackMessage();
  11667. /** Called when the message is delivered.
  11668. You should implement this method and make it do whatever action you want
  11669. to perform.
  11670. Note that like all other messages, this object will be deleted immediately
  11671. after this method has been invoked.
  11672. */
  11673. virtual void messageCallback() = 0;
  11674. /** Instead of sending this message to a MessageListener, just call this method
  11675. to post it to the event queue.
  11676. After you've called this, this object will belong to the MessageManager,
  11677. which will delete it later. So make sure you don't delete the object yourself,
  11678. call post() more than once, or call post() on a stack-based obect!
  11679. */
  11680. void post();
  11681. private:
  11682. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallbackMessage);
  11683. };
  11684. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  11685. /*** End of inlined file: juce_CallbackMessage.h ***/
  11686. /**
  11687. Has a callback method that is triggered asynchronously.
  11688. This object allows an asynchronous callback function to be triggered, for
  11689. tasks such as coalescing multiple updates into a single callback later on.
  11690. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  11691. message thread calling handleAsyncUpdate() as soon as it can.
  11692. */
  11693. class JUCE_API AsyncUpdater
  11694. {
  11695. public:
  11696. /** Creates an AsyncUpdater object. */
  11697. AsyncUpdater();
  11698. /** Destructor.
  11699. If there are any pending callbacks when the object is deleted, these are lost.
  11700. */
  11701. virtual ~AsyncUpdater();
  11702. /** Causes the callback to be triggered at a later time.
  11703. This method returns immediately, having made sure that a callback
  11704. to the handleAsyncUpdate() method will occur as soon as possible.
  11705. If an update callback is already pending but hasn't happened yet, calls
  11706. to this method will be ignored.
  11707. It's thread-safe to call this method from any number of threads without
  11708. needing to worry about locking.
  11709. */
  11710. void triggerAsyncUpdate();
  11711. /** This will stop any pending updates from happening.
  11712. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  11713. callback happens, this will cancel the handleAsyncUpdate() callback.
  11714. Note that this method simply cancels the next callback - if a callback is already
  11715. in progress on a different thread, this won't block until it finishes, so there's
  11716. no guarantee that the callback isn't still running when you return from
  11717. */
  11718. void cancelPendingUpdate() throw();
  11719. /** If an update has been triggered and is pending, this will invoke it
  11720. synchronously.
  11721. Use this as a kind of "flush" operation - if an update is pending, the
  11722. handleAsyncUpdate() method will be called immediately; if no update is
  11723. pending, then nothing will be done.
  11724. Because this may invoke the callback, this method must only be called on
  11725. the main event thread.
  11726. */
  11727. void handleUpdateNowIfNeeded();
  11728. /** Returns true if there's an update callback in the pipeline. */
  11729. bool isUpdatePending() const throw();
  11730. /** Called back to do whatever your class needs to do.
  11731. This method is called by the message thread at the next convenient time
  11732. after the triggerAsyncUpdate() method has been called.
  11733. */
  11734. virtual void handleAsyncUpdate() = 0;
  11735. private:
  11736. ReferenceCountedObjectPtr<CallbackMessage> message;
  11737. Atomic<int>& getDeliveryFlag() const throw();
  11738. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AsyncUpdater);
  11739. };
  11740. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  11741. /*** End of inlined file: juce_AsyncUpdater.h ***/
  11742. /*** Start of inlined file: juce_ListenerList.h ***/
  11743. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  11744. #define __JUCE_LISTENERLIST_JUCEHEADER__
  11745. /**
  11746. Holds a set of objects and can invoke a member function callback on each object
  11747. in the set with a single call.
  11748. Use a ListenerList to manage a set of objects which need a callback, and you
  11749. can invoke a member function by simply calling call() or callChecked().
  11750. E.g.
  11751. @code
  11752. class MyListenerType
  11753. {
  11754. public:
  11755. void myCallbackMethod (int foo, bool bar);
  11756. };
  11757. ListenerList <MyListenerType> listeners;
  11758. listeners.add (someCallbackObjects...);
  11759. // This will invoke myCallbackMethod (1234, true) on each of the objects
  11760. // in the list...
  11761. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  11762. @endcode
  11763. If you add or remove listeners from the list during one of the callbacks - i.e. while
  11764. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  11765. will be mistakenly called after they've been removed, but it may mean that some of the
  11766. listeners could be called more than once, or not at all, depending on the list's order.
  11767. Sometimes, there's a chance that invoking one of the callbacks might result in the
  11768. list itself being deleted while it's still iterating - to survive this situation, you can
  11769. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  11770. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  11771. the list will check this after each callback to determine whether it should abort the
  11772. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  11773. which can be used to check when a Component has been deleted. See also
  11774. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  11775. */
  11776. template <class ListenerClass,
  11777. class ArrayType = Array <ListenerClass*> >
  11778. class ListenerList
  11779. {
  11780. // Horrible macros required to support VC6/7..
  11781. #ifndef DOXYGEN
  11782. #if JUCE_VC8_OR_EARLIER
  11783. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  11784. #define LL_PARAM(a) Q##a& param##a
  11785. #else
  11786. #define LL_TEMPLATE(a) typename P##a
  11787. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  11788. #endif
  11789. #endif
  11790. public:
  11791. /** Creates an empty list. */
  11792. ListenerList()
  11793. {
  11794. }
  11795. /** Destructor. */
  11796. ~ListenerList()
  11797. {
  11798. }
  11799. /** Adds a listener to the list.
  11800. A listener can only be added once, so if the listener is already in the list,
  11801. this method has no effect.
  11802. @see remove
  11803. */
  11804. void add (ListenerClass* const listenerToAdd)
  11805. {
  11806. // Listeners can't be null pointers!
  11807. jassert (listenerToAdd != 0);
  11808. if (listenerToAdd != 0)
  11809. listeners.addIfNotAlreadyThere (listenerToAdd);
  11810. }
  11811. /** Removes a listener from the list.
  11812. If the listener wasn't in the list, this has no effect.
  11813. */
  11814. void remove (ListenerClass* const listenerToRemove)
  11815. {
  11816. // Listeners can't be null pointers!
  11817. jassert (listenerToRemove != 0);
  11818. listeners.removeValue (listenerToRemove);
  11819. }
  11820. /** Returns the number of registered listeners. */
  11821. int size() const throw()
  11822. {
  11823. return listeners.size();
  11824. }
  11825. /** Returns true if any listeners are registered. */
  11826. bool isEmpty() const throw()
  11827. {
  11828. return listeners.size() == 0;
  11829. }
  11830. /** Clears the list. */
  11831. void clear()
  11832. {
  11833. listeners.clear();
  11834. }
  11835. /** Returns true if the specified listener has been added to the list. */
  11836. bool contains (ListenerClass* const listener) const throw()
  11837. {
  11838. return listeners.contains (listener);
  11839. }
  11840. /** Calls a member function on each listener in the list, with no parameters. */
  11841. void call (void (ListenerClass::*callbackFunction) ())
  11842. {
  11843. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  11844. }
  11845. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  11846. See the class description for info about writing a bail-out checker. */
  11847. template <class BailOutCheckerType>
  11848. void callChecked (const BailOutCheckerType& bailOutChecker,
  11849. void (ListenerClass::*callbackFunction) ())
  11850. {
  11851. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11852. (iter.getListener()->*callbackFunction) ();
  11853. }
  11854. /** Calls a member function on each listener in the list, with 1 parameter. */
  11855. template <LL_TEMPLATE(1)>
  11856. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  11857. {
  11858. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  11859. (iter.getListener()->*callbackFunction) (param1);
  11860. }
  11861. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  11862. See the class description for info about writing a bail-out checker. */
  11863. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  11864. void callChecked (const BailOutCheckerType& bailOutChecker,
  11865. void (ListenerClass::*callbackFunction) (P1),
  11866. LL_PARAM(1))
  11867. {
  11868. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11869. (iter.getListener()->*callbackFunction) (param1);
  11870. }
  11871. /** Calls a member function on each listener in the list, with 2 parameters. */
  11872. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  11873. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  11874. LL_PARAM(1), LL_PARAM(2))
  11875. {
  11876. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  11877. (iter.getListener()->*callbackFunction) (param1, param2);
  11878. }
  11879. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  11880. See the class description for info about writing a bail-out checker. */
  11881. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  11882. void callChecked (const BailOutCheckerType& bailOutChecker,
  11883. void (ListenerClass::*callbackFunction) (P1, P2),
  11884. LL_PARAM(1), LL_PARAM(2))
  11885. {
  11886. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11887. (iter.getListener()->*callbackFunction) (param1, param2);
  11888. }
  11889. /** Calls a member function on each listener in the list, with 3 parameters. */
  11890. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  11891. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  11892. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  11893. {
  11894. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  11895. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  11896. }
  11897. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  11898. See the class description for info about writing a bail-out checker. */
  11899. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  11900. void callChecked (const BailOutCheckerType& bailOutChecker,
  11901. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  11902. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  11903. {
  11904. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11905. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  11906. }
  11907. /** Calls a member function on each listener in the list, with 4 parameters. */
  11908. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  11909. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  11910. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  11911. {
  11912. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  11913. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  11914. }
  11915. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  11916. See the class description for info about writing a bail-out checker. */
  11917. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  11918. void callChecked (const BailOutCheckerType& bailOutChecker,
  11919. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  11920. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  11921. {
  11922. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11923. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  11924. }
  11925. /** Calls a member function on each listener in the list, with 5 parameters. */
  11926. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  11927. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  11928. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  11929. {
  11930. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  11931. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  11932. }
  11933. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  11934. See the class description for info about writing a bail-out checker. */
  11935. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  11936. void callChecked (const BailOutCheckerType& bailOutChecker,
  11937. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  11938. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  11939. {
  11940. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11941. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  11942. }
  11943. /** A dummy bail-out checker that always returns false.
  11944. See the ListenerList notes for more info about bail-out checkers.
  11945. */
  11946. class DummyBailOutChecker
  11947. {
  11948. public:
  11949. inline bool shouldBailOut() const throw() { return false; }
  11950. };
  11951. /** Iterates the listeners in a ListenerList. */
  11952. template <class BailOutCheckerType, class ListType>
  11953. class Iterator
  11954. {
  11955. public:
  11956. Iterator (const ListType& list_)
  11957. : list (list_), index (list_.size())
  11958. {}
  11959. ~Iterator() {}
  11960. bool next()
  11961. {
  11962. if (index <= 0)
  11963. return false;
  11964. const int listSize = list.size();
  11965. if (--index < listSize)
  11966. return true;
  11967. index = listSize - 1;
  11968. return index >= 0;
  11969. }
  11970. bool next (const BailOutCheckerType& bailOutChecker)
  11971. {
  11972. return (! bailOutChecker.shouldBailOut()) && next();
  11973. }
  11974. typename ListType::ListenerType* getListener() const throw()
  11975. {
  11976. return list.getListeners().getUnchecked (index);
  11977. }
  11978. private:
  11979. const ListType& list;
  11980. int index;
  11981. JUCE_DECLARE_NON_COPYABLE (Iterator);
  11982. };
  11983. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  11984. typedef ListenerClass ListenerType;
  11985. const ArrayType& getListeners() const throw() { return listeners; }
  11986. private:
  11987. ArrayType listeners;
  11988. JUCE_DECLARE_NON_COPYABLE (ListenerList);
  11989. #undef LL_TEMPLATE
  11990. #undef LL_PARAM
  11991. };
  11992. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  11993. /*** End of inlined file: juce_ListenerList.h ***/
  11994. /**
  11995. Represents a shared variant value.
  11996. A Value object contains a reference to a var object, and can get and set its value.
  11997. Listeners can be attached to be told when the value is changed.
  11998. The Value class is a wrapper around a shared, reference-counted underlying data
  11999. object - this means that multiple Value objects can all refer to the same piece of
  12000. data, allowing all of them to be notified when any of them changes it.
  12001. When you create a Value with its default constructor, it acts as a wrapper around a
  12002. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  12003. you can map the Value onto any kind of underlying data.
  12004. */
  12005. class JUCE_API Value
  12006. {
  12007. public:
  12008. /** Creates an empty Value, containing a void var. */
  12009. Value();
  12010. /** Creates a Value that refers to the same value as another one.
  12011. Note that this doesn't make a copy of the other value - both this and the other
  12012. Value will share the same underlying value, so that when either one alters it, both
  12013. will see it change.
  12014. */
  12015. Value (const Value& other);
  12016. /** Creates a Value that is set to the specified value. */
  12017. explicit Value (const var& initialValue);
  12018. /** Destructor. */
  12019. ~Value();
  12020. /** Returns the current value. */
  12021. const var getValue() const;
  12022. /** Returns the current value. */
  12023. operator const var() const;
  12024. /** Returns the value as a string.
  12025. This is alternative to writing things like "myValue.getValue().toString()".
  12026. */
  12027. const String toString() const;
  12028. /** Sets the current value.
  12029. You can also use operator= to set the value.
  12030. If there are any listeners registered, they will be notified of the
  12031. change asynchronously.
  12032. */
  12033. void setValue (const var& newValue);
  12034. /** Sets the current value.
  12035. This is the same as calling setValue().
  12036. If there are any listeners registered, they will be notified of the
  12037. change asynchronously.
  12038. */
  12039. Value& operator= (const var& newValue);
  12040. /** Makes this object refer to the same underlying ValueSource as another one.
  12041. Once this object has been connected to another one, changing either one
  12042. will update the other.
  12043. Existing listeners will still be registered after you call this method, and
  12044. they'll continue to receive messages when the new value changes.
  12045. */
  12046. void referTo (const Value& valueToReferTo);
  12047. /** Returns true if this value and the other one are references to the same value.
  12048. */
  12049. bool refersToSameSourceAs (const Value& other) const;
  12050. /** Compares two values.
  12051. This is a compare-by-value comparison, so is effectively the same as
  12052. saying (this->getValue() == other.getValue()).
  12053. */
  12054. bool operator== (const Value& other) const;
  12055. /** Compares two values.
  12056. This is a compare-by-value comparison, so is effectively the same as
  12057. saying (this->getValue() != other.getValue()).
  12058. */
  12059. bool operator!= (const Value& other) const;
  12060. /** Receives callbacks when a Value object changes.
  12061. @see Value::addListener
  12062. */
  12063. class JUCE_API Listener
  12064. {
  12065. public:
  12066. Listener() {}
  12067. virtual ~Listener() {}
  12068. /** Called when a Value object is changed.
  12069. Note that the Value object passed as a parameter may not be exactly the same
  12070. object that you registered the listener with - it might be a copy that refers
  12071. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  12072. */
  12073. virtual void valueChanged (Value& value) = 0;
  12074. };
  12075. /** Adds a listener to receive callbacks when the value changes.
  12076. The listener is added to this specific Value object, and not to the shared
  12077. object that it refers to. When this object is deleted, all the listeners will
  12078. be lost, even if other references to the same Value still exist. So when you're
  12079. adding a listener, make sure that you add it to a ValueTree instance that will last
  12080. for as long as you need the listener. In general, you'd never want to add a listener
  12081. to a local stack-based ValueTree, but more likely to one that's a member variable.
  12082. @see removeListener
  12083. */
  12084. void addListener (Listener* listener);
  12085. /** Removes a listener that was previously added with addListener(). */
  12086. void removeListener (Listener* listener);
  12087. /**
  12088. Used internally by the Value class as the base class for its shared value objects.
  12089. The Value class is essentially a reference-counted pointer to a shared instance
  12090. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  12091. ValueSource classes to allow Value objects to represent your own custom data items.
  12092. */
  12093. class JUCE_API ValueSource : public ReferenceCountedObject,
  12094. public AsyncUpdater
  12095. {
  12096. public:
  12097. ValueSource();
  12098. virtual ~ValueSource();
  12099. /** Returns the current value of this object. */
  12100. virtual const var getValue() const = 0;
  12101. /** Changes the current value.
  12102. This must also trigger a change message if the value actually changes.
  12103. */
  12104. virtual void setValue (const var& newValue) = 0;
  12105. /** Delivers a change message to all the listeners that are registered with
  12106. this value.
  12107. If dispatchSynchronously is true, the method will call all the listeners
  12108. before returning; otherwise it'll dispatch a message and make the call later.
  12109. */
  12110. void sendChangeMessage (bool dispatchSynchronously);
  12111. protected:
  12112. friend class Value;
  12113. SortedSet <Value*> valuesWithListeners;
  12114. void handleAsyncUpdate();
  12115. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueSource);
  12116. };
  12117. /** Creates a Value object that uses this valueSource object as its underlying data. */
  12118. explicit Value (ValueSource* valueSource);
  12119. /** Returns the ValueSource that this value is referring to. */
  12120. ValueSource& getValueSource() throw() { return *value; }
  12121. private:
  12122. friend class ValueSource;
  12123. ReferenceCountedObjectPtr <ValueSource> value;
  12124. ListenerList <Listener> listeners;
  12125. void callListeners();
  12126. // This is disallowed to avoid confusion about whether it should
  12127. // do a by-value or by-reference copy.
  12128. Value& operator= (const Value& other);
  12129. };
  12130. /** Writes a Value to an OutputStream as a UTF8 string. */
  12131. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  12132. /** This typedef is just for compatibility with old code - newer code should use the Value::Listener class directly. */
  12133. typedef Value::Listener ValueListener;
  12134. #endif // __JUCE_VALUE_JUCEHEADER__
  12135. /*** End of inlined file: juce_Value.h ***/
  12136. #endif
  12137. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12138. /*** Start of inlined file: juce_ValueTree.h ***/
  12139. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12140. #define __JUCE_VALUETREE_JUCEHEADER__
  12141. /*** Start of inlined file: juce_UndoManager.h ***/
  12142. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  12143. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  12144. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  12145. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12146. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12147. /*** Start of inlined file: juce_ChangeListener.h ***/
  12148. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  12149. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  12150. class ChangeBroadcaster;
  12151. /**
  12152. Receives change event callbacks that are sent out by a ChangeBroadcaster.
  12153. A ChangeBroadcaster keeps a set of listeners to which it broadcasts a message when
  12154. the ChangeBroadcaster::sendChangeMessage() method is called. A subclass of
  12155. ChangeListener is used to receive these callbacks.
  12156. Note that the major difference between an ActionListener and a ChangeListener
  12157. is that for a ChangeListener, multiple changes will be coalesced into fewer
  12158. callbacks, but ActionListeners perform one callback for every event posted.
  12159. @see ChangeBroadcaster, ActionListener
  12160. */
  12161. class JUCE_API ChangeListener
  12162. {
  12163. public:
  12164. /** Destructor. */
  12165. virtual ~ChangeListener() {}
  12166. /** Your subclass should implement this method to receive the callback.
  12167. @param source the ChangeBroadcaster that triggered the callback.
  12168. */
  12169. virtual void changeListenerCallback (ChangeBroadcaster* source) = 0;
  12170. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  12171. // This method's signature has changed to take a ChangeBroadcaster parameter - please update your code!
  12172. private: virtual int changeListenerCallback (void*) { return 0; }
  12173. #endif
  12174. };
  12175. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  12176. /*** End of inlined file: juce_ChangeListener.h ***/
  12177. /**
  12178. Holds a list of ChangeListeners, and sends messages to them when instructed.
  12179. @see ChangeListener
  12180. */
  12181. class JUCE_API ChangeBroadcaster
  12182. {
  12183. public:
  12184. /** Creates an ChangeBroadcaster. */
  12185. ChangeBroadcaster() throw();
  12186. /** Destructor. */
  12187. virtual ~ChangeBroadcaster();
  12188. /** Registers a listener to receive change callbacks from this broadcaster.
  12189. Trying to add a listener that's already on the list will have no effect.
  12190. */
  12191. void addChangeListener (ChangeListener* listener);
  12192. /** Unregisters a listener from the list.
  12193. If the listener isn't on the list, this won't have any effect.
  12194. */
  12195. void removeChangeListener (ChangeListener* listener);
  12196. /** Removes all listeners from the list. */
  12197. void removeAllChangeListeners();
  12198. /** Causes an asynchronous change message to be sent to all the registered listeners.
  12199. The message will be delivered asynchronously by the main message thread, so this
  12200. method will return immediately. To call the listeners synchronously use
  12201. sendSynchronousChangeMessage().
  12202. */
  12203. void sendChangeMessage();
  12204. /** Sends a synchronous change message to all the registered listeners.
  12205. This will immediately call all the listeners that are registered. For thread-safety
  12206. reasons, you must only call this method on the main message thread.
  12207. @see dispatchPendingMessages
  12208. */
  12209. void sendSynchronousChangeMessage();
  12210. /** If a change message has been sent but not yet dispatched, this will call
  12211. sendSynchronousChangeMessage() to make the callback immediately.
  12212. For thread-safety reasons, you must only call this method on the main message thread.
  12213. */
  12214. void dispatchPendingMessages();
  12215. private:
  12216. class ChangeBroadcasterCallback : public AsyncUpdater
  12217. {
  12218. public:
  12219. ChangeBroadcasterCallback();
  12220. void handleAsyncUpdate();
  12221. ChangeBroadcaster* owner;
  12222. };
  12223. friend class ChangeBroadcasterCallback;
  12224. ChangeBroadcasterCallback callback;
  12225. ListenerList <ChangeListener> changeListeners;
  12226. void callListeners();
  12227. JUCE_DECLARE_NON_COPYABLE (ChangeBroadcaster);
  12228. };
  12229. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12230. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  12231. /*** Start of inlined file: juce_UndoableAction.h ***/
  12232. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  12233. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  12234. /**
  12235. Used by the UndoManager class to store an action which can be done
  12236. and undone.
  12237. @see UndoManager
  12238. */
  12239. class JUCE_API UndoableAction
  12240. {
  12241. protected:
  12242. /** Creates an action. */
  12243. UndoableAction() throw() {}
  12244. public:
  12245. /** Destructor. */
  12246. virtual ~UndoableAction() {}
  12247. /** Overridden by a subclass to perform the action.
  12248. This method is called by the UndoManager, and shouldn't be used directly by
  12249. applications.
  12250. Be careful not to make any calls in a perform() method that could call
  12251. recursively back into the UndoManager::perform() method
  12252. @returns true if the action could be performed.
  12253. @see UndoManager::perform
  12254. */
  12255. virtual bool perform() = 0;
  12256. /** Overridden by a subclass to undo the action.
  12257. This method is called by the UndoManager, and shouldn't be used directly by
  12258. applications.
  12259. Be careful not to make any calls in an undo() method that could call
  12260. recursively back into the UndoManager::perform() method
  12261. @returns true if the action could be undone without any errors.
  12262. @see UndoManager::perform
  12263. */
  12264. virtual bool undo() = 0;
  12265. /** Returns a value to indicate how much memory this object takes up.
  12266. Because the UndoManager keeps a list of UndoableActions, this is used
  12267. to work out how much space each one will take up, so that the UndoManager
  12268. can work out how many to keep.
  12269. The default value returned here is 10 - units are arbitrary and
  12270. don't have to be accurate.
  12271. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  12272. UndoManager::setMaxNumberOfStoredUnits
  12273. */
  12274. virtual int getSizeInUnits() { return 10; }
  12275. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  12276. If possible, this method should create and return a single action that does the same job as
  12277. this one followed by the supplied action.
  12278. If it's not possible to merge the two actions, the method should return zero.
  12279. */
  12280. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return 0; }
  12281. };
  12282. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  12283. /*** End of inlined file: juce_UndoableAction.h ***/
  12284. /**
  12285. Manages a list of undo/redo commands.
  12286. An UndoManager object keeps a list of past actions and can use these actions
  12287. to move backwards and forwards through an undo history.
  12288. To use it, create subclasses of UndoableAction which perform all the
  12289. actions you need, then when you need to actually perform an action, create one
  12290. and pass it to the UndoManager's perform() method.
  12291. The manager also uses the concept of 'transactions' to group the actions
  12292. together - all actions performed between calls to beginNewTransaction() are
  12293. grouped together and are all undone/redone as a group.
  12294. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  12295. when actions are performed or undone.
  12296. @see UndoableAction
  12297. */
  12298. class JUCE_API UndoManager : public ChangeBroadcaster
  12299. {
  12300. public:
  12301. /** Creates an UndoManager.
  12302. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  12303. to indicate how much storage it takes up
  12304. (UndoableAction::getSizeInUnits()), so this
  12305. lets you specify the maximum total number of
  12306. units that the undomanager is allowed to
  12307. keep in memory before letting the older actions
  12308. drop off the end of the list.
  12309. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  12310. that will be kept, even if this involves exceeding
  12311. the amount of space specified in maxNumberOfUnitsToKeep
  12312. */
  12313. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  12314. int minimumTransactionsToKeep = 30);
  12315. /** Destructor. */
  12316. ~UndoManager();
  12317. /** Deletes all stored actions in the list. */
  12318. void clearUndoHistory();
  12319. /** Returns the current amount of space to use for storing UndoableAction objects.
  12320. @see setMaxNumberOfStoredUnits
  12321. */
  12322. int getNumberOfUnitsTakenUpByStoredCommands() const;
  12323. /** Sets the amount of space that can be used for storing UndoableAction objects.
  12324. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  12325. to indicate how much storage it takes up
  12326. (UndoableAction::getSizeInUnits()), so this
  12327. lets you specify the maximum total number of
  12328. units that the undomanager is allowed to
  12329. keep in memory before letting the older actions
  12330. drop off the end of the list.
  12331. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  12332. that will be kept, even if this involves exceeding
  12333. the amount of space specified in maxNumberOfUnitsToKeep
  12334. @see getNumberOfUnitsTakenUpByStoredCommands
  12335. */
  12336. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  12337. int minimumTransactionsToKeep);
  12338. /** Performs an action and adds it to the undo history list.
  12339. @param action the action to perform - this will be deleted by the UndoManager
  12340. when no longer needed
  12341. @param actionName if this string is non-empty, the current transaction will be
  12342. given this name; if it's empty, the current transaction name will
  12343. be left unchanged. See setCurrentTransactionName()
  12344. @returns true if the command succeeds - see UndoableAction::perform
  12345. @see beginNewTransaction
  12346. */
  12347. bool perform (UndoableAction* action,
  12348. const String& actionName = String::empty);
  12349. /** Starts a new group of actions that together will be treated as a single transaction.
  12350. All actions that are passed to the perform() method between calls to this
  12351. method are grouped together and undone/redone together by a single call to
  12352. undo() or redo().
  12353. @param actionName a description of the transaction that is about to be
  12354. performed
  12355. */
  12356. void beginNewTransaction (const String& actionName = String::empty);
  12357. /** Changes the name stored for the current transaction.
  12358. Each transaction is given a name when the beginNewTransaction() method is
  12359. called, but this can be used to change that name without starting a new
  12360. transaction.
  12361. */
  12362. void setCurrentTransactionName (const String& newName);
  12363. /** Returns true if there's at least one action in the list to undo.
  12364. @see getUndoDescription, undo, canRedo
  12365. */
  12366. bool canUndo() const;
  12367. /** Returns the description of the transaction that would be next to get undone.
  12368. The description returned is the one that was passed into beginNewTransaction
  12369. before the set of actions was performed.
  12370. @see undo
  12371. */
  12372. const String getUndoDescription() const;
  12373. /** Tries to roll-back the last transaction.
  12374. @returns true if the transaction can be undone, and false if it fails, or
  12375. if there aren't any transactions to undo
  12376. */
  12377. bool undo();
  12378. /** Tries to roll-back any actions that were added to the current transaction.
  12379. This will perform an undo() only if there are some actions in the undo list
  12380. that were added after the last call to beginNewTransaction().
  12381. This is useful because it lets you call beginNewTransaction(), then
  12382. perform an operation which may or may not actually perform some actions, and
  12383. then call this method to get rid of any actions that might have been done
  12384. without it rolling back the previous transaction if nothing was actually
  12385. done.
  12386. @returns true if any actions were undone.
  12387. */
  12388. bool undoCurrentTransactionOnly();
  12389. /** Returns a list of the UndoableAction objects that have been performed during the
  12390. transaction that is currently open.
  12391. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  12392. were to be called now.
  12393. The first item in the list is the earliest action performed.
  12394. */
  12395. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  12396. /** Returns the number of UndoableAction objects that have been performed during the
  12397. transaction that is currently open.
  12398. @see getActionsInCurrentTransaction
  12399. */
  12400. int getNumActionsInCurrentTransaction() const;
  12401. /** Returns true if there's at least one action in the list to redo.
  12402. @see getRedoDescription, redo, canUndo
  12403. */
  12404. bool canRedo() const;
  12405. /** Returns the description of the transaction that would be next to get redone.
  12406. The description returned is the one that was passed into beginNewTransaction
  12407. before the set of actions was performed.
  12408. @see redo
  12409. */
  12410. const String getRedoDescription() const;
  12411. /** Tries to redo the last transaction that was undone.
  12412. @returns true if the transaction can be redone, and false if it fails, or
  12413. if there aren't any transactions to redo
  12414. */
  12415. bool redo();
  12416. private:
  12417. OwnedArray <OwnedArray <UndoableAction> > transactions;
  12418. StringArray transactionNames;
  12419. String currentTransactionName;
  12420. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  12421. bool newTransaction, reentrancyCheck;
  12422. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UndoManager);
  12423. };
  12424. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  12425. /*** End of inlined file: juce_UndoManager.h ***/
  12426. /**
  12427. A powerful tree structure that can be used to hold free-form data, and which can
  12428. handle its own undo and redo behaviour.
  12429. A ValueTree contains a list of named properties as var objects, and also holds
  12430. any number of sub-trees.
  12431. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  12432. they're simply a lightweight reference to a shared data container. Creating a copy
  12433. of another ValueTree simply creates a new reference to the same underlying object - to
  12434. make a separate, deep copy of a tree you should explicitly call createCopy().
  12435. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  12436. and much of the structure of a ValueTree is similar to an XmlElement tree.
  12437. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  12438. contain text elements, the conversion works well and makes a good serialisation
  12439. format. They can also be serialised to a binary format, which is very fast and compact.
  12440. All the methods that change data take an optional UndoManager, which will be used
  12441. to track any changes to the object. For this to work, you have to be careful to
  12442. consistently always use the same UndoManager for all operations to any node inside
  12443. the tree.
  12444. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  12445. one tree to another, be careful to always remove it first, before adding it. This
  12446. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  12447. assertions if you try to do anything dangerous, but there are still plenty of ways it
  12448. could go wrong.
  12449. Listeners can be added to a ValueTree to be told when properies change and when
  12450. nodes are added or removed.
  12451. @see var, XmlElement
  12452. */
  12453. class JUCE_API ValueTree
  12454. {
  12455. public:
  12456. /** Creates an empty, invalid ValueTree.
  12457. A ValueTree that is created with this constructor can't actually be used for anything,
  12458. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  12459. To create a real one, use the constructor that takes a string.
  12460. @see ValueTree::invalid
  12461. */
  12462. ValueTree() throw();
  12463. /** Creates an empty ValueTree with the given type name.
  12464. Like an XmlElement, each ValueTree node has a type, which you can access with
  12465. getType() and hasType().
  12466. */
  12467. explicit ValueTree (const Identifier& type);
  12468. /** Creates a reference to another ValueTree. */
  12469. ValueTree (const ValueTree& other);
  12470. /** Makes this object reference another node. */
  12471. ValueTree& operator= (const ValueTree& other);
  12472. /** Destructor. */
  12473. ~ValueTree();
  12474. /** Returns true if both this and the other tree node refer to the same underlying structure.
  12475. Note that this isn't a value comparison - two independently-created trees which
  12476. contain identical data are not considered equal.
  12477. */
  12478. bool operator== (const ValueTree& other) const throw();
  12479. /** Returns true if this and the other node refer to different underlying structures.
  12480. Note that this isn't a value comparison - two independently-created trees which
  12481. contain identical data are not considered equal.
  12482. */
  12483. bool operator!= (const ValueTree& other) const throw();
  12484. /** Performs a deep comparison between the properties and children of two trees.
  12485. If all the properties and children of the two trees are the same (recursively), this
  12486. returns true.
  12487. The normal operator==() only checks whether two trees refer to the same shared data
  12488. structure, so use this method if you need to do a proper value comparison.
  12489. */
  12490. bool isEquivalentTo (const ValueTree& other) const;
  12491. /** Returns true if this node refers to some valid data.
  12492. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  12493. call to getChild().
  12494. */
  12495. bool isValid() const { return object != 0; }
  12496. /** Returns a deep copy of this tree and all its sub-nodes. */
  12497. ValueTree createCopy() const;
  12498. /** Returns the type of this node.
  12499. The type is specified when the ValueTree is created.
  12500. @see hasType
  12501. */
  12502. const Identifier getType() const;
  12503. /** Returns true if the node has this type.
  12504. The comparison is case-sensitive.
  12505. */
  12506. bool hasType (const Identifier& typeName) const;
  12507. /** Returns the value of a named property.
  12508. If no such property has been set, this will return a void variant.
  12509. You can also use operator[] to get a property.
  12510. @see var, setProperty, hasProperty
  12511. */
  12512. const var& getProperty (const Identifier& name) const;
  12513. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  12514. If no such property has been set, this will return the value of defaultReturnValue.
  12515. You can also use operator[] and getProperty to get a property.
  12516. @see var, getProperty, setProperty, hasProperty
  12517. */
  12518. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  12519. /** Returns the value of a named property.
  12520. If no such property has been set, this will return a void variant. This is the same as
  12521. calling getProperty().
  12522. @see getProperty
  12523. */
  12524. const var& operator[] (const Identifier& name) const;
  12525. /** Changes a named property of the node.
  12526. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12527. so that this change can be undone.
  12528. @see var, getProperty, removeProperty
  12529. */
  12530. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  12531. /** Returns true if the node contains a named property. */
  12532. bool hasProperty (const Identifier& name) const;
  12533. /** Removes a property from the node.
  12534. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12535. so that this change can be undone.
  12536. */
  12537. void removeProperty (const Identifier& name, UndoManager* undoManager);
  12538. /** Removes all properties from the node.
  12539. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12540. so that this change can be undone.
  12541. */
  12542. void removeAllProperties (UndoManager* undoManager);
  12543. /** Returns the total number of properties that the node contains.
  12544. @see getProperty.
  12545. */
  12546. int getNumProperties() const;
  12547. /** Returns the identifier of the property with a given index.
  12548. @see getNumProperties
  12549. */
  12550. const Identifier getPropertyName (int index) const;
  12551. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  12552. The Value object will maintain a reference to this tree, and will use the undo manager when
  12553. it needs to change the value. Attaching a Value::Listener to the value object will provide
  12554. callbacks whenever the property changes.
  12555. */
  12556. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  12557. /** Returns the number of child nodes belonging to this one.
  12558. @see getChild
  12559. */
  12560. int getNumChildren() const;
  12561. /** Returns one of this node's child nodes.
  12562. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  12563. whether a node is valid).
  12564. */
  12565. ValueTree getChild (int index) const;
  12566. /** Returns the first child node with the speficied type name.
  12567. If no such node is found, it'll return an invalid node. (See isValid() to find out
  12568. whether a node is valid).
  12569. @see getOrCreateChildWithName
  12570. */
  12571. ValueTree getChildWithName (const Identifier& type) const;
  12572. /** Returns the first child node with the speficied type name, creating and adding
  12573. a child with this name if there wasn't already one there.
  12574. The only time this will return an invalid object is when the object that you're calling
  12575. the method on is itself invalid.
  12576. @see getChildWithName
  12577. */
  12578. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  12579. /** Looks for the first child node that has the speficied property value.
  12580. This will scan the child nodes in order, until it finds one that has property that matches
  12581. the specified value.
  12582. If no such node is found, it'll return an invalid node. (See isValid() to find out
  12583. whether a node is valid).
  12584. */
  12585. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  12586. /** Adds a child to this node.
  12587. Make sure that the child is removed from any former parent node before calling this, or
  12588. you'll hit an assertion.
  12589. If the index is < 0 or greater than the current number of child nodes, the new node will
  12590. be added at the end of the list.
  12591. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12592. so that this change can be undone.
  12593. */
  12594. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  12595. /** Removes the specified child from this node's child-list.
  12596. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12597. so that this change can be undone.
  12598. */
  12599. void removeChild (const ValueTree& child, UndoManager* undoManager);
  12600. /** Removes a child from this node's child-list.
  12601. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12602. so that this change can be undone.
  12603. */
  12604. void removeChild (int childIndex, UndoManager* undoManager);
  12605. /** Removes all child-nodes from this node.
  12606. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12607. so that this change can be undone.
  12608. */
  12609. void removeAllChildren (UndoManager* undoManager);
  12610. /** Moves one of the children to a different index.
  12611. This will move the child to a specified index, shuffling along any intervening
  12612. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  12613. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  12614. @param currentIndex the index of the item to be moved. If this isn't a
  12615. valid index, then nothing will be done
  12616. @param newIndex the index at which you'd like this item to end up. If this
  12617. is less than zero, the value will be moved to the end
  12618. of the list
  12619. @param undoManager the optional UndoManager to use to store this transaction
  12620. */
  12621. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  12622. /** Returns true if this node is anywhere below the specified parent node.
  12623. This returns true if the node is a child-of-a-child, as well as a direct child.
  12624. */
  12625. bool isAChildOf (const ValueTree& possibleParent) const;
  12626. /** Returns the index of a child item in this parent.
  12627. If the child isn't found, this returns -1.
  12628. */
  12629. int indexOf (const ValueTree& child) const;
  12630. /** Returns the parent node that contains this one.
  12631. If the node has no parent, this will return an invalid node. (See isValid() to find out
  12632. whether a node is valid).
  12633. */
  12634. ValueTree getParent() const;
  12635. /** Returns one of this node's siblings in its parent's child list.
  12636. The delta specifies how far to move through the list, so a value of 1 would return the node
  12637. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  12638. If the requested position is beyond the range of available nodes, this will return ValueTree::invalid.
  12639. */
  12640. ValueTree getSibling (int delta) const;
  12641. /** Creates an XmlElement that holds a complete image of this node and all its children.
  12642. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  12643. be used to recreate a similar node by calling fromXml()
  12644. @see fromXml
  12645. */
  12646. XmlElement* createXml() const;
  12647. /** Tries to recreate a node from its XML representation.
  12648. This isn't designed to cope with random XML data - for a sensible result, it should only
  12649. be fed XML that was created by the createXml() method.
  12650. */
  12651. static ValueTree fromXml (const XmlElement& xml);
  12652. /** Stores this tree (and all its children) in a binary format.
  12653. Once written, the data can be read back with readFromStream().
  12654. It's much faster to load/save your tree in binary form than as XML, but
  12655. obviously isn't human-readable.
  12656. */
  12657. void writeToStream (OutputStream& output);
  12658. /** Reloads a tree from a stream that was written with writeToStream(). */
  12659. static ValueTree readFromStream (InputStream& input);
  12660. /** Reloads a tree from a data block that was written with writeToStream(). */
  12661. static ValueTree readFromData (const void* data, size_t numBytes);
  12662. /** Listener class for events that happen to a ValueTree.
  12663. To get events from a ValueTree, make your class implement this interface, and use
  12664. ValueTree::addListener() and ValueTree::removeListener() to register it.
  12665. */
  12666. class JUCE_API Listener
  12667. {
  12668. public:
  12669. /** Destructor. */
  12670. virtual ~Listener() {}
  12671. /** This method is called when a property of this node (or of one of its sub-nodes) has
  12672. changed.
  12673. The tree parameter indicates which tree has had its property changed, and the property
  12674. parameter indicates the property.
  12675. Note that when you register a listener to a tree, it will receive this callback for
  12676. property changes in that tree, and also for any of its children, (recursively, at any depth).
  12677. If your tree has sub-trees but you only want to know about changes to the top level tree,
  12678. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  12679. */
  12680. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  12681. const Identifier& property) = 0;
  12682. /** This method is called when a child sub-tree is added.
  12683. Note that when you register a listener to a tree, it will receive this callback for
  12684. child changes in both that tree and any of its children, (recursively, at any depth).
  12685. If your tree has sub-trees but you only want to know about changes to the top level tree,
  12686. just check the parentTree parameter to make sure it's the one that you're interested in.
  12687. */
  12688. virtual void valueTreeChildAdded (ValueTree& parentTree,
  12689. ValueTree& childWhichHasBeenAdded) = 0;
  12690. /** This method is called when a child sub-tree is removed.
  12691. Note that when you register a listener to a tree, it will receive this callback for
  12692. child changes in both that tree and any of its children, (recursively, at any depth).
  12693. If your tree has sub-trees but you only want to know about changes to the top level tree,
  12694. just check the parentTree parameter to make sure it's the one that you're interested in.
  12695. */
  12696. virtual void valueTreeChildRemoved (ValueTree& parentTree,
  12697. ValueTree& childWhichHasBeenRemoved) = 0;
  12698. /** This method is called when a tree's children have been re-shuffled.
  12699. Note that when you register a listener to a tree, it will receive this callback for
  12700. child changes in both that tree and any of its children, (recursively, at any depth).
  12701. If your tree has sub-trees but you only want to know about changes to the top level tree,
  12702. just check the parameter to make sure it's the tree that you're interested in.
  12703. */
  12704. virtual void valueTreeChildOrderChanged (ValueTree& parentTreeWhoseChildrenHaveMoved) = 0;
  12705. /** This method is called when a tree has been added or removed from a parent node.
  12706. This callback happens when the tree to which the listener was registered is added or
  12707. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  12708. the listener is registered, and not to any of its children.
  12709. */
  12710. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  12711. };
  12712. /** Adds a listener to receive callbacks when this node is changed.
  12713. The listener is added to this specific ValueTree object, and not to the shared
  12714. object that it refers to. When this object is deleted, all the listeners will
  12715. be lost, even if other references to the same ValueTree still exist. And if you
  12716. use the operator= to make this refer to a different ValueTree, any listeners will
  12717. begin listening to changes to the new tree instead of the old one.
  12718. When you're adding a listener, make sure that you add it to a ValueTree instance that
  12719. will last for as long as you need the listener. In general, you'd never want to add a
  12720. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  12721. @see removeListener
  12722. */
  12723. void addListener (Listener* listener);
  12724. /** Removes a listener that was previously added with addListener(). */
  12725. void removeListener (Listener* listener);
  12726. /** This method uses a comparator object to sort the tree's children into order.
  12727. The object provided must have a method of the form:
  12728. @code
  12729. int compareElements (const ValueTree& first, const ValueTree& second);
  12730. @endcode
  12731. ..and this method must return:
  12732. - a value of < 0 if the first comes before the second
  12733. - a value of 0 if the two objects are equivalent
  12734. - a value of > 0 if the second comes before the first
  12735. To improve performance, the compareElements() method can be declared as static or const.
  12736. @param comparator the comparator to use for comparing elements.
  12737. @param undoManager optional UndoManager for storing the changes
  12738. @param retainOrderOfEquivalentItems if this is true, then items which the comparator says are
  12739. equivalent will be kept in the order in which they currently appear in the array.
  12740. This is slower to perform, but may be important in some cases. If it's false, a
  12741. faster algorithm is used, but equivalent elements may be rearranged.
  12742. */
  12743. template <typename ElementComparator>
  12744. void sort (ElementComparator& comparator, UndoManager* undoManager, bool retainOrderOfEquivalentItems)
  12745. {
  12746. if (object != 0)
  12747. {
  12748. ReferenceCountedArray <SharedObject> sortedList (object->children);
  12749. ComparatorAdapter <ElementComparator> adapter (comparator);
  12750. sortedList.sort (adapter, retainOrderOfEquivalentItems);
  12751. object->reorderChildren (sortedList, undoManager);
  12752. }
  12753. }
  12754. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  12755. This invalid object is equivalent to ValueTree created with its default constructor.
  12756. */
  12757. static const ValueTree invalid;
  12758. private:
  12759. class SetPropertyAction;
  12760. friend class SetPropertyAction;
  12761. class AddOrRemoveChildAction;
  12762. friend class AddOrRemoveChildAction;
  12763. class MoveChildAction;
  12764. friend class MoveChildAction;
  12765. class JUCE_API SharedObject : public ReferenceCountedObject
  12766. {
  12767. public:
  12768. explicit SharedObject (const Identifier& type);
  12769. SharedObject (const SharedObject& other);
  12770. ~SharedObject();
  12771. const Identifier type;
  12772. NamedValueSet properties;
  12773. ReferenceCountedArray <SharedObject> children;
  12774. SortedSet <ValueTree*> valueTreesWithListeners;
  12775. SharedObject* parent;
  12776. void sendPropertyChangeMessage (const Identifier& property);
  12777. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  12778. void sendChildAddedMessage (ValueTree& parent, ValueTree& child);
  12779. void sendChildAddedMessage (ValueTree child);
  12780. void sendChildRemovedMessage (ValueTree& parent, ValueTree& child);
  12781. void sendChildRemovedMessage (ValueTree child);
  12782. void sendChildOrderChangedMessage (ValueTree& parent);
  12783. void sendChildOrderChangedMessage();
  12784. void sendParentChangeMessage();
  12785. const var& getProperty (const Identifier& name) const;
  12786. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  12787. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  12788. bool hasProperty (const Identifier& name) const;
  12789. void removeProperty (const Identifier& name, UndoManager*);
  12790. void removeAllProperties (UndoManager*);
  12791. bool isAChildOf (const SharedObject* possibleParent) const;
  12792. int indexOf (const ValueTree& child) const;
  12793. ValueTree getChildWithName (const Identifier& type) const;
  12794. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  12795. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  12796. void addChild (SharedObject* child, int index, UndoManager*);
  12797. void removeChild (int childIndex, UndoManager*);
  12798. void removeAllChildren (UndoManager*);
  12799. void moveChild (int currentIndex, int newIndex, UndoManager*);
  12800. void reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager*);
  12801. bool isEquivalentTo (const SharedObject& other) const;
  12802. XmlElement* createXml() const;
  12803. private:
  12804. SharedObject& operator= (const SharedObject&);
  12805. JUCE_LEAK_DETECTOR (SharedObject);
  12806. };
  12807. template <typename ElementComparator>
  12808. class ComparatorAdapter
  12809. {
  12810. public:
  12811. ComparatorAdapter (ElementComparator& comparator_) throw() : comparator (comparator_) {}
  12812. int compareElements (SharedObject* const first, SharedObject* const second)
  12813. {
  12814. return comparator.compareElements (ValueTree (first), ValueTree (second));
  12815. }
  12816. private:
  12817. ElementComparator& comparator;
  12818. JUCE_DECLARE_NON_COPYABLE (ComparatorAdapter);
  12819. };
  12820. friend class SharedObject;
  12821. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  12822. SharedObjectPtr object;
  12823. ListenerList <Listener> listeners;
  12824. #if JUCE_MSVC && ! DOXYGEN
  12825. public: // (workaround for VC6)
  12826. #endif
  12827. explicit ValueTree (SharedObject*);
  12828. };
  12829. #endif // __JUCE_VALUETREE_JUCEHEADER__
  12830. /*** End of inlined file: juce_ValueTree.h ***/
  12831. #endif
  12832. #ifndef __JUCE_VARIANT_JUCEHEADER__
  12833. #endif
  12834. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  12835. /*** Start of inlined file: juce_FileLogger.h ***/
  12836. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  12837. #define __JUCE_FILELOGGER_JUCEHEADER__
  12838. /**
  12839. A simple implemenation of a Logger that writes to a file.
  12840. @see Logger
  12841. */
  12842. class JUCE_API FileLogger : public Logger
  12843. {
  12844. public:
  12845. /** Creates a FileLogger for a given file.
  12846. @param fileToWriteTo the file that to use - new messages will be appended
  12847. to the file. If the file doesn't exist, it will be created,
  12848. along with any parent directories that are needed.
  12849. @param welcomeMessage when opened, the logger will write a header to the log, along
  12850. with the current date and time, and this welcome message
  12851. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  12852. but is larger than this number of bytes, then the start of the
  12853. file will be truncated to keep the size down. This prevents a log
  12854. file getting ridiculously large over time. The file will be truncated
  12855. at a new-line boundary. If this value is less than zero, no size limit
  12856. will be imposed; if it's zero, the file will always be deleted. Note that
  12857. the size is only checked once when this object is created - any logging
  12858. that is done later will be appended without any checking
  12859. */
  12860. FileLogger (const File& fileToWriteTo,
  12861. const String& welcomeMessage,
  12862. const int maxInitialFileSizeBytes = 128 * 1024);
  12863. /** Destructor. */
  12864. ~FileLogger();
  12865. void logMessage (const String& message);
  12866. const File getLogFile() const { return logFile; }
  12867. /** Helper function to create a log file in the correct place for this platform.
  12868. On Windows this will return a logger with a path such as:
  12869. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  12870. On the Mac it'll create something like:
  12871. ~/Library/Logs/[logFileName]
  12872. The method might return 0 if the file can't be created for some reason.
  12873. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  12874. it's best to use the something like the name of your application here.
  12875. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  12876. call it "log.txt" because if it goes in a directory with logs
  12877. from other applications (as it will do on the Mac) then no-one
  12878. will know which one is yours!
  12879. @param welcomeMessage a message that will be written to the log when it's opened.
  12880. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  12881. */
  12882. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  12883. const String& logFileName,
  12884. const String& welcomeMessage,
  12885. const int maxInitialFileSizeBytes = 128 * 1024);
  12886. private:
  12887. File logFile;
  12888. CriticalSection logLock;
  12889. void trimFileSize (int maxFileSizeBytes) const;
  12890. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileLogger);
  12891. };
  12892. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  12893. /*** End of inlined file: juce_FileLogger.h ***/
  12894. #endif
  12895. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  12896. /*** Start of inlined file: juce_Initialisation.h ***/
  12897. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  12898. #define __JUCE_INITIALISATION_JUCEHEADER__
  12899. /** Initialises Juce's GUI classes.
  12900. If you're embedding Juce into an application that uses its own event-loop rather
  12901. than using the START_JUCE_APPLICATION macro, call this function before making any
  12902. Juce calls, to make sure things are initialised correctly.
  12903. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  12904. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  12905. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  12906. */
  12907. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI();
  12908. /** Clears up any static data being used by Juce's GUI classes.
  12909. If you're embedding Juce into an application that uses its own event-loop rather
  12910. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  12911. code to clean up any juce objects that might be lying around.
  12912. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  12913. */
  12914. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  12915. /** Initialises the core parts of Juce.
  12916. If you're embedding Juce into either a command-line program, call this function
  12917. at the start of your main() function to make sure that Juce is initialised correctly.
  12918. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  12919. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  12920. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  12921. */
  12922. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI();
  12923. /** Clears up any static data being used by Juce's non-gui core classes.
  12924. If you're embedding Juce into either a command-line program, call this function
  12925. at the end of your main() function if you want to make sure any Juce objects are
  12926. cleaned up correctly.
  12927. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  12928. */
  12929. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI();
  12930. /** A utility object that helps you initialise and shutdown Juce correctly
  12931. using an RAII pattern.
  12932. When an instance of this class is created, it calls initialiseJuce_NonGUI(),
  12933. and when it's deleted, it calls shutdownJuce_NonGUI(), which lets you easily
  12934. make sure that these functions are matched correctly.
  12935. This class is particularly handy to use at the beginning of a console app's
  12936. main() function, because it'll take care of shutting down whenever you return
  12937. from the main() call.
  12938. @see ScopedJuceInitialiser_GUI
  12939. */
  12940. class ScopedJuceInitialiser_NonGUI
  12941. {
  12942. public:
  12943. /** The constructor simply calls initialiseJuce_NonGUI(). */
  12944. ScopedJuceInitialiser_NonGUI() { initialiseJuce_NonGUI(); }
  12945. /** The destructor simply calls shutdownJuce_NonGUI(). */
  12946. ~ScopedJuceInitialiser_NonGUI() { shutdownJuce_NonGUI(); }
  12947. };
  12948. /** A utility object that helps you initialise and shutdown Juce correctly
  12949. using an RAII pattern.
  12950. When an instance of this class is created, it calls initialiseJuce_GUI(),
  12951. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  12952. make sure that these functions are matched correctly.
  12953. This class is particularly handy to use at the beginning of a console app's
  12954. main() function, because it'll take care of shutting down whenever you return
  12955. from the main() call.
  12956. @see ScopedJuceInitialiser_NonGUI
  12957. */
  12958. class ScopedJuceInitialiser_GUI
  12959. {
  12960. public:
  12961. /** The constructor simply calls initialiseJuce_GUI(). */
  12962. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  12963. /** The destructor simply calls shutdownJuce_GUI(). */
  12964. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  12965. };
  12966. /*
  12967. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  12968. AppSubClass is the name of a class derived from JUCEApplication.
  12969. See the JUCEApplication class documentation (juce_Application.h) for more details.
  12970. */
  12971. #if JUCE_ANDROID
  12972. #define START_JUCE_APPLICATION(AppClass) \
  12973. JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); }
  12974. #elif defined (JUCE_GCC) || defined (__MWERKS__)
  12975. #define START_JUCE_APPLICATION(AppClass) \
  12976. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  12977. int main (int argc, char* argv[]) \
  12978. { \
  12979. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  12980. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv); \
  12981. }
  12982. #elif JUCE_WINDOWS
  12983. #ifdef _CONSOLE
  12984. #define START_JUCE_APPLICATION(AppClass) \
  12985. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  12986. int main (int, char* argv[]) \
  12987. { \
  12988. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  12989. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  12990. }
  12991. #elif ! defined (_AFXDLL)
  12992. #ifdef _WINDOWS_
  12993. #define START_JUCE_APPLICATION(AppClass) \
  12994. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  12995. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  12996. { \
  12997. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  12998. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  12999. }
  13000. #else
  13001. #define START_JUCE_APPLICATION(AppClass) \
  13002. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  13003. int __stdcall WinMain (int, int, const char*, int) \
  13004. { \
  13005. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  13006. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  13007. }
  13008. #endif
  13009. #endif
  13010. #endif
  13011. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  13012. /*** End of inlined file: juce_Initialisation.h ***/
  13013. #endif
  13014. #ifndef __JUCE_LOGGER_JUCEHEADER__
  13015. #endif
  13016. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13017. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  13018. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13019. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13020. /** A timer for measuring performance of code and dumping the results to a file.
  13021. e.g. @code
  13022. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  13023. for (;;)
  13024. {
  13025. pc.start();
  13026. doSomethingFishy();
  13027. pc.stop();
  13028. }
  13029. @endcode
  13030. In this example, the time of each period between calling start/stop will be
  13031. measured and averaged over 50 runs, and the results printed to a file
  13032. every 50 times round the loop.
  13033. */
  13034. class JUCE_API PerformanceCounter
  13035. {
  13036. public:
  13037. /** Creates a PerformanceCounter object.
  13038. @param counterName the name used when printing out the statistics
  13039. @param runsPerPrintout the number of start/stop iterations before calling
  13040. printStatistics()
  13041. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  13042. the results are just written to the debugger output
  13043. */
  13044. PerformanceCounter (const String& counterName,
  13045. int runsPerPrintout = 100,
  13046. const File& loggingFile = File::nonexistent);
  13047. /** Destructor. */
  13048. ~PerformanceCounter();
  13049. /** Starts timing.
  13050. @see stop
  13051. */
  13052. void start();
  13053. /** Stops timing and prints out the results.
  13054. The number of iterations before doing a printout of the
  13055. results is set in the constructor.
  13056. @see start
  13057. */
  13058. void stop();
  13059. /** Dumps the current metrics to the debugger output and to a file.
  13060. As well as using Logger::outputDebugString to print the results,
  13061. this will write then to the file specified in the constructor (if
  13062. this was valid).
  13063. */
  13064. void printStatistics();
  13065. private:
  13066. String name;
  13067. int numRuns, runsPerPrint;
  13068. double totalTime;
  13069. int64 started;
  13070. File outputFile;
  13071. };
  13072. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13073. /*** End of inlined file: juce_PerformanceCounter.h ***/
  13074. #endif
  13075. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  13076. #endif
  13077. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13078. /*** Start of inlined file: juce_PlatformUtilities.h ***/
  13079. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13080. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13081. /**
  13082. A collection of miscellaneous platform-specific utilities.
  13083. */
  13084. class JUCE_API PlatformUtilities
  13085. {
  13086. public:
  13087. /** Plays the operating system's default alert 'beep' sound. */
  13088. static void beep();
  13089. /** Tries to launch the system's default reader for a given file or URL. */
  13090. static bool openDocument (const String& documentURL, const String& parameters);
  13091. /** Tries to launch the system's default email app to let the user create an email.
  13092. */
  13093. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  13094. const String& emailSubject,
  13095. const String& bodyText,
  13096. const StringArray& filesToAttach);
  13097. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  13098. /** MAC ONLY - Turns a Core CF String into a juce one. */
  13099. static const String cfStringToJuceString (CFStringRef cfString);
  13100. /** MAC ONLY - Turns a juce string into a Core CF one. */
  13101. static CFStringRef juceStringToCFString (const String& s);
  13102. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  13103. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  13104. /** MAC ONLY - Turns an FSRef into a juce string path. */
  13105. static const String makePathFromFSRef (FSRef* file);
  13106. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  13107. their precomposed equivalents.
  13108. */
  13109. static const String convertToPrecomposedUnicode (const String& s);
  13110. /** MAC ONLY - Gets the type of a file from the file's resources. */
  13111. static OSType getTypeOfFile (const String& filename);
  13112. /** MAC ONLY - Returns true if this file is actually a bundle. */
  13113. static bool isBundle (const String& filename);
  13114. /** MAC ONLY - Adds an item to the dock */
  13115. static void addItemToDock (const File& file);
  13116. /** MAC ONLY - Returns the current OS version number.
  13117. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  13118. */
  13119. static int getOSXMinorVersionNumber();
  13120. #endif
  13121. #if JUCE_WINDOWS || DOXYGEN
  13122. // Some registry helper functions:
  13123. /** WIN32 ONLY - Returns a string from the registry.
  13124. The path is a string for the entire path of a value in the registry,
  13125. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  13126. */
  13127. static const String getRegistryValue (const String& regValuePath,
  13128. const String& defaultValue = String::empty);
  13129. /** WIN32 ONLY - Sets a registry value as a string.
  13130. This will take care of creating any groups needed to get to the given
  13131. registry value.
  13132. */
  13133. static void setRegistryValue (const String& regValuePath,
  13134. const String& value);
  13135. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  13136. static bool registryValueExists (const String& regValuePath);
  13137. /** WIN32 ONLY - Deletes a registry value. */
  13138. static void deleteRegistryValue (const String& regValuePath);
  13139. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  13140. static void deleteRegistryKey (const String& regKeyPath);
  13141. /** WIN32 ONLY - Creates a file association in the registry.
  13142. This lets you set the exe that should be launched by a given file extension.
  13143. @param fileExtension the file extension to associate, including the
  13144. initial dot, e.g. ".txt"
  13145. @param symbolicDescription a space-free short token to identify the file type
  13146. @param fullDescription a human-readable description of the file type
  13147. @param targetExecutable the executable that should be launched
  13148. @param iconResourceNumber the icon that gets displayed for the file type will be
  13149. found by looking up this resource number in the
  13150. executable. Pass 0 here to not use an icon
  13151. */
  13152. static void registerFileAssociation (const String& fileExtension,
  13153. const String& symbolicDescription,
  13154. const String& fullDescription,
  13155. const File& targetExecutable,
  13156. int iconResourceNumber);
  13157. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  13158. In a normal Juce application this will be set to the module handle
  13159. of the application executable.
  13160. If you're writing a DLL using Juce and plan to use any Juce messaging or
  13161. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  13162. to set the correct module handle in your DllMain() function, because
  13163. the win32 system relies on the correct instance handle when opening windows.
  13164. */
  13165. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  13166. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  13167. @see getCurrentModuleInstanceHandle()
  13168. */
  13169. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  13170. /** WIN32 ONLY - Gets the command-line params as a string.
  13171. This is needed to avoid unicode problems with the argc type params.
  13172. */
  13173. static const String JUCE_CALLTYPE getCurrentCommandLineParams();
  13174. #endif
  13175. /** Clears the floating point unit's flags.
  13176. Only has an effect under win32, currently.
  13177. */
  13178. static void fpuReset();
  13179. #if JUCE_LINUX || JUCE_WINDOWS
  13180. /** Loads a dynamically-linked library into the process's address space.
  13181. @param pathOrFilename the platform-dependent name and search path
  13182. @returns a handle which can be used by getProcedureEntryPoint(), or
  13183. zero if it fails.
  13184. @see freeDynamicLibrary, getProcedureEntryPoint
  13185. */
  13186. static void* loadDynamicLibrary (const String& pathOrFilename);
  13187. /** Frees a dynamically-linked library.
  13188. @param libraryHandle a handle created by loadDynamicLibrary
  13189. @see loadDynamicLibrary, getProcedureEntryPoint
  13190. */
  13191. static void freeDynamicLibrary (void* libraryHandle);
  13192. /** Finds a procedure call in a dynamically-linked library.
  13193. @param libraryHandle a library handle returned by loadDynamicLibrary
  13194. @param procedureName the name of the procedure call to try to load
  13195. @returns a pointer to the function if found, or 0 if it fails
  13196. @see loadDynamicLibrary
  13197. */
  13198. static void* getProcedureEntryPoint (void* libraryHandle,
  13199. const String& procedureName);
  13200. #endif
  13201. private:
  13202. PlatformUtilities();
  13203. JUCE_DECLARE_NON_COPYABLE (PlatformUtilities);
  13204. };
  13205. #if JUCE_MAC || JUCE_IOS
  13206. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object using RAII.
  13207. */
  13208. class JUCE_API ScopedAutoReleasePool
  13209. {
  13210. public:
  13211. ScopedAutoReleasePool();
  13212. ~ScopedAutoReleasePool();
  13213. private:
  13214. void* pool;
  13215. JUCE_DECLARE_NON_COPYABLE (ScopedAutoReleasePool);
  13216. };
  13217. #define JUCE_AUTORELEASEPOOL const JUCE_NAMESPACE::ScopedAutoReleasePool pool;
  13218. #else
  13219. #define JUCE_AUTORELEASEPOOL
  13220. #endif
  13221. #if JUCE_LINUX
  13222. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  13223. using an RAII approach.
  13224. */
  13225. class ScopedXLock
  13226. {
  13227. public:
  13228. /** Creating a ScopedXLock object locks the X display.
  13229. This uses XLockDisplay() to grab the display that Juce is using.
  13230. */
  13231. ScopedXLock();
  13232. /** Deleting a ScopedXLock object unlocks the X display.
  13233. This calls XUnlockDisplay() to release the lock.
  13234. */
  13235. ~ScopedXLock();
  13236. };
  13237. #endif
  13238. #if JUCE_MAC
  13239. /**
  13240. A wrapper class for picking up events from an Apple IR remote control device.
  13241. To use it, just create a subclass of this class, implementing the buttonPressed()
  13242. callback, then call start() and stop() to start or stop receiving events.
  13243. */
  13244. class JUCE_API AppleRemoteDevice
  13245. {
  13246. public:
  13247. AppleRemoteDevice();
  13248. virtual ~AppleRemoteDevice();
  13249. /** The set of buttons that may be pressed.
  13250. @see buttonPressed
  13251. */
  13252. enum ButtonType
  13253. {
  13254. menuButton = 0, /**< The menu button (if it's held for a short time). */
  13255. playButton, /**< The play button. */
  13256. plusButton, /**< The plus or volume-up button. */
  13257. minusButton, /**< The minus or volume-down button. */
  13258. rightButton, /**< The right button (if it's held for a short time). */
  13259. leftButton, /**< The left button (if it's held for a short time). */
  13260. rightButton_Long, /**< The right button (if it's held for a long time). */
  13261. leftButton_Long, /**< The menu button (if it's held for a long time). */
  13262. menuButton_Long, /**< The menu button (if it's held for a long time). */
  13263. playButtonSleepMode,
  13264. switched
  13265. };
  13266. /** Override this method to receive the callback about a button press.
  13267. The callback will happen on the application's message thread.
  13268. Some buttons trigger matching up and down events, in which the isDown parameter
  13269. will be true and then false. Others only send a single event when the
  13270. button is pressed.
  13271. */
  13272. virtual void buttonPressed (ButtonType buttonId, bool isDown) = 0;
  13273. /** Starts the device running and responding to events.
  13274. Returns true if it managed to open the device.
  13275. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  13276. and will not be available to any other part of the system. If
  13277. false, it will be shared with other apps.
  13278. @see stop
  13279. */
  13280. bool start (bool inExclusiveMode);
  13281. /** Stops the device running.
  13282. @see start
  13283. */
  13284. void stop();
  13285. /** Returns true if the device has been started successfully.
  13286. */
  13287. bool isActive() const;
  13288. /** Returns the ID number of the remote, if it has sent one.
  13289. */
  13290. int getRemoteId() const { return remoteId; }
  13291. /** @internal */
  13292. void handleCallbackInternal();
  13293. private:
  13294. void* device;
  13295. void* queue;
  13296. int remoteId;
  13297. bool open (bool openInExclusiveMode);
  13298. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AppleRemoteDevice);
  13299. };
  13300. #endif
  13301. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13302. /*** End of inlined file: juce_PlatformUtilities.h ***/
  13303. #endif
  13304. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  13305. #endif
  13306. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  13307. /*** Start of inlined file: juce_Singleton.h ***/
  13308. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  13309. #define __JUCE_SINGLETON_JUCEHEADER__
  13310. /*** Start of inlined file: juce_ScopedLock.h ***/
  13311. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  13312. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  13313. /**
  13314. Automatically locks and unlocks a CriticalSection object.
  13315. Use one of these as a local variable to control access to a CriticalSection.
  13316. e.g. @code
  13317. CriticalSection myCriticalSection;
  13318. for (;;)
  13319. {
  13320. const ScopedLock myScopedLock (myCriticalSection);
  13321. // myCriticalSection is now locked
  13322. ...do some stuff...
  13323. // myCriticalSection gets unlocked here.
  13324. }
  13325. @endcode
  13326. @see CriticalSection, ScopedUnlock
  13327. */
  13328. class ScopedLock
  13329. {
  13330. public:
  13331. /** Creates a ScopedLock.
  13332. As soon as it is created, this will lock the CriticalSection, and
  13333. when the ScopedLock object is deleted, the CriticalSection will
  13334. be unlocked.
  13335. Make sure this object is created and deleted by the same thread,
  13336. otherwise there are no guarantees what will happen! Best just to use it
  13337. as a local stack object, rather than creating one with the new() operator.
  13338. */
  13339. inline explicit ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  13340. /** Destructor.
  13341. The CriticalSection will be unlocked when the destructor is called.
  13342. Make sure this object is created and deleted by the same thread,
  13343. otherwise there are no guarantees what will happen!
  13344. */
  13345. inline ~ScopedLock() throw() { lock_.exit(); }
  13346. private:
  13347. const CriticalSection& lock_;
  13348. JUCE_DECLARE_NON_COPYABLE (ScopedLock);
  13349. };
  13350. /**
  13351. Automatically unlocks and re-locks a CriticalSection object.
  13352. This is the reverse of a ScopedLock object - instead of locking the critical
  13353. section for the lifetime of this object, it unlocks it.
  13354. Make sure you don't try to unlock critical sections that aren't actually locked!
  13355. e.g. @code
  13356. CriticalSection myCriticalSection;
  13357. for (;;)
  13358. {
  13359. const ScopedLock myScopedLock (myCriticalSection);
  13360. // myCriticalSection is now locked
  13361. ... do some stuff with it locked ..
  13362. while (xyz)
  13363. {
  13364. ... do some stuff with it locked ..
  13365. const ScopedUnlock unlocker (myCriticalSection);
  13366. // myCriticalSection is now unlocked for the remainder of this block,
  13367. // and re-locked at the end.
  13368. ...do some stuff with it unlocked ...
  13369. }
  13370. // myCriticalSection gets unlocked here.
  13371. }
  13372. @endcode
  13373. @see CriticalSection, ScopedLock
  13374. */
  13375. class ScopedUnlock
  13376. {
  13377. public:
  13378. /** Creates a ScopedUnlock.
  13379. As soon as it is created, this will unlock the CriticalSection, and
  13380. when the ScopedLock object is deleted, the CriticalSection will
  13381. be re-locked.
  13382. Make sure this object is created and deleted by the same thread,
  13383. otherwise there are no guarantees what will happen! Best just to use it
  13384. as a local stack object, rather than creating one with the new() operator.
  13385. */
  13386. inline explicit ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  13387. /** Destructor.
  13388. The CriticalSection will be unlocked when the destructor is called.
  13389. Make sure this object is created and deleted by the same thread,
  13390. otherwise there are no guarantees what will happen!
  13391. */
  13392. inline ~ScopedUnlock() throw() { lock_.enter(); }
  13393. private:
  13394. const CriticalSection& lock_;
  13395. JUCE_DECLARE_NON_COPYABLE (ScopedUnlock);
  13396. };
  13397. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  13398. /*** End of inlined file: juce_ScopedLock.h ***/
  13399. /**
  13400. Macro to declare member variables and methods for a singleton class.
  13401. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  13402. to the class's definition.
  13403. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  13404. implementation code.
  13405. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  13406. destructor, in case it is deleted by other means than deleteInstance()
  13407. Clients can then call the static method MyClass::getInstance() to get a pointer
  13408. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  13409. no instance currently exists.
  13410. e.g. @code
  13411. class MySingleton
  13412. {
  13413. public:
  13414. MySingleton()
  13415. {
  13416. }
  13417. ~MySingleton()
  13418. {
  13419. // this ensures that no dangling pointers are left when the
  13420. // singleton is deleted.
  13421. clearSingletonInstance();
  13422. }
  13423. juce_DeclareSingleton (MySingleton, false)
  13424. };
  13425. juce_ImplementSingleton (MySingleton)
  13426. // example of usage:
  13427. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  13428. ...
  13429. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  13430. @endcode
  13431. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  13432. than once during the process's lifetime - i.e. after you've created and deleted the
  13433. object, getInstance() will refuse to create another one. This can be useful to stop
  13434. objects being accidentally re-created during your app's shutdown code.
  13435. If you know that your object will only be created and deleted by a single thread, you
  13436. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  13437. of this one.
  13438. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  13439. */
  13440. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  13441. \
  13442. static classname* _singletonInstance; \
  13443. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  13444. \
  13445. static classname* JUCE_CALLTYPE getInstance() \
  13446. { \
  13447. if (_singletonInstance == 0) \
  13448. {\
  13449. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  13450. \
  13451. if (_singletonInstance == 0) \
  13452. { \
  13453. static bool alreadyInside = false; \
  13454. static bool createdOnceAlready = false; \
  13455. \
  13456. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  13457. jassert (! problem); \
  13458. if (! problem) \
  13459. { \
  13460. createdOnceAlready = true; \
  13461. alreadyInside = true; \
  13462. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  13463. alreadyInside = false; \
  13464. \
  13465. _singletonInstance = newObject; \
  13466. } \
  13467. } \
  13468. } \
  13469. \
  13470. return _singletonInstance; \
  13471. } \
  13472. \
  13473. static inline classname* JUCE_CALLTYPE getInstanceWithoutCreating() throw() \
  13474. { \
  13475. return _singletonInstance; \
  13476. } \
  13477. \
  13478. static void JUCE_CALLTYPE deleteInstance() \
  13479. { \
  13480. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  13481. if (_singletonInstance != 0) \
  13482. { \
  13483. classname* const old = _singletonInstance; \
  13484. _singletonInstance = 0; \
  13485. delete old; \
  13486. } \
  13487. } \
  13488. \
  13489. void clearSingletonInstance() throw() \
  13490. { \
  13491. if (_singletonInstance == this) \
  13492. _singletonInstance = 0; \
  13493. }
  13494. /** This is a counterpart to the juce_DeclareSingleton macro.
  13495. After adding the juce_DeclareSingleton to the class definition, this macro has
  13496. to be used in the cpp file.
  13497. */
  13498. #define juce_ImplementSingleton(classname) \
  13499. \
  13500. classname* classname::_singletonInstance = 0; \
  13501. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  13502. /**
  13503. Macro to declare member variables and methods for a singleton class.
  13504. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  13505. section to make access to it thread-safe. If you know that your object will
  13506. only ever be created or deleted by a single thread, then this is a
  13507. more efficient version to use.
  13508. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  13509. than once during the process's lifetime - i.e. after you've created and deleted the
  13510. object, getInstance() will refuse to create another one. This can be useful to stop
  13511. objects being accidentally re-created during your app's shutdown code.
  13512. See the documentation for juce_DeclareSingleton for more information about
  13513. how to use it, the only difference being that you have to use
  13514. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  13515. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  13516. */
  13517. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  13518. \
  13519. static classname* _singletonInstance; \
  13520. \
  13521. static classname* getInstance() \
  13522. { \
  13523. if (_singletonInstance == 0) \
  13524. { \
  13525. static bool alreadyInside = false; \
  13526. static bool createdOnceAlready = false; \
  13527. \
  13528. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  13529. jassert (! problem); \
  13530. if (! problem) \
  13531. { \
  13532. createdOnceAlready = true; \
  13533. alreadyInside = true; \
  13534. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  13535. alreadyInside = false; \
  13536. \
  13537. _singletonInstance = newObject; \
  13538. } \
  13539. } \
  13540. \
  13541. return _singletonInstance; \
  13542. } \
  13543. \
  13544. static inline classname* getInstanceWithoutCreating() throw() \
  13545. { \
  13546. return _singletonInstance; \
  13547. } \
  13548. \
  13549. static void deleteInstance() \
  13550. { \
  13551. if (_singletonInstance != 0) \
  13552. { \
  13553. classname* const old = _singletonInstance; \
  13554. _singletonInstance = 0; \
  13555. delete old; \
  13556. } \
  13557. } \
  13558. \
  13559. void clearSingletonInstance() throw() \
  13560. { \
  13561. if (_singletonInstance == this) \
  13562. _singletonInstance = 0; \
  13563. }
  13564. /**
  13565. Macro to declare member variables and methods for a singleton class.
  13566. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  13567. for recursion or repeated instantiation. It's intended for use as a lightweight
  13568. version of a singleton, where you're using it in very straightforward
  13569. circumstances and don't need the extra checking.
  13570. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  13571. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  13572. See the documentation for juce_DeclareSingleton for more information about
  13573. how to use it, the only difference being that you have to use
  13574. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  13575. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  13576. */
  13577. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  13578. \
  13579. static classname* _singletonInstance; \
  13580. \
  13581. static classname* getInstance() \
  13582. { \
  13583. if (_singletonInstance == 0) \
  13584. _singletonInstance = new classname(); \
  13585. \
  13586. return _singletonInstance; \
  13587. } \
  13588. \
  13589. static inline classname* getInstanceWithoutCreating() throw() \
  13590. { \
  13591. return _singletonInstance; \
  13592. } \
  13593. \
  13594. static void deleteInstance() \
  13595. { \
  13596. if (_singletonInstance != 0) \
  13597. { \
  13598. classname* const old = _singletonInstance; \
  13599. _singletonInstance = 0; \
  13600. delete old; \
  13601. } \
  13602. } \
  13603. \
  13604. void clearSingletonInstance() throw() \
  13605. { \
  13606. if (_singletonInstance == this) \
  13607. _singletonInstance = 0; \
  13608. }
  13609. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  13610. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  13611. to the class definition, this macro has to be used somewhere in the cpp file.
  13612. */
  13613. #define juce_ImplementSingleton_SingleThreaded(classname) \
  13614. \
  13615. classname* classname::_singletonInstance = 0;
  13616. #endif // __JUCE_SINGLETON_JUCEHEADER__
  13617. /*** End of inlined file: juce_Singleton.h ***/
  13618. #endif
  13619. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  13620. #endif
  13621. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  13622. /*** Start of inlined file: juce_SystemStats.h ***/
  13623. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  13624. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  13625. /**
  13626. Contains methods for finding out about the current hardware and OS configuration.
  13627. */
  13628. class JUCE_API SystemStats
  13629. {
  13630. public:
  13631. /** Returns the current version of JUCE,
  13632. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  13633. */
  13634. static const String getJUCEVersion();
  13635. /** The set of possible results of the getOperatingSystemType() method.
  13636. */
  13637. enum OperatingSystemType
  13638. {
  13639. UnknownOS = 0,
  13640. MacOSX = 0x1000,
  13641. Linux = 0x2000,
  13642. Android = 0x3000,
  13643. Win95 = 0x4001,
  13644. Win98 = 0x4002,
  13645. WinNT351 = 0x4103,
  13646. WinNT40 = 0x4104,
  13647. Win2000 = 0x4105,
  13648. WinXP = 0x4106,
  13649. WinVista = 0x4107,
  13650. Windows7 = 0x4108,
  13651. Windows = 0x4000, /**< To test whether any version of Windows is running,
  13652. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  13653. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  13654. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  13655. };
  13656. /** Returns the type of operating system we're running on.
  13657. @returns one of the values from the OperatingSystemType enum.
  13658. @see getOperatingSystemName
  13659. */
  13660. static OperatingSystemType getOperatingSystemType();
  13661. /** Returns the name of the type of operating system we're running on.
  13662. @returns a string describing the OS type.
  13663. @see getOperatingSystemType
  13664. */
  13665. static const String getOperatingSystemName();
  13666. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  13667. */
  13668. static bool isOperatingSystem64Bit();
  13669. /** Returns the current user's name, if available.
  13670. @see getFullUserName()
  13671. */
  13672. static const String getLogonName();
  13673. /** Returns the current user's full name, if available.
  13674. On some OSes, this may just return the same value as getLogonName().
  13675. @see getLogonName()
  13676. */
  13677. static const String getFullUserName();
  13678. // CPU and memory information..
  13679. /** Returns the approximate CPU speed.
  13680. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  13681. what year you're reading this...)
  13682. */
  13683. static int getCpuSpeedInMegaherz();
  13684. /** Returns a string to indicate the CPU vendor.
  13685. Might not be known on some systems.
  13686. */
  13687. static const String getCpuVendor();
  13688. /** Checks whether Intel MMX instructions are available. */
  13689. static bool hasMMX() throw() { return cpuFlags.hasMMX; }
  13690. /** Checks whether Intel SSE instructions are available. */
  13691. static bool hasSSE() throw() { return cpuFlags.hasSSE; }
  13692. /** Checks whether Intel SSE2 instructions are available. */
  13693. static bool hasSSE2() throw() { return cpuFlags.hasSSE2; }
  13694. /** Checks whether AMD 3DNOW instructions are available. */
  13695. static bool has3DNow() throw() { return cpuFlags.has3DNow; }
  13696. /** Returns the number of CPUs. */
  13697. static int getNumCpus() throw() { return cpuFlags.numCpus; }
  13698. /** Finds out how much RAM is in the machine.
  13699. @returns the approximate number of megabytes of memory, or zero if
  13700. something goes wrong when finding out.
  13701. */
  13702. static int getMemorySizeInMegabytes();
  13703. /** Returns the system page-size.
  13704. This is only used by programmers with beards.
  13705. */
  13706. static int getPageSize();
  13707. // not-for-public-use platform-specific method gets called at startup to initialise things.
  13708. static void initialiseStats();
  13709. private:
  13710. struct CPUFlags
  13711. {
  13712. int numCpus;
  13713. bool hasMMX : 1;
  13714. bool hasSSE : 1;
  13715. bool hasSSE2 : 1;
  13716. bool has3DNow : 1;
  13717. };
  13718. static CPUFlags cpuFlags;
  13719. SystemStats();
  13720. JUCE_DECLARE_NON_COPYABLE (SystemStats);
  13721. };
  13722. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  13723. /*** End of inlined file: juce_SystemStats.h ***/
  13724. #endif
  13725. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  13726. #endif
  13727. #ifndef __JUCE_TIME_JUCEHEADER__
  13728. #endif
  13729. #ifndef __JUCE_UUID_JUCEHEADER__
  13730. /*** Start of inlined file: juce_Uuid.h ***/
  13731. #ifndef __JUCE_UUID_JUCEHEADER__
  13732. #define __JUCE_UUID_JUCEHEADER__
  13733. /**
  13734. A universally unique 128-bit identifier.
  13735. This class generates very random unique numbers based on the system time
  13736. and MAC addresses if any are available. It's extremely unlikely that two identical
  13737. UUIDs would ever be created by chance.
  13738. The class includes methods for saving the ID as a string or as raw binary data.
  13739. */
  13740. class JUCE_API Uuid
  13741. {
  13742. public:
  13743. /** Creates a new unique ID. */
  13744. Uuid();
  13745. /** Destructor. */
  13746. ~Uuid() throw();
  13747. /** Creates a copy of another UUID. */
  13748. Uuid (const Uuid& other);
  13749. /** Copies another UUID. */
  13750. Uuid& operator= (const Uuid& other);
  13751. /** Returns true if the ID is zero. */
  13752. bool isNull() const throw();
  13753. /** Compares two UUIDs. */
  13754. bool operator== (const Uuid& other) const;
  13755. /** Compares two UUIDs. */
  13756. bool operator!= (const Uuid& other) const;
  13757. /** Returns a stringified version of this UUID.
  13758. A Uuid object can later be reconstructed from this string using operator= or
  13759. the constructor that takes a string parameter.
  13760. @returns a 32 character hex string.
  13761. */
  13762. const String toString() const;
  13763. /** Creates an ID from an encoded string version.
  13764. @see toString
  13765. */
  13766. Uuid (const String& uuidString);
  13767. /** Copies from a stringified UUID.
  13768. The string passed in should be one that was created with the toString() method.
  13769. */
  13770. Uuid& operator= (const String& uuidString);
  13771. /** Returns a pointer to the internal binary representation of the ID.
  13772. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  13773. the constructor or operator= method that takes an array of uint8s.
  13774. */
  13775. const uint8* getRawData() const throw() { return value.asBytes; }
  13776. /** Creates a UUID from a 16-byte array.
  13777. @see getRawData
  13778. */
  13779. Uuid (const uint8* rawData);
  13780. /** Sets this UUID from 16-bytes of raw data. */
  13781. Uuid& operator= (const uint8* rawData);
  13782. private:
  13783. #ifndef DOXYGEN
  13784. union
  13785. {
  13786. uint8 asBytes [16];
  13787. int asInt[4];
  13788. int64 asInt64[2];
  13789. } value;
  13790. #endif
  13791. JUCE_LEAK_DETECTOR (Uuid);
  13792. };
  13793. #endif // __JUCE_UUID_JUCEHEADER__
  13794. /*** End of inlined file: juce_Uuid.h ***/
  13795. #endif
  13796. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  13797. /*** Start of inlined file: juce_BlowFish.h ***/
  13798. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  13799. #define __JUCE_BLOWFISH_JUCEHEADER__
  13800. /**
  13801. BlowFish encryption class.
  13802. */
  13803. class JUCE_API BlowFish
  13804. {
  13805. public:
  13806. /** Creates an object that can encode/decode based on the specified key.
  13807. The key data can be up to 72 bytes long.
  13808. */
  13809. BlowFish (const void* keyData, int keyBytes);
  13810. /** Creates a copy of another blowfish object. */
  13811. BlowFish (const BlowFish& other);
  13812. /** Copies another blowfish object. */
  13813. BlowFish& operator= (const BlowFish& other);
  13814. /** Destructor. */
  13815. ~BlowFish();
  13816. /** Encrypts a pair of 32-bit integers. */
  13817. void encrypt (uint32& data1, uint32& data2) const throw();
  13818. /** Decrypts a pair of 32-bit integers. */
  13819. void decrypt (uint32& data1, uint32& data2) const throw();
  13820. private:
  13821. uint32 p[18];
  13822. HeapBlock <uint32> s[4];
  13823. uint32 F (uint32 x) const throw();
  13824. JUCE_LEAK_DETECTOR (BlowFish);
  13825. };
  13826. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  13827. /*** End of inlined file: juce_BlowFish.h ***/
  13828. #endif
  13829. #ifndef __JUCE_MD5_JUCEHEADER__
  13830. /*** Start of inlined file: juce_MD5.h ***/
  13831. #ifndef __JUCE_MD5_JUCEHEADER__
  13832. #define __JUCE_MD5_JUCEHEADER__
  13833. /**
  13834. MD5 checksum class.
  13835. Create one of these with a block of source data or a string, and it calculates the
  13836. MD5 checksum of that data.
  13837. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  13838. */
  13839. class JUCE_API MD5
  13840. {
  13841. public:
  13842. /** Creates a null MD5 object. */
  13843. MD5();
  13844. /** Creates a copy of another MD5. */
  13845. MD5 (const MD5& other);
  13846. /** Copies another MD5. */
  13847. MD5& operator= (const MD5& other);
  13848. /** Creates a checksum for a block of binary data. */
  13849. explicit MD5 (const MemoryBlock& data);
  13850. /** Creates a checksum for a block of binary data. */
  13851. MD5 (const void* data, size_t numBytes);
  13852. /** Creates a checksum for a string.
  13853. Note that this operates on the string as a block of unicode characters, so the
  13854. result you get will differ from the value you'd get if the string was treated
  13855. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  13856. of this method with a checksum created by a different framework, which may have
  13857. used a different encoding.
  13858. */
  13859. explicit MD5 (const String& text);
  13860. /** Creates a checksum for the input from a stream.
  13861. This will read up to the given number of bytes from the stream, and produce the
  13862. checksum of that. If the number of bytes to read is negative, it'll read
  13863. until the stream is exhausted.
  13864. */
  13865. MD5 (InputStream& input, int64 numBytesToRead = -1);
  13866. /** Creates a checksum for a file. */
  13867. explicit MD5 (const File& file);
  13868. /** Destructor. */
  13869. ~MD5();
  13870. /** Returns the checksum as a 16-byte block of data. */
  13871. const MemoryBlock getRawChecksumData() const;
  13872. /** Returns the checksum as a 32-digit hex string. */
  13873. const String toHexString() const;
  13874. /** Compares this to another MD5. */
  13875. bool operator== (const MD5& other) const;
  13876. /** Compares this to another MD5. */
  13877. bool operator!= (const MD5& other) const;
  13878. private:
  13879. uint8 result [16];
  13880. struct ProcessContext
  13881. {
  13882. uint8 buffer [64];
  13883. uint32 state [4];
  13884. uint32 count [2];
  13885. ProcessContext();
  13886. void processBlock (const void* data, size_t dataSize);
  13887. void transform (const void* buffer);
  13888. void finish (void* result);
  13889. };
  13890. void processStream (InputStream& input, int64 numBytesToRead);
  13891. JUCE_LEAK_DETECTOR (MD5);
  13892. };
  13893. #endif // __JUCE_MD5_JUCEHEADER__
  13894. /*** End of inlined file: juce_MD5.h ***/
  13895. #endif
  13896. #ifndef __JUCE_PRIMES_JUCEHEADER__
  13897. /*** Start of inlined file: juce_Primes.h ***/
  13898. #ifndef __JUCE_PRIMES_JUCEHEADER__
  13899. #define __JUCE_PRIMES_JUCEHEADER__
  13900. /*** Start of inlined file: juce_BigInteger.h ***/
  13901. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  13902. #define __JUCE_BIGINTEGER_JUCEHEADER__
  13903. class MemoryBlock;
  13904. /**
  13905. An arbitrarily large integer class.
  13906. A BigInteger can be used in a similar way to a normal integer, but has no size
  13907. limit (except for memory and performance constraints).
  13908. Negative values are possible, but the value isn't stored as 2s-complement, so
  13909. be careful if you use negative values and look at the values of individual bits.
  13910. */
  13911. class JUCE_API BigInteger
  13912. {
  13913. public:
  13914. /** Creates an empty BigInteger */
  13915. BigInteger();
  13916. /** Creates a BigInteger containing an integer value in its low bits.
  13917. The low 32 bits of the number are initialised with this value.
  13918. */
  13919. BigInteger (uint32 value);
  13920. /** Creates a BigInteger containing an integer value in its low bits.
  13921. The low 32 bits of the number are initialised with the absolute value
  13922. passed in, and its sign is set to reflect the sign of the number.
  13923. */
  13924. BigInteger (int32 value);
  13925. /** Creates a BigInteger containing an integer value in its low bits.
  13926. The low 64 bits of the number are initialised with the absolute value
  13927. passed in, and its sign is set to reflect the sign of the number.
  13928. */
  13929. BigInteger (int64 value);
  13930. /** Creates a copy of another BigInteger. */
  13931. BigInteger (const BigInteger& other);
  13932. /** Destructor. */
  13933. ~BigInteger();
  13934. /** Copies another BigInteger onto this one. */
  13935. BigInteger& operator= (const BigInteger& other);
  13936. /** Swaps the internal contents of this with another object. */
  13937. void swapWith (BigInteger& other) throw();
  13938. /** Returns the value of a specified bit in the number.
  13939. If the index is out-of-range, the result will be false.
  13940. */
  13941. bool operator[] (int bit) const throw();
  13942. /** Returns true if no bits are set. */
  13943. bool isZero() const throw();
  13944. /** Returns true if the value is 1. */
  13945. bool isOne() const throw();
  13946. /** Attempts to get the lowest bits of the value as an integer.
  13947. If the value is bigger than the integer limits, this will return only the lower bits.
  13948. */
  13949. int toInteger() const throw();
  13950. /** Resets the value to 0. */
  13951. void clear();
  13952. /** Clears a particular bit in the number. */
  13953. void clearBit (int bitNumber) throw();
  13954. /** Sets a specified bit to 1. */
  13955. void setBit (int bitNumber);
  13956. /** Sets or clears a specified bit. */
  13957. void setBit (int bitNumber, bool shouldBeSet);
  13958. /** Sets a range of bits to be either on or off.
  13959. @param startBit the first bit to change
  13960. @param numBits the number of bits to change
  13961. @param shouldBeSet whether to turn these bits on or off
  13962. */
  13963. void setRange (int startBit, int numBits, bool shouldBeSet);
  13964. /** Inserts a bit an a given position, shifting up any bits above it. */
  13965. void insertBit (int bitNumber, bool shouldBeSet);
  13966. /** Returns a range of bits as a new BigInteger.
  13967. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  13968. @see getBitRangeAsInt
  13969. */
  13970. const BigInteger getBitRange (int startBit, int numBits) const;
  13971. /** Returns a range of bits as an integer value.
  13972. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  13973. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  13974. getBitRange().
  13975. */
  13976. int getBitRangeAsInt (int startBit, int numBits) const throw();
  13977. /** Sets a range of bits to an integer value.
  13978. Copies the given integer onto a range of bits, starting at startBit,
  13979. and using up to numBits of the available bits.
  13980. */
  13981. void setBitRangeAsInt (int startBit, int numBits, uint32 valueToSet);
  13982. /** Shifts a section of bits left or right.
  13983. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  13984. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  13985. */
  13986. void shiftBits (int howManyBitsLeft, int startBit);
  13987. /** Returns the total number of set bits in the value. */
  13988. int countNumberOfSetBits() const throw();
  13989. /** Looks for the index of the next set bit after a given starting point.
  13990. This searches from startIndex (inclusive) upwards for the first set bit,
  13991. and returns its index. If no set bits are found, it returns -1.
  13992. */
  13993. int findNextSetBit (int startIndex = 0) const throw();
  13994. /** Looks for the index of the next clear bit after a given starting point.
  13995. This searches from startIndex (inclusive) upwards for the first clear bit,
  13996. and returns its index.
  13997. */
  13998. int findNextClearBit (int startIndex = 0) const throw();
  13999. /** Returns the index of the highest set bit in the number.
  14000. If the value is zero, this will return -1.
  14001. */
  14002. int getHighestBit() const throw();
  14003. // All the standard arithmetic ops...
  14004. BigInteger& operator+= (const BigInteger& other);
  14005. BigInteger& operator-= (const BigInteger& other);
  14006. BigInteger& operator*= (const BigInteger& other);
  14007. BigInteger& operator/= (const BigInteger& other);
  14008. BigInteger& operator|= (const BigInteger& other);
  14009. BigInteger& operator&= (const BigInteger& other);
  14010. BigInteger& operator^= (const BigInteger& other);
  14011. BigInteger& operator%= (const BigInteger& other);
  14012. BigInteger& operator<<= (int numBitsToShift);
  14013. BigInteger& operator>>= (int numBitsToShift);
  14014. BigInteger& operator++();
  14015. BigInteger& operator--();
  14016. const BigInteger operator++ (int);
  14017. const BigInteger operator-- (int);
  14018. const BigInteger operator-() const;
  14019. const BigInteger operator+ (const BigInteger& other) const;
  14020. const BigInteger operator- (const BigInteger& other) const;
  14021. const BigInteger operator* (const BigInteger& other) const;
  14022. const BigInteger operator/ (const BigInteger& other) const;
  14023. const BigInteger operator| (const BigInteger& other) const;
  14024. const BigInteger operator& (const BigInteger& other) const;
  14025. const BigInteger operator^ (const BigInteger& other) const;
  14026. const BigInteger operator% (const BigInteger& other) const;
  14027. const BigInteger operator<< (int numBitsToShift) const;
  14028. const BigInteger operator>> (int numBitsToShift) const;
  14029. bool operator== (const BigInteger& other) const throw();
  14030. bool operator!= (const BigInteger& other) const throw();
  14031. bool operator< (const BigInteger& other) const throw();
  14032. bool operator<= (const BigInteger& other) const throw();
  14033. bool operator> (const BigInteger& other) const throw();
  14034. bool operator>= (const BigInteger& other) const throw();
  14035. /** Does a signed comparison of two BigIntegers.
  14036. Return values are:
  14037. - 0 if the numbers are the same
  14038. - < 0 if this number is smaller than the other
  14039. - > 0 if this number is bigger than the other
  14040. */
  14041. int compare (const BigInteger& other) const throw();
  14042. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  14043. Return values are:
  14044. - 0 if the numbers are the same
  14045. - < 0 if this number is smaller than the other
  14046. - > 0 if this number is bigger than the other
  14047. */
  14048. int compareAbsolute (const BigInteger& other) const throw();
  14049. /** Divides this value by another one and returns the remainder.
  14050. This number is divided by other, leaving the quotient in this number,
  14051. with the remainder being copied to the other BigInteger passed in.
  14052. */
  14053. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  14054. /** Returns the largest value that will divide both this value and the one passed-in.
  14055. */
  14056. const BigInteger findGreatestCommonDivisor (BigInteger other) const;
  14057. /** Performs a combined exponent and modulo operation.
  14058. This BigInteger's value becomes (this ^ exponent) % modulus.
  14059. */
  14060. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  14061. /** Performs an inverse modulo on the value.
  14062. i.e. the result is (this ^ -1) mod (modulus).
  14063. */
  14064. void inverseModulo (const BigInteger& modulus);
  14065. /** Returns true if the value is less than zero.
  14066. @see setNegative, negate
  14067. */
  14068. bool isNegative() const throw();
  14069. /** Changes the sign of the number to be positive or negative.
  14070. @see isNegative, negate
  14071. */
  14072. void setNegative (bool shouldBeNegative) throw();
  14073. /** Inverts the sign of the number.
  14074. @see isNegative, setNegative
  14075. */
  14076. void negate() throw();
  14077. /** Converts the number to a string.
  14078. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14079. If minimumNumCharacters is greater than 0, the returned string will be
  14080. padded with leading zeros to reach at least that length.
  14081. */
  14082. const String toString (int base, int minimumNumCharacters = 1) const;
  14083. /** Reads the numeric value from a string.
  14084. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14085. Any invalid characters will be ignored.
  14086. */
  14087. void parseString (const String& text, int base);
  14088. /** Turns the number into a block of binary data.
  14089. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14090. of the number, and so on.
  14091. @see loadFromMemoryBlock
  14092. */
  14093. const MemoryBlock toMemoryBlock() const;
  14094. /** Converts a block of raw data into a number.
  14095. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14096. of the number, and so on.
  14097. @see toMemoryBlock
  14098. */
  14099. void loadFromMemoryBlock (const MemoryBlock& data);
  14100. private:
  14101. HeapBlock <uint32> values;
  14102. int numValues, highestBit;
  14103. bool negative;
  14104. void ensureSize (int numVals);
  14105. static const BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  14106. static inline int bitToIndex (const int bit) throw() { return bit >> 5; }
  14107. static inline uint32 bitToMask (const int bit) throw() { return 1 << (bit & 31); }
  14108. JUCE_LEAK_DETECTOR (BigInteger);
  14109. };
  14110. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  14111. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  14112. #ifndef DOXYGEN
  14113. // For backwards compatibility, BitArray is defined as an alias for BigInteger.
  14114. typedef BigInteger BitArray;
  14115. #endif
  14116. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  14117. /*** End of inlined file: juce_BigInteger.h ***/
  14118. /**
  14119. Prime number creation class.
  14120. This class contains static methods for generating and testing prime numbers.
  14121. @see BigInteger
  14122. */
  14123. class JUCE_API Primes
  14124. {
  14125. public:
  14126. /** Creates a random prime number with a given bit-length.
  14127. The certainty parameter specifies how many iterations to use when testing
  14128. for primality. A safe value might be anything over about 20-30.
  14129. The randomSeeds parameter lets you optionally pass it a set of values with
  14130. which to seed the random number generation, improving the security of the
  14131. keys generated.
  14132. */
  14133. static const BigInteger createProbablePrime (int bitLength,
  14134. int certainty,
  14135. const int* randomSeeds = 0,
  14136. int numRandomSeeds = 0);
  14137. /** Tests a number to see if it's prime.
  14138. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  14139. whether the number is prime.
  14140. The certainty parameter specifies how many iterations to use when testing - a
  14141. safe value might be anything over about 20-30.
  14142. */
  14143. static bool isProbablyPrime (const BigInteger& number, int certainty);
  14144. private:
  14145. Primes();
  14146. JUCE_DECLARE_NON_COPYABLE (Primes);
  14147. };
  14148. #endif // __JUCE_PRIMES_JUCEHEADER__
  14149. /*** End of inlined file: juce_Primes.h ***/
  14150. #endif
  14151. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14152. /*** Start of inlined file: juce_RSAKey.h ***/
  14153. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14154. #define __JUCE_RSAKEY_JUCEHEADER__
  14155. /**
  14156. RSA public/private key-pair encryption class.
  14157. An object of this type makes up one half of a public/private RSA key pair. Use the
  14158. createKeyPair() method to create a matching pair for encoding/decoding.
  14159. */
  14160. class JUCE_API RSAKey
  14161. {
  14162. public:
  14163. /** Creates a null key object.
  14164. Initialise a pair of objects for use with the createKeyPair() method.
  14165. */
  14166. RSAKey();
  14167. /** Loads a key from an encoded string representation.
  14168. This reloads a key from a string created by the toString() method.
  14169. */
  14170. explicit RSAKey (const String& stringRepresentation);
  14171. /** Destructor. */
  14172. ~RSAKey();
  14173. bool operator== (const RSAKey& other) const throw();
  14174. bool operator!= (const RSAKey& other) const throw();
  14175. /** Turns the key into a string representation.
  14176. This can be reloaded using the constructor that takes a string.
  14177. */
  14178. const String toString() const;
  14179. /** Encodes or decodes a value.
  14180. Call this on the public key object to encode some data, then use the matching
  14181. private key object to decode it.
  14182. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  14183. initialised correctly.
  14184. NOTE: This method dumbly applies this key to this data. If you encode some data
  14185. and then try to decode it with a key that doesn't match, this method will still
  14186. happily do its job and return true, but the result won't be what you were expecting.
  14187. It's your responsibility to check that the result is what you wanted.
  14188. */
  14189. bool applyToValue (BigInteger& value) const;
  14190. /** Creates a public/private key-pair.
  14191. Each key will perform one-way encryption that can only be reversed by
  14192. using the other key.
  14193. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  14194. sizes are more secure, but this method will take longer to execute.
  14195. The randomSeeds parameter lets you optionally pass it a set of values with
  14196. which to seed the random number generation, improving the security of the
  14197. keys generated. If you supply these, make sure you provide more than 2 values,
  14198. and the more your provide, the better the security.
  14199. */
  14200. static void createKeyPair (RSAKey& publicKey,
  14201. RSAKey& privateKey,
  14202. int numBits,
  14203. const int* randomSeeds = 0,
  14204. int numRandomSeeds = 0);
  14205. protected:
  14206. BigInteger part1, part2;
  14207. private:
  14208. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q);
  14209. JUCE_LEAK_DETECTOR (RSAKey);
  14210. };
  14211. #endif // __JUCE_RSAKEY_JUCEHEADER__
  14212. /*** End of inlined file: juce_RSAKey.h ***/
  14213. #endif
  14214. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14215. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  14216. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14217. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14218. /**
  14219. Searches through a the files in a directory, returning each file that is found.
  14220. A DirectoryIterator will search through a directory and its subdirectories using
  14221. a wildcard filepattern match.
  14222. If you may be finding a large number of files, this is better than
  14223. using File::findChildFiles() because it doesn't block while it finds them
  14224. all, and this is more memory-efficient.
  14225. It can also guess how far it's got using a wildly inaccurate algorithm.
  14226. */
  14227. class JUCE_API DirectoryIterator
  14228. {
  14229. public:
  14230. /** Creates a DirectoryIterator for a given directory.
  14231. After creating one of these, call its next() method to get the
  14232. first file - e.g. @code
  14233. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  14234. while (iter.next())
  14235. {
  14236. File theFileItFound (iter.getFile());
  14237. ... etc
  14238. }
  14239. @endcode
  14240. @param directory the directory to search in
  14241. @param isRecursive whether all the subdirectories should also be searched
  14242. @param wildCard the file pattern to match
  14243. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  14244. whether to look for files, directories, or both.
  14245. */
  14246. DirectoryIterator (const File& directory,
  14247. bool isRecursive,
  14248. const String& wildCard = "*",
  14249. int whatToLookFor = File::findFiles);
  14250. /** Destructor. */
  14251. ~DirectoryIterator();
  14252. /** Moves the iterator along to the next file.
  14253. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14254. false if there are no more matching files.
  14255. */
  14256. bool next();
  14257. /** Moves the iterator along to the next file, and returns various properties of that file.
  14258. If you need to find out details about the file, it's more efficient to call this method than
  14259. to call the normal next() method and then find out the details afterwards.
  14260. All the parameters are optional, so pass null pointers for any items that you're not
  14261. interested in.
  14262. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14263. false if there are no more matching files. If it returns false, then none of the
  14264. parameters will be filled-in.
  14265. */
  14266. bool next (bool* isDirectory, bool* isHidden, int64* fileSize,
  14267. Time* modTime, Time* creationTime, bool* isReadOnly);
  14268. /** Returns the file that the iterator is currently pointing at.
  14269. The result of this call is only valid after a call to next() has returned true.
  14270. */
  14271. const File getFile() const;
  14272. /** Returns a guess of how far through the search the iterator has got.
  14273. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  14274. very accurate.
  14275. */
  14276. float getEstimatedProgress() const;
  14277. private:
  14278. class NativeIterator
  14279. {
  14280. public:
  14281. NativeIterator (const File& directory, const String& wildCard);
  14282. ~NativeIterator();
  14283. bool next (String& filenameFound,
  14284. bool* isDirectory, bool* isHidden, int64* fileSize,
  14285. Time* modTime, Time* creationTime, bool* isReadOnly);
  14286. class Pimpl;
  14287. private:
  14288. friend class DirectoryIterator;
  14289. friend class ScopedPointer<Pimpl>;
  14290. ScopedPointer<Pimpl> pimpl;
  14291. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeIterator);
  14292. };
  14293. friend class ScopedPointer<NativeIterator::Pimpl>;
  14294. NativeIterator fileFinder;
  14295. String wildCard, path;
  14296. int index;
  14297. mutable int totalNumFiles;
  14298. const int whatToLookFor;
  14299. const bool isRecursive;
  14300. bool hasBeenAdvanced;
  14301. ScopedPointer <DirectoryIterator> subIterator;
  14302. File currentFile;
  14303. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryIterator);
  14304. };
  14305. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14306. /*** End of inlined file: juce_DirectoryIterator.h ***/
  14307. #endif
  14308. #ifndef __JUCE_FILE_JUCEHEADER__
  14309. #endif
  14310. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14311. /*** Start of inlined file: juce_FileInputStream.h ***/
  14312. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14313. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14314. /**
  14315. An input stream that reads from a local file.
  14316. @see InputStream, FileOutputStream, File::createInputStream
  14317. */
  14318. class JUCE_API FileInputStream : public InputStream
  14319. {
  14320. public:
  14321. /** Creates a FileInputStream.
  14322. @param fileToRead the file to read from - if the file can't be accessed for some
  14323. reason, then the stream will just contain no data
  14324. */
  14325. explicit FileInputStream (const File& fileToRead);
  14326. /** Destructor. */
  14327. ~FileInputStream();
  14328. const File& getFile() const throw() { return file; }
  14329. int64 getTotalLength();
  14330. int read (void* destBuffer, int maxBytesToRead);
  14331. bool isExhausted();
  14332. int64 getPosition();
  14333. bool setPosition (int64 pos);
  14334. private:
  14335. File file;
  14336. void* fileHandle;
  14337. int64 currentPosition, totalSize;
  14338. bool needToSeek;
  14339. void openHandle();
  14340. void closeHandle();
  14341. size_t readInternal (void* buffer, size_t numBytes);
  14342. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputStream);
  14343. };
  14344. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14345. /*** End of inlined file: juce_FileInputStream.h ***/
  14346. #endif
  14347. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14348. /*** Start of inlined file: juce_FileOutputStream.h ***/
  14349. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14350. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14351. /**
  14352. An output stream that writes into a local file.
  14353. @see OutputStream, FileInputStream, File::createOutputStream
  14354. */
  14355. class JUCE_API FileOutputStream : public OutputStream
  14356. {
  14357. public:
  14358. /** Creates a FileOutputStream.
  14359. If the file doesn't exist, it will first be created. If the file can't be
  14360. created or opened, the failedToOpen() method will return
  14361. true.
  14362. If the file already exists when opened, the stream's write-postion will
  14363. be set to the end of the file. To overwrite an existing file,
  14364. use File::deleteFile() before opening the stream, or use setPosition(0)
  14365. after it's opened (although this won't truncate the file).
  14366. It's better to use File::createOutputStream() to create one of these, rather
  14367. than using the class directly.
  14368. @see TemporaryFile
  14369. */
  14370. FileOutputStream (const File& fileToWriteTo,
  14371. int bufferSizeToUse = 16384);
  14372. /** Destructor. */
  14373. ~FileOutputStream();
  14374. /** Returns the file that this stream is writing to.
  14375. */
  14376. const File& getFile() const { return file; }
  14377. /** Returns true if the stream couldn't be opened for some reason.
  14378. */
  14379. bool failedToOpen() const { return fileHandle == 0; }
  14380. void flush();
  14381. int64 getPosition();
  14382. bool setPosition (int64 pos);
  14383. bool write (const void* data, int numBytes);
  14384. private:
  14385. File file;
  14386. void* fileHandle;
  14387. int64 currentPosition;
  14388. int bufferSize, bytesInBuffer;
  14389. HeapBlock <char> buffer;
  14390. void openHandle();
  14391. void closeHandle();
  14392. void flushInternal();
  14393. int64 setPositionInternal (int64 newPosition);
  14394. int writeInternal (const void* data, int numBytes);
  14395. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileOutputStream);
  14396. };
  14397. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14398. /*** End of inlined file: juce_FileOutputStream.h ***/
  14399. #endif
  14400. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  14401. /*** Start of inlined file: juce_FileSearchPath.h ***/
  14402. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  14403. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  14404. /**
  14405. Encapsulates a set of folders that make up a search path.
  14406. @see File
  14407. */
  14408. class JUCE_API FileSearchPath
  14409. {
  14410. public:
  14411. /** Creates an empty search path. */
  14412. FileSearchPath();
  14413. /** Creates a search path from a string of pathnames.
  14414. The path can be semicolon- or comma-separated, e.g.
  14415. "/foo/bar;/foo/moose;/fish/moose"
  14416. The separate folders are tokenised and added to the search path.
  14417. */
  14418. FileSearchPath (const String& path);
  14419. /** Creates a copy of another search path. */
  14420. FileSearchPath (const FileSearchPath& other);
  14421. /** Destructor. */
  14422. ~FileSearchPath();
  14423. /** Uses a string containing a list of pathnames to re-initialise this list.
  14424. This search path is cleared and the semicolon- or comma-separated folders
  14425. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  14426. */
  14427. FileSearchPath& operator= (const String& path);
  14428. /** Returns the number of folders in this search path.
  14429. @see operator[]
  14430. */
  14431. int getNumPaths() const;
  14432. /** Returns one of the folders in this search path.
  14433. The file returned isn't guaranteed to actually be a valid directory.
  14434. @see getNumPaths
  14435. */
  14436. const File operator[] (int index) const;
  14437. /** Returns the search path as a semicolon-separated list of directories. */
  14438. const String toString() const;
  14439. /** Adds a new directory to the search path.
  14440. The new directory is added to the end of the list if the insertIndex parameter is
  14441. less than zero, otherwise it is inserted at the given index.
  14442. */
  14443. void add (const File& directoryToAdd,
  14444. int insertIndex = -1);
  14445. /** Adds a new directory to the search path if it's not already in there. */
  14446. void addIfNotAlreadyThere (const File& directoryToAdd);
  14447. /** Removes a directory from the search path. */
  14448. void remove (int indexToRemove);
  14449. /** Merges another search path into this one.
  14450. This will remove any duplicate directories.
  14451. */
  14452. void addPath (const FileSearchPath& other);
  14453. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  14454. If the search is intended to be recursive, there's no point having nested folders in the search
  14455. path, because they'll just get searched twice and you'll get duplicate results.
  14456. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  14457. */
  14458. void removeRedundantPaths();
  14459. /** Removes any directories that don't actually exist. */
  14460. void removeNonExistentPaths();
  14461. /** Searches the path for a wildcard.
  14462. This will search all the directories in the search path in order, adding any
  14463. matching files to the results array.
  14464. @param results an array to append the results to
  14465. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  14466. return files, directories, or both.
  14467. @param searchRecursively whether to recursively search the subdirectories too
  14468. @param wildCardPattern a pattern to match against the filenames
  14469. @returns the number of files added to the array
  14470. @see File::findChildFiles
  14471. */
  14472. int findChildFiles (Array<File>& results,
  14473. int whatToLookFor,
  14474. bool searchRecursively,
  14475. const String& wildCardPattern = "*") const;
  14476. /** Finds out whether a file is inside one of the path's directories.
  14477. This will return true if the specified file is a child of one of the
  14478. directories specified by this path. Note that this doesn't actually do any
  14479. searching or check that the files exist - it just looks at the pathnames
  14480. to work out whether the file would be inside a directory.
  14481. @param fileToCheck the file to look for
  14482. @param checkRecursively if true, then this will return true if the file is inside a
  14483. subfolder of one of the path's directories (at any depth). If false
  14484. it will only return true if the file is actually a direct child
  14485. of one of the directories.
  14486. @see File::isAChildOf
  14487. */
  14488. bool isFileInPath (const File& fileToCheck,
  14489. bool checkRecursively) const;
  14490. private:
  14491. StringArray directories;
  14492. void init (const String& path);
  14493. JUCE_LEAK_DETECTOR (FileSearchPath);
  14494. };
  14495. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  14496. /*** End of inlined file: juce_FileSearchPath.h ***/
  14497. #endif
  14498. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  14499. /*** Start of inlined file: juce_NamedPipe.h ***/
  14500. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  14501. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  14502. /**
  14503. A cross-process pipe that can have data written to and read from it.
  14504. Two or more processes can use these for inter-process communication.
  14505. @see InterprocessConnection
  14506. */
  14507. class JUCE_API NamedPipe
  14508. {
  14509. public:
  14510. /** Creates a NamedPipe. */
  14511. NamedPipe();
  14512. /** Destructor. */
  14513. ~NamedPipe();
  14514. /** Tries to open a pipe that already exists.
  14515. Returns true if it succeeds.
  14516. */
  14517. bool openExisting (const String& pipeName);
  14518. /** Tries to create a new pipe.
  14519. Returns true if it succeeds.
  14520. */
  14521. bool createNewPipe (const String& pipeName);
  14522. /** Closes the pipe, if it's open. */
  14523. void close();
  14524. /** True if the pipe is currently open. */
  14525. bool isOpen() const;
  14526. /** Returns the last name that was used to try to open this pipe. */
  14527. const String getName() const;
  14528. /** Reads data from the pipe.
  14529. This will block until another thread has written enough data into the pipe to fill
  14530. the number of bytes specified, or until another thread calls the cancelPendingReads()
  14531. method.
  14532. If the operation fails, it returns -1, otherwise, it will return the number of
  14533. bytes read.
  14534. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  14535. this is a maximum timeout for reading from the pipe.
  14536. */
  14537. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  14538. /** Writes some data to the pipe.
  14539. If the operation fails, it returns -1, otherwise, it will return the number of
  14540. bytes written.
  14541. */
  14542. int write (const void* sourceBuffer, int numBytesToWrite,
  14543. int timeOutMilliseconds = 2000);
  14544. /** If any threads are currently blocked on a read operation, this tells them to abort.
  14545. */
  14546. void cancelPendingReads();
  14547. private:
  14548. void* internal;
  14549. String currentPipeName;
  14550. CriticalSection lock;
  14551. bool openInternal (const String& pipeName, const bool createPipe);
  14552. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NamedPipe);
  14553. };
  14554. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  14555. /*** End of inlined file: juce_NamedPipe.h ***/
  14556. #endif
  14557. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  14558. /*** Start of inlined file: juce_TemporaryFile.h ***/
  14559. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  14560. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  14561. /**
  14562. Manages a temporary file, which will be deleted when this object is deleted.
  14563. This object is intended to be used as a stack based object, using its scope
  14564. to make sure the temporary file isn't left lying around.
  14565. For example:
  14566. @code
  14567. {
  14568. File myTargetFile ("~/myfile.txt");
  14569. // this will choose a file called something like "~/myfile_temp239348.txt"
  14570. // which definitely doesn't exist at the time the constructor is called.
  14571. TemporaryFile temp (myTargetFile);
  14572. // create a stream to the temporary file, and write some data to it...
  14573. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  14574. if (out != 0)
  14575. {
  14576. out->write ( ...etc )
  14577. out->flush();
  14578. out = 0; // (deletes the stream)
  14579. // ..now we've finished writing, this will rename the temp file to
  14580. // make it replace the target file we specified above.
  14581. bool succeeded = temp.overwriteTargetFileWithTemporary();
  14582. }
  14583. // ..and even if something went wrong and our overwrite failed,
  14584. // as the TemporaryFile object goes out of scope here, it'll make sure
  14585. // that the temp file gets deleted.
  14586. }
  14587. @endcode
  14588. @see File, FileOutputStream
  14589. */
  14590. class JUCE_API TemporaryFile
  14591. {
  14592. public:
  14593. enum OptionFlags
  14594. {
  14595. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  14596. i.e. its name should start with a dot. */
  14597. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  14598. the file is unique, they should go in brackets rather
  14599. than just being appended (see File::getNonexistentSibling() )*/
  14600. };
  14601. /** Creates a randomly-named temporary file in the default temp directory.
  14602. @param suffix a file suffix to use for the file
  14603. @param optionFlags a combination of the values listed in the OptionFlags enum
  14604. The file will not be created until you write to it. And remember that when
  14605. this object is deleted, the file will also be deleted!
  14606. */
  14607. TemporaryFile (const String& suffix = String::empty,
  14608. int optionFlags = 0);
  14609. /** Creates a temporary file in the same directory as a specified file.
  14610. This is useful if you have a file that you want to overwrite, but don't
  14611. want to harm the original file if the write operation fails. You can
  14612. use this to create a temporary file next to the target file, then
  14613. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  14614. to replace the target file with the one you've just written.
  14615. This class won't create any files until you actually write to them. And remember
  14616. that when this object is deleted, the temporary file will also be deleted!
  14617. @param targetFile the file that you intend to overwrite - the temporary
  14618. file will be created in the same directory as this
  14619. @param optionFlags a combination of the values listed in the OptionFlags enum
  14620. */
  14621. TemporaryFile (const File& targetFile,
  14622. int optionFlags = 0);
  14623. /** Destructor.
  14624. When this object is deleted it will make sure that its temporary file is
  14625. also deleted! If the operation fails, it'll throw an assertion in debug
  14626. mode.
  14627. */
  14628. ~TemporaryFile();
  14629. /** Returns the temporary file. */
  14630. const File getFile() const { return temporaryFile; }
  14631. /** Returns the target file that was specified in the constructor. */
  14632. const File getTargetFile() const { return targetFile; }
  14633. /** Tries to move the temporary file to overwrite the target file that was
  14634. specified in the constructor.
  14635. If you used the constructor that specified a target file, this will attempt
  14636. to replace that file with the temporary one.
  14637. Before calling this, make sure:
  14638. - that you've actually written to the temporary file
  14639. - that you've closed any open streams that you were using to write to it
  14640. - and that you don't have any streams open to the target file, which would
  14641. prevent it being overwritten
  14642. If the file move succeeds, this returns false, and the temporary file will
  14643. have disappeared. If it fails, the temporary file will probably still exist,
  14644. but will be deleted when this object is destroyed.
  14645. */
  14646. bool overwriteTargetFileWithTemporary() const;
  14647. /** Attempts to delete the temporary file, if it exists.
  14648. @returns true if the file is successfully deleted (or if it didn't exist).
  14649. */
  14650. bool deleteTemporaryFile() const;
  14651. private:
  14652. File temporaryFile, targetFile;
  14653. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  14654. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryFile);
  14655. };
  14656. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  14657. /*** End of inlined file: juce_TemporaryFile.h ***/
  14658. #endif
  14659. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  14660. /*** Start of inlined file: juce_ZipFile.h ***/
  14661. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  14662. #define __JUCE_ZIPFILE_JUCEHEADER__
  14663. /*** Start of inlined file: juce_InputSource.h ***/
  14664. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  14665. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  14666. /**
  14667. A lightweight object that can create a stream to read some kind of resource.
  14668. This may be used to refer to a file, or some other kind of source, allowing a
  14669. caller to create an input stream that can read from it when required.
  14670. @see FileInputSource
  14671. */
  14672. class JUCE_API InputSource
  14673. {
  14674. public:
  14675. InputSource() throw() {}
  14676. /** Destructor. */
  14677. virtual ~InputSource() {}
  14678. /** Returns a new InputStream to read this item.
  14679. @returns an inputstream that the caller will delete, or 0 if
  14680. the filename isn't found.
  14681. */
  14682. virtual InputStream* createInputStream() = 0;
  14683. /** Returns a new InputStream to read an item, relative.
  14684. @param relatedItemPath the relative pathname of the resource that is required
  14685. @returns an inputstream that the caller will delete, or 0 if
  14686. the item isn't found.
  14687. */
  14688. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  14689. /** Returns a hash code that uniquely represents this item.
  14690. */
  14691. virtual int64 hashCode() const = 0;
  14692. private:
  14693. JUCE_LEAK_DETECTOR (InputSource);
  14694. };
  14695. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  14696. /*** End of inlined file: juce_InputSource.h ***/
  14697. /**
  14698. Decodes a ZIP file from a stream.
  14699. This can enumerate the items in a ZIP file and can create suitable stream objects
  14700. to read each one.
  14701. */
  14702. class JUCE_API ZipFile
  14703. {
  14704. public:
  14705. /** Creates a ZipFile for a given stream.
  14706. @param inputStream the stream to read from
  14707. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  14708. will be deleted when this ZipFile object is deleted
  14709. */
  14710. ZipFile (InputStream* inputStream, bool deleteStreamWhenDestroyed);
  14711. /** Creates a ZipFile based for a file. */
  14712. ZipFile (const File& file);
  14713. /** Creates a ZipFile for an input source.
  14714. The inputSource object will be owned by the zip file, which will delete
  14715. it later when not needed.
  14716. */
  14717. ZipFile (InputSource* inputSource);
  14718. /** Destructor. */
  14719. ~ZipFile();
  14720. /**
  14721. Contains information about one of the entries in a ZipFile.
  14722. @see ZipFile::getEntry
  14723. */
  14724. struct ZipEntry
  14725. {
  14726. /** The name of the file, which may also include a partial pathname. */
  14727. String filename;
  14728. /** The file's original size. */
  14729. unsigned int uncompressedSize;
  14730. /** The last time the file was modified. */
  14731. Time fileTime;
  14732. };
  14733. /** Returns the number of items in the zip file. */
  14734. int getNumEntries() const throw();
  14735. /** Returns a structure that describes one of the entries in the zip file.
  14736. This may return zero if the index is out of range.
  14737. @see ZipFile::ZipEntry
  14738. */
  14739. const ZipEntry* getEntry (int index) const throw();
  14740. /** Returns the index of the first entry with a given filename.
  14741. This uses a case-sensitive comparison to look for a filename in the
  14742. list of entries. It might return -1 if no match is found.
  14743. @see ZipFile::ZipEntry
  14744. */
  14745. int getIndexOfFileName (const String& fileName) const throw();
  14746. /** Returns a structure that describes one of the entries in the zip file.
  14747. This uses a case-sensitive comparison to look for a filename in the
  14748. list of entries. It might return 0 if no match is found.
  14749. @see ZipFile::ZipEntry
  14750. */
  14751. const ZipEntry* getEntry (const String& fileName) const throw();
  14752. /** Sorts the list of entries, based on the filename.
  14753. */
  14754. void sortEntriesByFilename();
  14755. /** Creates a stream that can read from one of the zip file's entries.
  14756. The stream that is returned must be deleted by the caller (and
  14757. zero might be returned if a stream can't be opened for some reason).
  14758. The stream must not be used after the ZipFile object that created
  14759. has been deleted.
  14760. */
  14761. InputStream* createStreamForEntry (int index);
  14762. /** Creates a stream that can read from one of the zip file's entries.
  14763. The stream that is returned must be deleted by the caller (and
  14764. zero might be returned if a stream can't be opened for some reason).
  14765. The stream must not be used after the ZipFile object that created
  14766. has been deleted.
  14767. */
  14768. InputStream* createStreamForEntry (ZipEntry& entry);
  14769. /** Uncompresses all of the files in the zip file.
  14770. This will expand all the entries into a target directory. The relative
  14771. paths of the entries are used.
  14772. @param targetDirectory the root folder to uncompress to
  14773. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  14774. @returns true if all the files are successfully unzipped
  14775. */
  14776. bool uncompressTo (const File& targetDirectory,
  14777. bool shouldOverwriteFiles = true);
  14778. /** Uncompresses one of the entries from the zip file.
  14779. This will expand the entry and write it in a target directory. The entry's path is used to
  14780. determine which subfolder of the target should contain the new file.
  14781. @param index the index of the entry to uncompress
  14782. @param targetDirectory the root folder to uncompress into
  14783. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  14784. @returns true if the files is successfully unzipped
  14785. */
  14786. bool uncompressEntry (int index,
  14787. const File& targetDirectory,
  14788. bool shouldOverwriteFiles = true);
  14789. /** Used to create a new zip file.
  14790. Create a ZipFile::Builder object, and call its addFile() method to add some files,
  14791. then you can write it to a stream with write().
  14792. Currently this just stores the files with no compression.. That will be added
  14793. soon!
  14794. */
  14795. class Builder
  14796. {
  14797. public:
  14798. Builder();
  14799. ~Builder();
  14800. /** Adds a file while should be added to the archive.
  14801. The file isn't read immediately, all the files will be read later when the writeToStream()
  14802. method is called.
  14803. The compressionLevel can be between 0 (no compression), and 9 (maximum compression).
  14804. If the storedPathName parameter is specified, you can customise the partial pathname that
  14805. will be stored for this file.
  14806. */
  14807. void addFile (const File& fileToAdd, int compressionLevel,
  14808. const String& storedPathName = String::empty);
  14809. /** Generates the zip file, writing it to the specified stream. */
  14810. bool writeToStream (OutputStream& target) const;
  14811. private:
  14812. class Item;
  14813. friend class OwnedArray<Item>;
  14814. OwnedArray<Item> items;
  14815. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Builder);
  14816. };
  14817. private:
  14818. class ZipInputStream;
  14819. class ZipFilenameComparator;
  14820. class ZipEntryInfo;
  14821. friend class ZipInputStream;
  14822. friend class ZipFilenameComparator;
  14823. friend class ZipEntryInfo;
  14824. OwnedArray <ZipEntryInfo> entries;
  14825. CriticalSection lock;
  14826. InputStream* inputStream;
  14827. ScopedPointer <InputStream> streamToDelete;
  14828. ScopedPointer <InputSource> inputSource;
  14829. #if JUCE_DEBUG
  14830. int numOpenStreams;
  14831. #endif
  14832. void init();
  14833. int findEndOfZipEntryTable (InputStream& input, int& numEntries);
  14834. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  14835. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipFile);
  14836. };
  14837. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  14838. /*** End of inlined file: juce_ZipFile.h ***/
  14839. #endif
  14840. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  14841. /*** Start of inlined file: juce_MACAddress.h ***/
  14842. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  14843. #define __JUCE_MACADDRESS_JUCEHEADER__
  14844. /**
  14845. A wrapper for a streaming (TCP) socket.
  14846. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  14847. sockets, you could also try the InterprocessConnection class.
  14848. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  14849. */
  14850. class JUCE_API MACAddress
  14851. {
  14852. public:
  14853. /** Populates a list of the MAC addresses of all the available network cards. */
  14854. static void findAllAddresses (Array<MACAddress>& results);
  14855. /** Creates a null address (00-00-00-00-00-00). */
  14856. MACAddress();
  14857. /** Creates a copy of another address. */
  14858. MACAddress (const MACAddress& other);
  14859. /** Creates a copy of another address. */
  14860. MACAddress& operator= (const MACAddress& other);
  14861. /** Creates an address from 6 bytes. */
  14862. explicit MACAddress (const uint8 bytes[6]);
  14863. /** Returns a pointer to the 6 bytes that make up this address. */
  14864. const uint8* getBytes() const throw() { return asBytes; }
  14865. /** Returns a dash-separated string in the form "11-22-33-44-55-66" */
  14866. const String toString() const;
  14867. /** Returns the address in the lower 6 bytes of an int64.
  14868. This uses a little-endian arrangement, with the first byte of the address being
  14869. stored in the least-significant byte of the result value.
  14870. */
  14871. int64 toInt64() const throw();
  14872. /** Returns true if this address is null (00-00-00-00-00-00). */
  14873. bool isNull() const throw();
  14874. bool operator== (const MACAddress& other) const throw();
  14875. bool operator!= (const MACAddress& other) const throw();
  14876. private:
  14877. #ifndef DOXYGEN
  14878. union
  14879. {
  14880. uint64 asInt64;
  14881. uint8 asBytes[6];
  14882. };
  14883. #endif
  14884. };
  14885. #endif // __JUCE_MACADDRESS_JUCEHEADER__
  14886. /*** End of inlined file: juce_MACAddress.h ***/
  14887. #endif
  14888. #ifndef __JUCE_SOCKET_JUCEHEADER__
  14889. /*** Start of inlined file: juce_Socket.h ***/
  14890. #ifndef __JUCE_SOCKET_JUCEHEADER__
  14891. #define __JUCE_SOCKET_JUCEHEADER__
  14892. /**
  14893. A wrapper for a streaming (TCP) socket.
  14894. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  14895. sockets, you could also try the InterprocessConnection class.
  14896. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  14897. */
  14898. class JUCE_API StreamingSocket
  14899. {
  14900. public:
  14901. /** Creates an uninitialised socket.
  14902. To connect it, use the connect() method, after which you can read() or write()
  14903. to it.
  14904. To wait for other sockets to connect to this one, the createListener() method
  14905. enters "listener" mode, and can be used to spawn new sockets for each connection
  14906. that comes along.
  14907. */
  14908. StreamingSocket();
  14909. /** Destructor. */
  14910. ~StreamingSocket();
  14911. /** Binds the socket to the specified local port.
  14912. @returns true on success; false may indicate that another socket is already bound
  14913. on the same port
  14914. */
  14915. bool bindToPort (int localPortNumber);
  14916. /** Tries to connect the socket to hostname:port.
  14917. If timeOutMillisecs is 0, then this method will block until the operating system
  14918. rejects the connection (which could take a long time).
  14919. @returns true if it succeeds.
  14920. @see isConnected
  14921. */
  14922. bool connect (const String& remoteHostname,
  14923. int remotePortNumber,
  14924. int timeOutMillisecs = 3000);
  14925. /** True if the socket is currently connected. */
  14926. bool isConnected() const throw() { return connected; }
  14927. /** Closes the connection. */
  14928. void close();
  14929. /** Returns the name of the currently connected host. */
  14930. const String& getHostName() const throw() { return hostName; }
  14931. /** Returns the port number that's currently open. */
  14932. int getPort() const throw() { return portNumber; }
  14933. /** True if the socket is connected to this machine rather than over the network. */
  14934. bool isLocal() const throw();
  14935. /** Waits until the socket is ready for reading or writing.
  14936. If readyForReading is true, it will wait until the socket is ready for
  14937. reading; if false, it will wait until it's ready for writing.
  14938. If the timeout is < 0, it will wait forever, or else will give up after
  14939. the specified time.
  14940. If the socket is ready on return, this returns 1. If it times-out before
  14941. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  14942. */
  14943. int waitUntilReady (bool readyForReading,
  14944. int timeoutMsecs) const;
  14945. /** Reads bytes from the socket.
  14946. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  14947. maxBytesToRead bytes have been read, (or until an error occurs). If this
  14948. flag is false, the method will return as much data as is currently available
  14949. without blocking.
  14950. @returns the number of bytes read, or -1 if there was an error.
  14951. @see waitUntilReady
  14952. */
  14953. int read (void* destBuffer, int maxBytesToRead,
  14954. bool blockUntilSpecifiedAmountHasArrived);
  14955. /** Writes bytes to the socket from a buffer.
  14956. Note that this method will block unless you have checked the socket is ready
  14957. for writing before calling it (see the waitUntilReady() method).
  14958. @returns the number of bytes written, or -1 if there was an error.
  14959. */
  14960. int write (const void* sourceBuffer, int numBytesToWrite);
  14961. /** Puts this socket into "listener" mode.
  14962. When in this mode, your thread can call waitForNextConnection() repeatedly,
  14963. which will spawn new sockets for each new connection, so that these can
  14964. be handled in parallel by other threads.
  14965. @param portNumber the port number to listen on
  14966. @param localHostName the interface address to listen on - pass an empty
  14967. string to listen on all addresses
  14968. @returns true if it manages to open the socket successfully.
  14969. @see waitForNextConnection
  14970. */
  14971. bool createListener (int portNumber, const String& localHostName = String::empty);
  14972. /** When in "listener" mode, this waits for a connection and spawns it as a new
  14973. socket.
  14974. The object that gets returned will be owned by the caller.
  14975. This method can only be called after using createListener().
  14976. @see createListener
  14977. */
  14978. StreamingSocket* waitForNextConnection() const;
  14979. private:
  14980. String hostName;
  14981. int volatile portNumber, handle;
  14982. bool connected, isListener;
  14983. StreamingSocket (const String& hostname, int portNumber, int handle);
  14984. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StreamingSocket);
  14985. };
  14986. /**
  14987. A wrapper for a datagram (UDP) socket.
  14988. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  14989. sockets, you could also try the InterprocessConnection class.
  14990. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  14991. */
  14992. class JUCE_API DatagramSocket
  14993. {
  14994. public:
  14995. /**
  14996. Creates an (uninitialised) datagram socket.
  14997. The localPortNumber is the port on which to bind this socket. If this value is 0,
  14998. the port number is assigned by the operating system.
  14999. To use the socket for sending, call the connect() method. This will not immediately
  15000. make a connection, but will save the destination you've provided. After this, you can
  15001. call read() or write().
  15002. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  15003. (may require extra privileges on linux)
  15004. To wait for other sockets to connect to this one, call waitForNextConnection().
  15005. */
  15006. DatagramSocket (int localPortNumber,
  15007. bool enableBroadcasting = false);
  15008. /** Destructor. */
  15009. ~DatagramSocket();
  15010. /** Binds the socket to the specified local port.
  15011. @returns true on success; false may indicate that another socket is already bound
  15012. on the same port
  15013. */
  15014. bool bindToPort (int localPortNumber);
  15015. /** Tries to connect the socket to hostname:port.
  15016. If timeOutMillisecs is 0, then this method will block until the operating system
  15017. rejects the connection (which could take a long time).
  15018. @returns true if it succeeds.
  15019. @see isConnected
  15020. */
  15021. bool connect (const String& remoteHostname,
  15022. int remotePortNumber,
  15023. int timeOutMillisecs = 3000);
  15024. /** True if the socket is currently connected. */
  15025. bool isConnected() const throw() { return connected; }
  15026. /** Closes the connection. */
  15027. void close();
  15028. /** Returns the name of the currently connected host. */
  15029. const String& getHostName() const throw() { return hostName; }
  15030. /** Returns the port number that's currently open. */
  15031. int getPort() const throw() { return portNumber; }
  15032. /** True if the socket is connected to this machine rather than over the network. */
  15033. bool isLocal() const throw();
  15034. /** Waits until the socket is ready for reading or writing.
  15035. If readyForReading is true, it will wait until the socket is ready for
  15036. reading; if false, it will wait until it's ready for writing.
  15037. If the timeout is < 0, it will wait forever, or else will give up after
  15038. the specified time.
  15039. If the socket is ready on return, this returns 1. If it times-out before
  15040. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  15041. */
  15042. int waitUntilReady (bool readyForReading,
  15043. int timeoutMsecs) const;
  15044. /** Reads bytes from the socket.
  15045. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  15046. maxBytesToRead bytes have been read, (or until an error occurs). If this
  15047. flag is false, the method will return as much data as is currently available
  15048. without blocking.
  15049. @returns the number of bytes read, or -1 if there was an error.
  15050. @see waitUntilReady
  15051. */
  15052. int read (void* destBuffer, int maxBytesToRead,
  15053. bool blockUntilSpecifiedAmountHasArrived);
  15054. /** Writes bytes to the socket from a buffer.
  15055. Note that this method will block unless you have checked the socket is ready
  15056. for writing before calling it (see the waitUntilReady() method).
  15057. @returns the number of bytes written, or -1 if there was an error.
  15058. */
  15059. int write (const void* sourceBuffer, int numBytesToWrite);
  15060. /** This waits for incoming data to be sent, and returns a socket that can be used
  15061. to read it.
  15062. The object that gets returned is owned by the caller, and can't be used for
  15063. sending, but can be used to read the data.
  15064. */
  15065. DatagramSocket* waitForNextConnection() const;
  15066. private:
  15067. String hostName;
  15068. int volatile portNumber, handle;
  15069. bool connected, allowBroadcast;
  15070. void* serverAddress;
  15071. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  15072. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DatagramSocket);
  15073. };
  15074. #endif // __JUCE_SOCKET_JUCEHEADER__
  15075. /*** End of inlined file: juce_Socket.h ***/
  15076. #endif
  15077. #ifndef __JUCE_URL_JUCEHEADER__
  15078. /*** Start of inlined file: juce_URL.h ***/
  15079. #ifndef __JUCE_URL_JUCEHEADER__
  15080. #define __JUCE_URL_JUCEHEADER__
  15081. /**
  15082. Represents a URL and has a bunch of useful functions to manipulate it.
  15083. This class can be used to launch URLs in browsers, and also to create
  15084. InputStreams that can read from remote http or ftp sources.
  15085. */
  15086. class JUCE_API URL
  15087. {
  15088. public:
  15089. /** Creates an empty URL. */
  15090. URL();
  15091. /** Creates a URL from a string. */
  15092. URL (const String& url);
  15093. /** Creates a copy of another URL. */
  15094. URL (const URL& other);
  15095. /** Destructor. */
  15096. ~URL();
  15097. /** Copies this URL from another one. */
  15098. URL& operator= (const URL& other);
  15099. /** Returns a string version of the URL.
  15100. If includeGetParameters is true and any parameters have been set with the
  15101. withParameter() method, then the string will have these appended on the
  15102. end and url-encoded.
  15103. */
  15104. const String toString (bool includeGetParameters) const;
  15105. /** True if it seems to be valid. */
  15106. bool isWellFormed() const;
  15107. /** Returns just the domain part of the URL.
  15108. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  15109. */
  15110. const String getDomain() const;
  15111. /** Returns the path part of the URL.
  15112. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  15113. */
  15114. const String getSubPath() const;
  15115. /** Returns the scheme of the URL.
  15116. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  15117. include the colon).
  15118. */
  15119. const String getScheme() const;
  15120. /** Returns a new version of this URL that uses a different sub-path.
  15121. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  15122. "bar", it'll return "http://www.xyz.com/bar?x=1".
  15123. */
  15124. const URL withNewSubPath (const String& newPath) const;
  15125. /** Returns a copy of this URL, with a GET or POST parameter added to the end.
  15126. Any control characters in the value will be encoded.
  15127. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  15128. would produce a new url whose toString(true) method would return
  15129. "www.fish.com?amount=some+fish".
  15130. */
  15131. const URL withParameter (const String& parameterName,
  15132. const String& parameterValue) const;
  15133. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  15134. When performing a POST where one of your parameters is a binary file, this
  15135. lets you specify the file.
  15136. Note that the filename is stored, but the file itself won't actually be read
  15137. until this URL is later used to create a network input stream.
  15138. */
  15139. const URL withFileToUpload (const String& parameterName,
  15140. const File& fileToUpload,
  15141. const String& mimeType) const;
  15142. /** Returns a set of all the parameters encoded into the url.
  15143. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  15144. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  15145. The values returned will have been cleaned up to remove any escape characters.
  15146. @see getNamedParameter, withParameter
  15147. */
  15148. const StringPairArray& getParameters() const;
  15149. /** Returns the set of files that should be uploaded as part of a POST operation.
  15150. This is the set of files that were added to the URL with the withFileToUpload()
  15151. method.
  15152. */
  15153. const StringPairArray& getFilesToUpload() const;
  15154. /** Returns the set of mime types associated with each of the upload files.
  15155. */
  15156. const StringPairArray& getMimeTypesOfUploadFiles() const;
  15157. /** Returns a copy of this URL, with a block of data to send as the POST data.
  15158. If you're setting the POST data, be careful not to have any parameters set
  15159. as well, otherwise it'll all get thrown in together, and might not have the
  15160. desired effect.
  15161. If the URL already contains some POST data, this will replace it, rather
  15162. than being appended to it.
  15163. This data will only be used if you specify a post operation when you call
  15164. createInputStream().
  15165. */
  15166. const URL withPOSTData (const String& postData) const;
  15167. /** Returns the data that was set using withPOSTData().
  15168. */
  15169. const String getPostData() const { return postData; }
  15170. /** Tries to launch the system's default browser to open the URL.
  15171. Returns true if this seems to have worked.
  15172. */
  15173. bool launchInDefaultBrowser() const;
  15174. /** Takes a guess as to whether a string might be a valid website address.
  15175. This isn't foolproof!
  15176. */
  15177. static bool isProbablyAWebsiteURL (const String& possibleURL);
  15178. /** Takes a guess as to whether a string might be a valid email address.
  15179. This isn't foolproof!
  15180. */
  15181. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  15182. /** This callback function can be used by the createInputStream() method.
  15183. It allows your app to receive progress updates during a lengthy POST operation. If you
  15184. want to continue the operation, this should return true, or false to abort.
  15185. */
  15186. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  15187. /** Attempts to open a stream that can read from this URL.
  15188. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  15189. the paramters, otherwise it'll encode them into the
  15190. URL and do a 'GET'.
  15191. @param progressCallback if this is non-zero, it lets you supply a callback function
  15192. to keep track of the operation's progress. This can be useful
  15193. for lengthy POST operations, so that you can provide user feedback.
  15194. @param progressCallbackContext if a callback is specified, this value will be passed to
  15195. the function
  15196. @param extraHeaders if not empty, this string is appended onto the headers that
  15197. are used for the request. It must therefore be a valid set of HTML
  15198. header directives, separated by newlines.
  15199. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  15200. a negative number, it will be infinite. Otherwise it specifies a
  15201. time in milliseconds.
  15202. @param responseHeaders if this is non-zero, all the (key, value) pairs received as headers
  15203. in the response will be stored in this array
  15204. @returns an input stream that the caller must delete, or a null pointer if there was an
  15205. error trying to open it.
  15206. */
  15207. InputStream* createInputStream (bool usePostCommand,
  15208. OpenStreamProgressCallback* progressCallback = 0,
  15209. void* progressCallbackContext = 0,
  15210. const String& extraHeaders = String::empty,
  15211. int connectionTimeOutMs = 0,
  15212. StringPairArray* responseHeaders = 0) const;
  15213. /** Tries to download the entire contents of this URL into a binary data block.
  15214. If it succeeds, this will return true and append the data it read onto the end
  15215. of the memory block.
  15216. @param destData the memory block to append the new data to
  15217. @param usePostCommand whether to use a POST command to get the data (uses
  15218. a GET command if this is false)
  15219. @see readEntireTextStream, readEntireXmlStream
  15220. */
  15221. bool readEntireBinaryStream (MemoryBlock& destData,
  15222. bool usePostCommand = false) const;
  15223. /** Tries to download the entire contents of this URL as a string.
  15224. If it fails, this will return an empty string, otherwise it will return the
  15225. contents of the downloaded file. If you need to distinguish between a read
  15226. operation that fails and one that returns an empty string, you'll need to use
  15227. a different method, such as readEntireBinaryStream().
  15228. @param usePostCommand whether to use a POST command to get the data (uses
  15229. a GET command if this is false)
  15230. @see readEntireBinaryStream, readEntireXmlStream
  15231. */
  15232. const String readEntireTextStream (bool usePostCommand = false) const;
  15233. /** Tries to download the entire contents of this URL and parse it as XML.
  15234. If it fails, or if the text that it reads can't be parsed as XML, this will
  15235. return 0.
  15236. When it returns a valid XmlElement object, the caller is responsibile for deleting
  15237. this object when no longer needed.
  15238. @param usePostCommand whether to use a POST command to get the data (uses
  15239. a GET command if this is false)
  15240. @see readEntireBinaryStream, readEntireTextStream
  15241. */
  15242. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  15243. /** Adds escape sequences to a string to encode any characters that aren't
  15244. legal in a URL.
  15245. E.g. any spaces will be replaced with "%20".
  15246. This is the opposite of removeEscapeChars().
  15247. If isParameter is true, it means that the string is going to be used
  15248. as a parameter, so it also encodes '$' and ',' (which would otherwise
  15249. be legal in a URL.
  15250. @see removeEscapeChars
  15251. */
  15252. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  15253. bool isParameter);
  15254. /** Replaces any escape character sequences in a string with their original
  15255. character codes.
  15256. E.g. any instances of "%20" will be replaced by a space.
  15257. This is the opposite of addEscapeChars().
  15258. @see addEscapeChars
  15259. */
  15260. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  15261. private:
  15262. String url, postData;
  15263. StringPairArray parameters, filesToUpload, mimeTypes;
  15264. static InputStream* createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  15265. OpenStreamProgressCallback* progressCallback,
  15266. void* progressCallbackContext, const String& headers,
  15267. const int timeOutMs, StringPairArray* responseHeaders);
  15268. JUCE_LEAK_DETECTOR (URL);
  15269. };
  15270. #endif // __JUCE_URL_JUCEHEADER__
  15271. /*** End of inlined file: juce_URL.h ***/
  15272. #endif
  15273. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15274. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  15275. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15276. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15277. /*** Start of inlined file: juce_OptionalScopedPointer.h ***/
  15278. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15279. #define __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15280. /**
  15281. Holds a pointer to an object which can optionally be deleted when this pointer
  15282. goes out of scope.
  15283. This acts in many ways like a ScopedPointer, but allows you to specify whether or
  15284. not the object is deleted.
  15285. @see ScopedPointer
  15286. */
  15287. template <class ObjectType>
  15288. class OptionalScopedPointer
  15289. {
  15290. public:
  15291. /** Creates an empty OptionalScopedPointer. */
  15292. OptionalScopedPointer() : shouldDelete (false) {}
  15293. /** Creates an OptionalScopedPointer to point to a given object, and specifying whether
  15294. the OptionalScopedPointer will delete it.
  15295. If takeOwnership is true, then the OptionalScopedPointer will act like a ScopedPointer,
  15296. deleting the object when it is itself deleted. If this parameter is false, then the
  15297. OptionalScopedPointer just holds a normal pointer to the object, and won't delete it.
  15298. */
  15299. OptionalScopedPointer (ObjectType* objectToHold, bool takeOwnership)
  15300. : object (objectToHold), shouldDelete (takeOwnership)
  15301. {
  15302. }
  15303. /** Takes ownership of the object that another OptionalScopedPointer holds.
  15304. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  15305. as ownership of the managed object is transferred to this object.
  15306. The flag to indicate whether or not to delete the managed object is also
  15307. copied from the source object.
  15308. */
  15309. OptionalScopedPointer (OptionalScopedPointer& objectToTransferFrom)
  15310. : object (objectToTransferFrom.release()),
  15311. shouldDelete (objectToTransferFrom.shouldDelete)
  15312. {
  15313. }
  15314. /** Takes ownership of the object that another OptionalScopedPointer holds.
  15315. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  15316. as ownership of the managed object is transferred to this object.
  15317. The ownership flag that says whether or not to delete the managed object is also
  15318. copied from the source object.
  15319. */
  15320. OptionalScopedPointer& operator= (OptionalScopedPointer& objectToTransferFrom)
  15321. {
  15322. if (object != objectToTransferFrom.object)
  15323. {
  15324. clear();
  15325. object = objectToTransferFrom.object;
  15326. }
  15327. shouldDelete = objectToTransferFrom.shouldDelete;
  15328. return *this;
  15329. }
  15330. /** The destructor may or may not delete the object that is being held, depending on the
  15331. takeOwnership flag that was specified when the object was first passed into an
  15332. OptionalScopedPointer constructor.
  15333. */
  15334. ~OptionalScopedPointer()
  15335. {
  15336. clear();
  15337. }
  15338. /** Returns the object that this pointer is managing. */
  15339. inline operator ObjectType*() const throw() { return object; }
  15340. /** Returns the object that this pointer is managing. */
  15341. inline ObjectType& operator*() const throw() { return *object; }
  15342. /** Lets you access methods and properties of the object that this pointer is holding. */
  15343. inline ObjectType* operator->() const throw() { return object; }
  15344. /** Removes the current object from this OptionalScopedPointer without deleting it.
  15345. This will return the current object, and set this OptionalScopedPointer to a null pointer.
  15346. */
  15347. ObjectType* release() throw() { return object.release(); }
  15348. /** Resets this pointer to null, possibly deleting the object that it holds, if it has
  15349. ownership of it.
  15350. */
  15351. void clear()
  15352. {
  15353. if (! shouldDelete)
  15354. object.release();
  15355. }
  15356. /** Swaps this object with another OptionalScopedPointer.
  15357. The two objects simply exchange their states.
  15358. */
  15359. void swapWith (OptionalScopedPointer<ObjectType>& other) throw()
  15360. {
  15361. object.swapWith (other.object);
  15362. swapVariables (shouldDelete, other.shouldDelete);
  15363. }
  15364. private:
  15365. ScopedPointer<ObjectType> object;
  15366. bool shouldDelete;
  15367. };
  15368. #endif // __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15369. /*** End of inlined file: juce_OptionalScopedPointer.h ***/
  15370. /** Wraps another input stream, and reads from it using an intermediate buffer
  15371. If you're using an input stream such as a file input stream, and making lots of
  15372. small read accesses to it, it's probably sensible to wrap it in one of these,
  15373. so that the source stream gets accessed in larger chunk sizes, meaning less
  15374. work for the underlying stream.
  15375. */
  15376. class JUCE_API BufferedInputStream : public InputStream
  15377. {
  15378. public:
  15379. /** Creates a BufferedInputStream from an input source.
  15380. @param sourceStream the source stream to read from
  15381. @param bufferSize the size of reservoir to use to buffer the source
  15382. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  15383. deleted by this object when it is itself deleted.
  15384. */
  15385. BufferedInputStream (InputStream* sourceStream,
  15386. int bufferSize,
  15387. bool deleteSourceWhenDestroyed);
  15388. /** Creates a BufferedInputStream from an input source.
  15389. @param sourceStream the source stream to read from - the source stream must not
  15390. be deleted until this object has been destroyed.
  15391. @param bufferSize the size of reservoir to use to buffer the source
  15392. */
  15393. BufferedInputStream (InputStream& sourceStream, int bufferSize);
  15394. /** Destructor.
  15395. This may also delete the source stream, if that option was chosen when the
  15396. buffered stream was created.
  15397. */
  15398. ~BufferedInputStream();
  15399. int64 getTotalLength();
  15400. int64 getPosition();
  15401. bool setPosition (int64 newPosition);
  15402. int read (void* destBuffer, int maxBytesToRead);
  15403. const String readString();
  15404. bool isExhausted();
  15405. private:
  15406. OptionalScopedPointer<InputStream> source;
  15407. int bufferSize;
  15408. int64 position, lastReadPos, bufferStart, bufferOverlap;
  15409. HeapBlock <char> buffer;
  15410. void ensureBuffered();
  15411. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferedInputStream);
  15412. };
  15413. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15414. /*** End of inlined file: juce_BufferedInputStream.h ***/
  15415. #endif
  15416. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15417. /*** Start of inlined file: juce_FileInputSource.h ***/
  15418. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15419. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15420. /**
  15421. A type of InputSource that represents a normal file.
  15422. @see InputSource
  15423. */
  15424. class JUCE_API FileInputSource : public InputSource
  15425. {
  15426. public:
  15427. FileInputSource (const File& file, bool useFileTimeInHashGeneration = false);
  15428. ~FileInputSource();
  15429. InputStream* createInputStream();
  15430. InputStream* createInputStreamFor (const String& relatedItemPath);
  15431. int64 hashCode() const;
  15432. private:
  15433. const File file;
  15434. bool useFileTimeInHashGeneration;
  15435. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputSource);
  15436. };
  15437. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15438. /*** End of inlined file: juce_FileInputSource.h ***/
  15439. #endif
  15440. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15441. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  15442. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15443. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15444. /**
  15445. A stream which uses zlib to compress the data written into it.
  15446. @see GZIPDecompressorInputStream
  15447. */
  15448. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  15449. {
  15450. public:
  15451. /** Creates a compression stream.
  15452. @param destStream the stream into which the compressed data should
  15453. be written
  15454. @param compressionLevel how much to compress the data, between 1 and 9, where
  15455. 1 is the fastest/lowest compression, and 9 is the
  15456. slowest/highest compression. Any value outside this range
  15457. indicates that a default compression level should be used.
  15458. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  15459. this stream is destroyed
  15460. @param windowBits this is used internally to change the window size used
  15461. by zlib - leave it as 0 unless you specifically need to set
  15462. its value for some reason
  15463. */
  15464. GZIPCompressorOutputStream (OutputStream* destStream,
  15465. int compressionLevel = 0,
  15466. bool deleteDestStreamWhenDestroyed = false,
  15467. int windowBits = 0);
  15468. /** Destructor. */
  15469. ~GZIPCompressorOutputStream();
  15470. void flush();
  15471. int64 getPosition();
  15472. bool setPosition (int64 newPosition);
  15473. bool write (const void* destBuffer, int howMany);
  15474. /** These are preset values that can be used for the constructor's windowBits paramter.
  15475. For more info about this, see the zlib documentation for its windowBits parameter.
  15476. */
  15477. enum WindowBitsValues
  15478. {
  15479. windowBitsRaw = -15,
  15480. windowBitsGZIP = 15 + 16
  15481. };
  15482. private:
  15483. OptionalScopedPointer<OutputStream> destStream;
  15484. HeapBlock <uint8> buffer;
  15485. class GZIPCompressorHelper;
  15486. friend class ScopedPointer <GZIPCompressorHelper>;
  15487. ScopedPointer <GZIPCompressorHelper> helper;
  15488. bool doNextBlock();
  15489. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPCompressorOutputStream);
  15490. };
  15491. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15492. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  15493. #endif
  15494. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  15495. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  15496. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  15497. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  15498. /**
  15499. This stream will decompress a source-stream using zlib.
  15500. Tip: if you're reading lots of small items from one of these streams, you
  15501. can increase the performance enormously by passing it through a
  15502. BufferedInputStream, so that it has to read larger blocks less often.
  15503. @see GZIPCompressorOutputStream
  15504. */
  15505. class JUCE_API GZIPDecompressorInputStream : public InputStream
  15506. {
  15507. public:
  15508. /** Creates a decompressor stream.
  15509. @param sourceStream the stream to read from
  15510. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  15511. when this object is destroyed
  15512. @param noWrap this is used internally by the ZipFile class
  15513. and should be ignored by user applications
  15514. @param uncompressedStreamLength if the creator knows the length that the
  15515. uncompressed stream will be, then it can supply this
  15516. value, which will be returned by getTotalLength()
  15517. */
  15518. GZIPDecompressorInputStream (InputStream* sourceStream,
  15519. bool deleteSourceWhenDestroyed,
  15520. bool noWrap = false,
  15521. int64 uncompressedStreamLength = -1);
  15522. /** Creates a decompressor stream.
  15523. @param sourceStream the stream to read from - the source stream must not be
  15524. deleted until this object has been destroyed
  15525. */
  15526. GZIPDecompressorInputStream (InputStream& sourceStream);
  15527. /** Destructor. */
  15528. ~GZIPDecompressorInputStream();
  15529. int64 getPosition();
  15530. bool setPosition (int64 pos);
  15531. int64 getTotalLength();
  15532. bool isExhausted();
  15533. int read (void* destBuffer, int maxBytesToRead);
  15534. private:
  15535. OptionalScopedPointer<InputStream> sourceStream;
  15536. const int64 uncompressedStreamLength;
  15537. const bool noWrap;
  15538. bool isEof;
  15539. int activeBufferSize;
  15540. int64 originalSourcePos, currentPos;
  15541. HeapBlock <uint8> buffer;
  15542. class GZIPDecompressHelper;
  15543. friend class ScopedPointer <GZIPDecompressHelper>;
  15544. ScopedPointer <GZIPDecompressHelper> helper;
  15545. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPDecompressorInputStream);
  15546. };
  15547. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  15548. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  15549. #endif
  15550. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  15551. #endif
  15552. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  15553. #endif
  15554. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  15555. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  15556. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  15557. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  15558. /**
  15559. Allows a block of data and to be accessed as a stream.
  15560. This can either be used to refer to a shared block of memory, or can make its
  15561. own internal copy of the data when the MemoryInputStream is created.
  15562. */
  15563. class JUCE_API MemoryInputStream : public InputStream
  15564. {
  15565. public:
  15566. /** Creates a MemoryInputStream.
  15567. @param sourceData the block of data to use as the stream's source
  15568. @param sourceDataSize the number of bytes in the source data block
  15569. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  15570. the source data, so this data shouldn't be changed
  15571. for the lifetime of the stream; if this parameter is
  15572. true, the stream will make its own copy of the
  15573. data and use that.
  15574. */
  15575. MemoryInputStream (const void* sourceData,
  15576. size_t sourceDataSize,
  15577. bool keepInternalCopyOfData);
  15578. /** Creates a MemoryInputStream.
  15579. @param data a block of data to use as the stream's source
  15580. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  15581. the source data, so this data shouldn't be changed
  15582. for the lifetime of the stream; if this parameter is
  15583. true, the stream will make its own copy of the
  15584. data and use that.
  15585. */
  15586. MemoryInputStream (const MemoryBlock& data,
  15587. bool keepInternalCopyOfData);
  15588. /** Destructor. */
  15589. ~MemoryInputStream();
  15590. int64 getPosition();
  15591. bool setPosition (int64 pos);
  15592. int64 getTotalLength();
  15593. bool isExhausted();
  15594. int read (void* destBuffer, int maxBytesToRead);
  15595. private:
  15596. const char* data;
  15597. size_t dataSize, position;
  15598. MemoryBlock internalCopy;
  15599. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryInputStream);
  15600. };
  15601. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  15602. /*** End of inlined file: juce_MemoryInputStream.h ***/
  15603. #endif
  15604. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  15605. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  15606. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  15607. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  15608. /**
  15609. Writes data to an internal memory buffer, which grows as required.
  15610. The data that was written into the stream can then be accessed later as
  15611. a contiguous block of memory.
  15612. */
  15613. class JUCE_API MemoryOutputStream : public OutputStream
  15614. {
  15615. public:
  15616. /** Creates an empty memory stream ready for writing into.
  15617. @param initialSize the intial amount of capacity to allocate for writing into
  15618. */
  15619. MemoryOutputStream (size_t initialSize = 256);
  15620. /** Creates a memory stream for writing into into a pre-existing MemoryBlock object.
  15621. Note that the destination block will always be larger than the amount of data
  15622. that has been written to the stream, because the MemoryOutputStream keeps some
  15623. spare capactity at its end. To trim the block's size down to fit the actual
  15624. data, call flush(), or delete the MemoryOutputStream.
  15625. @param memoryBlockToWriteTo the block into which new data will be written.
  15626. @param appendToExistingBlockContent if this is true, the contents of the block will be
  15627. kept, and new data will be appended to it. If false,
  15628. the block will be cleared before use
  15629. */
  15630. MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  15631. bool appendToExistingBlockContent);
  15632. /** Destructor.
  15633. This will free any data that was written to it.
  15634. */
  15635. ~MemoryOutputStream();
  15636. /** Returns a pointer to the data that has been written to the stream.
  15637. @see getDataSize
  15638. */
  15639. const void* getData() const throw();
  15640. /** Returns the number of bytes of data that have been written to the stream.
  15641. @see getData
  15642. */
  15643. size_t getDataSize() const throw() { return size; }
  15644. /** Resets the stream, clearing any data that has been written to it so far. */
  15645. void reset() throw();
  15646. /** Increases the internal storage capacity to be able to contain at least the specified
  15647. amount of data without needing to be resized.
  15648. */
  15649. void preallocate (size_t bytesToPreallocate);
  15650. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  15651. const String toUTF8() const;
  15652. /** Attempts to detect the encoding of the data and convert it to a string.
  15653. @see String::createStringFromData
  15654. */
  15655. const String toString() const;
  15656. /** If the stream is writing to a user-supplied MemoryBlock, this will trim any excess
  15657. capacity off the block, so that its length matches the amount of actual data that
  15658. has been written so far.
  15659. */
  15660. void flush();
  15661. bool write (const void* buffer, int howMany);
  15662. int64 getPosition() { return position; }
  15663. bool setPosition (int64 newPosition);
  15664. int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  15665. private:
  15666. MemoryBlock& data;
  15667. MemoryBlock internalBlock;
  15668. size_t position, size;
  15669. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryOutputStream);
  15670. };
  15671. /** Copies all the data that has been written to a MemoryOutputStream into another stream. */
  15672. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead);
  15673. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  15674. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  15675. #endif
  15676. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  15677. #endif
  15678. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  15679. /*** Start of inlined file: juce_SubregionStream.h ***/
  15680. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  15681. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  15682. /** Wraps another input stream, and reads from a specific part of it.
  15683. This lets you take a subsection of a stream and present it as an entire
  15684. stream in its own right.
  15685. */
  15686. class JUCE_API SubregionStream : public InputStream
  15687. {
  15688. public:
  15689. /** Creates a SubregionStream from an input source.
  15690. @param sourceStream the source stream to read from
  15691. @param startPositionInSourceStream this is the position in the source stream that
  15692. corresponds to position 0 in this stream
  15693. @param lengthOfSourceStream this specifies the maximum number of bytes
  15694. from the source stream that will be passed through
  15695. by this stream. When the position of this stream
  15696. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  15697. If the length passed in here is greater than the length
  15698. of the source stream (as returned by getTotalLength()),
  15699. then the smaller value will be used.
  15700. Passing a negative value for this parameter means it
  15701. will keep reading until the source's end-of-stream.
  15702. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  15703. deleted by this object when it is itself deleted.
  15704. */
  15705. SubregionStream (InputStream* sourceStream,
  15706. int64 startPositionInSourceStream,
  15707. int64 lengthOfSourceStream,
  15708. bool deleteSourceWhenDestroyed);
  15709. /** Destructor.
  15710. This may also delete the source stream, if that option was chosen when the
  15711. buffered stream was created.
  15712. */
  15713. ~SubregionStream();
  15714. int64 getTotalLength();
  15715. int64 getPosition();
  15716. bool setPosition (int64 newPosition);
  15717. int read (void* destBuffer, int maxBytesToRead);
  15718. bool isExhausted();
  15719. private:
  15720. OptionalScopedPointer<InputStream> source;
  15721. const int64 startPositionInSourceStream, lengthOfSourceStream;
  15722. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubregionStream);
  15723. };
  15724. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  15725. /*** End of inlined file: juce_SubregionStream.h ***/
  15726. #endif
  15727. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  15728. #endif
  15729. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  15730. /*** Start of inlined file: juce_Expression.h ***/
  15731. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  15732. #define __JUCE_EXPRESSION_JUCEHEADER__
  15733. /**
  15734. A class for dynamically evaluating simple numeric expressions.
  15735. This class can parse a simple C-style string expression involving floating point
  15736. numbers, named symbols and functions. The basic arithmetic operations of +, -, *, /
  15737. are supported, as well as parentheses, and any alphanumeric identifiers are
  15738. assumed to be named symbols which will be resolved when the expression is
  15739. evaluated.
  15740. Expressions which use identifiers and functions require a subclass of
  15741. Expression::Scope to be supplied when evaluating them, and this object
  15742. is expected to be able to resolve the symbol names and perform the functions that
  15743. are used.
  15744. */
  15745. class JUCE_API Expression
  15746. {
  15747. public:
  15748. /** Creates a simple expression with a value of 0. */
  15749. Expression();
  15750. /** Destructor. */
  15751. ~Expression();
  15752. /** Creates a simple expression with a specified constant value. */
  15753. explicit Expression (double constant);
  15754. /** Creates a copy of an expression. */
  15755. Expression (const Expression& other);
  15756. /** Copies another expression. */
  15757. Expression& operator= (const Expression& other);
  15758. /** Creates an expression by parsing a string.
  15759. If there's a syntax error in the string, this will throw a ParseError exception.
  15760. @throws ParseError
  15761. */
  15762. explicit Expression (const String& stringToParse);
  15763. /** Returns a string version of the expression. */
  15764. const String toString() const;
  15765. /** Returns an expression which is an addtion operation of two existing expressions. */
  15766. const Expression operator+ (const Expression& other) const;
  15767. /** Returns an expression which is a subtraction operation of two existing expressions. */
  15768. const Expression operator- (const Expression& other) const;
  15769. /** Returns an expression which is a multiplication operation of two existing expressions. */
  15770. const Expression operator* (const Expression& other) const;
  15771. /** Returns an expression which is a division operation of two existing expressions. */
  15772. const Expression operator/ (const Expression& other) const;
  15773. /** Returns an expression which performs a negation operation on an existing expression. */
  15774. const Expression operator-() const;
  15775. /** Returns an Expression which is an identifier reference. */
  15776. static const Expression symbol (const String& symbol);
  15777. /** Returns an Expression which is a function call. */
  15778. static const Expression function (const String& functionName, const Array<Expression>& parameters);
  15779. /** Returns an Expression which parses a string from a character pointer, and updates the pointer
  15780. to indicate where it finished.
  15781. The pointer is incremented so that on return, it indicates the character that follows
  15782. the end of the expression that was parsed.
  15783. If there's a syntax error in the string, this will throw a ParseError exception.
  15784. @throws ParseError
  15785. */
  15786. static const Expression parse (String::CharPointerType& stringToParse);
  15787. /** When evaluating an Expression object, this class is used to resolve symbols and
  15788. perform functions that the expression uses.
  15789. */
  15790. class JUCE_API Scope
  15791. {
  15792. public:
  15793. Scope();
  15794. virtual ~Scope();
  15795. /** Returns some kind of globally unique ID that identifies this scope. */
  15796. virtual const String getScopeUID() const;
  15797. /** Returns the value of a symbol.
  15798. If the symbol is unknown, this can throw an Expression::EvaluationError exception.
  15799. The member value is set to the part of the symbol that followed the dot, if there is
  15800. one, e.g. for "foo.bar", symbol = "foo" and member = "bar".
  15801. @throws Expression::EvaluationError
  15802. */
  15803. virtual const Expression getSymbolValue (const String& symbol) const;
  15804. /** Executes a named function.
  15805. If the function name is unknown, this can throw an Expression::EvaluationError exception.
  15806. @throws Expression::EvaluationError
  15807. */
  15808. virtual double evaluateFunction (const String& functionName,
  15809. const double* parameters, int numParameters) const;
  15810. /** Used as a callback by the Scope::visitRelativeScope() method.
  15811. You should never create an instance of this class yourself, it's used by the
  15812. expression evaluation code.
  15813. */
  15814. class Visitor
  15815. {
  15816. public:
  15817. virtual ~Visitor() {}
  15818. virtual void visit (const Scope&) = 0;
  15819. };
  15820. /** Creates a Scope object for a named scope, and then calls a visitor
  15821. to do some kind of processing with this new scope.
  15822. If the name is valid, this method must create a suitable (temporary) Scope
  15823. object to represent it, and must call the Visitor::visit() method with this
  15824. new scope.
  15825. */
  15826. virtual void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  15827. };
  15828. /** Evaluates this expression, without using a Scope.
  15829. Without a Scope, no symbols can be used, and only basic functions such as sin, cos, tan,
  15830. min, max are available.
  15831. To find out about any errors during evaluation, use the other version of this method which
  15832. takes a String parameter.
  15833. */
  15834. double evaluate() const;
  15835. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  15836. or functions that it uses.
  15837. To find out about any errors during evaluation, use the other version of this method which
  15838. takes a String parameter.
  15839. */
  15840. double evaluate (const Scope& scope) const;
  15841. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  15842. or functions that it uses.
  15843. */
  15844. double evaluate (const Scope& scope, String& evaluationError) const;
  15845. /** Attempts to return an expression which is a copy of this one, but with a constant adjusted
  15846. to make the expression resolve to a target value.
  15847. E.g. if the expression is "x + 10" and x is 5, then asking for a target value of 8 will return
  15848. the expression "x + 3". Obviously some expressions can't be reversed in this way, in which
  15849. case they might just be adjusted by adding a constant to the original expression.
  15850. @throws Expression::EvaluationError
  15851. */
  15852. const Expression adjustedToGiveNewResult (double targetValue, const Scope& scope) const;
  15853. /** Represents a symbol that is used in an Expression. */
  15854. struct Symbol
  15855. {
  15856. Symbol (const String& scopeUID, const String& symbolName);
  15857. bool operator== (const Symbol&) const throw();
  15858. bool operator!= (const Symbol&) const throw();
  15859. String scopeUID; /**< The unique ID of the Scope that contains this symbol. */
  15860. String symbolName; /**< The name of the symbol. */
  15861. };
  15862. /** Returns a copy of this expression in which all instances of a given symbol have been renamed. */
  15863. const Expression withRenamedSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope) const;
  15864. /** Returns true if this expression makes use of the specified symbol.
  15865. If a suitable scope is supplied, the search will dereference and recursively check
  15866. all symbols, so that it can be determined whether this expression relies on the given
  15867. symbol at any level in its evaluation. If the scope parameter is null, this just checks
  15868. whether the expression contains any direct references to the symbol.
  15869. @throws Expression::EvaluationError
  15870. */
  15871. bool referencesSymbol (const Symbol& symbol, const Scope& scope) const;
  15872. /** Returns true if this expression contains any symbols. */
  15873. bool usesAnySymbols() const;
  15874. /** Returns a list of all symbols that may be needed to resolve this expression in the given scope. */
  15875. void findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const;
  15876. /** An exception that can be thrown by Expression::parse(). */
  15877. class ParseError : public std::exception
  15878. {
  15879. public:
  15880. ParseError (const String& message);
  15881. String description;
  15882. };
  15883. /** Expression type.
  15884. @see Expression::getType()
  15885. */
  15886. enum Type
  15887. {
  15888. constantType,
  15889. functionType,
  15890. operatorType,
  15891. symbolType
  15892. };
  15893. /** Returns the type of this expression. */
  15894. Type getType() const throw();
  15895. /** If this expression is a symbol, function or operator, this returns its identifier. */
  15896. const String getSymbolOrFunction() const;
  15897. /** Returns the number of inputs to this expression.
  15898. @see getInput
  15899. */
  15900. int getNumInputs() const;
  15901. /** Retrieves one of the inputs to this expression.
  15902. @see getNumInputs
  15903. */
  15904. const Expression getInput (int index) const;
  15905. private:
  15906. class Term;
  15907. class Helpers;
  15908. friend class Term;
  15909. friend class Helpers;
  15910. friend class ScopedPointer<Term>;
  15911. friend class ReferenceCountedObjectPtr<Term>;
  15912. ReferenceCountedObjectPtr<Term> term;
  15913. explicit Expression (Term* term);
  15914. };
  15915. #endif // __JUCE_EXPRESSION_JUCEHEADER__
  15916. /*** End of inlined file: juce_Expression.h ***/
  15917. #endif
  15918. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  15919. #endif
  15920. #ifndef __JUCE_RANDOM_JUCEHEADER__
  15921. /*** Start of inlined file: juce_Random.h ***/
  15922. #ifndef __JUCE_RANDOM_JUCEHEADER__
  15923. #define __JUCE_RANDOM_JUCEHEADER__
  15924. /**
  15925. A random number generator.
  15926. You can create a Random object and use it to generate a sequence of random numbers.
  15927. As a handy shortcut to avoid having to create and seed one yourself, you can call
  15928. Random::getSystemRandom() to return a global RNG that is seeded randomly when the
  15929. app launches.
  15930. */
  15931. class JUCE_API Random
  15932. {
  15933. public:
  15934. /** Creates a Random object based on a seed value.
  15935. For a given seed value, the subsequent numbers generated by this object
  15936. will be predictable, so a good idea is to set this value based
  15937. on the time, e.g.
  15938. new Random (Time::currentTimeMillis())
  15939. */
  15940. explicit Random (int64 seedValue) throw();
  15941. /** Destructor. */
  15942. ~Random() throw();
  15943. /** Returns the next random 32 bit integer.
  15944. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  15945. */
  15946. int nextInt() throw();
  15947. /** Returns the next random number, limited to a given range.
  15948. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  15949. */
  15950. int nextInt (int maxValue) throw();
  15951. /** Returns the next 64-bit random number.
  15952. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  15953. */
  15954. int64 nextInt64() throw();
  15955. /** Returns the next random floating-point number.
  15956. @returns a random value in the range 0 to 1.0
  15957. */
  15958. float nextFloat() throw();
  15959. /** Returns the next random floating-point number.
  15960. @returns a random value in the range 0 to 1.0
  15961. */
  15962. double nextDouble() throw();
  15963. /** Returns the next random boolean value.
  15964. */
  15965. bool nextBool() throw();
  15966. /** Returns a BigInteger containing a random number.
  15967. @returns a random value in the range 0 to (maximumValue - 1).
  15968. */
  15969. const BigInteger nextLargeNumber (const BigInteger& maximumValue);
  15970. /** Sets a range of bits in a BigInteger to random values. */
  15971. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  15972. /** To avoid the overhead of having to create a new Random object whenever
  15973. you need a number, this is a shared application-wide object that
  15974. can be used.
  15975. It's not thread-safe though, so threads should use their own Random object.
  15976. */
  15977. static Random& getSystemRandom() throw();
  15978. /** Resets this Random object to a given seed value. */
  15979. void setSeed (int64 newSeed) throw();
  15980. /** Merges this object's seed with another value.
  15981. This sets the seed to be a value created by combining the current seed and this
  15982. new value.
  15983. */
  15984. void combineSeed (int64 seedValue) throw();
  15985. /** Reseeds this generator using a value generated from various semi-random system
  15986. properties like the current time, etc.
  15987. Because this function convolves the time with the last seed value, calling
  15988. it repeatedly will increase the randomness of the final result.
  15989. */
  15990. void setSeedRandomly();
  15991. private:
  15992. int64 seed;
  15993. JUCE_LEAK_DETECTOR (Random);
  15994. };
  15995. #endif // __JUCE_RANDOM_JUCEHEADER__
  15996. /*** End of inlined file: juce_Random.h ***/
  15997. #endif
  15998. #ifndef __JUCE_RANGE_JUCEHEADER__
  15999. #endif
  16000. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  16001. #endif
  16002. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  16003. #endif
  16004. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  16005. #endif
  16006. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  16007. #endif
  16008. #ifndef __JUCE_MEMORY_JUCEHEADER__
  16009. #endif
  16010. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  16011. #endif
  16012. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  16013. #endif
  16014. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  16015. #endif
  16016. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  16017. #endif
  16018. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  16019. /*** Start of inlined file: juce_WeakReference.h ***/
  16020. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  16021. #define __JUCE_WEAKREFERENCE_JUCEHEADER__
  16022. /**
  16023. This class acts as a pointer which will automatically become null if the object
  16024. to which it points is deleted.
  16025. To accomplish this, the source object needs to cooperate by performing a couple of simple tasks.
  16026. It must provide a getWeakReference() method and embed a WeakReference::Master object, which stores
  16027. a shared pointer object. It must also clear this master pointer when it's getting deleted.
  16028. E.g.
  16029. @code
  16030. class MyObject
  16031. {
  16032. public:
  16033. MyObject()
  16034. {
  16035. // If you're planning on using your WeakReferences in a multi-threaded situation, you may choose
  16036. // to call getWeakReference() here in the constructor, which will pre-initialise it, avoiding an
  16037. // (extremely unlikely) race condition that could occur if multiple threads overlap while making
  16038. // the first call to getWeakReference().
  16039. }
  16040. ~MyObject()
  16041. {
  16042. // This will zero all the references - you need to call this in your destructor.
  16043. masterReference.clear();
  16044. }
  16045. // Your object must provide a method that looks pretty much identical to this (except
  16046. // for the templated class name, of course).
  16047. const WeakReference<MyObject>::SharedRef& getWeakReference()
  16048. {
  16049. return masterReference (this);
  16050. }
  16051. private:
  16052. // You need to embed one of these inside your object. It can be private.
  16053. WeakReference<MyObject>::Master masterReference;
  16054. };
  16055. // Here's an example of using a pointer..
  16056. MyObject* n = new MyObject();
  16057. WeakReference<MyObject> myObjectRef = n;
  16058. MyObject* pointer1 = myObjectRef; // returns a valid pointer to 'n'
  16059. delete n;
  16060. MyObject* pointer2 = myObjectRef; // returns a null pointer
  16061. @endcode
  16062. @see WeakReference::Master
  16063. */
  16064. template <class ObjectType>
  16065. class WeakReference
  16066. {
  16067. public:
  16068. /** Creates a null SafePointer. */
  16069. WeakReference() throw() {}
  16070. /** Creates a WeakReference that points at the given object. */
  16071. WeakReference (ObjectType* const object) : holder (object != 0 ? object->getWeakReference() : 0) {}
  16072. /** Creates a copy of another WeakReference. */
  16073. WeakReference (const WeakReference& other) throw() : holder (other.holder) {}
  16074. /** Copies another pointer to this one. */
  16075. WeakReference& operator= (const WeakReference& other) { holder = other.holder; return *this; }
  16076. /** Copies another pointer to this one. */
  16077. WeakReference& operator= (ObjectType* const newObject) { holder = newObject != 0 ? newObject->getWeakReference() : 0; return *this; }
  16078. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16079. ObjectType* get() const throw() { return holder != 0 ? holder->get() : 0; }
  16080. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16081. operator ObjectType*() const throw() { return get(); }
  16082. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16083. ObjectType* operator->() throw() { return get(); }
  16084. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16085. const ObjectType* operator->() const throw() { return get(); }
  16086. /** This returns true if this reference has been pointing at an object, but that object has
  16087. since been deleted.
  16088. If this reference was only ever pointing at a null pointer, this will return false. Using
  16089. operator=() to make this refer to a different object will reset this flag to match the status
  16090. of the reference from which you're copying.
  16091. */
  16092. bool wasObjectDeleted() const throw() { return holder != 0 && holder->get() == 0; }
  16093. bool operator== (ObjectType* const object) const throw() { return get() == object; }
  16094. bool operator!= (ObjectType* const object) const throw() { return get() != object; }
  16095. /** This class is used internally by the WeakReference class - don't use it directly
  16096. in your code!
  16097. @see WeakReference
  16098. */
  16099. class SharedPointer : public ReferenceCountedObject
  16100. {
  16101. public:
  16102. explicit SharedPointer (ObjectType* const owner_) throw() : owner (owner_) {}
  16103. inline ObjectType* get() const throw() { return owner; }
  16104. void clearPointer() throw() { owner = 0; }
  16105. private:
  16106. ObjectType* volatile owner;
  16107. JUCE_DECLARE_NON_COPYABLE (SharedPointer);
  16108. };
  16109. typedef ReferenceCountedObjectPtr<SharedPointer> SharedRef;
  16110. /**
  16111. This class is embedded inside an object to which you want to attach WeakReference pointers.
  16112. See the WeakReference class notes for an example of how to use this class.
  16113. @see WeakReference
  16114. */
  16115. class Master
  16116. {
  16117. public:
  16118. Master() throw() {}
  16119. ~Master()
  16120. {
  16121. // You must remember to call clear() in your source object's destructor! See the notes
  16122. // for the WeakReference class for an example of how to do this.
  16123. jassert (sharedPointer == 0 || sharedPointer->get() == 0);
  16124. }
  16125. /** The first call to this method will create an internal object that is shared by all weak
  16126. references to the object.
  16127. You need to call this from your main object's getWeakReference() method - see the WeakReference
  16128. class notes for an example.
  16129. */
  16130. const SharedRef& operator() (ObjectType* const object)
  16131. {
  16132. if (sharedPointer == 0)
  16133. {
  16134. sharedPointer = new SharedPointer (object);
  16135. }
  16136. else
  16137. {
  16138. // You're trying to create a weak reference to an object that has already been deleted!!
  16139. jassert (sharedPointer->get() != 0);
  16140. }
  16141. return sharedPointer;
  16142. }
  16143. /** The object that owns this master pointer should call this before it gets destroyed,
  16144. to zero all the references to this object that may be out there. See the WeakReference
  16145. class notes for an example of how to do this.
  16146. */
  16147. void clear()
  16148. {
  16149. if (sharedPointer != 0)
  16150. sharedPointer->clearPointer();
  16151. }
  16152. private:
  16153. SharedRef sharedPointer;
  16154. JUCE_DECLARE_NON_COPYABLE (Master);
  16155. };
  16156. private:
  16157. SharedRef holder;
  16158. };
  16159. #endif // __JUCE_WEAKREFERENCE_JUCEHEADER__
  16160. /*** End of inlined file: juce_WeakReference.h ***/
  16161. #endif
  16162. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  16163. #endif
  16164. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  16165. #endif
  16166. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  16167. #endif
  16168. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  16169. #endif
  16170. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  16171. #endif
  16172. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  16173. #endif
  16174. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16175. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  16176. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16177. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16178. /** Used in the same way as the T(text) macro, this will attempt to translate a
  16179. string into a localised version using the LocalisedStrings class.
  16180. @see LocalisedStrings
  16181. */
  16182. #define TRANS(stringLiteral) \
  16183. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  16184. /**
  16185. Used to convert strings to localised foreign-language versions.
  16186. This is basically a look-up table of strings and their translated equivalents.
  16187. It can be loaded from a text file, so that you can supply a set of localised
  16188. versions of strings that you use in your app.
  16189. To use it in your code, simply call the translate() method on each string that
  16190. might have foreign versions, and if none is found, the method will just return
  16191. the original string.
  16192. The translation file should start with some lines specifying a description of
  16193. the language it contains, and also a list of ISO country codes where it might
  16194. be appropriate to use the file. After that, each line of the file should contain
  16195. a pair of quoted strings with an '=' sign.
  16196. E.g. for a french translation, the file might be:
  16197. @code
  16198. language: French
  16199. countries: fr be mc ch lu
  16200. "hello" = "bonjour"
  16201. "goodbye" = "au revoir"
  16202. @endcode
  16203. If the strings need to contain a quote character, they can use '\"' instead, and
  16204. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  16205. (you can use this to add comments).
  16206. Note that this is a singleton class, so don't create or destroy the object directly.
  16207. There's also a TRANS(text) macro defined to make it easy to use the this.
  16208. E.g. @code
  16209. printSomething (TRANS("hello"));
  16210. @endcode
  16211. This macro is used in the Juce classes themselves, so your application has a chance to
  16212. intercept and translate any internal Juce text strings that might be shown. (You can easily
  16213. get a list of all the messages by searching for the TRANS() macro in the Juce source
  16214. code).
  16215. */
  16216. class JUCE_API LocalisedStrings
  16217. {
  16218. public:
  16219. /** Creates a set of translations from the text of a translation file.
  16220. When you create one of these, you can call setCurrentMappings() to make it
  16221. the set of mappings that the system's using.
  16222. */
  16223. LocalisedStrings (const String& fileContents);
  16224. /** Creates a set of translations from a file.
  16225. When you create one of these, you can call setCurrentMappings() to make it
  16226. the set of mappings that the system's using.
  16227. */
  16228. LocalisedStrings (const File& fileToLoad);
  16229. /** Destructor. */
  16230. ~LocalisedStrings();
  16231. /** Selects the current set of mappings to be used by the system.
  16232. The object you pass in will be automatically deleted when no longer needed, so
  16233. don't keep a pointer to it. You can also pass in zero to remove the current
  16234. mappings.
  16235. See also the TRANS() macro, which uses the current set to do its translation.
  16236. @see translateWithCurrentMappings
  16237. */
  16238. static void setCurrentMappings (LocalisedStrings* newTranslations);
  16239. /** Returns the currently selected set of mappings.
  16240. This is the object that was last passed to setCurrentMappings(). It may
  16241. be 0 if none has been created.
  16242. */
  16243. static LocalisedStrings* getCurrentMappings();
  16244. /** Tries to translate a string using the currently selected set of mappings.
  16245. If no mapping has been set, or if the mapping doesn't contain a translation
  16246. for the string, this will just return the original string.
  16247. See also the TRANS() macro, which uses this method to do its translation.
  16248. @see setCurrentMappings, getCurrentMappings
  16249. */
  16250. static const String translateWithCurrentMappings (const String& text);
  16251. /** Tries to translate a string using the currently selected set of mappings.
  16252. If no mapping has been set, or if the mapping doesn't contain a translation
  16253. for the string, this will just return the original string.
  16254. See also the TRANS() macro, which uses this method to do its translation.
  16255. @see setCurrentMappings, getCurrentMappings
  16256. */
  16257. static const String translateWithCurrentMappings (const char* text);
  16258. /** Attempts to look up a string and return its localised version.
  16259. If the string isn't found in the list, the original string will be returned.
  16260. */
  16261. const String translate (const String& text) const;
  16262. /** Returns the name of the language specified in the translation file.
  16263. This is specified in the file using a line starting with "language:", e.g.
  16264. @code
  16265. language: german
  16266. @endcode
  16267. */
  16268. const String getLanguageName() const { return languageName; }
  16269. /** Returns the list of suitable country codes listed in the translation file.
  16270. These is specified in the file using a line starting with "countries:", e.g.
  16271. @code
  16272. countries: fr be mc ch lu
  16273. @endcode
  16274. The country codes are supposed to be 2-character ISO complient codes.
  16275. */
  16276. const StringArray getCountryCodes() const { return countryCodes; }
  16277. /** Indicates whether to use a case-insensitive search when looking up a string.
  16278. This defaults to true.
  16279. */
  16280. void setIgnoresCase (bool shouldIgnoreCase);
  16281. private:
  16282. String languageName;
  16283. StringArray countryCodes;
  16284. StringPairArray translations;
  16285. void loadFromText (const String& fileContents);
  16286. JUCE_LEAK_DETECTOR (LocalisedStrings);
  16287. };
  16288. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16289. /*** End of inlined file: juce_LocalisedStrings.h ***/
  16290. #endif
  16291. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  16292. #endif
  16293. #ifndef __JUCE_STRING_JUCEHEADER__
  16294. #endif
  16295. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  16296. #endif
  16297. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  16298. #endif
  16299. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  16300. #endif
  16301. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  16302. /*** Start of inlined file: juce_XmlDocument.h ***/
  16303. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  16304. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  16305. /**
  16306. Parses a text-based XML document and creates an XmlElement object from it.
  16307. The parser will parse DTDs to load external entities but won't
  16308. check the document for validity against the DTD.
  16309. e.g.
  16310. @code
  16311. XmlDocument myDocument (File ("myfile.xml"));
  16312. XmlElement* mainElement = myDocument.getDocumentElement();
  16313. if (mainElement == 0)
  16314. {
  16315. String error = myDocument.getLastParseError();
  16316. }
  16317. else
  16318. {
  16319. ..use the element
  16320. }
  16321. @endcode
  16322. Or you can use the static helper methods for quick parsing..
  16323. @code
  16324. XmlElement* xml = XmlDocument::parse (myXmlFile);
  16325. if (xml != 0 && xml->hasTagName ("foobar"))
  16326. {
  16327. ...etc
  16328. @endcode
  16329. @see XmlElement
  16330. */
  16331. class JUCE_API XmlDocument
  16332. {
  16333. public:
  16334. /** Creates an XmlDocument from the xml text.
  16335. The text doesn't actually get parsed until the getDocumentElement() method is called.
  16336. */
  16337. XmlDocument (const String& documentText);
  16338. /** Creates an XmlDocument from a file.
  16339. The text doesn't actually get parsed until the getDocumentElement() method is called.
  16340. */
  16341. XmlDocument (const File& file);
  16342. /** Destructor. */
  16343. ~XmlDocument();
  16344. /** Creates an XmlElement object to represent the main document node.
  16345. This method will do the actual parsing of the text, and if there's a
  16346. parse error, it may returns 0 (and you can find out the error using
  16347. the getLastParseError() method).
  16348. See also the parse() methods, which provide a shorthand way to quickly
  16349. parse a file or string.
  16350. @param onlyReadOuterDocumentElement if true, the parser will only read the
  16351. first section of the file, and will only
  16352. return the outer document element - this
  16353. allows quick checking of large files to
  16354. see if they contain the correct type of
  16355. tag, without having to parse the entire file
  16356. @returns a new XmlElement which the caller will need to delete, or null if
  16357. there was an error.
  16358. @see getLastParseError
  16359. */
  16360. XmlElement* getDocumentElement (bool onlyReadOuterDocumentElement = false);
  16361. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  16362. @returns the error, or an empty string if there was no error.
  16363. */
  16364. const String& getLastParseError() const throw();
  16365. /** Sets an input source object to use for parsing documents that reference external entities.
  16366. If the document has been created from a file, this probably won't be needed, but
  16367. if you're parsing some text and there might be a DTD that references external
  16368. files, you may need to create a custom input source that can retrieve the
  16369. other files it needs.
  16370. The object that is passed-in will be deleted automatically when no longer needed.
  16371. @see InputSource
  16372. */
  16373. void setInputSource (InputSource* newSource) throw();
  16374. /** Sets a flag to change the treatment of empty text elements.
  16375. If this is true (the default state), then any text elements that contain only
  16376. whitespace characters will be ingored during parsing. If you need to catch
  16377. whitespace-only text, then you should set this to false before calling the
  16378. getDocumentElement() method.
  16379. */
  16380. void setEmptyTextElementsIgnored (bool shouldBeIgnored) throw();
  16381. /** A handy static method that parses a file.
  16382. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  16383. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  16384. */
  16385. static XmlElement* parse (const File& file);
  16386. /** A handy static method that parses some XML data.
  16387. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  16388. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  16389. */
  16390. static XmlElement* parse (const String& xmlData);
  16391. private:
  16392. String originalText;
  16393. String::CharPointerType input;
  16394. bool outOfData, errorOccurred;
  16395. String lastError, dtdText;
  16396. StringArray tokenisedDTD;
  16397. bool needToLoadDTD, ignoreEmptyTextElements;
  16398. ScopedPointer <InputSource> inputSource;
  16399. void setLastError (const String& desc, bool carryOn);
  16400. void skipHeader();
  16401. void skipNextWhiteSpace();
  16402. juce_wchar readNextChar() throw();
  16403. XmlElement* readNextElement (bool alsoParseSubElements);
  16404. void readChildElements (XmlElement* parent);
  16405. int findNextTokenLength() throw();
  16406. void readQuotedString (String& result);
  16407. void readEntity (String& result);
  16408. const String getFileContents (const String& filename) const;
  16409. const String expandEntity (const String& entity);
  16410. const String expandExternalEntity (const String& entity);
  16411. const String getParameterEntity (const String& entity);
  16412. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XmlDocument);
  16413. };
  16414. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  16415. /*** End of inlined file: juce_XmlDocument.h ***/
  16416. #endif
  16417. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  16418. #endif
  16419. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  16420. #endif
  16421. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16422. /*** Start of inlined file: juce_InterProcessLock.h ***/
  16423. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16424. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16425. /**
  16426. Acts as a critical section which processes can use to block each other.
  16427. @see CriticalSection
  16428. */
  16429. class JUCE_API InterProcessLock
  16430. {
  16431. public:
  16432. /** Creates a lock object.
  16433. @param name a name that processes will use to identify this lock object
  16434. */
  16435. explicit InterProcessLock (const String& name);
  16436. /** Destructor.
  16437. This will also release the lock if it's currently held by this process.
  16438. */
  16439. ~InterProcessLock();
  16440. /** Attempts to lock the critical section.
  16441. @param timeOutMillisecs how many milliseconds to wait if the lock
  16442. is already held by another process - a value of
  16443. 0 will return immediately, negative values will wait
  16444. forever
  16445. @returns true if the lock could be gained within the timeout period, or
  16446. false if the timeout expired.
  16447. */
  16448. bool enter (int timeOutMillisecs = -1);
  16449. /** Releases the lock if it's currently held by this process.
  16450. */
  16451. void exit();
  16452. /**
  16453. Automatically locks and unlocks an InterProcessLock object.
  16454. This works like a ScopedLock, but using an InterprocessLock rather than
  16455. a CriticalSection.
  16456. @see ScopedLock
  16457. */
  16458. class ScopedLockType
  16459. {
  16460. public:
  16461. /** Creates a scoped lock.
  16462. As soon as it is created, this will lock the InterProcessLock, and
  16463. when the ScopedLockType object is deleted, the InterProcessLock will
  16464. be unlocked.
  16465. Note that since an InterprocessLock can fail due to errors, you should check
  16466. isLocked() to make sure that the lock was successful before using it.
  16467. Make sure this object is created and deleted by the same thread,
  16468. otherwise there are no guarantees what will happen! Best just to use it
  16469. as a local stack object, rather than creating one with the new() operator.
  16470. */
  16471. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  16472. /** Destructor.
  16473. The InterProcessLock will be unlocked when the destructor is called.
  16474. Make sure this object is created and deleted by the same thread,
  16475. otherwise there are no guarantees what will happen!
  16476. */
  16477. inline ~ScopedLockType() { lock_.exit(); }
  16478. /** Returns true if the InterProcessLock was successfully locked. */
  16479. bool isLocked() const throw() { return lockWasSuccessful; }
  16480. private:
  16481. InterProcessLock& lock_;
  16482. bool lockWasSuccessful;
  16483. JUCE_DECLARE_NON_COPYABLE (ScopedLockType);
  16484. };
  16485. private:
  16486. class Pimpl;
  16487. friend class ScopedPointer <Pimpl>;
  16488. ScopedPointer <Pimpl> pimpl;
  16489. CriticalSection lock;
  16490. String name;
  16491. JUCE_DECLARE_NON_COPYABLE (InterProcessLock);
  16492. };
  16493. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16494. /*** End of inlined file: juce_InterProcessLock.h ***/
  16495. #endif
  16496. #ifndef __JUCE_PROCESS_JUCEHEADER__
  16497. /*** Start of inlined file: juce_Process.h ***/
  16498. #ifndef __JUCE_PROCESS_JUCEHEADER__
  16499. #define __JUCE_PROCESS_JUCEHEADER__
  16500. /** Represents the current executable's process.
  16501. This contains methods for controlling the current application at the
  16502. process-level.
  16503. @see Thread, JUCEApplication
  16504. */
  16505. class JUCE_API Process
  16506. {
  16507. public:
  16508. enum ProcessPriority
  16509. {
  16510. LowPriority = 0,
  16511. NormalPriority = 1,
  16512. HighPriority = 2,
  16513. RealtimePriority = 3
  16514. };
  16515. /** Changes the current process's priority.
  16516. @param priority the process priority, where
  16517. 0=low, 1=normal, 2=high, 3=realtime
  16518. */
  16519. static void setPriority (const ProcessPriority priority);
  16520. /** Kills the current process immediately.
  16521. This is an emergency process terminator that kills the application
  16522. immediately - it's intended only for use only when something goes
  16523. horribly wrong.
  16524. @see JUCEApplication::quit
  16525. */
  16526. static void terminate();
  16527. /** Returns true if this application process is the one that the user is
  16528. currently using.
  16529. */
  16530. static bool isForegroundProcess();
  16531. /** Raises the current process's privilege level.
  16532. Does nothing if this isn't supported by the current OS, or if process
  16533. privilege level is fixed.
  16534. */
  16535. static void raisePrivilege();
  16536. /** Lowers the current process's privilege level.
  16537. Does nothing if this isn't supported by the current OS, or if process
  16538. privilege level is fixed.
  16539. */
  16540. static void lowerPrivilege();
  16541. /** Returns true if this process is being hosted by a debugger.
  16542. */
  16543. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  16544. private:
  16545. Process();
  16546. JUCE_DECLARE_NON_COPYABLE (Process);
  16547. };
  16548. #endif // __JUCE_PROCESS_JUCEHEADER__
  16549. /*** End of inlined file: juce_Process.h ***/
  16550. #endif
  16551. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  16552. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  16553. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  16554. #define __JUCE_READWRITELOCK_JUCEHEADER__
  16555. /*** Start of inlined file: juce_WaitableEvent.h ***/
  16556. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  16557. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  16558. /**
  16559. Allows threads to wait for events triggered by other threads.
  16560. A thread can call wait() on a WaitableObject, and this will suspend the
  16561. calling thread until another thread wakes it up by calling the signal()
  16562. method.
  16563. */
  16564. class JUCE_API WaitableEvent
  16565. {
  16566. public:
  16567. /** Creates a WaitableEvent object.
  16568. @param manualReset If this is false, the event will be reset automatically when the wait()
  16569. method is called. If manualReset is true, then once the event is signalled,
  16570. the only way to reset it will be by calling the reset() method.
  16571. */
  16572. WaitableEvent (bool manualReset = false) throw();
  16573. /** Destructor.
  16574. If other threads are waiting on this object when it gets deleted, this
  16575. can cause nasty errors, so be careful!
  16576. */
  16577. ~WaitableEvent() throw();
  16578. /** Suspends the calling thread until the event has been signalled.
  16579. This will wait until the object's signal() method is called by another thread,
  16580. or until the timeout expires.
  16581. After the event has been signalled, this method will return true and if manualReset
  16582. was set to false in the WaitableEvent's constructor, then the event will be reset.
  16583. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  16584. value will cause it to wait forever.
  16585. @returns true if the object has been signalled, false if the timeout expires first.
  16586. @see signal, reset
  16587. */
  16588. bool wait (int timeOutMilliseconds = -1) const throw();
  16589. /** Wakes up any threads that are currently waiting on this object.
  16590. If signal() is called when nothing is waiting, the next thread to call wait()
  16591. will return immediately and reset the signal.
  16592. @see wait, reset
  16593. */
  16594. void signal() const throw();
  16595. /** Resets the event to an unsignalled state.
  16596. If it's not already signalled, this does nothing.
  16597. */
  16598. void reset() const throw();
  16599. private:
  16600. void* internal;
  16601. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WaitableEvent);
  16602. };
  16603. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  16604. /*** End of inlined file: juce_WaitableEvent.h ***/
  16605. /*** Start of inlined file: juce_Thread.h ***/
  16606. #ifndef __JUCE_THREAD_JUCEHEADER__
  16607. #define __JUCE_THREAD_JUCEHEADER__
  16608. /**
  16609. Encapsulates a thread.
  16610. Subclasses derive from Thread and implement the run() method, in which they
  16611. do their business. The thread can then be started with the startThread() method
  16612. and controlled with various other methods.
  16613. This class also contains some thread-related static methods, such
  16614. as sleep(), yield(), getCurrentThreadId() etc.
  16615. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  16616. MessageManagerLock
  16617. */
  16618. class JUCE_API Thread
  16619. {
  16620. public:
  16621. /**
  16622. Creates a thread.
  16623. When first created, the thread is not running. Use the startThread()
  16624. method to start it.
  16625. */
  16626. explicit Thread (const String& threadName);
  16627. /** Destructor.
  16628. Deleting a Thread object that is running will only give the thread a
  16629. brief opportunity to stop itself cleanly, so it's recommended that you
  16630. should always call stopThread() with a decent timeout before deleting,
  16631. to avoid the thread being forcibly killed (which is a Bad Thing).
  16632. */
  16633. virtual ~Thread();
  16634. /** Must be implemented to perform the thread's actual code.
  16635. Remember that the thread must regularly check the threadShouldExit()
  16636. method whilst running, and if this returns true it should return from
  16637. the run() method as soon as possible to avoid being forcibly killed.
  16638. @see threadShouldExit, startThread
  16639. */
  16640. virtual void run() = 0;
  16641. // Thread control functions..
  16642. /** Starts the thread running.
  16643. This will start the thread's run() method.
  16644. (if it's already started, startThread() won't do anything).
  16645. @see stopThread
  16646. */
  16647. void startThread();
  16648. /** Starts the thread with a given priority.
  16649. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  16650. If the thread is already running, its priority will be changed.
  16651. @see startThread, setPriority
  16652. */
  16653. void startThread (int priority);
  16654. /** Attempts to stop the thread running.
  16655. This method will cause the threadShouldExit() method to return true
  16656. and call notify() in case the thread is currently waiting.
  16657. Hopefully the thread will then respond to this by exiting cleanly, and
  16658. the stopThread method will wait for a given time-period for this to
  16659. happen.
  16660. If the thread is stuck and fails to respond after the time-out, it gets
  16661. forcibly killed, which is a very bad thing to happen, as it could still
  16662. be holding locks, etc. which are needed by other parts of your program.
  16663. @param timeOutMilliseconds The number of milliseconds to wait for the
  16664. thread to finish before killing it by force. A negative
  16665. value in here will wait forever.
  16666. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  16667. */
  16668. void stopThread (int timeOutMilliseconds);
  16669. /** Returns true if the thread is currently active */
  16670. bool isThreadRunning() const;
  16671. /** Sets a flag to tell the thread it should stop.
  16672. Calling this means that the threadShouldExit() method will then return true.
  16673. The thread should be regularly checking this to see whether it should exit.
  16674. If your thread makes use of wait(), you might want to call notify() after calling
  16675. this method, to interrupt any waits that might be in progress, and allow it
  16676. to reach a point where it can exit.
  16677. @see threadShouldExit
  16678. @see waitForThreadToExit
  16679. */
  16680. void signalThreadShouldExit();
  16681. /** Checks whether the thread has been told to stop running.
  16682. Threads need to check this regularly, and if it returns true, they should
  16683. return from their run() method at the first possible opportunity.
  16684. @see signalThreadShouldExit
  16685. */
  16686. inline bool threadShouldExit() const { return threadShouldExit_; }
  16687. /** Waits for the thread to stop.
  16688. This will waits until isThreadRunning() is false or until a timeout expires.
  16689. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  16690. is less than zero, it will wait forever.
  16691. @returns true if the thread exits, or false if the timeout expires first.
  16692. */
  16693. bool waitForThreadToExit (int timeOutMilliseconds) const;
  16694. /** Changes the thread's priority.
  16695. May return false if for some reason the priority can't be changed.
  16696. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  16697. of 5 is normal.
  16698. */
  16699. bool setPriority (int priority);
  16700. /** Changes the priority of the caller thread.
  16701. Similar to setPriority(), but this static method acts on the caller thread.
  16702. May return false if for some reason the priority can't be changed.
  16703. @see setPriority
  16704. */
  16705. static bool setCurrentThreadPriority (int priority);
  16706. /** Sets the affinity mask for the thread.
  16707. This will only have an effect next time the thread is started - i.e. if the
  16708. thread is already running when called, it'll have no effect.
  16709. @see setCurrentThreadAffinityMask
  16710. */
  16711. void setAffinityMask (uint32 affinityMask);
  16712. /** Changes the affinity mask for the caller thread.
  16713. This will change the affinity mask for the thread that calls this static method.
  16714. @see setAffinityMask
  16715. */
  16716. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  16717. // this can be called from any thread that needs to pause..
  16718. static void JUCE_CALLTYPE sleep (int milliseconds);
  16719. /** Yields the calling thread's current time-slot. */
  16720. static void JUCE_CALLTYPE yield();
  16721. /** Makes the thread wait for a notification.
  16722. This puts the thread to sleep until either the timeout period expires, or
  16723. another thread calls the notify() method to wake it up.
  16724. A negative time-out value means that the method will wait indefinitely.
  16725. @returns true if the event has been signalled, false if the timeout expires.
  16726. */
  16727. bool wait (int timeOutMilliseconds) const;
  16728. /** Wakes up the thread.
  16729. If the thread has called the wait() method, this will wake it up.
  16730. @see wait
  16731. */
  16732. void notify() const;
  16733. /** A value type used for thread IDs.
  16734. @see getCurrentThreadId(), getThreadId()
  16735. */
  16736. typedef void* ThreadID;
  16737. /** Returns an id that identifies the caller thread.
  16738. To find the ID of a particular thread object, use getThreadId().
  16739. @returns a unique identifier that identifies the calling thread.
  16740. @see getThreadId
  16741. */
  16742. static ThreadID getCurrentThreadId();
  16743. /** Finds the thread object that is currently running.
  16744. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  16745. object associated with them, so this will return 0.
  16746. */
  16747. static Thread* getCurrentThread();
  16748. /** Returns the ID of this thread.
  16749. That means the ID of this thread object - not of the thread that's calling the method.
  16750. This can change when the thread is started and stopped, and will be invalid if the
  16751. thread's not actually running.
  16752. @see getCurrentThreadId
  16753. */
  16754. ThreadID getThreadId() const throw() { return threadId_; }
  16755. /** Returns the name of the thread.
  16756. This is the name that gets set in the constructor.
  16757. */
  16758. const String getThreadName() const { return threadName_; }
  16759. /** Returns the number of currently-running threads.
  16760. @returns the number of Thread objects known to be currently running.
  16761. @see stopAllThreads
  16762. */
  16763. static int getNumRunningThreads();
  16764. /** Tries to stop all currently-running threads.
  16765. This will attempt to stop all the threads known to be running at the moment.
  16766. */
  16767. static void stopAllThreads (int timeoutInMillisecs);
  16768. private:
  16769. const String threadName_;
  16770. void* volatile threadHandle_;
  16771. ThreadID threadId_;
  16772. CriticalSection startStopLock;
  16773. WaitableEvent startSuspensionEvent_, defaultEvent_;
  16774. int threadPriority_;
  16775. uint32 affinityMask_;
  16776. bool volatile threadShouldExit_;
  16777. #ifndef DOXYGEN
  16778. friend class MessageManager;
  16779. friend void JUCE_API juce_threadEntryPoint (void*);
  16780. #endif
  16781. void launchThread();
  16782. void closeThreadHandle();
  16783. void killThread();
  16784. void threadEntryPoint();
  16785. static void setCurrentThreadName (const String& name);
  16786. static bool setThreadPriority (void* handle, int priority);
  16787. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread);
  16788. };
  16789. #endif // __JUCE_THREAD_JUCEHEADER__
  16790. /*** End of inlined file: juce_Thread.h ***/
  16791. /**
  16792. A critical section that allows multiple simultaneous readers.
  16793. Features of this type of lock are:
  16794. - Multiple readers can hold the lock at the same time, but only one writer
  16795. can hold it at once.
  16796. - Writers trying to gain the lock will be blocked until all readers and writers
  16797. have released it
  16798. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  16799. blocked until the writer has obtained and released it
  16800. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  16801. there are no other readers
  16802. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  16803. - Recursive locking is supported.
  16804. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  16805. */
  16806. class JUCE_API ReadWriteLock
  16807. {
  16808. public:
  16809. /**
  16810. Creates a ReadWriteLock object.
  16811. */
  16812. ReadWriteLock() throw();
  16813. /** Destructor.
  16814. If the object is deleted whilst locked, any subsequent behaviour
  16815. is unpredictable.
  16816. */
  16817. ~ReadWriteLock() throw();
  16818. /** Locks this object for reading.
  16819. Multiple threads can simulaneously lock the object for reading, but if another
  16820. thread has it locked for writing, then this will block until it releases the
  16821. lock.
  16822. @see exitRead, ScopedReadLock
  16823. */
  16824. void enterRead() const throw();
  16825. /** Releases the read-lock.
  16826. If the caller thread hasn't got the lock, this can have unpredictable results.
  16827. If the enterRead() method has been called multiple times by the thread, each
  16828. call must be matched by a call to exitRead() before other threads will be allowed
  16829. to take over the lock.
  16830. @see enterRead, ScopedReadLock
  16831. */
  16832. void exitRead() const throw();
  16833. /** Locks this object for writing.
  16834. This will block until any other threads that have it locked for reading or
  16835. writing have released their lock.
  16836. @see exitWrite, ScopedWriteLock
  16837. */
  16838. void enterWrite() const throw();
  16839. /** Tries to lock this object for writing.
  16840. This is like enterWrite(), but doesn't block - it returns true if it manages
  16841. to obtain the lock.
  16842. @see enterWrite
  16843. */
  16844. bool tryEnterWrite() const throw();
  16845. /** Releases the write-lock.
  16846. If the caller thread hasn't got the lock, this can have unpredictable results.
  16847. If the enterWrite() method has been called multiple times by the thread, each
  16848. call must be matched by a call to exit() before other threads will be allowed
  16849. to take over the lock.
  16850. @see enterWrite, ScopedWriteLock
  16851. */
  16852. void exitWrite() const throw();
  16853. private:
  16854. CriticalSection accessLock;
  16855. WaitableEvent waitEvent;
  16856. mutable int numWaitingWriters, numWriters;
  16857. mutable Thread::ThreadID writerThreadId;
  16858. mutable Array <Thread::ThreadID> readerThreads;
  16859. JUCE_DECLARE_NON_COPYABLE (ReadWriteLock);
  16860. };
  16861. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  16862. /*** End of inlined file: juce_ReadWriteLock.h ***/
  16863. #endif
  16864. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  16865. #endif
  16866. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  16867. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  16868. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  16869. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  16870. /**
  16871. Automatically locks and unlocks a ReadWriteLock object.
  16872. Use one of these as a local variable to control access to a ReadWriteLock.
  16873. e.g. @code
  16874. ReadWriteLock myLock;
  16875. for (;;)
  16876. {
  16877. const ScopedReadLock myScopedLock (myLock);
  16878. // myLock is now locked
  16879. ...do some stuff...
  16880. // myLock gets unlocked here.
  16881. }
  16882. @endcode
  16883. @see ReadWriteLock, ScopedWriteLock
  16884. */
  16885. class JUCE_API ScopedReadLock
  16886. {
  16887. public:
  16888. /** Creates a ScopedReadLock.
  16889. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  16890. when the ScopedReadLock object is deleted, the ReadWriteLock will
  16891. be unlocked.
  16892. Make sure this object is created and deleted by the same thread,
  16893. otherwise there are no guarantees what will happen! Best just to use it
  16894. as a local stack object, rather than creating one with the new() operator.
  16895. */
  16896. inline explicit ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  16897. /** Destructor.
  16898. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  16899. Make sure this object is created and deleted by the same thread,
  16900. otherwise there are no guarantees what will happen!
  16901. */
  16902. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  16903. private:
  16904. const ReadWriteLock& lock_;
  16905. JUCE_DECLARE_NON_COPYABLE (ScopedReadLock);
  16906. };
  16907. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  16908. /*** End of inlined file: juce_ScopedReadLock.h ***/
  16909. #endif
  16910. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  16911. /*** Start of inlined file: juce_ScopedTryLock.h ***/
  16912. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  16913. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  16914. /**
  16915. Automatically tries to lock and unlock a CriticalSection object.
  16916. Use one of these as a local variable to control access to a CriticalSection.
  16917. e.g. @code
  16918. CriticalSection myCriticalSection;
  16919. for (;;)
  16920. {
  16921. const ScopedTryLock myScopedTryLock (myCriticalSection);
  16922. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  16923. // should test this with the isLocked() method before doing your thread-unsafe
  16924. // action..
  16925. if (myScopedTryLock.isLocked())
  16926. {
  16927. ...do some stuff...
  16928. }
  16929. else
  16930. {
  16931. ..our attempt at locking failed because another thread had already locked it..
  16932. }
  16933. // myCriticalSection gets unlocked here (if it was locked)
  16934. }
  16935. @endcode
  16936. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  16937. */
  16938. class JUCE_API ScopedTryLock
  16939. {
  16940. public:
  16941. /** Creates a ScopedTryLock.
  16942. As soon as it is created, this will try to lock the CriticalSection, and
  16943. when the ScopedTryLock object is deleted, the CriticalSection will
  16944. be unlocked if the lock was successful.
  16945. Make sure this object is created and deleted by the same thread,
  16946. otherwise there are no guarantees what will happen! Best just to use it
  16947. as a local stack object, rather than creating one with the new() operator.
  16948. */
  16949. inline explicit ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  16950. /** Destructor.
  16951. The CriticalSection will be unlocked (if locked) when the destructor is called.
  16952. Make sure this object is created and deleted by the same thread,
  16953. otherwise there are no guarantees what will happen!
  16954. */
  16955. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  16956. /** Returns true if the CriticalSection was successfully locked. */
  16957. bool isLocked() const throw() { return lockWasSuccessful; }
  16958. private:
  16959. const CriticalSection& lock_;
  16960. const bool lockWasSuccessful;
  16961. JUCE_DECLARE_NON_COPYABLE (ScopedTryLock);
  16962. };
  16963. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  16964. /*** End of inlined file: juce_ScopedTryLock.h ***/
  16965. #endif
  16966. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  16967. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  16968. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  16969. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  16970. /**
  16971. Automatically locks and unlocks a ReadWriteLock object.
  16972. Use one of these as a local variable to control access to a ReadWriteLock.
  16973. e.g. @code
  16974. ReadWriteLock myLock;
  16975. for (;;)
  16976. {
  16977. const ScopedWriteLock myScopedLock (myLock);
  16978. // myLock is now locked
  16979. ...do some stuff...
  16980. // myLock gets unlocked here.
  16981. }
  16982. @endcode
  16983. @see ReadWriteLock, ScopedReadLock
  16984. */
  16985. class JUCE_API ScopedWriteLock
  16986. {
  16987. public:
  16988. /** Creates a ScopedWriteLock.
  16989. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  16990. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  16991. be unlocked.
  16992. Make sure this object is created and deleted by the same thread,
  16993. otherwise there are no guarantees what will happen! Best just to use it
  16994. as a local stack object, rather than creating one with the new() operator.
  16995. */
  16996. inline explicit ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  16997. /** Destructor.
  16998. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  16999. Make sure this object is created and deleted by the same thread,
  17000. otherwise there are no guarantees what will happen!
  17001. */
  17002. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  17003. private:
  17004. const ReadWriteLock& lock_;
  17005. JUCE_DECLARE_NON_COPYABLE (ScopedWriteLock);
  17006. };
  17007. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  17008. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  17009. #endif
  17010. #ifndef __JUCE_THREAD_JUCEHEADER__
  17011. #endif
  17012. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  17013. /*** Start of inlined file: juce_ThreadPool.h ***/
  17014. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  17015. #define __JUCE_THREADPOOL_JUCEHEADER__
  17016. class ThreadPool;
  17017. class ThreadPoolThread;
  17018. /**
  17019. A task that is executed by a ThreadPool object.
  17020. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  17021. its threads.
  17022. The runJob() method needs to be implemented to do the task, and if the code that
  17023. does the work takes a significant time to run, it must keep checking the shouldExit()
  17024. method to see if something is trying to interrupt the job. If shouldExit() returns
  17025. true, the runJob() method must return immediately.
  17026. @see ThreadPool, Thread
  17027. */
  17028. class JUCE_API ThreadPoolJob
  17029. {
  17030. public:
  17031. /** Creates a thread pool job object.
  17032. After creating your job, add it to a thread pool with ThreadPool::addJob().
  17033. */
  17034. explicit ThreadPoolJob (const String& name);
  17035. /** Destructor. */
  17036. virtual ~ThreadPoolJob();
  17037. /** Returns the name of this job.
  17038. @see setJobName
  17039. */
  17040. const String getJobName() const;
  17041. /** Changes the job's name.
  17042. @see getJobName
  17043. */
  17044. void setJobName (const String& newName);
  17045. /** These are the values that can be returned by the runJob() method.
  17046. */
  17047. enum JobStatus
  17048. {
  17049. jobHasFinished = 0, /**< indicates that the job has finished and can be
  17050. removed from the pool. */
  17051. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  17052. should be automatically deleted by the pool. */
  17053. jobNeedsRunningAgain /**< indicates that the job would like to be called
  17054. again when a thread is free. */
  17055. };
  17056. /** Peforms the actual work that this job needs to do.
  17057. Your subclass must implement this method, in which is does its work.
  17058. If the code in this method takes a significant time to run, it must repeatedly check
  17059. the shouldExit() method to see if something is trying to interrupt the job.
  17060. If shouldExit() ever returns true, the runJob() method must return immediately.
  17061. If this method returns jobHasFinished, then the job will be removed from the pool
  17062. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  17063. pool and will get a chance to run again as soon as a thread is free.
  17064. @see shouldExit()
  17065. */
  17066. virtual JobStatus runJob() = 0;
  17067. /** Returns true if this job is currently running its runJob() method. */
  17068. bool isRunning() const { return isActive; }
  17069. /** Returns true if something is trying to interrupt this job and make it stop.
  17070. Your runJob() method must call this whenever it gets a chance, and if it ever
  17071. returns true, the runJob() method must return immediately.
  17072. @see signalJobShouldExit()
  17073. */
  17074. bool shouldExit() const { return shouldStop; }
  17075. /** Calling this will cause the shouldExit() method to return true, and the job
  17076. should (if it's been implemented correctly) stop as soon as possible.
  17077. @see shouldExit()
  17078. */
  17079. void signalJobShouldExit();
  17080. private:
  17081. friend class ThreadPool;
  17082. friend class ThreadPoolThread;
  17083. String jobName;
  17084. ThreadPool* pool;
  17085. bool shouldStop, isActive, shouldBeDeleted;
  17086. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob);
  17087. };
  17088. /**
  17089. A set of threads that will run a list of jobs.
  17090. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  17091. will be called by the next pooled thread that becomes free.
  17092. @see ThreadPoolJob, Thread
  17093. */
  17094. class JUCE_API ThreadPool
  17095. {
  17096. public:
  17097. /** Creates a thread pool.
  17098. Once you've created a pool, you can give it some things to do with the addJob()
  17099. method.
  17100. @param numberOfThreads the maximum number of actual threads to run.
  17101. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  17102. until there are some jobs to run. If false, then
  17103. all the threads will be fired-up immediately so that
  17104. they're ready for action
  17105. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  17106. inactive for this length of time, they will automatically
  17107. be stopped until more jobs come along and they're needed
  17108. */
  17109. ThreadPool (int numberOfThreads,
  17110. bool startThreadsOnlyWhenNeeded = true,
  17111. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  17112. /** Destructor.
  17113. This will attempt to remove all the jobs before deleting, but if you want to
  17114. specify a timeout, you should call removeAllJobs() explicitly before deleting
  17115. the pool.
  17116. */
  17117. ~ThreadPool();
  17118. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  17119. for some kind of operation.
  17120. @see ThreadPool::removeAllJobs
  17121. */
  17122. class JUCE_API JobSelector
  17123. {
  17124. public:
  17125. virtual ~JobSelector() {}
  17126. /** Should return true if the specified thread matches your criteria for whatever
  17127. operation that this object is being used for.
  17128. Any implementation of this method must be extremely fast and thread-safe!
  17129. */
  17130. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  17131. };
  17132. /** Adds a job to the queue.
  17133. Once a job has been added, then the next time a thread is free, it will run
  17134. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  17135. runJob() method, the pool will either remove the job from the pool or add it to
  17136. the back of the queue to be run again.
  17137. */
  17138. void addJob (ThreadPoolJob* job);
  17139. /** Tries to remove a job from the pool.
  17140. If the job isn't yet running, this will simply remove it. If it is running, it
  17141. will wait for it to finish.
  17142. If the timeout period expires before the job finishes running, then the job will be
  17143. left in the pool and this will return false. It returns true if the job is sucessfully
  17144. stopped and removed.
  17145. @param job the job to remove
  17146. @param interruptIfRunning if true, then if the job is currently busy, its
  17147. ThreadPoolJob::signalJobShouldExit() method will be called to try
  17148. to interrupt it. If false, then if the job will be allowed to run
  17149. until it stops normally (or the timeout expires)
  17150. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  17151. before giving up and returning false
  17152. */
  17153. bool removeJob (ThreadPoolJob* job,
  17154. bool interruptIfRunning,
  17155. int timeOutMilliseconds);
  17156. /** Tries to remove all jobs from the pool.
  17157. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  17158. methods called to try to interrupt them
  17159. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  17160. before giving up and returning false
  17161. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  17162. they will simply be removed from the pool. Jobs that are already running when
  17163. this method is called can choose whether they should be deleted by
  17164. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  17165. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  17166. jobs should be removed. If it is zero, all jobs are removed
  17167. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  17168. expires while waiting for one or more jobs to stop
  17169. */
  17170. bool removeAllJobs (bool interruptRunningJobs,
  17171. int timeOutMilliseconds,
  17172. bool deleteInactiveJobs = false,
  17173. JobSelector* selectedJobsToRemove = 0);
  17174. /** Returns the number of jobs currently running or queued.
  17175. */
  17176. int getNumJobs() const;
  17177. /** Returns one of the jobs in the queue.
  17178. Note that this can be a very volatile list as jobs might be continuously getting shifted
  17179. around in the list, and this method may return 0 if the index is currently out-of-range.
  17180. */
  17181. ThreadPoolJob* getJob (int index) const;
  17182. /** Returns true if the given job is currently queued or running.
  17183. @see isJobRunning()
  17184. */
  17185. bool contains (const ThreadPoolJob* job) const;
  17186. /** Returns true if the given job is currently being run by a thread.
  17187. */
  17188. bool isJobRunning (const ThreadPoolJob* job) const;
  17189. /** Waits until a job has finished running and has been removed from the pool.
  17190. This will wait until the job is no longer in the pool - i.e. until its
  17191. runJob() method returns ThreadPoolJob::jobHasFinished.
  17192. If the timeout period expires before the job finishes, this will return false;
  17193. it returns true if the job has finished successfully.
  17194. */
  17195. bool waitForJobToFinish (const ThreadPoolJob* job,
  17196. int timeOutMilliseconds) const;
  17197. /** Returns a list of the names of all the jobs currently running or queued.
  17198. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  17199. */
  17200. const StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  17201. /** Changes the priority of all the threads.
  17202. This will call Thread::setPriority() for each thread in the pool.
  17203. May return false if for some reason the priority can't be changed.
  17204. */
  17205. bool setThreadPriorities (int newPriority);
  17206. private:
  17207. const int threadStopTimeout;
  17208. int priority;
  17209. class ThreadPoolThread;
  17210. friend class OwnedArray <ThreadPoolThread>;
  17211. OwnedArray <ThreadPoolThread> threads;
  17212. Array <ThreadPoolJob*> jobs;
  17213. CriticalSection lock;
  17214. uint32 lastJobEndTime;
  17215. WaitableEvent jobFinishedSignal;
  17216. friend class ThreadPoolThread;
  17217. bool runNextJob();
  17218. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool);
  17219. };
  17220. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  17221. /*** End of inlined file: juce_ThreadPool.h ***/
  17222. #endif
  17223. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17224. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  17225. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17226. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17227. class TimeSliceThread;
  17228. /**
  17229. Used by the TimeSliceThread class.
  17230. To register your class with a TimeSliceThread, derive from this class and
  17231. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  17232. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  17233. deleting your client!
  17234. @see TimeSliceThread
  17235. */
  17236. class JUCE_API TimeSliceClient
  17237. {
  17238. public:
  17239. /** Destructor. */
  17240. virtual ~TimeSliceClient() {}
  17241. /** Called back by a TimeSliceThread.
  17242. When you register this class with it, a TimeSliceThread will repeatedly call
  17243. this method.
  17244. The implementation of this method should use its time-slice to do something that's
  17245. quick - never block for longer than absolutely necessary.
  17246. @returns Your method should return the number of milliseconds which it would like to wait before being called
  17247. again. Returning 0 will make the thread call again as soon as possible (after possibly servicing
  17248. other busy clients). If you return a value below zero, your client will be removed from the list of clients,
  17249. and won't be called again. The value you specify isn't a guaranteee, and is only used as a hint by the
  17250. thread - the actual time before the next callback may be more or less than specified.
  17251. You can force the TimeSliceThread to wake up and poll again immediately by calling its notify() method.
  17252. */
  17253. virtual int useTimeSlice() = 0;
  17254. private:
  17255. friend class TimeSliceThread;
  17256. Time nextCallTime;
  17257. };
  17258. /**
  17259. A thread that keeps a list of clients, and calls each one in turn, giving them
  17260. all a chance to run some sort of short task.
  17261. @see TimeSliceClient, Thread
  17262. */
  17263. class JUCE_API TimeSliceThread : public Thread
  17264. {
  17265. public:
  17266. /**
  17267. Creates a TimeSliceThread.
  17268. When first created, the thread is not running. Use the startThread()
  17269. method to start it.
  17270. */
  17271. explicit TimeSliceThread (const String& threadName);
  17272. /** Destructor.
  17273. Deleting a Thread object that is running will only give the thread a
  17274. brief opportunity to stop itself cleanly, so it's recommended that you
  17275. should always call stopThread() with a decent timeout before deleting,
  17276. to avoid the thread being forcibly killed (which is a Bad Thing).
  17277. */
  17278. ~TimeSliceThread();
  17279. /** Adds a client to the list.
  17280. The client's callbacks will start after the number of milliseconds specified
  17281. by millisecondsBeforeStarting (and this may happen before this method has returned).
  17282. */
  17283. void addTimeSliceClient (TimeSliceClient* client, int millisecondsBeforeStarting = 0);
  17284. /** Removes a client from the list.
  17285. This method will make sure that all callbacks to the client have completely
  17286. finished before the method returns.
  17287. */
  17288. void removeTimeSliceClient (TimeSliceClient* client);
  17289. /** Returns the number of registered clients. */
  17290. int getNumClients() const;
  17291. /** Returns one of the registered clients. */
  17292. TimeSliceClient* getClient (int index) const;
  17293. /** @internal */
  17294. void run();
  17295. private:
  17296. CriticalSection callbackLock, listLock;
  17297. Array <TimeSliceClient*> clients;
  17298. TimeSliceClient* clientBeingCalled;
  17299. TimeSliceClient* getNextClient (int index) const;
  17300. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimeSliceThread);
  17301. };
  17302. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17303. /*** End of inlined file: juce_TimeSliceThread.h ***/
  17304. #endif
  17305. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  17306. #endif
  17307. #endif
  17308. /*** End of inlined file: juce_core_includes.h ***/
  17309. // if you're compiling a command-line app, you might want to just include the core headers,
  17310. // so you can set this macro before including juce.h
  17311. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  17312. /*** Start of inlined file: juce_app_includes.h ***/
  17313. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  17314. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  17315. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  17316. /*** Start of inlined file: juce_Application.h ***/
  17317. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  17318. #define __JUCE_APPLICATION_JUCEHEADER__
  17319. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  17320. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17321. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17322. /*** Start of inlined file: juce_Component.h ***/
  17323. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  17324. #define __JUCE_COMPONENT_JUCEHEADER__
  17325. /*** Start of inlined file: juce_MouseCursor.h ***/
  17326. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  17327. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  17328. class Image;
  17329. class ComponentPeer;
  17330. class Component;
  17331. /**
  17332. Represents a mouse cursor image.
  17333. This object can either be used to represent one of the standard mouse
  17334. cursor shapes, or a custom one generated from an image.
  17335. */
  17336. class JUCE_API MouseCursor
  17337. {
  17338. public:
  17339. /** The set of available standard mouse cursors. */
  17340. enum StandardCursorType
  17341. {
  17342. NoCursor = 0, /**< An invisible cursor. */
  17343. NormalCursor, /**< The stardard arrow cursor. */
  17344. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  17345. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  17346. CrosshairCursor, /**< A pair of crosshairs. */
  17347. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  17348. that you're dragging a copy of something. */
  17349. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  17350. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  17351. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  17352. UpDownResizeCursor, /**< an arrow pointing up and down. */
  17353. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  17354. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  17355. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  17356. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  17357. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  17358. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  17359. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  17360. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  17361. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  17362. };
  17363. /** Creates the standard arrow cursor. */
  17364. MouseCursor();
  17365. /** Creates one of the standard mouse cursor */
  17366. MouseCursor (StandardCursorType type);
  17367. /** Creates a custom cursor from an image.
  17368. @param image the image to use for the cursor - if this is bigger than the
  17369. system can manage, it might get scaled down first, and might
  17370. also have to be turned to black-and-white if it can't do colour
  17371. cursors.
  17372. @param hotSpotX the x position of the cursor's hotspot within the image
  17373. @param hotSpotY the y position of the cursor's hotspot within the image
  17374. */
  17375. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  17376. /** Creates a copy of another cursor object. */
  17377. MouseCursor (const MouseCursor& other);
  17378. /** Copies this cursor from another object. */
  17379. MouseCursor& operator= (const MouseCursor& other);
  17380. /** Destructor. */
  17381. ~MouseCursor();
  17382. /** Checks whether two mouse cursors are the same.
  17383. For custom cursors, two cursors created from the same image won't be
  17384. recognised as the same, only MouseCursor objects that have been
  17385. copied from the same object.
  17386. */
  17387. bool operator== (const MouseCursor& other) const throw();
  17388. /** Checks whether two mouse cursors are the same.
  17389. For custom cursors, two cursors created from the same image won't be
  17390. recognised as the same, only MouseCursor objects that have been
  17391. copied from the same object.
  17392. */
  17393. bool operator!= (const MouseCursor& other) const throw();
  17394. /** Makes the system show its default 'busy' cursor.
  17395. This will turn the system cursor to an hourglass or spinning beachball
  17396. until the next time the mouse is moved, or hideWaitCursor() is called.
  17397. This is handy if the message loop is about to block for a couple of
  17398. seconds while busy and you want to give the user feedback about this.
  17399. @see MessageManager::setTimeBeforeShowingWaitCursor
  17400. */
  17401. static void showWaitCursor();
  17402. /** If showWaitCursor has been called, this will return the mouse to its
  17403. normal state.
  17404. This will look at what component is under the mouse, and update the
  17405. cursor to be the correct one for that component.
  17406. @see showWaitCursor
  17407. */
  17408. static void hideWaitCursor();
  17409. private:
  17410. class SharedCursorHandle;
  17411. friend class SharedCursorHandle;
  17412. SharedCursorHandle* cursorHandle;
  17413. friend class MouseInputSourceInternal;
  17414. void showInWindow (ComponentPeer* window) const;
  17415. void showInAllWindows() const;
  17416. void* getHandle() const throw();
  17417. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  17418. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  17419. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  17420. JUCE_LEAK_DETECTOR (MouseCursor);
  17421. };
  17422. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  17423. /*** End of inlined file: juce_MouseCursor.h ***/
  17424. /*** Start of inlined file: juce_MouseListener.h ***/
  17425. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  17426. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  17427. class MouseEvent;
  17428. /**
  17429. A MouseListener can be registered with a component to receive callbacks
  17430. about mouse events that happen to that component.
  17431. @see Component::addMouseListener, Component::removeMouseListener
  17432. */
  17433. class JUCE_API MouseListener
  17434. {
  17435. public:
  17436. /** Destructor. */
  17437. virtual ~MouseListener() {}
  17438. /** Called when the mouse moves inside a component.
  17439. If the mouse button isn't pressed and the mouse moves over a component,
  17440. this will be called to let the component react to this.
  17441. A component will always get a mouseEnter callback before a mouseMove.
  17442. @param e details about the position and status of the mouse event, including
  17443. the source component in which it occurred
  17444. @see mouseEnter, mouseExit, mouseDrag, contains
  17445. */
  17446. virtual void mouseMove (const MouseEvent& e);
  17447. /** Called when the mouse first enters a component.
  17448. If the mouse button isn't pressed and the mouse moves into a component,
  17449. this will be called to let the component react to this.
  17450. When the mouse button is pressed and held down while being moved in
  17451. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  17452. mouseDrag messages are sent to the component that the mouse was originally
  17453. clicked on, until the button is released.
  17454. @param e details about the position and status of the mouse event, including
  17455. the source component in which it occurred
  17456. @see mouseExit, mouseDrag, mouseMove, contains
  17457. */
  17458. virtual void mouseEnter (const MouseEvent& e);
  17459. /** Called when the mouse moves out of a component.
  17460. This will be called when the mouse moves off the edge of this
  17461. component.
  17462. If the mouse button was pressed, and it was then dragged off the
  17463. edge of the component and released, then this callback will happen
  17464. when the button is released, after the mouseUp callback.
  17465. @param e details about the position and status of the mouse event, including
  17466. the source component in which it occurred
  17467. @see mouseEnter, mouseDrag, mouseMove, contains
  17468. */
  17469. virtual void mouseExit (const MouseEvent& e);
  17470. /** Called when a mouse button is pressed.
  17471. The MouseEvent object passed in contains lots of methods for finding out
  17472. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  17473. were held down at the time.
  17474. Once a button is held down, the mouseDrag method will be called when the
  17475. mouse moves, until the button is released.
  17476. @param e details about the position and status of the mouse event, including
  17477. the source component in which it occurred
  17478. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  17479. */
  17480. virtual void mouseDown (const MouseEvent& e);
  17481. /** Called when the mouse is moved while a button is held down.
  17482. When a mouse button is pressed inside a component, that component
  17483. receives mouseDrag callbacks each time the mouse moves, even if the
  17484. mouse strays outside the component's bounds.
  17485. @param e details about the position and status of the mouse event, including
  17486. the source component in which it occurred
  17487. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  17488. */
  17489. virtual void mouseDrag (const MouseEvent& e);
  17490. /** Called when a mouse button is released.
  17491. A mouseUp callback is sent to the component in which a button was pressed
  17492. even if the mouse is actually over a different component when the
  17493. button is released.
  17494. The MouseEvent object passed in contains lots of methods for finding out
  17495. which buttons were down just before they were released.
  17496. @param e details about the position and status of the mouse event, including
  17497. the source component in which it occurred
  17498. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  17499. */
  17500. virtual void mouseUp (const MouseEvent& e);
  17501. /** Called when a mouse button has been double-clicked on a component.
  17502. The MouseEvent object passed in contains lots of methods for finding out
  17503. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  17504. were held down at the time.
  17505. @param e details about the position and status of the mouse event, including
  17506. the source component in which it occurred
  17507. @see mouseDown, mouseUp
  17508. */
  17509. virtual void mouseDoubleClick (const MouseEvent& e);
  17510. /** Called when the mouse-wheel is moved.
  17511. This callback is sent to the component that the mouse is over when the
  17512. wheel is moved.
  17513. If not overridden, the component will forward this message to its parent, so
  17514. that parent components can collect mouse-wheel messages that happen to
  17515. child components which aren't interested in them.
  17516. @param e details about the position and status of the mouse event, including
  17517. the source component in which it occurred
  17518. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  17519. value means the wheel has been pushed to the right, negative means it
  17520. was pushed to the left
  17521. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  17522. value means the wheel has been pushed upwards, negative means it
  17523. was pushed downwards
  17524. */
  17525. virtual void mouseWheelMove (const MouseEvent& e,
  17526. float wheelIncrementX,
  17527. float wheelIncrementY);
  17528. };
  17529. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  17530. /*** End of inlined file: juce_MouseListener.h ***/
  17531. /*** Start of inlined file: juce_MouseEvent.h ***/
  17532. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  17533. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  17534. class Component;
  17535. class MouseInputSource;
  17536. /*** Start of inlined file: juce_ModifierKeys.h ***/
  17537. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  17538. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  17539. /**
  17540. Represents the state of the mouse buttons and modifier keys.
  17541. This is used both by mouse events and by KeyPress objects to describe
  17542. the state of keys such as shift, control, alt, etc.
  17543. @see KeyPress, MouseEvent::mods
  17544. */
  17545. class JUCE_API ModifierKeys
  17546. {
  17547. public:
  17548. /** Creates a ModifierKeys object from a raw set of flags.
  17549. @param flags to represent the keys that are down
  17550. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  17551. rightButtonModifier, commandModifier, popupMenuClickModifier
  17552. */
  17553. ModifierKeys (int flags = 0) throw();
  17554. /** Creates a copy of another object. */
  17555. ModifierKeys (const ModifierKeys& other) throw();
  17556. /** Copies this object from another one. */
  17557. ModifierKeys& operator= (const ModifierKeys& other) throw();
  17558. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  17559. This is a platform-agnostic way of checking for the operating system's
  17560. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  17561. Windows/Linux, it's actually checking for the CTRL key.
  17562. */
  17563. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  17564. /** Checks whether the user is trying to launch a pop-up menu.
  17565. This checks for platform-specific modifiers that might indicate that the user
  17566. is following the operating system's normal method of showing a pop-up menu.
  17567. So on Windows/Linux, this method is really testing for a right-click.
  17568. On the Mac, it tests for either the CTRL key being down, or a right-click.
  17569. */
  17570. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  17571. /** Checks whether the flag is set for the left mouse-button. */
  17572. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  17573. /** Checks whether the flag is set for the right mouse-button.
  17574. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  17575. this is platform-independent (and makes your code more explanatory too).
  17576. */
  17577. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  17578. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  17579. /** Tests for any of the mouse-button flags. */
  17580. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  17581. /** Tests for any of the modifier key flags. */
  17582. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  17583. /** Checks whether the shift key's flag is set. */
  17584. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  17585. /** Checks whether the CTRL key's flag is set.
  17586. Remember that it's better to use the platform-agnostic routines to test for command-key and
  17587. popup-menu modifiers.
  17588. @see isCommandDown, isPopupMenu
  17589. */
  17590. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  17591. /** Checks whether the shift key's flag is set. */
  17592. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  17593. /** Flags that represent the different keys. */
  17594. enum Flags
  17595. {
  17596. /** Shift key flag. */
  17597. shiftModifier = 1,
  17598. /** CTRL key flag. */
  17599. ctrlModifier = 2,
  17600. /** ALT key flag. */
  17601. altModifier = 4,
  17602. /** Left mouse button flag. */
  17603. leftButtonModifier = 16,
  17604. /** Right mouse button flag. */
  17605. rightButtonModifier = 32,
  17606. /** Middle mouse button flag. */
  17607. middleButtonModifier = 64,
  17608. #if JUCE_MAC
  17609. /** Command key flag - on windows this is the same as the CTRL key flag. */
  17610. commandModifier = 8,
  17611. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  17612. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  17613. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  17614. #else
  17615. /** Command key flag - on windows this is the same as the CTRL key flag. */
  17616. commandModifier = ctrlModifier,
  17617. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  17618. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  17619. popupMenuClickModifier = rightButtonModifier,
  17620. #endif
  17621. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  17622. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  17623. /** Represents a combination of all the mouse buttons at once. */
  17624. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  17625. };
  17626. /** Returns a copy of only the mouse-button flags */
  17627. const ModifierKeys withOnlyMouseButtons() const throw() { return ModifierKeys (flags & allMouseButtonModifiers); }
  17628. /** Returns a copy of only the non-mouse flags */
  17629. const ModifierKeys withoutMouseButtons() const throw() { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  17630. bool operator== (const ModifierKeys& other) const throw() { return flags == other.flags; }
  17631. bool operator!= (const ModifierKeys& other) const throw() { return flags != other.flags; }
  17632. /** Returns the raw flags for direct testing. */
  17633. inline int getRawFlags() const throw() { return flags; }
  17634. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const throw() { return ModifierKeys (flags & ~rawFlagsToClear); }
  17635. inline const ModifierKeys withFlags (int rawFlagsToSet) const throw() { return ModifierKeys (flags | rawFlagsToSet); }
  17636. /** Tests a combination of flags and returns true if any of them are set. */
  17637. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  17638. /** Returns the total number of mouse buttons that are down. */
  17639. int getNumMouseButtonsDown() const throw();
  17640. /** Creates a ModifierKeys object to represent the last-known state of the
  17641. keyboard and mouse buttons.
  17642. @see getCurrentModifiersRealtime
  17643. */
  17644. static const ModifierKeys getCurrentModifiers() throw();
  17645. /** Creates a ModifierKeys object to represent the current state of the
  17646. keyboard and mouse buttons.
  17647. This isn't often needed and isn't recommended, but will actively check all the
  17648. mouse and key states rather than just returning their last-known state like
  17649. getCurrentModifiers() does.
  17650. This is only needed in special circumstances for up-to-date modifier information
  17651. at times when the app's event loop isn't running normally.
  17652. Another reason to avoid this method is that it's not stateless, and calling it may
  17653. update the value returned by getCurrentModifiers(), which could cause subtle changes
  17654. in the behaviour of some components.
  17655. */
  17656. static const ModifierKeys getCurrentModifiersRealtime() throw();
  17657. private:
  17658. int flags;
  17659. static ModifierKeys currentModifiers;
  17660. friend class ComponentPeer;
  17661. friend class MouseInputSource;
  17662. friend class MouseInputSourceInternal;
  17663. static void updateCurrentModifiers() throw();
  17664. };
  17665. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  17666. /*** End of inlined file: juce_ModifierKeys.h ***/
  17667. /*** Start of inlined file: juce_Point.h ***/
  17668. #ifndef __JUCE_POINT_JUCEHEADER__
  17669. #define __JUCE_POINT_JUCEHEADER__
  17670. /*** Start of inlined file: juce_AffineTransform.h ***/
  17671. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  17672. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  17673. /**
  17674. Represents a 2D affine-transformation matrix.
  17675. An affine transformation is a transformation such as a rotation, scale, shear,
  17676. resize or translation.
  17677. These are used for various 2D transformation tasks, e.g. with Path objects.
  17678. @see Path, Point, Line
  17679. */
  17680. class JUCE_API AffineTransform
  17681. {
  17682. public:
  17683. /** Creates an identity transform. */
  17684. AffineTransform() throw();
  17685. /** Creates a copy of another transform. */
  17686. AffineTransform (const AffineTransform& other) throw();
  17687. /** Creates a transform from a set of raw matrix values.
  17688. The resulting matrix is:
  17689. (mat00 mat01 mat02)
  17690. (mat10 mat11 mat12)
  17691. ( 0 0 1 )
  17692. */
  17693. AffineTransform (float mat00, float mat01, float mat02,
  17694. float mat10, float mat11, float mat12) throw();
  17695. /** Copies from another AffineTransform object */
  17696. AffineTransform& operator= (const AffineTransform& other) throw();
  17697. /** Compares two transforms. */
  17698. bool operator== (const AffineTransform& other) const throw();
  17699. /** Compares two transforms. */
  17700. bool operator!= (const AffineTransform& other) const throw();
  17701. /** A ready-to-use identity transform, which you can use to append other
  17702. transformations to.
  17703. e.g. @code
  17704. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  17705. .scaled (2.0f);
  17706. @endcode
  17707. */
  17708. static const AffineTransform identity;
  17709. /** Transforms a 2D co-ordinate using this matrix. */
  17710. template <typename ValueType>
  17711. void transformPoint (ValueType& x, ValueType& y) const throw()
  17712. {
  17713. const ValueType oldX = x;
  17714. x = static_cast <ValueType> (mat00 * oldX + mat01 * y + mat02);
  17715. y = static_cast <ValueType> (mat10 * oldX + mat11 * y + mat12);
  17716. }
  17717. /** Transforms two 2D co-ordinates using this matrix.
  17718. This is just a shortcut for calling transformPoint() on each of these pairs of
  17719. coordinates in turn. (And putting all the calculations into one function hopefully
  17720. also gives the compiler a bit more scope for pipelining it).
  17721. */
  17722. template <typename ValueType>
  17723. void transformPoints (ValueType& x1, ValueType& y1,
  17724. ValueType& x2, ValueType& y2) const throw()
  17725. {
  17726. const ValueType oldX1 = x1, oldX2 = x2;
  17727. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  17728. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  17729. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  17730. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  17731. }
  17732. /** Transforms three 2D co-ordinates using this matrix.
  17733. This is just a shortcut for calling transformPoint() on each of these pairs of
  17734. coordinates in turn. (And putting all the calculations into one function hopefully
  17735. also gives the compiler a bit more scope for pipelining it).
  17736. */
  17737. template <typename ValueType>
  17738. void transformPoints (ValueType& x1, ValueType& y1,
  17739. ValueType& x2, ValueType& y2,
  17740. ValueType& x3, ValueType& y3) const throw()
  17741. {
  17742. const ValueType oldX1 = x1, oldX2 = x2, oldX3 = x3;
  17743. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  17744. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  17745. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  17746. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  17747. x3 = static_cast <ValueType> (mat00 * oldX3 + mat01 * y3 + mat02);
  17748. y3 = static_cast <ValueType> (mat10 * oldX3 + mat11 * y3 + mat12);
  17749. }
  17750. /** Returns a new transform which is the same as this one followed by a translation. */
  17751. const AffineTransform translated (float deltaX,
  17752. float deltaY) const throw();
  17753. /** Returns a new transform which is a translation. */
  17754. static const AffineTransform translation (float deltaX,
  17755. float deltaY) throw();
  17756. /** Returns a transform which is the same as this one followed by a rotation.
  17757. The rotation is specified by a number of radians to rotate clockwise, centred around
  17758. the origin (0, 0).
  17759. */
  17760. const AffineTransform rotated (float angleInRadians) const throw();
  17761. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  17762. The rotation is specified by a number of radians to rotate clockwise, centred around
  17763. the co-ordinates passed in.
  17764. */
  17765. const AffineTransform rotated (float angleInRadians,
  17766. float pivotX,
  17767. float pivotY) const throw();
  17768. /** Returns a new transform which is a rotation about (0, 0). */
  17769. static const AffineTransform rotation (float angleInRadians) throw();
  17770. /** Returns a new transform which is a rotation about a given point. */
  17771. static const AffineTransform rotation (float angleInRadians,
  17772. float pivotX,
  17773. float pivotY) throw();
  17774. /** Returns a transform which is the same as this one followed by a re-scaling.
  17775. The scaling is centred around the origin (0, 0).
  17776. */
  17777. const AffineTransform scaled (float factorX,
  17778. float factorY) const throw();
  17779. /** Returns a transform which is the same as this one followed by a re-scaling.
  17780. The scaling is centred around the origin provided.
  17781. */
  17782. const AffineTransform scaled (float factorX, float factorY,
  17783. float pivotX, float pivotY) const throw();
  17784. /** Returns a new transform which is a re-scale about the origin. */
  17785. static const AffineTransform scale (float factorX,
  17786. float factorY) throw();
  17787. /** Returns a new transform which is a re-scale centred around the point provided. */
  17788. static const AffineTransform scale (float factorX, float factorY,
  17789. float pivotX, float pivotY) throw();
  17790. /** Returns a transform which is the same as this one followed by a shear.
  17791. The shear is centred around the origin (0, 0).
  17792. */
  17793. const AffineTransform sheared (float shearX, float shearY) const throw();
  17794. /** Returns a shear transform, centred around the origin (0, 0). */
  17795. static const AffineTransform shear (float shearX, float shearY) throw();
  17796. /** Returns a matrix which is the inverse operation of this one.
  17797. Some matrices don't have an inverse - in this case, the method will just return
  17798. an identity transform.
  17799. */
  17800. const AffineTransform inverted() const throw();
  17801. /** Returns the transform that will map three known points onto three coordinates
  17802. that are supplied.
  17803. This returns the transform that will transform (0, 0) into (x00, y00),
  17804. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  17805. */
  17806. static const AffineTransform fromTargetPoints (float x00, float y00,
  17807. float x10, float y10,
  17808. float x01, float y01) throw();
  17809. /** Returns the transform that will map three specified points onto three target points.
  17810. */
  17811. static const AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
  17812. float sourceX2, float sourceY2, float targetX2, float targetY2,
  17813. float sourceX3, float sourceY3, float targetX3, float targetY3) throw();
  17814. /** Returns the result of concatenating another transformation after this one. */
  17815. const AffineTransform followedBy (const AffineTransform& other) const throw();
  17816. /** Returns true if this transform has no effect on points. */
  17817. bool isIdentity() const throw();
  17818. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  17819. bool isSingularity() const throw();
  17820. /** Returns true if the transform only translates, and doesn't scale or rotate the
  17821. points. */
  17822. bool isOnlyTranslation() const throw();
  17823. /** If this transform is only a translation, this returns the X offset.
  17824. @see isOnlyTranslation
  17825. */
  17826. float getTranslationX() const throw() { return mat02; }
  17827. /** If this transform is only a translation, this returns the X offset.
  17828. @see isOnlyTranslation
  17829. */
  17830. float getTranslationY() const throw() { return mat12; }
  17831. /** Returns the approximate scale factor by which lengths will be transformed.
  17832. Obviously a length may be scaled by entirely different amounts depending on its
  17833. direction, so this is only appropriate as a rough guide.
  17834. */
  17835. float getScaleFactor() const throw();
  17836. /* The transform matrix is:
  17837. (mat00 mat01 mat02)
  17838. (mat10 mat11 mat12)
  17839. ( 0 0 1 )
  17840. */
  17841. float mat00, mat01, mat02;
  17842. float mat10, mat11, mat12;
  17843. private:
  17844. JUCE_LEAK_DETECTOR (AffineTransform);
  17845. };
  17846. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  17847. /*** End of inlined file: juce_AffineTransform.h ***/
  17848. /**
  17849. A pair of (x, y) co-ordinates.
  17850. The ValueType template should be a primitive type such as int, float, double,
  17851. rather than a class.
  17852. @see Line, Path, AffineTransform
  17853. */
  17854. template <typename ValueType>
  17855. class Point
  17856. {
  17857. public:
  17858. /** Creates a point with co-ordinates (0, 0). */
  17859. Point() throw() : x(), y() {}
  17860. /** Creates a copy of another point. */
  17861. Point (const Point& other) throw() : x (other.x), y (other.y) {}
  17862. /** Creates a point from an (x, y) position. */
  17863. Point (const ValueType initialX, const ValueType initialY) throw() : x (initialX), y (initialY) {}
  17864. /** Destructor. */
  17865. ~Point() throw() {}
  17866. /** Copies this point from another one. */
  17867. Point& operator= (const Point& other) throw() { x = other.x; y = other.y; return *this; }
  17868. inline bool operator== (const Point& other) const throw() { return x == other.x && y == other.y; }
  17869. inline bool operator!= (const Point& other) const throw() { return x != other.x || y != other.y; }
  17870. /** Returns true if the point is (0, 0). */
  17871. bool isOrigin() const throw() { return x == ValueType() && y == ValueType(); }
  17872. /** Returns the point's x co-ordinate. */
  17873. inline ValueType getX() const throw() { return x; }
  17874. /** Returns the point's y co-ordinate. */
  17875. inline ValueType getY() const throw() { return y; }
  17876. /** Sets the point's x co-ordinate. */
  17877. inline void setX (const ValueType newX) throw() { x = newX; }
  17878. /** Sets the point's y co-ordinate. */
  17879. inline void setY (const ValueType newY) throw() { y = newY; }
  17880. /** Returns a point which has the same Y position as this one, but a new X. */
  17881. const Point withX (const ValueType newX) const throw() { return Point (newX, y); }
  17882. /** Returns a point which has the same X position as this one, but a new Y. */
  17883. const Point withY (const ValueType newY) const throw() { return Point (x, newY); }
  17884. /** Changes the point's x and y co-ordinates. */
  17885. void setXY (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  17886. /** Adds a pair of co-ordinates to this value. */
  17887. void addXY (const ValueType xToAdd, const ValueType yToAdd) throw() { x += xToAdd; y += yToAdd; }
  17888. /** Returns a point with a given offset from this one. */
  17889. const Point translated (const ValueType xDelta, const ValueType yDelta) const throw() { return Point (x + xDelta, y + yDelta); }
  17890. /** Adds two points together. */
  17891. const Point operator+ (const Point& other) const throw() { return Point (x + other.x, y + other.y); }
  17892. /** Adds another point's co-ordinates to this one. */
  17893. Point& operator+= (const Point& other) throw() { x += other.x; y += other.y; return *this; }
  17894. /** Subtracts one points from another. */
  17895. const Point operator- (const Point& other) const throw() { return Point (x - other.x, y - other.y); }
  17896. /** Subtracts another point's co-ordinates to this one. */
  17897. Point& operator-= (const Point& other) throw() { x -= other.x; y -= other.y; return *this; }
  17898. /** Returns a point whose coordinates are multiplied by a given value. */
  17899. const Point operator* (const ValueType multiplier) const throw() { return Point (x * multiplier, y * multiplier); }
  17900. /** Multiplies the point's co-ordinates by a value. */
  17901. Point& operator*= (const ValueType multiplier) throw() { x *= multiplier; y *= multiplier; return *this; }
  17902. /** Returns a point whose coordinates are divided by a given value. */
  17903. const Point operator/ (const ValueType divisor) const throw() { return Point (x / divisor, y / divisor); }
  17904. /** Divides the point's co-ordinates by a value. */
  17905. Point& operator/= (const ValueType divisor) throw() { x /= divisor; y /= divisor; return *this; }
  17906. /** Returns the inverse of this point. */
  17907. const Point operator-() const throw() { return Point (-x, -y); }
  17908. /** Returns the straight-line distance between this point and another one. */
  17909. ValueType getDistanceFromOrigin() const throw() { return juce_hypot (x, y); }
  17910. /** Returns the straight-line distance between this point and another one. */
  17911. ValueType getDistanceFrom (const Point& other) const throw() { return juce_hypot (x - other.x, y - other.y); }
  17912. /** Returns the angle from this point to another one.
  17913. The return value is the number of radians clockwise from the 3 o'clock direction,
  17914. where this point is the centre and the other point is on the circumference.
  17915. */
  17916. ValueType getAngleToPoint (const Point& other) const throw() { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  17917. /** Taking this point to be the centre of a circle, this returns a point on its circumference.
  17918. @param radius the radius of the circle.
  17919. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  17920. */
  17921. const Point getPointOnCircumference (const float radius, const float angle) const throw() { return Point<float> (x + radius * std::sin (angle),
  17922. y - radius * std::cos (angle)); }
  17923. /** Taking this point to be the centre of an ellipse, this returns a point on its circumference.
  17924. @param radiusX the horizontal radius of the circle.
  17925. @param radiusY the vertical radius of the circle.
  17926. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  17927. */
  17928. const Point getPointOnCircumference (const float radiusX, const float radiusY, const float angle) const throw() { return Point<float> (x + radiusX * std::sin (angle),
  17929. y - radiusY * std::cos (angle)); }
  17930. /** Uses a transform to change the point's co-ordinates.
  17931. This will only compile if ValueType = float!
  17932. @see AffineTransform::transformPoint
  17933. */
  17934. void applyTransform (const AffineTransform& transform) throw() { transform.transformPoint (x, y); }
  17935. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  17936. const Point transformedBy (const AffineTransform& transform) const throw() { return Point (transform.mat00 * x + transform.mat01 * y + transform.mat02,
  17937. transform.mat10 * x + transform.mat11 * y + transform.mat12); }
  17938. /** Casts this point to a Point<int> object. */
  17939. const Point<int> toInt() const throw() { return Point<int> (static_cast <int> (x), static_cast<int> (y)); }
  17940. /** Casts this point to a Point<float> object. */
  17941. const Point<float> toFloat() const throw() { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  17942. /** Casts this point to a Point<double> object. */
  17943. const Point<double> toDouble() const throw() { return Point<double> (static_cast <double> (x), static_cast<double> (y)); }
  17944. /** Returns the point as a string in the form "x, y". */
  17945. const String toString() const { return String (x) + ", " + String (y); }
  17946. private:
  17947. ValueType x, y;
  17948. };
  17949. #endif // __JUCE_POINT_JUCEHEADER__
  17950. /*** End of inlined file: juce_Point.h ***/
  17951. /**
  17952. Contains position and status information about a mouse event.
  17953. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  17954. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  17955. */
  17956. class JUCE_API MouseEvent
  17957. {
  17958. public:
  17959. /** Creates a MouseEvent.
  17960. Normally an application will never need to use this.
  17961. @param source the source that's invoking the event
  17962. @param position the position of the mouse, relative to the component that is passed-in
  17963. @param modifiers the key modifiers at the time of the event
  17964. @param eventComponent the component that the mouse event applies to
  17965. @param originator the component that originally received the event
  17966. @param eventTime the time the event happened
  17967. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  17968. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  17969. the same as the current mouse-x position.
  17970. @param mouseDownTime the time at which the corresponding mouse-down event happened
  17971. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  17972. the same as the current mouse-event time.
  17973. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  17974. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  17975. */
  17976. MouseEvent (MouseInputSource& source,
  17977. const Point<int>& position,
  17978. const ModifierKeys& modifiers,
  17979. Component* eventComponent,
  17980. Component* originator,
  17981. const Time& eventTime,
  17982. const Point<int> mouseDownPos,
  17983. const Time& mouseDownTime,
  17984. int numberOfClicks,
  17985. bool mouseWasDragged) throw();
  17986. /** Destructor. */
  17987. ~MouseEvent() throw();
  17988. /** The x-position of the mouse when the event occurred.
  17989. This value is relative to the top-left of the component to which the
  17990. event applies (as indicated by the MouseEvent::eventComponent field).
  17991. */
  17992. const int x;
  17993. /** The y-position of the mouse when the event occurred.
  17994. This value is relative to the top-left of the component to which the
  17995. event applies (as indicated by the MouseEvent::eventComponent field).
  17996. */
  17997. const int y;
  17998. /** The key modifiers associated with the event.
  17999. This will let you find out which mouse buttons were down, as well as which
  18000. modifier keys were held down.
  18001. When used for mouse-up events, this will indicate the state of the mouse buttons
  18002. just before they were released, so that you can tell which button they let go of.
  18003. */
  18004. const ModifierKeys mods;
  18005. /** The component that this event applies to.
  18006. This is usually the component that the mouse was over at the time, but for mouse-drag
  18007. events the mouse could actually be over a different component and the events are
  18008. still sent to the component that the button was originally pressed on.
  18009. The x and y member variables are relative to this component's position.
  18010. If you use getEventRelativeTo() to retarget this object to be relative to a different
  18011. component, this pointer will be updated, but originalComponent remains unchanged.
  18012. @see originalComponent
  18013. */
  18014. Component* const eventComponent;
  18015. /** The component that the event first occurred on.
  18016. If you use getEventRelativeTo() to retarget this object to be relative to a different
  18017. component, this value remains unchanged to indicate the first component that received it.
  18018. @see eventComponent
  18019. */
  18020. Component* const originalComponent;
  18021. /** The time that this mouse-event occurred.
  18022. */
  18023. const Time eventTime;
  18024. /** The source device that generated this event.
  18025. */
  18026. MouseInputSource& source;
  18027. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  18028. The co-ordinate is relative to the component specified in MouseEvent::component.
  18029. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18030. */
  18031. int getMouseDownX() const throw();
  18032. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  18033. The co-ordinate is relative to the component specified in MouseEvent::component.
  18034. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18035. */
  18036. int getMouseDownY() const throw();
  18037. /** Returns the co-ordinates of the last place that a mouse was pressed.
  18038. The co-ordinates are relative to the component specified in MouseEvent::component.
  18039. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  18040. */
  18041. const Point<int> getMouseDownPosition() const throw();
  18042. /** Returns the straight-line distance between where the mouse is now and where it
  18043. was the last time the button was pressed.
  18044. This is quite handy for things like deciding whether the user has moved far enough
  18045. for it to be considered a drag operation.
  18046. @see getDistanceFromDragStartX
  18047. */
  18048. int getDistanceFromDragStart() const throw();
  18049. /** Returns the difference between the mouse's current x postion and where it was
  18050. when the button was last pressed.
  18051. @see getDistanceFromDragStart
  18052. */
  18053. int getDistanceFromDragStartX() const throw();
  18054. /** Returns the difference between the mouse's current y postion and where it was
  18055. when the button was last pressed.
  18056. @see getDistanceFromDragStart
  18057. */
  18058. int getDistanceFromDragStartY() const throw();
  18059. /** Returns the difference between the mouse's current postion and where it was
  18060. when the button was last pressed.
  18061. @see getDistanceFromDragStart
  18062. */
  18063. const Point<int> getOffsetFromDragStart() const throw();
  18064. /** Returns true if the mouse has just been clicked.
  18065. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  18066. the user has dragged the mouse more than a few pixels from the place where the
  18067. mouse-down occurred.
  18068. Once they have dragged it far enough for this method to return false, it will continue
  18069. to return false until the mouse-up, even if they move the mouse back to the same
  18070. position where they originally pressed it. This means that it's very handy for
  18071. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  18072. callback to ignore any small movements they might make while clicking.
  18073. @returns true if the mouse wasn't dragged by more than a few pixels between
  18074. the last time the button was pressed and released.
  18075. */
  18076. bool mouseWasClicked() const throw();
  18077. /** For a click event, the number of times the mouse was clicked in succession.
  18078. So for example a double-click event will return 2, a triple-click 3, etc.
  18079. */
  18080. int getNumberOfClicks() const throw() { return numberOfClicks; }
  18081. /** Returns the time that the mouse button has been held down for.
  18082. If called from a mouseDrag or mouseUp callback, this will return the
  18083. number of milliseconds since the corresponding mouseDown event occurred.
  18084. If called in other contexts, e.g. a mouseMove, then the returned value
  18085. may be 0 or an undefined value.
  18086. */
  18087. int getLengthOfMousePress() const throw();
  18088. /** The position of the mouse when the event occurred.
  18089. This position is relative to the top-left of the component to which the
  18090. event applies (as indicated by the MouseEvent::eventComponent field).
  18091. */
  18092. const Point<int> getPosition() const throw();
  18093. /** Returns the mouse x position of this event, in global screen co-ordinates.
  18094. The co-ordinates are relative to the top-left of the main monitor.
  18095. @see getScreenPosition
  18096. */
  18097. int getScreenX() const;
  18098. /** Returns the mouse y position of this event, in global screen co-ordinates.
  18099. The co-ordinates are relative to the top-left of the main monitor.
  18100. @see getScreenPosition
  18101. */
  18102. int getScreenY() const;
  18103. /** Returns the mouse position of this event, in global screen co-ordinates.
  18104. The co-ordinates are relative to the top-left of the main monitor.
  18105. @see getMouseDownScreenPosition
  18106. */
  18107. const Point<int> getScreenPosition() const;
  18108. /** Returns the x co-ordinate at which the mouse button was last pressed.
  18109. The co-ordinates are relative to the top-left of the main monitor.
  18110. @see getMouseDownScreenPosition
  18111. */
  18112. int getMouseDownScreenX() const;
  18113. /** Returns the y co-ordinate at which the mouse button was last pressed.
  18114. The co-ordinates are relative to the top-left of the main monitor.
  18115. @see getMouseDownScreenPosition
  18116. */
  18117. int getMouseDownScreenY() const;
  18118. /** Returns the co-ordinates at which the mouse button was last pressed.
  18119. The co-ordinates are relative to the top-left of the main monitor.
  18120. @see getScreenPosition
  18121. */
  18122. const Point<int> getMouseDownScreenPosition() const;
  18123. /** Creates a version of this event that is relative to a different component.
  18124. The x and y positions of the event that is returned will have been
  18125. adjusted to be relative to the new component.
  18126. */
  18127. const MouseEvent getEventRelativeTo (Component* otherComponent) const throw();
  18128. /** Creates a copy of this event with a different position.
  18129. All other members of the event object are the same, but the x and y are
  18130. replaced with these new values.
  18131. */
  18132. const MouseEvent withNewPosition (const Point<int>& newPosition) const throw();
  18133. /** Changes the application-wide setting for the double-click time limit.
  18134. This is the maximum length of time between mouse-clicks for it to be
  18135. considered a double-click. It's used by the Component class.
  18136. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  18137. */
  18138. static void setDoubleClickTimeout (int timeOutMilliseconds) throw();
  18139. /** Returns the application-wide setting for the double-click time limit.
  18140. This is the maximum length of time between mouse-clicks for it to be
  18141. considered a double-click. It's used by the Component class.
  18142. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  18143. */
  18144. static int getDoubleClickTimeout() throw();
  18145. private:
  18146. const Point<int> mouseDownPos;
  18147. const Time mouseDownTime;
  18148. const int numberOfClicks;
  18149. const bool wasMovedSinceMouseDown;
  18150. static int doubleClickTimeOutMs;
  18151. MouseEvent& operator= (const MouseEvent&);
  18152. };
  18153. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  18154. /*** End of inlined file: juce_MouseEvent.h ***/
  18155. /*** Start of inlined file: juce_ComponentListener.h ***/
  18156. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18157. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18158. class Component;
  18159. /**
  18160. Gets informed about changes to a component's hierarchy or position.
  18161. To monitor a component for changes, register a subclass of ComponentListener
  18162. with the component using Component::addComponentListener().
  18163. Be sure to deregister listeners before you delete them!
  18164. @see Component::addComponentListener, Component::removeComponentListener
  18165. */
  18166. class JUCE_API ComponentListener
  18167. {
  18168. public:
  18169. /** Destructor. */
  18170. virtual ~ComponentListener() {}
  18171. /** Called when the component's position or size changes.
  18172. @param component the component that was moved or resized
  18173. @param wasMoved true if the component's top-left corner has just moved
  18174. @param wasResized true if the component's width or height has just changed
  18175. @see Component::setBounds, Component::resized, Component::moved
  18176. */
  18177. virtual void componentMovedOrResized (Component& component,
  18178. bool wasMoved,
  18179. bool wasResized);
  18180. /** Called when the component is brought to the top of the z-order.
  18181. @param component the component that was moved
  18182. @see Component::toFront, Component::broughtToFront
  18183. */
  18184. virtual void componentBroughtToFront (Component& component);
  18185. /** Called when the component is made visible or invisible.
  18186. @param component the component that changed
  18187. @see Component::setVisible
  18188. */
  18189. virtual void componentVisibilityChanged (Component& component);
  18190. /** Called when the component has children added or removed.
  18191. @param component the component whose children were changed
  18192. @see Component::childrenChanged, Component::addChildComponent,
  18193. Component::removeChildComponent
  18194. */
  18195. virtual void componentChildrenChanged (Component& component);
  18196. /** Called to indicate that the component's parents have changed.
  18197. When a component is added or removed from its parent, all of its children
  18198. will produce this notification (recursively - so all children of its
  18199. children will also be called as well).
  18200. @param component the component that this listener is registered with
  18201. @see Component::parentHierarchyChanged
  18202. */
  18203. virtual void componentParentHierarchyChanged (Component& component);
  18204. /** Called when the component's name is changed.
  18205. @see Component::setName, Component::getName
  18206. */
  18207. virtual void componentNameChanged (Component& component);
  18208. /** Called when the component is in the process of being deleted.
  18209. This callback is made from inside the destructor, so be very, very cautious
  18210. about what you do in here.
  18211. In particular, bear in mind that it's the Component base class's destructor that calls
  18212. this - so if the object that's being deleted is a subclass of Component, then the
  18213. subclass layers of the object will already have been destructed when it gets to this
  18214. point!
  18215. */
  18216. virtual void componentBeingDeleted (Component& component);
  18217. };
  18218. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18219. /*** End of inlined file: juce_ComponentListener.h ***/
  18220. /*** Start of inlined file: juce_KeyListener.h ***/
  18221. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  18222. #define __JUCE_KEYLISTENER_JUCEHEADER__
  18223. /*** Start of inlined file: juce_KeyPress.h ***/
  18224. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  18225. #define __JUCE_KEYPRESS_JUCEHEADER__
  18226. /**
  18227. Represents a key press, including any modifier keys that are needed.
  18228. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  18229. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  18230. */
  18231. class JUCE_API KeyPress
  18232. {
  18233. public:
  18234. /** Creates an (invalid) KeyPress.
  18235. @see isValid
  18236. */
  18237. KeyPress() throw();
  18238. /** Creates a KeyPress for a key and some modifiers.
  18239. e.g.
  18240. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  18241. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  18242. @param keyCode a code that represents the key - this value must be
  18243. one of special constants listed in this class, or an
  18244. 8-bit character code such as a letter (case is ignored),
  18245. digit or a simple key like "," or ".". Note that this
  18246. isn't the same as the textCharacter parameter, so for example
  18247. a keyCode of 'a' and a shift-key modifier should have a
  18248. textCharacter value of 'A'.
  18249. @param modifiers the modifiers to associate with the keystroke
  18250. @param textCharacter the character that would be printed if someone typed
  18251. this keypress into a text editor. This value may be
  18252. null if the keypress is a non-printing character
  18253. @see getKeyCode, isKeyCode, getModifiers
  18254. */
  18255. KeyPress (int keyCode,
  18256. const ModifierKeys& modifiers,
  18257. juce_wchar textCharacter) throw();
  18258. /** Creates a keypress with a keyCode but no modifiers or text character.
  18259. */
  18260. KeyPress (int keyCode) throw();
  18261. /** Creates a copy of another KeyPress. */
  18262. KeyPress (const KeyPress& other) throw();
  18263. /** Copies this KeyPress from another one. */
  18264. KeyPress& operator= (const KeyPress& other) throw();
  18265. /** Compares two KeyPress objects. */
  18266. bool operator== (const KeyPress& other) const throw();
  18267. /** Compares two KeyPress objects. */
  18268. bool operator!= (const KeyPress& other) const throw();
  18269. /** Returns true if this is a valid KeyPress.
  18270. A null keypress can be created by the default constructor, in case it's
  18271. needed.
  18272. */
  18273. bool isValid() const throw() { return keyCode != 0; }
  18274. /** Returns the key code itself.
  18275. This will either be one of the special constants defined in this class,
  18276. or an 8-bit character code.
  18277. */
  18278. int getKeyCode() const throw() { return keyCode; }
  18279. /** Returns the key modifiers.
  18280. @see ModifierKeys
  18281. */
  18282. const ModifierKeys getModifiers() const throw() { return mods; }
  18283. /** Returns the character that is associated with this keypress.
  18284. This is the character that you'd expect to see printed if you press this
  18285. keypress in a text editor or similar component.
  18286. */
  18287. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  18288. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  18289. the modifiers.
  18290. The values for key codes can either be one of the special constants defined in
  18291. this class, or an 8-bit character code.
  18292. @see getKeyCode
  18293. */
  18294. bool isKeyCode (int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  18295. /** Converts a textual key description to a KeyPress.
  18296. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  18297. This isn't designed to cope with any kind of input, but should be given the
  18298. strings that are created by the getTextDescription() method.
  18299. If the string can't be parsed, the object returned will be invalid.
  18300. @see getTextDescription
  18301. */
  18302. static const KeyPress createFromDescription (const String& textVersion);
  18303. /** Creates a textual description of the key combination.
  18304. e.g. "CTRL + C" or "DELETE".
  18305. To store a keypress in a file, use this method, along with createFromDescription()
  18306. to retrieve it later.
  18307. */
  18308. const String getTextDescription() const;
  18309. /** Creates a textual description of the key combination, using unicode icon symbols if possible.
  18310. On OSX, this uses the Apple symbols for command, option, shift, etc, instead of the textual
  18311. modifier key descriptions that are returned by getTextDescription()
  18312. */
  18313. const String getTextDescriptionWithIcons() const;
  18314. /** Checks whether the user is currently holding down the keys that make up this
  18315. KeyPress.
  18316. Note that this will return false if any extra modifier keys are
  18317. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  18318. then it will be false.
  18319. */
  18320. bool isCurrentlyDown() const;
  18321. /** Checks whether a particular key is held down, irrespective of modifiers.
  18322. The values for key codes can either be one of the special constants defined in
  18323. this class, or an 8-bit character code.
  18324. */
  18325. static bool isKeyCurrentlyDown (int keyCode);
  18326. // Key codes
  18327. //
  18328. // Note that the actual values of these are platform-specific and may change
  18329. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  18330. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  18331. //
  18332. static const int spaceKey; /**< key-code for the space bar */
  18333. static const int escapeKey; /**< key-code for the escape key */
  18334. static const int returnKey; /**< key-code for the return key*/
  18335. static const int tabKey; /**< key-code for the tab key*/
  18336. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  18337. static const int backspaceKey; /**< key-code for the backspace key */
  18338. static const int insertKey; /**< key-code for the insert key */
  18339. static const int upKey; /**< key-code for the cursor-up key */
  18340. static const int downKey; /**< key-code for the cursor-down key */
  18341. static const int leftKey; /**< key-code for the cursor-left key */
  18342. static const int rightKey; /**< key-code for the cursor-right key */
  18343. static const int pageUpKey; /**< key-code for the page-up key */
  18344. static const int pageDownKey; /**< key-code for the page-down key */
  18345. static const int homeKey; /**< key-code for the home key */
  18346. static const int endKey; /**< key-code for the end key */
  18347. static const int F1Key; /**< key-code for the F1 key */
  18348. static const int F2Key; /**< key-code for the F2 key */
  18349. static const int F3Key; /**< key-code for the F3 key */
  18350. static const int F4Key; /**< key-code for the F4 key */
  18351. static const int F5Key; /**< key-code for the F5 key */
  18352. static const int F6Key; /**< key-code for the F6 key */
  18353. static const int F7Key; /**< key-code for the F7 key */
  18354. static const int F8Key; /**< key-code for the F8 key */
  18355. static const int F9Key; /**< key-code for the F9 key */
  18356. static const int F10Key; /**< key-code for the F10 key */
  18357. static const int F11Key; /**< key-code for the F11 key */
  18358. static const int F12Key; /**< key-code for the F12 key */
  18359. static const int F13Key; /**< key-code for the F13 key */
  18360. static const int F14Key; /**< key-code for the F14 key */
  18361. static const int F15Key; /**< key-code for the F15 key */
  18362. static const int F16Key; /**< key-code for the F16 key */
  18363. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  18364. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  18365. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  18366. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  18367. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  18368. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  18369. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  18370. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  18371. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  18372. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  18373. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  18374. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  18375. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  18376. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  18377. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  18378. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  18379. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  18380. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  18381. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  18382. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  18383. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  18384. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  18385. private:
  18386. int keyCode;
  18387. ModifierKeys mods;
  18388. juce_wchar textCharacter;
  18389. JUCE_LEAK_DETECTOR (KeyPress);
  18390. };
  18391. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  18392. /*** End of inlined file: juce_KeyPress.h ***/
  18393. class Component;
  18394. /**
  18395. Receives callbacks when keys are pressed.
  18396. You can add a key listener to a component to be informed when that component
  18397. gets key events. See the Component::addListener method for more details.
  18398. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  18399. */
  18400. class JUCE_API KeyListener
  18401. {
  18402. public:
  18403. /** Destructor. */
  18404. virtual ~KeyListener() {}
  18405. /** Called to indicate that a key has been pressed.
  18406. If your implementation returns true, then the key event is considered to have
  18407. been consumed, and will not be passed on to any other components. If it returns
  18408. false, then the key will be passed to other components that might want to use it.
  18409. @param key the keystroke, including modifier keys
  18410. @param originatingComponent the component that received the key event
  18411. @see keyStateChanged, Component::keyPressed
  18412. */
  18413. virtual bool keyPressed (const KeyPress& key,
  18414. Component* originatingComponent) = 0;
  18415. /** Called when any key is pressed or released.
  18416. When this is called, classes that might be interested in
  18417. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  18418. check whether their key has changed.
  18419. If your implementation returns true, then the key event is considered to have
  18420. been consumed, and will not be passed on to any other components. If it returns
  18421. false, then the key will be passed to other components that might want to use it.
  18422. @param originatingComponent the component that received the key event
  18423. @param isKeyDown true if a key is being pressed, false if one is being released
  18424. @see KeyPress, Component::keyStateChanged
  18425. */
  18426. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  18427. };
  18428. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  18429. /*** End of inlined file: juce_KeyListener.h ***/
  18430. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  18431. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  18432. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  18433. class Component;
  18434. /**
  18435. Controls the order in which focus moves between components.
  18436. The default algorithm used by this class to work out the order of traversal
  18437. is as follows:
  18438. - if two components both have an explicit focus order specified, then the
  18439. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  18440. method).
  18441. - any component with an explicit focus order greater than 0 comes before ones
  18442. that don't have an order specified.
  18443. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  18444. order.
  18445. If you need traversal in a more customised way, you can create a subclass
  18446. of KeyboardFocusTraverser that uses your own algorithm, and use
  18447. Component::createFocusTraverser() to create it.
  18448. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  18449. */
  18450. class JUCE_API KeyboardFocusTraverser
  18451. {
  18452. public:
  18453. KeyboardFocusTraverser();
  18454. /** Destructor. */
  18455. virtual ~KeyboardFocusTraverser();
  18456. /** Returns the component that should be given focus after the specified one
  18457. when moving "forwards".
  18458. The default implementation will return the next component which is to the
  18459. right of or below this one.
  18460. This may return 0 if there's no suitable candidate.
  18461. */
  18462. virtual Component* getNextComponent (Component* current);
  18463. /** Returns the component that should be given focus after the specified one
  18464. when moving "backwards".
  18465. The default implementation will return the next component which is to the
  18466. left of or above this one.
  18467. This may return 0 if there's no suitable candidate.
  18468. */
  18469. virtual Component* getPreviousComponent (Component* current);
  18470. /** Returns the component that should receive focus be default within the given
  18471. parent component.
  18472. The default implementation will just return the foremost child component that
  18473. wants focus.
  18474. This may return 0 if there's no suitable candidate.
  18475. */
  18476. virtual Component* getDefaultComponent (Component* parentComponent);
  18477. };
  18478. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  18479. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  18480. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  18481. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  18482. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  18483. /*** Start of inlined file: juce_Graphics.h ***/
  18484. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  18485. #define __JUCE_GRAPHICS_JUCEHEADER__
  18486. /*** Start of inlined file: juce_Font.h ***/
  18487. #ifndef __JUCE_FONT_JUCEHEADER__
  18488. #define __JUCE_FONT_JUCEHEADER__
  18489. /*** Start of inlined file: juce_Typeface.h ***/
  18490. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  18491. #define __JUCE_TYPEFACE_JUCEHEADER__
  18492. /*** Start of inlined file: juce_Path.h ***/
  18493. #ifndef __JUCE_PATH_JUCEHEADER__
  18494. #define __JUCE_PATH_JUCEHEADER__
  18495. /*** Start of inlined file: juce_Line.h ***/
  18496. #ifndef __JUCE_LINE_JUCEHEADER__
  18497. #define __JUCE_LINE_JUCEHEADER__
  18498. /**
  18499. Represents a line.
  18500. This class contains a bunch of useful methods for various geometric
  18501. tasks.
  18502. The ValueType template parameter should be a primitive type - float or double
  18503. are what it's designed for. Integer types will work in a basic way, but some methods
  18504. that perform mathematical operations may not compile, or they may not produce
  18505. sensible results.
  18506. @see Point, Rectangle, Path, Graphics::drawLine
  18507. */
  18508. template <typename ValueType>
  18509. class Line
  18510. {
  18511. public:
  18512. /** Creates a line, using (0, 0) as its start and end points. */
  18513. Line() throw() {}
  18514. /** Creates a copy of another line. */
  18515. Line (const Line& other) throw()
  18516. : start (other.start),
  18517. end (other.end)
  18518. {
  18519. }
  18520. /** Creates a line based on the co-ordinates of its start and end points. */
  18521. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) throw()
  18522. : start (startX, startY),
  18523. end (endX, endY)
  18524. {
  18525. }
  18526. /** Creates a line from its start and end points. */
  18527. Line (const Point<ValueType>& startPoint,
  18528. const Point<ValueType>& endPoint) throw()
  18529. : start (startPoint),
  18530. end (endPoint)
  18531. {
  18532. }
  18533. /** Copies a line from another one. */
  18534. Line& operator= (const Line& other) throw()
  18535. {
  18536. start = other.start;
  18537. end = other.end;
  18538. return *this;
  18539. }
  18540. /** Destructor. */
  18541. ~Line() throw() {}
  18542. /** Returns the x co-ordinate of the line's start point. */
  18543. inline ValueType getStartX() const throw() { return start.getX(); }
  18544. /** Returns the y co-ordinate of the line's start point. */
  18545. inline ValueType getStartY() const throw() { return start.getY(); }
  18546. /** Returns the x co-ordinate of the line's end point. */
  18547. inline ValueType getEndX() const throw() { return end.getX(); }
  18548. /** Returns the y co-ordinate of the line's end point. */
  18549. inline ValueType getEndY() const throw() { return end.getY(); }
  18550. /** Returns the line's start point. */
  18551. inline const Point<ValueType>& getStart() const throw() { return start; }
  18552. /** Returns the line's end point. */
  18553. inline const Point<ValueType>& getEnd() const throw() { return end; }
  18554. /** Changes this line's start point */
  18555. void setStart (ValueType newStartX, ValueType newStartY) throw() { start.setXY (newStartX, newStartY); }
  18556. /** Changes this line's end point */
  18557. void setEnd (ValueType newEndX, ValueType newEndY) throw() { end.setXY (newEndX, newEndY); }
  18558. /** Changes this line's start point */
  18559. void setStart (const Point<ValueType>& newStart) throw() { start = newStart; }
  18560. /** Changes this line's end point */
  18561. void setEnd (const Point<ValueType>& newEnd) throw() { end = newEnd; }
  18562. /** Returns a line that is the same as this one, but with the start and end reversed, */
  18563. const Line reversed() const throw() { return Line (end, start); }
  18564. /** Applies an affine transform to the line's start and end points. */
  18565. void applyTransform (const AffineTransform& transform) throw()
  18566. {
  18567. start.applyTransform (transform);
  18568. end.applyTransform (transform);
  18569. }
  18570. /** Returns the length of the line. */
  18571. ValueType getLength() const throw() { return start.getDistanceFrom (end); }
  18572. /** Returns true if the line's start and end x co-ordinates are the same. */
  18573. bool isVertical() const throw() { return start.getX() == end.getX(); }
  18574. /** Returns true if the line's start and end y co-ordinates are the same. */
  18575. bool isHorizontal() const throw() { return start.getY() == end.getY(); }
  18576. /** Returns the line's angle.
  18577. This value is the number of radians clockwise from the 3 o'clock direction,
  18578. where the line's start point is considered to be at the centre.
  18579. */
  18580. ValueType getAngle() const throw() { return start.getAngleToPoint (end); }
  18581. /** Compares two lines. */
  18582. bool operator== (const Line& other) const throw() { return start == other.start && end == other.end; }
  18583. /** Compares two lines. */
  18584. bool operator!= (const Line& other) const throw() { return start != other.start || end != other.end; }
  18585. /** Finds the intersection between two lines.
  18586. @param line the other line
  18587. @param intersection the position of the point where the lines meet (or
  18588. where they would meet if they were infinitely long)
  18589. the intersection (if the lines intersect). If the lines
  18590. are parallel, this will just be set to the position
  18591. of one of the line's endpoints.
  18592. @returns true if the line segments intersect; false if they dont. Even if they
  18593. don't intersect, the intersection co-ordinates returned will still
  18594. be valid
  18595. */
  18596. bool intersects (const Line& line, Point<ValueType>& intersection) const throw()
  18597. {
  18598. return findIntersection (start, end, line.start, line.end, intersection);
  18599. }
  18600. /** Finds the intersection between two lines.
  18601. @param line the line to intersect with
  18602. @returns the point at which the lines intersect, even if this lies beyond the end of the lines
  18603. */
  18604. const Point<ValueType> getIntersection (const Line& line) const throw()
  18605. {
  18606. Point<ValueType> p;
  18607. findIntersection (start, end, line.start, line.end, p);
  18608. return p;
  18609. }
  18610. /** Returns the location of the point which is a given distance along this line.
  18611. @param distanceFromStart the distance to move along the line from its
  18612. start point. This value can be negative or longer
  18613. than the line itself
  18614. @see getPointAlongLineProportionally
  18615. */
  18616. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const throw()
  18617. {
  18618. return start + (end - start) * (distanceFromStart / getLength());
  18619. }
  18620. /** Returns a point which is a certain distance along and to the side of this line.
  18621. This effectively moves a given distance along the line, then another distance
  18622. perpendicularly to this, and returns the resulting position.
  18623. @param distanceFromStart the distance to move along the line from its
  18624. start point. This value can be negative or longer
  18625. than the line itself
  18626. @param perpendicularDistance how far to move sideways from the line. If you're
  18627. looking along the line from its start towards its
  18628. end, then a positive value here will move to the
  18629. right, negative value move to the left.
  18630. */
  18631. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  18632. ValueType perpendicularDistance) const throw()
  18633. {
  18634. const Point<ValueType> delta (end - start);
  18635. const double length = juce_hypot ((double) delta.getX(),
  18636. (double) delta.getY());
  18637. if (length <= 0)
  18638. return start;
  18639. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  18640. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  18641. }
  18642. /** Returns the location of the point which is a given distance along this line
  18643. proportional to the line's length.
  18644. @param proportionOfLength the distance to move along the line from its
  18645. start point, in multiples of the line's length.
  18646. So a value of 0.0 will return the line's start point
  18647. and a value of 1.0 will return its end point. (This value
  18648. can be negative or greater than 1.0).
  18649. @see getPointAlongLine
  18650. */
  18651. const Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const throw()
  18652. {
  18653. return start + (end - start) * proportionOfLength;
  18654. }
  18655. /** Returns the smallest distance between this line segment and a given point.
  18656. So if the point is close to the line, this will return the perpendicular
  18657. distance from the line; if the point is a long way beyond one of the line's
  18658. end-point's, it'll return the straight-line distance to the nearest end-point.
  18659. pointOnLine receives the position of the point that is found.
  18660. @returns the point's distance from the line
  18661. @see getPositionAlongLineOfNearestPoint
  18662. */
  18663. ValueType getDistanceFromPoint (const Point<ValueType>& targetPoint,
  18664. Point<ValueType>& pointOnLine) const throw()
  18665. {
  18666. const Point<ValueType> delta (end - start);
  18667. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  18668. if (length > 0)
  18669. {
  18670. const double prop = ((targetPoint.getX() - start.getX()) * delta.getX()
  18671. + (targetPoint.getY() - start.getY()) * delta.getY()) / length;
  18672. if (prop >= 0 && prop <= 1.0)
  18673. {
  18674. pointOnLine = start + delta * (ValueType) prop;
  18675. return targetPoint.getDistanceFrom (pointOnLine);
  18676. }
  18677. }
  18678. const float fromStart = targetPoint.getDistanceFrom (start);
  18679. const float fromEnd = targetPoint.getDistanceFrom (end);
  18680. if (fromStart < fromEnd)
  18681. {
  18682. pointOnLine = start;
  18683. return fromStart;
  18684. }
  18685. else
  18686. {
  18687. pointOnLine = end;
  18688. return fromEnd;
  18689. }
  18690. }
  18691. /** Finds the point on this line which is nearest to a given point, and
  18692. returns its position as a proportional position along the line.
  18693. @returns a value 0 to 1.0 which is the distance along this line from the
  18694. line's start to the point which is nearest to the point passed-in. To
  18695. turn this number into a position, use getPointAlongLineProportionally().
  18696. @see getDistanceFromPoint, getPointAlongLineProportionally
  18697. */
  18698. ValueType findNearestProportionalPositionTo (const Point<ValueType>& point) const throw()
  18699. {
  18700. const Point<ValueType> delta (end - start);
  18701. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  18702. return length <= 0 ? 0
  18703. : jlimit ((ValueType) 0, (ValueType) 1,
  18704. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  18705. + (point.getY() - start.getY()) * delta.getY()) / length));
  18706. }
  18707. /** Finds the point on this line which is nearest to a given point.
  18708. @see getDistanceFromPoint, findNearestProportionalPositionTo
  18709. */
  18710. const Point<ValueType> findNearestPointTo (const Point<ValueType>& point) const throw()
  18711. {
  18712. return getPointAlongLineProportionally (findNearestProportionalPositionTo (point));
  18713. }
  18714. /** Returns true if the given point lies above this line.
  18715. The return value is true if the point's y coordinate is less than the y
  18716. coordinate of this line at the given x (assuming the line extends infinitely
  18717. in both directions).
  18718. */
  18719. bool isPointAbove (const Point<ValueType>& point) const throw()
  18720. {
  18721. return start.getX() != end.getX()
  18722. && point.getY() < ((end.getY() - start.getY())
  18723. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  18724. }
  18725. /** Returns a shortened copy of this line.
  18726. This will chop off part of the start of this line by a certain amount, (leaving the
  18727. end-point the same), and return the new line.
  18728. */
  18729. const Line withShortenedStart (ValueType distanceToShortenBy) const throw()
  18730. {
  18731. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  18732. }
  18733. /** Returns a shortened copy of this line.
  18734. This will chop off part of the end of this line by a certain amount, (leaving the
  18735. start-point the same), and return the new line.
  18736. */
  18737. const Line withShortenedEnd (ValueType distanceToShortenBy) const throw()
  18738. {
  18739. const ValueType length = getLength();
  18740. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  18741. }
  18742. private:
  18743. Point<ValueType> start, end;
  18744. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  18745. const Point<ValueType>& p3, const Point<ValueType>& p4,
  18746. Point<ValueType>& intersection) throw()
  18747. {
  18748. if (p2 == p3)
  18749. {
  18750. intersection = p2;
  18751. return true;
  18752. }
  18753. const Point<ValueType> d1 (p2 - p1);
  18754. const Point<ValueType> d2 (p4 - p3);
  18755. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  18756. if (divisor == 0)
  18757. {
  18758. if (! (d1.isOrigin() || d2.isOrigin()))
  18759. {
  18760. if (d1.getY() == 0 && d2.getY() != 0)
  18761. {
  18762. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  18763. intersection = p1.withX (p3.getX() + along * d2.getX());
  18764. return along >= 0 && along <= (ValueType) 1;
  18765. }
  18766. else if (d2.getY() == 0 && d1.getY() != 0)
  18767. {
  18768. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  18769. intersection = p3.withX (p1.getX() + along * d1.getX());
  18770. return along >= 0 && along <= (ValueType) 1;
  18771. }
  18772. else if (d1.getX() == 0 && d2.getX() != 0)
  18773. {
  18774. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  18775. intersection = p1.withY (p3.getY() + along * d2.getY());
  18776. return along >= 0 && along <= (ValueType) 1;
  18777. }
  18778. else if (d2.getX() == 0 && d1.getX() != 0)
  18779. {
  18780. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  18781. intersection = p3.withY (p1.getY() + along * d1.getY());
  18782. return along >= 0 && along <= (ValueType) 1;
  18783. }
  18784. }
  18785. intersection = (p2 + p3) / (ValueType) 2;
  18786. return false;
  18787. }
  18788. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  18789. intersection = p1 + d1 * along1;
  18790. if (along1 < 0 || along1 > (ValueType) 1)
  18791. return false;
  18792. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  18793. return along2 >= 0 && along2 <= (ValueType) 1;
  18794. }
  18795. };
  18796. #endif // __JUCE_LINE_JUCEHEADER__
  18797. /*** End of inlined file: juce_Line.h ***/
  18798. /*** Start of inlined file: juce_Rectangle.h ***/
  18799. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  18800. #define __JUCE_RECTANGLE_JUCEHEADER__
  18801. class RectangleList;
  18802. /**
  18803. Manages a rectangle and allows geometric operations to be performed on it.
  18804. @see RectangleList, Path, Line, Point
  18805. */
  18806. template <typename ValueType>
  18807. class Rectangle
  18808. {
  18809. public:
  18810. /** Creates a rectangle of zero size.
  18811. The default co-ordinates will be (0, 0, 0, 0).
  18812. */
  18813. Rectangle() throw()
  18814. : x(), y(), w(), h()
  18815. {
  18816. }
  18817. /** Creates a copy of another rectangle. */
  18818. Rectangle (const Rectangle& other) throw()
  18819. : x (other.x), y (other.y),
  18820. w (other.w), h (other.h)
  18821. {
  18822. }
  18823. /** Creates a rectangle with a given position and size. */
  18824. Rectangle (const ValueType initialX, const ValueType initialY,
  18825. const ValueType width, const ValueType height) throw()
  18826. : x (initialX), y (initialY),
  18827. w (width), h (height)
  18828. {
  18829. }
  18830. /** Creates a rectangle with a given size, and a position of (0, 0). */
  18831. Rectangle (const ValueType width, const ValueType height) throw()
  18832. : x(), y(), w (width), h (height)
  18833. {
  18834. }
  18835. /** Creates a Rectangle from the positions of two opposite corners. */
  18836. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) throw()
  18837. : x (jmin (corner1.getX(), corner2.getX())),
  18838. y (jmin (corner1.getY(), corner2.getY())),
  18839. w (corner1.getX() - corner2.getX()),
  18840. h (corner1.getY() - corner2.getY())
  18841. {
  18842. if (w < ValueType()) w = -w;
  18843. if (h < ValueType()) h = -h;
  18844. }
  18845. /** Creates a Rectangle from a set of left, right, top, bottom coordinates.
  18846. The right and bottom values must be larger than the left and top ones, or the resulting
  18847. rectangle will have a negative size.
  18848. */
  18849. static const Rectangle leftTopRightBottom (const ValueType left, const ValueType top,
  18850. const ValueType right, const ValueType bottom) throw()
  18851. {
  18852. return Rectangle (left, top, right - left, bottom - top);
  18853. }
  18854. Rectangle& operator= (const Rectangle& other) throw()
  18855. {
  18856. x = other.x; y = other.y;
  18857. w = other.w; h = other.h;
  18858. return *this;
  18859. }
  18860. /** Destructor. */
  18861. ~Rectangle() throw() {}
  18862. /** Returns true if the rectangle's width and height are both zero or less */
  18863. bool isEmpty() const throw() { return w <= ValueType() || h <= ValueType(); }
  18864. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  18865. inline ValueType getX() const throw() { return x; }
  18866. /** Returns the y co-ordinate of the rectangle's top edge. */
  18867. inline ValueType getY() const throw() { return y; }
  18868. /** Returns the width of the rectangle. */
  18869. inline ValueType getWidth() const throw() { return w; }
  18870. /** Returns the height of the rectangle. */
  18871. inline ValueType getHeight() const throw() { return h; }
  18872. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  18873. inline ValueType getRight() const throw() { return x + w; }
  18874. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  18875. inline ValueType getBottom() const throw() { return y + h; }
  18876. /** Returns the x co-ordinate of the rectangle's centre. */
  18877. ValueType getCentreX() const throw() { return x + w / (ValueType) 2; }
  18878. /** Returns the y co-ordinate of the rectangle's centre. */
  18879. ValueType getCentreY() const throw() { return y + h / (ValueType) 2; }
  18880. /** Returns the centre point of the rectangle. */
  18881. const Point<ValueType> getCentre() const throw() { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  18882. /** Returns the aspect ratio of the rectangle's width / height.
  18883. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  18884. it returns height / width. */
  18885. ValueType getAspectRatio (const bool widthOverHeight = true) const throw() { return widthOverHeight ? w / h : h / w; }
  18886. /** Returns the rectangle's top-left position as a Point. */
  18887. const Point<ValueType> getPosition() const throw() { return Point<ValueType> (x, y); }
  18888. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  18889. void setPosition (const Point<ValueType>& newPos) throw() { x = newPos.getX(); y = newPos.getY(); }
  18890. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  18891. void setPosition (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  18892. /** Returns a rectangle with the same size as this one, but a new position. */
  18893. const Rectangle withPosition (const ValueType newX, const ValueType newY) const throw() { return Rectangle (newX, newY, w, h); }
  18894. /** Returns a rectangle with the same size as this one, but a new position. */
  18895. const Rectangle withPosition (const Point<ValueType>& newPos) const throw() { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  18896. /** Returns the rectangle's top-left position as a Point. */
  18897. const Point<ValueType> getTopLeft() const throw() { return getPosition(); }
  18898. /** Returns the rectangle's top-right position as a Point. */
  18899. const Point<ValueType> getTopRight() const throw() { return Point<ValueType> (x + w, y); }
  18900. /** Returns the rectangle's bottom-left position as a Point. */
  18901. const Point<ValueType> getBottomLeft() const throw() { return Point<ValueType> (x, y + h); }
  18902. /** Returns the rectangle's bottom-right position as a Point. */
  18903. const Point<ValueType> getBottomRight() const throw() { return Point<ValueType> (x + w, y + h); }
  18904. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  18905. void setSize (const ValueType newWidth, const ValueType newHeight) throw() { w = newWidth; h = newHeight; }
  18906. /** Returns a rectangle with the same position as this one, but a new size. */
  18907. const Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const throw() { return Rectangle (x, y, newWidth, newHeight); }
  18908. /** Changes all the rectangle's co-ordinates. */
  18909. void setBounds (const ValueType newX, const ValueType newY,
  18910. const ValueType newWidth, const ValueType newHeight) throw()
  18911. {
  18912. x = newX; y = newY; w = newWidth; h = newHeight;
  18913. }
  18914. /** Changes the rectangle's X coordinate */
  18915. void setX (const ValueType newX) throw() { x = newX; }
  18916. /** Changes the rectangle's Y coordinate */
  18917. void setY (const ValueType newY) throw() { y = newY; }
  18918. /** Changes the rectangle's width */
  18919. void setWidth (const ValueType newWidth) throw() { w = newWidth; }
  18920. /** Changes the rectangle's height */
  18921. void setHeight (const ValueType newHeight) throw() { h = newHeight; }
  18922. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  18923. const Rectangle withX (const ValueType newX) const throw() { return Rectangle (newX, y, w, h); }
  18924. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  18925. const Rectangle withY (const ValueType newY) const throw() { return Rectangle (x, newY, w, h); }
  18926. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  18927. const Rectangle withWidth (const ValueType newWidth) const throw() { return Rectangle (x, y, newWidth, h); }
  18928. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  18929. const Rectangle withHeight (const ValueType newHeight) const throw() { return Rectangle (x, y, w, newHeight); }
  18930. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  18931. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  18932. @see withLeft
  18933. */
  18934. void setLeft (const ValueType newLeft) throw()
  18935. {
  18936. w = jmax (ValueType(), x + w - newLeft);
  18937. x = newLeft;
  18938. }
  18939. /** Returns a new rectangle with a different x position, but the same right-hand edge as this one.
  18940. If the new x is beyond the right of the current right-hand edge, the width will be set to zero.
  18941. @see setLeft
  18942. */
  18943. const Rectangle withLeft (const ValueType newLeft) const throw() { return Rectangle (newLeft, y, jmax (ValueType(), x + w - newLeft), h); }
  18944. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  18945. If the y is moved to be below the current bottom edge, the height will be set to zero.
  18946. @see withTop
  18947. */
  18948. void setTop (const ValueType newTop) throw()
  18949. {
  18950. h = jmax (ValueType(), y + h - newTop);
  18951. y = newTop;
  18952. }
  18953. /** Returns a new rectangle with a different y position, but the same bottom edge as this one.
  18954. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  18955. @see setTop
  18956. */
  18957. const Rectangle withTop (const ValueType newTop) const throw() { return Rectangle (x, newTop, w, jmax (ValueType(), y + h - newTop)); }
  18958. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  18959. If the new right is below the current X value, the X will be pushed down to match it.
  18960. @see getRight, withRight
  18961. */
  18962. void setRight (const ValueType newRight) throw()
  18963. {
  18964. x = jmin (x, newRight);
  18965. w = newRight - x;
  18966. }
  18967. /** Returns a new rectangle with a different right-hand edge position, but the same left-hand edge as this one.
  18968. If the new right edge is below the current left-hand edge, the width will be set to zero.
  18969. @see setRight
  18970. */
  18971. const Rectangle withRight (const ValueType newRight) const throw() { return Rectangle (jmin (x, newRight), y, jmax (ValueType(), newRight - x), h); }
  18972. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  18973. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  18974. @see getBottom, withBottom
  18975. */
  18976. void setBottom (const ValueType newBottom) throw()
  18977. {
  18978. y = jmin (y, newBottom);
  18979. h = newBottom - y;
  18980. }
  18981. /** Returns a new rectangle with a different bottom edge position, but the same top edge as this one.
  18982. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  18983. @see setBottom
  18984. */
  18985. const Rectangle withBottom (const ValueType newBottom) const throw() { return Rectangle (x, jmin (y, newBottom), w, jmax (ValueType(), newBottom - y)); }
  18986. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  18987. void translate (const ValueType deltaX,
  18988. const ValueType deltaY) throw()
  18989. {
  18990. x += deltaX;
  18991. y += deltaY;
  18992. }
  18993. /** Returns a rectangle which is the same as this one moved by a given amount. */
  18994. const Rectangle translated (const ValueType deltaX,
  18995. const ValueType deltaY) const throw()
  18996. {
  18997. return Rectangle (x + deltaX, y + deltaY, w, h);
  18998. }
  18999. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19000. const Rectangle operator+ (const Point<ValueType>& deltaPosition) const throw()
  19001. {
  19002. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  19003. }
  19004. /** Moves this rectangle by a given amount. */
  19005. Rectangle& operator+= (const Point<ValueType>& deltaPosition) throw()
  19006. {
  19007. x += deltaPosition.getX(); y += deltaPosition.getY();
  19008. return *this;
  19009. }
  19010. /** Returns a rectangle which is the same as this one moved by a given amount. */
  19011. const Rectangle operator- (const Point<ValueType>& deltaPosition) const throw()
  19012. {
  19013. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  19014. }
  19015. /** Moves this rectangle by a given amount. */
  19016. Rectangle& operator-= (const Point<ValueType>& deltaPosition) throw()
  19017. {
  19018. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  19019. return *this;
  19020. }
  19021. /** Expands the rectangle by a given amount.
  19022. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  19023. @see expanded, reduce, reduced
  19024. */
  19025. void expand (const ValueType deltaX,
  19026. const ValueType deltaY) throw()
  19027. {
  19028. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  19029. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  19030. setBounds (x - deltaX, y - deltaY, nw, nh);
  19031. }
  19032. /** Returns a rectangle that is larger than this one by a given amount.
  19033. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  19034. @see expand, reduce, reduced
  19035. */
  19036. const Rectangle expanded (const ValueType deltaX,
  19037. const ValueType deltaY) const throw()
  19038. {
  19039. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  19040. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  19041. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  19042. }
  19043. /** Shrinks the rectangle by a given amount.
  19044. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  19045. @see reduced, expand, expanded
  19046. */
  19047. void reduce (const ValueType deltaX,
  19048. const ValueType deltaY) throw()
  19049. {
  19050. expand (-deltaX, -deltaY);
  19051. }
  19052. /** Returns a rectangle that is smaller than this one by a given amount.
  19053. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  19054. @see reduce, expand, expanded
  19055. */
  19056. const Rectangle reduced (const ValueType deltaX,
  19057. const ValueType deltaY) const throw()
  19058. {
  19059. return expanded (-deltaX, -deltaY);
  19060. }
  19061. /** Removes a strip from the top of this rectangle, reducing this rectangle
  19062. by the specified amount and returning the section that was removed.
  19063. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19064. return (100, 100, 300, 50) and leave this rectangle as (100, 150, 300, 250).
  19065. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  19066. that value.
  19067. */
  19068. const Rectangle removeFromTop (const ValueType amountToRemove) throw()
  19069. {
  19070. const Rectangle r (x, y, w, jmin (amountToRemove, h));
  19071. y += r.h; h -= r.h;
  19072. return r;
  19073. }
  19074. /** Removes a strip from the left-hand edge of this rectangle, reducing this rectangle
  19075. by the specified amount and returning the section that was removed.
  19076. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19077. return (100, 100, 50, 300) and leave this rectangle as (150, 100, 250, 300).
  19078. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19079. that value.
  19080. */
  19081. const Rectangle removeFromLeft (const ValueType amountToRemove) throw()
  19082. {
  19083. const Rectangle r (x, y, jmin (amountToRemove, w), h);
  19084. x += r.w; w -= r.w;
  19085. return r;
  19086. }
  19087. /** Removes a strip from the right-hand edge of this rectangle, reducing this rectangle
  19088. by the specified amount and returning the section that was removed.
  19089. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19090. return (250, 100, 50, 300) and leave this rectangle as (100, 100, 250, 300).
  19091. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19092. that value.
  19093. */
  19094. const Rectangle removeFromRight (ValueType amountToRemove) throw()
  19095. {
  19096. amountToRemove = jmin (amountToRemove, w);
  19097. const Rectangle r (x + w - amountToRemove, y, amountToRemove, h);
  19098. w -= amountToRemove;
  19099. return r;
  19100. }
  19101. /** Removes a strip from the bottom of this rectangle, reducing this rectangle
  19102. by the specified amount and returning the section that was removed.
  19103. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19104. return (100, 250, 300, 50) and leave this rectangle as (100, 100, 300, 250).
  19105. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  19106. that value.
  19107. */
  19108. const Rectangle removeFromBottom (ValueType amountToRemove) throw()
  19109. {
  19110. amountToRemove = jmin (amountToRemove, h);
  19111. const Rectangle r (x, y + h - amountToRemove, w, amountToRemove);
  19112. h -= amountToRemove;
  19113. return r;
  19114. }
  19115. /** Returns true if the two rectangles are identical. */
  19116. bool operator== (const Rectangle& other) const throw()
  19117. {
  19118. return x == other.x && y == other.y
  19119. && w == other.w && h == other.h;
  19120. }
  19121. /** Returns true if the two rectangles are not identical. */
  19122. bool operator!= (const Rectangle& other) const throw()
  19123. {
  19124. return x != other.x || y != other.y
  19125. || w != other.w || h != other.h;
  19126. }
  19127. /** Returns true if this co-ordinate is inside the rectangle. */
  19128. bool contains (const ValueType xCoord, const ValueType yCoord) const throw()
  19129. {
  19130. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  19131. }
  19132. /** Returns true if this co-ordinate is inside the rectangle. */
  19133. bool contains (const Point<ValueType>& point) const throw()
  19134. {
  19135. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  19136. }
  19137. /** Returns true if this other rectangle is completely inside this one. */
  19138. bool contains (const Rectangle& other) const throw()
  19139. {
  19140. return x <= other.x && y <= other.y
  19141. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  19142. }
  19143. /** Returns the nearest point to the specified point that lies within this rectangle. */
  19144. const Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const throw()
  19145. {
  19146. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  19147. jlimit (y, y + h, point.getY()));
  19148. }
  19149. /** Returns true if any part of another rectangle overlaps this one. */
  19150. bool intersects (const Rectangle& other) const throw()
  19151. {
  19152. return x + w > other.x
  19153. && y + h > other.y
  19154. && x < other.x + other.w
  19155. && y < other.y + other.h
  19156. && w > ValueType() && h > ValueType();
  19157. }
  19158. /** Returns the region that is the overlap between this and another rectangle.
  19159. If the two rectangles don't overlap, the rectangle returned will be empty.
  19160. */
  19161. const Rectangle getIntersection (const Rectangle& other) const throw()
  19162. {
  19163. const ValueType nx = jmax (x, other.x);
  19164. const ValueType ny = jmax (y, other.y);
  19165. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  19166. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  19167. if (nw >= ValueType() && nh >= ValueType())
  19168. return Rectangle (nx, ny, nw, nh);
  19169. return Rectangle();
  19170. }
  19171. /** Clips a rectangle so that it lies only within this one.
  19172. This is a non-static version of intersectRectangles().
  19173. Returns false if the two regions didn't overlap.
  19174. */
  19175. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const throw()
  19176. {
  19177. const int maxX = jmax (otherX, x);
  19178. otherW = jmin (otherX + otherW, x + w) - maxX;
  19179. if (otherW > ValueType())
  19180. {
  19181. const int maxY = jmax (otherY, y);
  19182. otherH = jmin (otherY + otherH, y + h) - maxY;
  19183. if (otherH > ValueType())
  19184. {
  19185. otherX = maxX; otherY = maxY;
  19186. return true;
  19187. }
  19188. }
  19189. return false;
  19190. }
  19191. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  19192. If either this or the other rectangle are empty, they will not be counted as
  19193. part of the resulting region.
  19194. */
  19195. const Rectangle getUnion (const Rectangle& other) const throw()
  19196. {
  19197. if (other.isEmpty()) return *this;
  19198. if (isEmpty()) return other;
  19199. const ValueType newX = jmin (x, other.x);
  19200. const ValueType newY = jmin (y, other.y);
  19201. return Rectangle (newX, newY,
  19202. jmax (x + w, other.x + other.w) - newX,
  19203. jmax (y + h, other.y + other.h) - newY);
  19204. }
  19205. /** If this rectangle merged with another one results in a simple rectangle, this
  19206. will set this rectangle to the result, and return true.
  19207. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  19208. or if they form a complex region.
  19209. */
  19210. bool enlargeIfAdjacent (const Rectangle& other) throw()
  19211. {
  19212. if (x == other.x && getRight() == other.getRight()
  19213. && (other.getBottom() >= y && other.y <= getBottom()))
  19214. {
  19215. const ValueType newY = jmin (y, other.y);
  19216. h = jmax (getBottom(), other.getBottom()) - newY;
  19217. y = newY;
  19218. return true;
  19219. }
  19220. else if (y == other.y && getBottom() == other.getBottom()
  19221. && (other.getRight() >= x && other.x <= getRight()))
  19222. {
  19223. const ValueType newX = jmin (x, other.x);
  19224. w = jmax (getRight(), other.getRight()) - newX;
  19225. x = newX;
  19226. return true;
  19227. }
  19228. return false;
  19229. }
  19230. /** If after removing another rectangle from this one the result is a simple rectangle,
  19231. this will set this object's bounds to be the result, and return true.
  19232. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  19233. or if removing the other one would form a complex region.
  19234. */
  19235. bool reduceIfPartlyContainedIn (const Rectangle& other) throw()
  19236. {
  19237. int inside = 0;
  19238. const int otherR = other.getRight();
  19239. if (x >= other.x && x < otherR) inside = 1;
  19240. const int otherB = other.getBottom();
  19241. if (y >= other.y && y < otherB) inside |= 2;
  19242. const int r = x + w;
  19243. if (r >= other.x && r < otherR) inside |= 4;
  19244. const int b = y + h;
  19245. if (b >= other.y && b < otherB) inside |= 8;
  19246. switch (inside)
  19247. {
  19248. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  19249. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  19250. case 2 + 4 + 8: w = other.x - x; return true;
  19251. case 1 + 4 + 8: h = other.y - y; return true;
  19252. }
  19253. return false;
  19254. }
  19255. /** Returns the smallest rectangle that can contain the shape created by applying
  19256. a transform to this rectangle.
  19257. This should only be used on floating point rectangles.
  19258. */
  19259. const Rectangle transformed (const AffineTransform& transform) const throw()
  19260. {
  19261. float x1 = x, y1 = y;
  19262. float x2 = x + w, y2 = y;
  19263. float x3 = x, y3 = y + h;
  19264. float x4 = x2, y4 = y3;
  19265. transform.transformPoints (x1, y1, x2, y2);
  19266. transform.transformPoints (x3, y3, x4, y4);
  19267. const float rx = jmin (x1, x2, x3, x4);
  19268. const float ry = jmin (y1, y2, y3, y4);
  19269. return Rectangle (rx, ry,
  19270. jmax (x1, x2, x3, x4) - rx,
  19271. jmax (y1, y2, y3, y4) - ry);
  19272. }
  19273. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  19274. This is only relevent for floating-point rectangles, of course.
  19275. @see toFloat()
  19276. */
  19277. const Rectangle<int> getSmallestIntegerContainer() const throw()
  19278. {
  19279. const int x1 = (int) std::floor (static_cast<float> (x));
  19280. const int y1 = (int) std::floor (static_cast<float> (y));
  19281. const int x2 = (int) std::ceil (static_cast<float> (x + w));
  19282. const int y2 = (int) std::ceil (static_cast<float> (y + h));
  19283. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  19284. }
  19285. /** Returns the smallest Rectangle that can contain a set of points. */
  19286. static const Rectangle findAreaContainingPoints (const Point<ValueType>* const points, const int numPoints) throw()
  19287. {
  19288. if (numPoints == 0)
  19289. return Rectangle();
  19290. ValueType minX (points[0].getX());
  19291. ValueType maxX (minX);
  19292. ValueType minY (points[0].getY());
  19293. ValueType maxY (minY);
  19294. for (int i = 1; i < numPoints; ++i)
  19295. {
  19296. minX = jmin (minX, points[i].getX());
  19297. maxX = jmax (maxX, points[i].getX());
  19298. minY = jmin (minY, points[i].getY());
  19299. maxY = jmax (maxY, points[i].getY());
  19300. }
  19301. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  19302. }
  19303. /** Casts this rectangle to a Rectangle<float>.
  19304. Obviously this is mainly useful for rectangles that use integer types.
  19305. @see getSmallestIntegerContainer
  19306. */
  19307. const Rectangle<float> toFloat() const throw()
  19308. {
  19309. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  19310. static_cast<float> (w), static_cast<float> (h));
  19311. }
  19312. /** Static utility to intersect two sets of rectangular co-ordinates.
  19313. Returns false if the two regions didn't overlap.
  19314. @see intersectRectangle
  19315. */
  19316. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  19317. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) throw()
  19318. {
  19319. const ValueType x = jmax (x1, x2);
  19320. w1 = jmin (x1 + w1, x2 + w2) - x;
  19321. if (w1 > ValueType())
  19322. {
  19323. const ValueType y = jmax (y1, y2);
  19324. h1 = jmin (y1 + h1, y2 + h2) - y;
  19325. if (h1 > ValueType())
  19326. {
  19327. x1 = x; y1 = y;
  19328. return true;
  19329. }
  19330. }
  19331. return false;
  19332. }
  19333. /** Creates a string describing this rectangle.
  19334. The string will be of the form "x y width height", e.g. "100 100 400 200".
  19335. Coupled with the fromString() method, this is very handy for things like
  19336. storing rectangles (particularly component positions) in XML attributes.
  19337. @see fromString
  19338. */
  19339. const String toString() const
  19340. {
  19341. String s;
  19342. s.preallocateBytes (32);
  19343. s << x << ' ' << y << ' ' << w << ' ' << h;
  19344. return s;
  19345. }
  19346. /** Parses a string containing a rectangle's details.
  19347. The string should contain 4 integer tokens, in the form "x y width height". They
  19348. can be comma or whitespace separated.
  19349. This method is intended to go with the toString() method, to form an easy way
  19350. of saving/loading rectangles as strings.
  19351. @see toString
  19352. */
  19353. static const Rectangle fromString (const String& stringVersion)
  19354. {
  19355. StringArray toks;
  19356. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  19357. return Rectangle (toks[0].trim().getIntValue(),
  19358. toks[1].trim().getIntValue(),
  19359. toks[2].trim().getIntValue(),
  19360. toks[3].trim().getIntValue());
  19361. }
  19362. private:
  19363. friend class RectangleList;
  19364. ValueType x, y, w, h;
  19365. };
  19366. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  19367. /*** End of inlined file: juce_Rectangle.h ***/
  19368. /*** Start of inlined file: juce_Justification.h ***/
  19369. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  19370. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  19371. /**
  19372. Represents a type of justification to be used when positioning graphical items.
  19373. e.g. it indicates whether something should be placed top-left, top-right,
  19374. centred, etc.
  19375. It is used in various places wherever this kind of information is needed.
  19376. */
  19377. class JUCE_API Justification
  19378. {
  19379. public:
  19380. /** Creates a Justification object using a combination of flags. */
  19381. inline Justification (int flags_) throw() : flags (flags_) {}
  19382. /** Creates a copy of another Justification object. */
  19383. Justification (const Justification& other) throw();
  19384. /** Copies another Justification object. */
  19385. Justification& operator= (const Justification& other) throw();
  19386. bool operator== (const Justification& other) const throw() { return flags == other.flags; }
  19387. bool operator!= (const Justification& other) const throw() { return flags != other.flags; }
  19388. /** Returns the raw flags that are set for this Justification object. */
  19389. inline int getFlags() const throw() { return flags; }
  19390. /** Tests a set of flags for this object.
  19391. @returns true if any of the flags passed in are set on this object.
  19392. */
  19393. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  19394. /** Returns just the flags from this object that deal with vertical layout. */
  19395. int getOnlyVerticalFlags() const throw();
  19396. /** Returns just the flags from this object that deal with horizontal layout. */
  19397. int getOnlyHorizontalFlags() const throw();
  19398. /** Adjusts the position of a rectangle to fit it into a space.
  19399. The (x, y) position of the rectangle will be updated to position it inside the
  19400. given space according to the justification flags.
  19401. */
  19402. template <typename ValueType>
  19403. void applyToRectangle (ValueType& x, ValueType& y, ValueType w, ValueType h,
  19404. ValueType spaceX, ValueType spaceY, ValueType spaceW, ValueType spaceH) const throw()
  19405. {
  19406. x = spaceX;
  19407. if ((flags & horizontallyCentred) != 0) x += (spaceW - w) / (ValueType) 2;
  19408. else if ((flags & right) != 0) x += spaceW - w;
  19409. y = spaceY;
  19410. if ((flags & verticallyCentred) != 0) y += (spaceH - h) / (ValueType) 2;
  19411. else if ((flags & bottom) != 0) y += spaceH - h;
  19412. }
  19413. /** Returns the new position of a rectangle that has been justified to fit within a given space.
  19414. */
  19415. template <typename ValueType>
  19416. const Rectangle<ValueType> appliedToRectangle (const Rectangle<ValueType>& areaToAdjust,
  19417. const Rectangle<ValueType>& targetSpace) const throw()
  19418. {
  19419. ValueType x = areaToAdjust.getX(), y = areaToAdjust.getY();
  19420. applyToRectangle (x, y, areaToAdjust.getWidth(), areaToAdjust.getHeight(),
  19421. targetSpace.getX(), targetSpace.getY(), targetSpace.getWidth(), targetSpace.getHeight());
  19422. return areaToAdjust.withPosition (x, y);
  19423. }
  19424. /** Flag values that can be combined and used in the constructor. */
  19425. enum
  19426. {
  19427. /** Indicates that the item should be aligned against the left edge of the available space. */
  19428. left = 1,
  19429. /** Indicates that the item should be aligned against the right edge of the available space. */
  19430. right = 2,
  19431. /** Indicates that the item should be placed in the centre between the left and right
  19432. sides of the available space. */
  19433. horizontallyCentred = 4,
  19434. /** Indicates that the item should be aligned against the top edge of the available space. */
  19435. top = 8,
  19436. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  19437. bottom = 16,
  19438. /** Indicates that the item should be placed in the centre between the top and bottom
  19439. sides of the available space. */
  19440. verticallyCentred = 32,
  19441. /** Indicates that lines of text should be spread out to fill the maximum width
  19442. available, so that both margins are aligned vertically.
  19443. */
  19444. horizontallyJustified = 64,
  19445. /** Indicates that the item should be centred vertically and horizontally.
  19446. This is equivalent to (horizontallyCentred | verticallyCentred)
  19447. */
  19448. centred = 36,
  19449. /** Indicates that the item should be centred vertically but placed on the left hand side.
  19450. This is equivalent to (left | verticallyCentred)
  19451. */
  19452. centredLeft = 33,
  19453. /** Indicates that the item should be centred vertically but placed on the right hand side.
  19454. This is equivalent to (right | verticallyCentred)
  19455. */
  19456. centredRight = 34,
  19457. /** Indicates that the item should be centred horizontally and placed at the top.
  19458. This is equivalent to (horizontallyCentred | top)
  19459. */
  19460. centredTop = 12,
  19461. /** Indicates that the item should be centred horizontally and placed at the bottom.
  19462. This is equivalent to (horizontallyCentred | bottom)
  19463. */
  19464. centredBottom = 20,
  19465. /** Indicates that the item should be placed in the top-left corner.
  19466. This is equivalent to (left | top)
  19467. */
  19468. topLeft = 9,
  19469. /** Indicates that the item should be placed in the top-right corner.
  19470. This is equivalent to (right | top)
  19471. */
  19472. topRight = 10,
  19473. /** Indicates that the item should be placed in the bottom-left corner.
  19474. This is equivalent to (left | bottom)
  19475. */
  19476. bottomLeft = 17,
  19477. /** Indicates that the item should be placed in the bottom-left corner.
  19478. This is equivalent to (right | bottom)
  19479. */
  19480. bottomRight = 18
  19481. };
  19482. private:
  19483. int flags;
  19484. };
  19485. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  19486. /*** End of inlined file: juce_Justification.h ***/
  19487. class Image;
  19488. /**
  19489. A path is a sequence of lines and curves that may either form a closed shape
  19490. or be open-ended.
  19491. To use a path, you can create an empty one, then add lines and curves to it
  19492. to create shapes, then it can be rendered by a Graphics context or used
  19493. for geometric operations.
  19494. e.g. @code
  19495. Path myPath;
  19496. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  19497. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  19498. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  19499. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  19500. // add an ellipse as well, which will form a second sub-path within the path..
  19501. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  19502. // double the width of the whole thing..
  19503. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  19504. // and draw it to a graphics context with a 5-pixel thick outline.
  19505. g.strokePath (myPath, PathStrokeType (5.0f));
  19506. @endcode
  19507. A path object can actually contain multiple sub-paths, which may themselves
  19508. be open or closed.
  19509. @see PathFlatteningIterator, PathStrokeType, Graphics
  19510. */
  19511. class JUCE_API Path
  19512. {
  19513. public:
  19514. /** Creates an empty path. */
  19515. Path();
  19516. /** Creates a copy of another path. */
  19517. Path (const Path& other);
  19518. /** Destructor. */
  19519. ~Path();
  19520. /** Copies this path from another one. */
  19521. Path& operator= (const Path& other);
  19522. bool operator== (const Path& other) const throw();
  19523. bool operator!= (const Path& other) const throw();
  19524. /** Returns true if the path doesn't contain any lines or curves. */
  19525. bool isEmpty() const throw();
  19526. /** Returns the smallest rectangle that contains all points within the path.
  19527. */
  19528. const Rectangle<float> getBounds() const throw();
  19529. /** Returns the smallest rectangle that contains all points within the path
  19530. after it's been transformed with the given tranasform matrix.
  19531. */
  19532. const Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const throw();
  19533. /** Checks whether a point lies within the path.
  19534. This is only relevent for closed paths (see closeSubPath()), and
  19535. may produce false results if used on a path which has open sub-paths.
  19536. The path's winding rule is taken into account by this method.
  19537. The tolerance parameter is the maximum error allowed when flattening the path,
  19538. so this method could return a false positive when your point is up to this distance
  19539. outside the path's boundary.
  19540. @see closeSubPath, setUsingNonZeroWinding
  19541. */
  19542. bool contains (float x, float y,
  19543. float tolerance = 1.0f) const;
  19544. /** Checks whether a point lies within the path.
  19545. This is only relevent for closed paths (see closeSubPath()), and
  19546. may produce false results if used on a path which has open sub-paths.
  19547. The path's winding rule is taken into account by this method.
  19548. The tolerance parameter is the maximum error allowed when flattening the path,
  19549. so this method could return a false positive when your point is up to this distance
  19550. outside the path's boundary.
  19551. @see closeSubPath, setUsingNonZeroWinding
  19552. */
  19553. bool contains (const Point<float>& point,
  19554. float tolerance = 1.0f) const;
  19555. /** Checks whether a line crosses the path.
  19556. This will return positive if the line crosses any of the paths constituent
  19557. lines or curves. It doesn't take into account whether the line is inside
  19558. or outside the path, or whether the path is open or closed.
  19559. The tolerance parameter is the maximum error allowed when flattening the path,
  19560. so this method could return a false positive when your point is up to this distance
  19561. outside the path's boundary.
  19562. */
  19563. bool intersectsLine (const Line<float>& line,
  19564. float tolerance = 1.0f);
  19565. /** Cuts off parts of a line to keep the parts that are either inside or
  19566. outside this path.
  19567. Note that this isn't smart enough to cope with situations where the
  19568. line would need to be cut into multiple pieces to correctly clip against
  19569. a re-entrant shape.
  19570. @param line the line to clip
  19571. @param keepSectionOutsidePath if true, it's the section outside the path
  19572. that will be kept; if false its the section inside
  19573. the path
  19574. */
  19575. const Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  19576. /** Returns the length of the path.
  19577. @see getPointAlongPath
  19578. */
  19579. float getLength (const AffineTransform& transform = AffineTransform::identity) const;
  19580. /** Returns a point that is the specified distance along the path.
  19581. If the distance is greater than the total length of the path, this will return the
  19582. end point.
  19583. @see getLength
  19584. */
  19585. const Point<float> getPointAlongPath (float distanceFromStart,
  19586. const AffineTransform& transform = AffineTransform::identity) const;
  19587. /** Finds the point along the path which is nearest to a given position.
  19588. This sets pointOnPath to the nearest point, and returns the distance of this point from the start
  19589. of the path.
  19590. */
  19591. float getNearestPoint (const Point<float>& targetPoint,
  19592. Point<float>& pointOnPath,
  19593. const AffineTransform& transform = AffineTransform::identity) const;
  19594. /** Removes all lines and curves, resetting the path completely. */
  19595. void clear() throw();
  19596. /** Begins a new subpath with a given starting position.
  19597. This will move the path's current position to the co-ordinates passed in and
  19598. make it ready to draw lines or curves starting from this position.
  19599. After adding whatever lines and curves are needed, you can either
  19600. close the current sub-path using closeSubPath() or call startNewSubPath()
  19601. to move to a new sub-path, leaving the old one open-ended.
  19602. @see lineTo, quadraticTo, cubicTo, closeSubPath
  19603. */
  19604. void startNewSubPath (float startX, float startY);
  19605. /** Begins a new subpath with a given starting position.
  19606. This will move the path's current position to the co-ordinates passed in and
  19607. make it ready to draw lines or curves starting from this position.
  19608. After adding whatever lines and curves are needed, you can either
  19609. close the current sub-path using closeSubPath() or call startNewSubPath()
  19610. to move to a new sub-path, leaving the old one open-ended.
  19611. @see lineTo, quadraticTo, cubicTo, closeSubPath
  19612. */
  19613. void startNewSubPath (const Point<float>& start);
  19614. /** Closes a the current sub-path with a line back to its start-point.
  19615. When creating a closed shape such as a triangle, don't use 3 lineTo()
  19616. calls - instead use two lineTo() calls, followed by a closeSubPath()
  19617. to join the final point back to the start.
  19618. This ensures that closes shapes are recognised as such, and this is
  19619. important for tasks like drawing strokes, which needs to know whether to
  19620. draw end-caps or not.
  19621. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  19622. */
  19623. void closeSubPath();
  19624. /** Adds a line from the shape's last position to a new end-point.
  19625. This will connect the end-point of the last line or curve that was added
  19626. to a new point, using a straight line.
  19627. See the class description for an example of how to add lines and curves to a path.
  19628. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  19629. */
  19630. void lineTo (float endX, float endY);
  19631. /** Adds a line from the shape's last position to a new end-point.
  19632. This will connect the end-point of the last line or curve that was added
  19633. to a new point, using a straight line.
  19634. See the class description for an example of how to add lines and curves to a path.
  19635. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  19636. */
  19637. void lineTo (const Point<float>& end);
  19638. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  19639. This will connect the end-point of the last line or curve that was added
  19640. to a new point, using a quadratic spline with one control-point.
  19641. See the class description for an example of how to add lines and curves to a path.
  19642. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  19643. */
  19644. void quadraticTo (float controlPointX,
  19645. float controlPointY,
  19646. float endPointX,
  19647. float endPointY);
  19648. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  19649. This will connect the end-point of the last line or curve that was added
  19650. to a new point, using a quadratic spline with one control-point.
  19651. See the class description for an example of how to add lines and curves to a path.
  19652. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  19653. */
  19654. void quadraticTo (const Point<float>& controlPoint,
  19655. const Point<float>& endPoint);
  19656. /** Adds a cubic bezier curve from the shape's last position to a new position.
  19657. This will connect the end-point of the last line or curve that was added
  19658. to a new point, using a cubic spline with two control-points.
  19659. See the class description for an example of how to add lines and curves to a path.
  19660. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  19661. */
  19662. void cubicTo (float controlPoint1X,
  19663. float controlPoint1Y,
  19664. float controlPoint2X,
  19665. float controlPoint2Y,
  19666. float endPointX,
  19667. float endPointY);
  19668. /** Adds a cubic bezier curve from the shape's last position to a new position.
  19669. This will connect the end-point of the last line or curve that was added
  19670. to a new point, using a cubic spline with two control-points.
  19671. See the class description for an example of how to add lines and curves to a path.
  19672. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  19673. */
  19674. void cubicTo (const Point<float>& controlPoint1,
  19675. const Point<float>& controlPoint2,
  19676. const Point<float>& endPoint);
  19677. /** Returns the last point that was added to the path by one of the drawing methods.
  19678. */
  19679. const Point<float> getCurrentPosition() const;
  19680. /** Adds a rectangle to the path.
  19681. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19682. @see addRoundedRectangle, addTriangle
  19683. */
  19684. void addRectangle (float x, float y, float width, float height);
  19685. /** Adds a rectangle to the path.
  19686. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19687. @see addRoundedRectangle, addTriangle
  19688. */
  19689. template <typename ValueType>
  19690. void addRectangle (const Rectangle<ValueType>& rectangle)
  19691. {
  19692. addRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  19693. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()));
  19694. }
  19695. /** Adds a rectangle with rounded corners to the path.
  19696. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19697. @see addRectangle, addTriangle
  19698. */
  19699. void addRoundedRectangle (float x, float y, float width, float height,
  19700. float cornerSize);
  19701. /** Adds a rectangle with rounded corners to the path.
  19702. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19703. @see addRectangle, addTriangle
  19704. */
  19705. void addRoundedRectangle (float x, float y, float width, float height,
  19706. float cornerSizeX,
  19707. float cornerSizeY);
  19708. /** Adds a rectangle with rounded corners to the path.
  19709. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19710. @see addRectangle, addTriangle
  19711. */
  19712. template <typename ValueType>
  19713. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSizeX, float cornerSizeY)
  19714. {
  19715. addRoundedRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  19716. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()),
  19717. cornerSizeX, cornerSizeY);
  19718. }
  19719. /** Adds a rectangle with rounded corners to the path.
  19720. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19721. @see addRectangle, addTriangle
  19722. */
  19723. template <typename ValueType>
  19724. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSize)
  19725. {
  19726. addRoundedRectangle (rectangle, cornerSize, cornerSize);
  19727. }
  19728. /** Adds a triangle to the path.
  19729. The triangle is added as a new closed sub-path. (Any currently open paths will be left open).
  19730. Note that whether the vertices are specified in clockwise or anticlockwise
  19731. order will affect how the triangle is filled when it overlaps other
  19732. shapes (the winding order setting will affect this of course).
  19733. */
  19734. void addTriangle (float x1, float y1,
  19735. float x2, float y2,
  19736. float x3, float y3);
  19737. /** Adds a quadrilateral to the path.
  19738. The quad is added as a new closed sub-path. (Any currently open paths will be left open).
  19739. Note that whether the vertices are specified in clockwise or anticlockwise
  19740. order will affect how the quad is filled when it overlaps other
  19741. shapes (the winding order setting will affect this of course).
  19742. */
  19743. void addQuadrilateral (float x1, float y1,
  19744. float x2, float y2,
  19745. float x3, float y3,
  19746. float x4, float y4);
  19747. /** Adds an ellipse to the path.
  19748. The shape is added as a new sub-path. (Any currently open paths will be left open).
  19749. @see addArc
  19750. */
  19751. void addEllipse (float x, float y, float width, float height);
  19752. /** Adds an elliptical arc to the current path.
  19753. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  19754. or anti-clockwise according to whether the end angle is greater than the start. This means
  19755. that sometimes you may need to use values greater than 2*Pi for the end angle.
  19756. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  19757. @param y the top edge of the rectangle in which the elliptical outline fits
  19758. @param width the width of the rectangle in which the elliptical outline fits
  19759. @param height the height of the rectangle in which the elliptical outline fits
  19760. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  19761. top-centre of the ellipse)
  19762. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  19763. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  19764. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  19765. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  19766. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  19767. it will be added to the current sub-path, continuing from the current postition
  19768. @see addCentredArc, arcTo, addPieSegment, addEllipse
  19769. */
  19770. void addArc (float x, float y, float width, float height,
  19771. float fromRadians,
  19772. float toRadians,
  19773. bool startAsNewSubPath = false);
  19774. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  19775. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  19776. or anti-clockwise according to whether the end angle is greater than the start. This means
  19777. that sometimes you may need to use values greater than 2*Pi for the end angle.
  19778. @param centreX the centre x of the ellipse
  19779. @param centreY the centre y of the ellipse
  19780. @param radiusX the horizontal radius of the ellipse
  19781. @param radiusY the vertical radius of the ellipse
  19782. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  19783. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  19784. top-centre of the ellipse)
  19785. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  19786. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  19787. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  19788. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  19789. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  19790. it will be added to the current sub-path, continuing from the current postition
  19791. @see addArc, arcTo
  19792. */
  19793. void addCentredArc (float centreX, float centreY,
  19794. float radiusX, float radiusY,
  19795. float rotationOfEllipse,
  19796. float fromRadians,
  19797. float toRadians,
  19798. bool startAsNewSubPath = false);
  19799. /** Adds a "pie-chart" shape to the path.
  19800. The shape is added as a new sub-path. (Any currently open paths will be
  19801. left open).
  19802. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  19803. or anti-clockwise according to whether the end angle is greater than the start. This means
  19804. that sometimes you may need to use values greater than 2*Pi for the end angle.
  19805. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  19806. @param y the top edge of the rectangle in which the elliptical outline fits
  19807. @param width the width of the rectangle in which the elliptical outline fits
  19808. @param height the height of the rectangle in which the elliptical outline fits
  19809. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  19810. top-centre of the ellipse)
  19811. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  19812. top-centre of the ellipse)
  19813. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  19814. ellipse at its centre, where this value indicates the inner ellipse's size with
  19815. respect to the outer one.
  19816. @see addArc
  19817. */
  19818. void addPieSegment (float x, float y,
  19819. float width, float height,
  19820. float fromRadians,
  19821. float toRadians,
  19822. float innerCircleProportionalSize);
  19823. /** Adds a line with a specified thickness.
  19824. The line is added as a new closed sub-path. (Any currently open paths will be
  19825. left open).
  19826. @see addArrow
  19827. */
  19828. void addLineSegment (const Line<float>& line, float lineThickness);
  19829. /** Adds a line with an arrowhead on the end.
  19830. The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
  19831. @see PathStrokeType::createStrokeWithArrowheads
  19832. */
  19833. void addArrow (const Line<float>& line,
  19834. float lineThickness,
  19835. float arrowheadWidth,
  19836. float arrowheadLength);
  19837. /** Adds a polygon shape to the path.
  19838. @see addStar
  19839. */
  19840. void addPolygon (const Point<float>& centre,
  19841. int numberOfSides,
  19842. float radius,
  19843. float startAngle = 0.0f);
  19844. /** Adds a star shape to the path.
  19845. @see addPolygon
  19846. */
  19847. void addStar (const Point<float>& centre,
  19848. int numberOfPoints,
  19849. float innerRadius,
  19850. float outerRadius,
  19851. float startAngle = 0.0f);
  19852. /** Adds a speech-bubble shape to the path.
  19853. @param bodyX the left of the main body area of the bubble
  19854. @param bodyY the top of the main body area of the bubble
  19855. @param bodyW the width of the main body area of the bubble
  19856. @param bodyH the height of the main body area of the bubble
  19857. @param cornerSize the amount by which to round off the corners of the main body rectangle
  19858. @param arrowTipX the x position that the tip of the arrow should connect to
  19859. @param arrowTipY the y position that the tip of the arrow should connect to
  19860. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  19861. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  19862. arrow's base should be - this is a proportional distance between 0 and 1.0
  19863. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  19864. */
  19865. void addBubble (float bodyX, float bodyY,
  19866. float bodyW, float bodyH,
  19867. float cornerSize,
  19868. float arrowTipX,
  19869. float arrowTipY,
  19870. int whichSide,
  19871. float arrowPositionAlongEdgeProportional,
  19872. float arrowWidth);
  19873. /** Adds another path to this one.
  19874. The new path is added as a new sub-path. (Any currently open paths in this
  19875. path will be left open).
  19876. @param pathToAppend the path to add
  19877. */
  19878. void addPath (const Path& pathToAppend);
  19879. /** Adds another path to this one, transforming it on the way in.
  19880. The new path is added as a new sub-path, its points being transformed by the given
  19881. matrix before being added.
  19882. @param pathToAppend the path to add
  19883. @param transformToApply an optional transform to apply to the incoming vertices
  19884. */
  19885. void addPath (const Path& pathToAppend,
  19886. const AffineTransform& transformToApply);
  19887. /** Swaps the contents of this path with another one.
  19888. The internal data of the two paths is swapped over, so this is much faster than
  19889. copying it to a temp variable and back.
  19890. */
  19891. void swapWithPath (Path& other) throw();
  19892. /** Applies a 2D transform to all the vertices in the path.
  19893. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  19894. */
  19895. void applyTransform (const AffineTransform& transform) throw();
  19896. /** Rescales this path to make it fit neatly into a given space.
  19897. This is effectively a quick way of calling
  19898. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  19899. @param x the x position of the rectangle to fit the path inside
  19900. @param y the y position of the rectangle to fit the path inside
  19901. @param width the width of the rectangle to fit the path inside
  19902. @param height the height of the rectangle to fit the path inside
  19903. @param preserveProportions if true, it will fit the path into the space without altering its
  19904. horizontal/vertical scale ratio; if false, it will distort the
  19905. path to fill the specified ratio both horizontally and vertically
  19906. @see applyTransform, getTransformToScaleToFit
  19907. */
  19908. void scaleToFit (float x, float y, float width, float height,
  19909. bool preserveProportions) throw();
  19910. /** Returns a transform that can be used to rescale the path to fit into a given space.
  19911. @param x the x position of the rectangle to fit the path inside
  19912. @param y the y position of the rectangle to fit the path inside
  19913. @param width the width of the rectangle to fit the path inside
  19914. @param height the height of the rectangle to fit the path inside
  19915. @param preserveProportions if true, it will fit the path into the space without altering its
  19916. horizontal/vertical scale ratio; if false, it will distort the
  19917. path to fill the specified ratio both horizontally and vertically
  19918. @param justificationType if the proportions are preseved, the resultant path may be smaller
  19919. than the available rectangle, so this describes how it should be
  19920. positioned within the space.
  19921. @returns an appropriate transformation
  19922. @see applyTransform, scaleToFit
  19923. */
  19924. const AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  19925. bool preserveProportions,
  19926. const Justification& justificationType = Justification::centred) const;
  19927. /** Creates a version of this path where all sharp corners have been replaced by curves.
  19928. Wherever two lines meet at an angle, this will replace the corner with a curve
  19929. of the given radius.
  19930. */
  19931. const Path createPathWithRoundedCorners (float cornerRadius) const;
  19932. /** Changes the winding-rule to be used when filling the path.
  19933. If set to true (which is the default), then the path uses a non-zero-winding rule
  19934. to determine which points are inside the path. If set to false, it uses an
  19935. alternate-winding rule.
  19936. The winding-rule comes into play when areas of the shape overlap other
  19937. areas, and determines whether the overlapping regions are considered to be
  19938. inside or outside.
  19939. Changing this value just sets a flag - it doesn't affect the contents of the
  19940. path.
  19941. @see isUsingNonZeroWinding
  19942. */
  19943. void setUsingNonZeroWinding (bool isNonZeroWinding) throw();
  19944. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  19945. The default for a new path is true.
  19946. @see setUsingNonZeroWinding
  19947. */
  19948. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  19949. /** Iterates the lines and curves that a path contains.
  19950. @see Path, PathFlatteningIterator
  19951. */
  19952. class JUCE_API Iterator
  19953. {
  19954. public:
  19955. Iterator (const Path& path);
  19956. ~Iterator();
  19957. /** Moves onto the next element in the path.
  19958. If this returns false, there are no more elements. If it returns true,
  19959. the elementType variable will be set to the type of the current element,
  19960. and some of the x and y variables will be filled in with values.
  19961. */
  19962. bool next();
  19963. enum PathElementType
  19964. {
  19965. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  19966. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  19967. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  19968. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  19969. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  19970. };
  19971. PathElementType elementType;
  19972. float x1, y1, x2, y2, x3, y3;
  19973. private:
  19974. const Path& path;
  19975. size_t index;
  19976. JUCE_DECLARE_NON_COPYABLE (Iterator);
  19977. };
  19978. /** Loads a stored path from a data stream.
  19979. The data in the stream must have been written using writePathToStream().
  19980. Note that this will append the stored path to whatever is currently in
  19981. this path, so you might need to call clear() beforehand.
  19982. @see loadPathFromData, writePathToStream
  19983. */
  19984. void loadPathFromStream (InputStream& source);
  19985. /** Loads a stored path from a block of data.
  19986. This is similar to loadPathFromStream(), but just reads from a block
  19987. of data. Useful if you're including stored shapes in your code as a
  19988. block of static data.
  19989. @see loadPathFromStream, writePathToStream
  19990. */
  19991. void loadPathFromData (const void* data, int numberOfBytes);
  19992. /** Stores the path by writing it out to a stream.
  19993. After writing out a path, you can reload it using loadPathFromStream().
  19994. @see loadPathFromStream, loadPathFromData
  19995. */
  19996. void writePathToStream (OutputStream& destination) const;
  19997. /** Creates a string containing a textual representation of this path.
  19998. @see restoreFromString
  19999. */
  20000. const String toString() const;
  20001. /** Restores this path from a string that was created with the toString() method.
  20002. @see toString()
  20003. */
  20004. void restoreFromString (const String& stringVersion);
  20005. private:
  20006. friend class PathFlatteningIterator;
  20007. friend class Path::Iterator;
  20008. ArrayAllocationBase <float, DummyCriticalSection> data;
  20009. size_t numElements;
  20010. float pathXMin, pathXMax, pathYMin, pathYMax;
  20011. bool useNonZeroWinding;
  20012. static const float lineMarker;
  20013. static const float moveMarker;
  20014. static const float quadMarker;
  20015. static const float cubicMarker;
  20016. static const float closeSubPathMarker;
  20017. JUCE_LEAK_DETECTOR (Path);
  20018. };
  20019. #endif // __JUCE_PATH_JUCEHEADER__
  20020. /*** End of inlined file: juce_Path.h ***/
  20021. class Font;
  20022. class EdgeTable;
  20023. /** A typeface represents a size-independent font.
  20024. This base class is abstract, but calling createSystemTypefaceFor() will return
  20025. a platform-specific subclass that can be used.
  20026. The CustomTypeface subclass allow you to build your own typeface, and to
  20027. load and save it in the Juce typeface format.
  20028. Normally you should never need to deal directly with Typeface objects - the Font
  20029. class does everything you typically need for rendering text.
  20030. @see CustomTypeface, Font
  20031. */
  20032. class JUCE_API Typeface : public ReferenceCountedObject
  20033. {
  20034. public:
  20035. /** A handy typedef for a pointer to a typeface. */
  20036. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  20037. /** Returns the name of the typeface.
  20038. @see Font::getTypefaceName
  20039. */
  20040. const String getName() const throw() { return name; }
  20041. /** Creates a new system typeface. */
  20042. static const Ptr createSystemTypefaceFor (const Font& font);
  20043. /** Destructor. */
  20044. virtual ~Typeface();
  20045. /** Returns true if this typeface can be used to render the specified font.
  20046. When called, the font will already have been checked to make sure that its name and
  20047. style flags match the typeface.
  20048. */
  20049. virtual bool isSuitableForFont (const Font&) const { return true; }
  20050. /** Returns the ascent of the font, as a proportion of its height.
  20051. The height is considered to always be normalised as 1.0, so this will be a
  20052. value less that 1.0, indicating the proportion of the font that lies above
  20053. its baseline.
  20054. */
  20055. virtual float getAscent() const = 0;
  20056. /** Returns the descent of the font, as a proportion of its height.
  20057. The height is considered to always be normalised as 1.0, so this will be a
  20058. value less that 1.0, indicating the proportion of the font that lies below
  20059. its baseline.
  20060. */
  20061. virtual float getDescent() const = 0;
  20062. /** Measures the width of a line of text.
  20063. The distance returned is based on the font having an normalised height of 1.0.
  20064. You should never need to call this directly! Use Font::getStringWidth() instead!
  20065. */
  20066. virtual float getStringWidth (const String& text) = 0;
  20067. /** Converts a line of text into its glyph numbers and their positions.
  20068. The distances returned are based on the font having an normalised height of 1.0.
  20069. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  20070. */
  20071. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  20072. /** Returns the outline for a glyph.
  20073. The path returned will be normalised to a font height of 1.0.
  20074. */
  20075. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  20076. /** Returns a new EdgeTable that contains the path for the givem glyph, with the specified transform applied. */
  20077. virtual EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  20078. /** Returns true if the typeface uses hinting. */
  20079. virtual bool isHinted() const { return false; }
  20080. /** Changes the number of fonts that are cached in memory. */
  20081. static void setTypefaceCacheSize (int numFontsToCache);
  20082. protected:
  20083. String name;
  20084. bool isFallbackFont;
  20085. explicit Typeface (const String& name) throw();
  20086. static const Ptr getFallbackTypeface();
  20087. private:
  20088. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Typeface);
  20089. };
  20090. /** A typeface that can be populated with custom glyphs.
  20091. You can create a CustomTypeface if you need one that contains your own glyphs,
  20092. or if you need to load a typeface from a Juce-formatted binary stream.
  20093. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  20094. to copy glyphs into this face.
  20095. @see Typeface, Font
  20096. */
  20097. class JUCE_API CustomTypeface : public Typeface
  20098. {
  20099. public:
  20100. /** Creates a new, empty typeface. */
  20101. CustomTypeface();
  20102. /** Loads a typeface from a previously saved stream.
  20103. The stream must have been created by writeToStream().
  20104. @see writeToStream
  20105. */
  20106. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  20107. /** Destructor. */
  20108. ~CustomTypeface();
  20109. /** Resets this typeface, deleting all its glyphs and settings. */
  20110. void clear();
  20111. /** Sets the vital statistics for the typeface.
  20112. @param name the typeface's name
  20113. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  20114. the value that will be returned by Typeface::getAscent(). The
  20115. descent is assumed to be (1.0 - ascent)
  20116. @param isBold should be true if the typeface is bold
  20117. @param isItalic should be true if the typeface is italic
  20118. @param defaultCharacter the character to be used as a replacement if there's
  20119. no glyph available for the character that's being drawn
  20120. */
  20121. void setCharacteristics (const String& name, float ascent,
  20122. bool isBold, bool isItalic,
  20123. juce_wchar defaultCharacter) throw();
  20124. /** Adds a glyph to the typeface.
  20125. The path that is passed in is normalised so that the font height is 1.0, and its
  20126. origin is the anchor point of the character on its baseline.
  20127. The width is the nominal width of the character, and any extra kerning values that
  20128. are specified will be added to this width.
  20129. */
  20130. void addGlyph (juce_wchar character, const Path& path, float width) throw();
  20131. /** Specifies an extra kerning amount to be used between a pair of characters.
  20132. The amount will be added to the nominal width of the first character when laying out a string.
  20133. */
  20134. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) throw();
  20135. /** Adds a range of glyphs from another typeface.
  20136. This will attempt to pull in the paths and kerning information from another typeface and
  20137. add it to this one.
  20138. */
  20139. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw();
  20140. /** Saves this typeface as a Juce-formatted font file.
  20141. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  20142. constructor.
  20143. */
  20144. bool writeToStream (OutputStream& outputStream);
  20145. // The following methods implement the basic Typeface behaviour.
  20146. float getAscent() const;
  20147. float getDescent() const;
  20148. float getStringWidth (const String& text);
  20149. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  20150. bool getOutlineForGlyph (int glyphNumber, Path& path);
  20151. EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform);
  20152. int getGlyphForCharacter (juce_wchar character);
  20153. protected:
  20154. juce_wchar defaultCharacter;
  20155. float ascent;
  20156. bool isBold, isItalic;
  20157. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  20158. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  20159. particular character and there's no corresponding glyph, they'll call this
  20160. method so that a subclass can try to add that glyph, returning true if it
  20161. manages to do so.
  20162. */
  20163. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  20164. private:
  20165. class GlyphInfo;
  20166. friend class OwnedArray<GlyphInfo>;
  20167. OwnedArray <GlyphInfo> glyphs;
  20168. short lookupTable [128];
  20169. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) throw();
  20170. GlyphInfo* findGlyphSubstituting (juce_wchar character) throw();
  20171. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomTypeface);
  20172. };
  20173. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  20174. /*** End of inlined file: juce_Typeface.h ***/
  20175. class LowLevelGraphicsContext;
  20176. /**
  20177. Represents a particular font, including its size, style, etc.
  20178. Apart from the typeface to be used, a Font object also dictates whether
  20179. the font is bold, italic, underlined, how big it is, and its kerning and
  20180. horizontal scale factor.
  20181. @see Typeface
  20182. */
  20183. class JUCE_API Font
  20184. {
  20185. public:
  20186. /** A combination of these values is used by the constructor to specify the
  20187. style of font to use.
  20188. */
  20189. enum FontStyleFlags
  20190. {
  20191. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  20192. bold = 1, /**< boldens the font. @see setStyleFlags */
  20193. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  20194. underlined = 4 /**< underlines the font. @see setStyleFlags */
  20195. };
  20196. /** Creates a sans-serif font in a given size.
  20197. @param fontHeight the height in pixels (can be fractional)
  20198. @param styleFlags the style to use - this can be a combination of the
  20199. Font::bold, Font::italic and Font::underlined, or
  20200. just Font::plain for the normal style.
  20201. @see FontStyleFlags, getDefaultSansSerifFontName
  20202. */
  20203. Font (float fontHeight, int styleFlags = plain);
  20204. /** Creates a font with a given typeface and parameters.
  20205. @param typefaceName the name of the typeface to use
  20206. @param fontHeight the height in pixels (can be fractional)
  20207. @param styleFlags the style to use - this can be a combination of the
  20208. Font::bold, Font::italic and Font::underlined, or
  20209. just Font::plain for the normal style.
  20210. @see FontStyleFlags, getDefaultSansSerifFontName
  20211. */
  20212. Font (const String& typefaceName, float fontHeight, int styleFlags);
  20213. /** Creates a copy of another Font object. */
  20214. Font (const Font& other) throw();
  20215. /** Creates a font for a typeface. */
  20216. Font (const Typeface::Ptr& typeface);
  20217. /** Creates a basic sans-serif font at a default height.
  20218. You should use one of the other constructors for creating a font that you're planning
  20219. on drawing with - this constructor is here to help initialise objects before changing
  20220. the font's settings later.
  20221. */
  20222. Font();
  20223. /** Copies this font from another one. */
  20224. Font& operator= (const Font& other) throw();
  20225. bool operator== (const Font& other) const throw();
  20226. bool operator!= (const Font& other) const throw();
  20227. /** Destructor. */
  20228. ~Font() throw();
  20229. /** Changes the name of the typeface family.
  20230. e.g. "Arial", "Courier", etc.
  20231. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  20232. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  20233. but are generic names that are used to represent the various default fonts.
  20234. If you need to know the exact typeface name being used, you can call
  20235. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  20236. If a suitable font isn't found on the machine, it'll just use a default instead.
  20237. */
  20238. void setTypefaceName (const String& faceName);
  20239. /** Returns the name of the typeface family that this font uses.
  20240. e.g. "Arial", "Courier", etc.
  20241. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  20242. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  20243. but are generic names that are used to represent the various default fonts.
  20244. If you need to know the exact typeface name being used, you can call
  20245. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  20246. */
  20247. const String& getTypefaceName() const throw() { return font->typefaceName; }
  20248. /** Returns a typeface name that represents the default sans-serif font.
  20249. This is also the typeface that will be used when a font is created without
  20250. specifying any typeface details.
  20251. Note that this method just returns a generic placeholder string that means "the default
  20252. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  20253. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  20254. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  20255. */
  20256. static const String getDefaultSansSerifFontName();
  20257. /** Returns a typeface name that represents the default sans-serif font.
  20258. Note that this method just returns a generic placeholder string that means "the default
  20259. serif font" - it's not the actual name of this font. To get the actual name, use
  20260. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  20261. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  20262. */
  20263. static const String getDefaultSerifFontName();
  20264. /** Returns a typeface name that represents the default sans-serif font.
  20265. Note that this method just returns a generic placeholder string that means "the default
  20266. monospaced font" - it's not the actual name of this font. To get the actual name, use
  20267. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  20268. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  20269. */
  20270. static const String getDefaultMonospacedFontName();
  20271. /** Returns the typeface names of the default fonts on the current platform. */
  20272. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback);
  20273. /** Returns the total height of this font.
  20274. This is the maximum height, from the top of the ascent to the bottom of the
  20275. descenders.
  20276. @see setHeight, setHeightWithoutChangingWidth, getAscent
  20277. */
  20278. float getHeight() const throw() { return font->height; }
  20279. /** Changes the font's height.
  20280. @see getHeight, setHeightWithoutChangingWidth
  20281. */
  20282. void setHeight (float newHeight);
  20283. /** Changes the font's height without changing its width.
  20284. This alters the horizontal scale to compensate for the change in height.
  20285. */
  20286. void setHeightWithoutChangingWidth (float newHeight);
  20287. /** Returns the height of the font above its baseline.
  20288. This is the maximum height from the baseline to the top.
  20289. @see getHeight, getDescent
  20290. */
  20291. float getAscent() const;
  20292. /** Returns the amount that the font descends below its baseline.
  20293. This is calculated as (getHeight() - getAscent()).
  20294. @see getAscent, getHeight
  20295. */
  20296. float getDescent() const;
  20297. /** Returns the font's style flags.
  20298. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  20299. enum, to describe whether the font is bold, italic, etc.
  20300. @see FontStyleFlags
  20301. */
  20302. int getStyleFlags() const throw() { return font->styleFlags; }
  20303. /** Changes the font's style.
  20304. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  20305. enum, to set the font's properties
  20306. @see FontStyleFlags
  20307. */
  20308. void setStyleFlags (int newFlags);
  20309. /** Makes the font bold or non-bold. */
  20310. void setBold (bool shouldBeBold);
  20311. /** Returns a copy of this font with the bold attribute set. */
  20312. const Font boldened() const;
  20313. /** Returns true if the font is bold. */
  20314. bool isBold() const throw();
  20315. /** Makes the font italic or non-italic. */
  20316. void setItalic (bool shouldBeItalic);
  20317. /** Returns a copy of this font with the italic attribute set. */
  20318. const Font italicised() const;
  20319. /** Returns true if the font is italic. */
  20320. bool isItalic() const throw();
  20321. /** Makes the font underlined or non-underlined. */
  20322. void setUnderline (bool shouldBeUnderlined);
  20323. /** Returns true if the font is underlined. */
  20324. bool isUnderlined() const throw();
  20325. /** Changes the font's horizontal scale factor.
  20326. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  20327. narrower, greater than 1.0 will be stretched out.
  20328. */
  20329. void setHorizontalScale (float scaleFactor);
  20330. /** Returns the font's horizontal scale.
  20331. A value of 1.0 is the normal scale, less than this will be narrower, greater
  20332. than 1.0 will be stretched out.
  20333. @see setHorizontalScale
  20334. */
  20335. float getHorizontalScale() const throw() { return font->horizontalScale; }
  20336. /** Changes the font's kerning.
  20337. @param extraKerning a multiple of the font's height that will be added
  20338. to space between the characters. So a value of zero is
  20339. normal spacing, positive values spread the letters out,
  20340. negative values make them closer together.
  20341. */
  20342. void setExtraKerningFactor (float extraKerning);
  20343. /** Returns the font's kerning.
  20344. This is the extra space added between adjacent characters, as a proportion
  20345. of the font's height.
  20346. A value of zero is normal spacing, positive values will spread the letters
  20347. out more, and negative values make them closer together.
  20348. */
  20349. float getExtraKerningFactor() const throw() { return font->kerning; }
  20350. /** Changes all the font's characteristics with one call. */
  20351. void setSizeAndStyle (float newHeight,
  20352. int newStyleFlags,
  20353. float newHorizontalScale,
  20354. float newKerningAmount);
  20355. /** Returns the total width of a string as it would be drawn using this font.
  20356. For a more accurate floating-point result, use getStringWidthFloat().
  20357. */
  20358. int getStringWidth (const String& text) const;
  20359. /** Returns the total width of a string as it would be drawn using this font.
  20360. @see getStringWidth
  20361. */
  20362. float getStringWidthFloat (const String& text) const;
  20363. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  20364. An extra x offset is added at the end of the run, to indicate where the right hand
  20365. edge of the last character is.
  20366. */
  20367. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const;
  20368. /** Returns the typeface used by this font.
  20369. Note that the object returned may go out of scope if this font is deleted
  20370. or has its style changed.
  20371. */
  20372. Typeface* getTypeface() const;
  20373. /** Creates an array of Font objects to represent all the fonts on the system.
  20374. If you just need the names of the typefaces, you can also use
  20375. findAllTypefaceNames() instead.
  20376. @param results the array to which new Font objects will be added.
  20377. */
  20378. static void findFonts (Array<Font>& results);
  20379. /** Returns a list of all the available typeface names.
  20380. The names returned can be passed into setTypefaceName().
  20381. You can use this instead of findFonts() if you only need their names, and not
  20382. font objects.
  20383. */
  20384. static const StringArray findAllTypefaceNames();
  20385. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  20386. in the requested typeface.
  20387. */
  20388. static const String getFallbackFontName();
  20389. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  20390. available in whatever font you're trying to use.
  20391. */
  20392. static void setFallbackFontName (const String& name);
  20393. /** Creates a string to describe this font.
  20394. The string will contain information to describe the font's typeface, size, and
  20395. style. To recreate the font from this string, use fromString().
  20396. */
  20397. const String toString() const;
  20398. /** Recreates a font from its stringified encoding.
  20399. This method takes a string that was created by toString(), and recreates the
  20400. original font.
  20401. */
  20402. static const Font fromString (const String& fontDescription);
  20403. private:
  20404. friend class FontGlyphAlphaMap;
  20405. friend class TypefaceCache;
  20406. class SharedFontInternal : public ReferenceCountedObject
  20407. {
  20408. public:
  20409. SharedFontInternal (float height, int styleFlags) throw();
  20410. SharedFontInternal (const String& typefaceName, float height, int styleFlags) throw();
  20411. SharedFontInternal (const Typeface::Ptr& typeface) throw();
  20412. SharedFontInternal (const SharedFontInternal& other) throw();
  20413. bool operator== (const SharedFontInternal&) const throw();
  20414. String typefaceName;
  20415. float height, horizontalScale, kerning, ascent;
  20416. int styleFlags;
  20417. Typeface::Ptr typeface;
  20418. };
  20419. ReferenceCountedObjectPtr <SharedFontInternal> font;
  20420. void dupeInternalIfShared();
  20421. JUCE_LEAK_DETECTOR (Font);
  20422. };
  20423. #endif // __JUCE_FONT_JUCEHEADER__
  20424. /*** End of inlined file: juce_Font.h ***/
  20425. /*** Start of inlined file: juce_PathStrokeType.h ***/
  20426. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20427. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20428. /**
  20429. Describes a type of stroke used to render a solid outline along a path.
  20430. A PathStrokeType object can be used directly to create the shape of an outline
  20431. around a path, and is used by Graphics::strokePath to specify the type of
  20432. stroke to draw.
  20433. @see Path, Graphics::strokePath
  20434. */
  20435. class JUCE_API PathStrokeType
  20436. {
  20437. public:
  20438. /** The type of shape to use for the corners between two adjacent line segments. */
  20439. enum JointStyle
  20440. {
  20441. mitered, /**< Indicates that corners should be drawn with sharp joints.
  20442. Note that for angles that curve back on themselves, drawing a
  20443. mitre could require extending the point too far away from the
  20444. path, so a mitre limit is imposed and any corners that exceed it
  20445. are drawn as bevelled instead. */
  20446. curved, /**< Indicates that corners should be drawn as rounded-off. */
  20447. beveled /**< Indicates that corners should be drawn with a line flattening their
  20448. outside edge. */
  20449. };
  20450. /** The type shape to use for the ends of lines. */
  20451. enum EndCapStyle
  20452. {
  20453. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  20454. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  20455. the thickness of the stroke. */
  20456. rounded /**< Ends of lines are rounded-off with a circular shape. */
  20457. };
  20458. /** Creates a stroke type.
  20459. @param strokeThickness the width of the line to use
  20460. @param jointStyle the type of joints to use for corners
  20461. @param endStyle the type of end-caps to use for the ends of open paths.
  20462. */
  20463. PathStrokeType (float strokeThickness,
  20464. JointStyle jointStyle = mitered,
  20465. EndCapStyle endStyle = butt) throw();
  20466. /** Createes a copy of another stroke type. */
  20467. PathStrokeType (const PathStrokeType& other) throw();
  20468. /** Copies another stroke onto this one. */
  20469. PathStrokeType& operator= (const PathStrokeType& other) throw();
  20470. /** Destructor. */
  20471. ~PathStrokeType() throw();
  20472. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  20473. @param destPath the resultant stroked outline shape will be copied into this path.
  20474. Note that it's ok for the source and destination Paths to be
  20475. the same object, so you can easily turn a path into a stroked version
  20476. of itself.
  20477. @param sourcePath the path to use as the source
  20478. @param transform an optional transform to apply to the points from the source path
  20479. as they are being used
  20480. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  20481. a higher resolution, which improves the quality if you'll later want
  20482. to enlarge the stroked path. So for example, if you're planning on drawing
  20483. the stroke at 3x the size that you're creating it, you should set this to 3.
  20484. @see createDashedStroke
  20485. */
  20486. void createStrokedPath (Path& destPath,
  20487. const Path& sourcePath,
  20488. const AffineTransform& transform = AffineTransform::identity,
  20489. float extraAccuracy = 1.0f) const;
  20490. /** Applies this stroke type to a path, creating a dashed line.
  20491. This is similar to createStrokedPath, but uses the array passed in to
  20492. break the stroke up into a series of dashes.
  20493. @param destPath the resultant stroked outline shape will be copied into this path.
  20494. Note that it's ok for the source and destination Paths to be
  20495. the same object, so you can easily turn a path into a stroked version
  20496. of itself.
  20497. @param sourcePath the path to use as the source
  20498. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  20499. a line of length 2, then skip a length of 3, then add a line of length 4,
  20500. skip 5, and keep repeating this pattern.
  20501. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  20502. an even number, otherwise the pattern will get out of step as it
  20503. repeats.
  20504. @param transform an optional transform to apply to the points from the source path
  20505. as they are being used
  20506. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  20507. a higher resolution, which improves the quality if you'll later want
  20508. to enlarge the stroked path. So for example, if you're planning on drawing
  20509. the stroke at 3x the size that you're creating it, you should set this to 3.
  20510. */
  20511. void createDashedStroke (Path& destPath,
  20512. const Path& sourcePath,
  20513. const float* dashLengths,
  20514. int numDashLengths,
  20515. const AffineTransform& transform = AffineTransform::identity,
  20516. float extraAccuracy = 1.0f) const;
  20517. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  20518. @param destPath the resultant stroked outline shape will be copied into this path.
  20519. Note that it's ok for the source and destination Paths to be
  20520. the same object, so you can easily turn a path into a stroked version
  20521. of itself.
  20522. @param sourcePath the path to use as the source
  20523. @param arrowheadStartWidth the width of the arrowhead at the start of the path
  20524. @param arrowheadStartLength the length of the arrowhead at the start of the path
  20525. @param arrowheadEndWidth the width of the arrowhead at the end of the path
  20526. @param arrowheadEndLength the length of the arrowhead at the end of the path
  20527. @param transform an optional transform to apply to the points from the source path
  20528. as they are being used
  20529. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  20530. a higher resolution, which improves the quality if you'll later want
  20531. to enlarge the stroked path. So for example, if you're planning on drawing
  20532. the stroke at 3x the size that you're creating it, you should set this to 3.
  20533. @see createDashedStroke
  20534. */
  20535. void createStrokeWithArrowheads (Path& destPath,
  20536. const Path& sourcePath,
  20537. float arrowheadStartWidth, float arrowheadStartLength,
  20538. float arrowheadEndWidth, float arrowheadEndLength,
  20539. const AffineTransform& transform = AffineTransform::identity,
  20540. float extraAccuracy = 1.0f) const;
  20541. /** Returns the stroke thickness. */
  20542. float getStrokeThickness() const throw() { return thickness; }
  20543. /** Sets the stroke thickness. */
  20544. void setStrokeThickness (float newThickness) throw() { thickness = newThickness; }
  20545. /** Returns the joint style. */
  20546. JointStyle getJointStyle() const throw() { return jointStyle; }
  20547. /** Sets the joint style. */
  20548. void setJointStyle (JointStyle newStyle) throw() { jointStyle = newStyle; }
  20549. /** Returns the end-cap style. */
  20550. EndCapStyle getEndStyle() const throw() { return endStyle; }
  20551. /** Sets the end-cap style. */
  20552. void setEndStyle (EndCapStyle newStyle) throw() { endStyle = newStyle; }
  20553. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  20554. bool operator== (const PathStrokeType& other) const throw();
  20555. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  20556. bool operator!= (const PathStrokeType& other) const throw();
  20557. private:
  20558. float thickness;
  20559. JointStyle jointStyle;
  20560. EndCapStyle endStyle;
  20561. JUCE_LEAK_DETECTOR (PathStrokeType);
  20562. };
  20563. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20564. /*** End of inlined file: juce_PathStrokeType.h ***/
  20565. /*** Start of inlined file: juce_Colours.h ***/
  20566. #ifndef __JUCE_COLOURS_JUCEHEADER__
  20567. #define __JUCE_COLOURS_JUCEHEADER__
  20568. /*** Start of inlined file: juce_Colour.h ***/
  20569. #ifndef __JUCE_COLOUR_JUCEHEADER__
  20570. #define __JUCE_COLOUR_JUCEHEADER__
  20571. /*** Start of inlined file: juce_PixelFormats.h ***/
  20572. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  20573. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  20574. #ifndef DOXYGEN
  20575. #if JUCE_MSVC
  20576. #pragma pack (push, 1)
  20577. #define PACKED
  20578. #elif JUCE_GCC
  20579. #define PACKED __attribute__((packed))
  20580. #else
  20581. #define PACKED
  20582. #endif
  20583. #endif
  20584. class PixelRGB;
  20585. class PixelAlpha;
  20586. /**
  20587. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  20588. operations with it.
  20589. This is used internally by the imaging classes.
  20590. @see PixelRGB
  20591. */
  20592. class JUCE_API PixelARGB
  20593. {
  20594. public:
  20595. /** Creates a pixel without defining its colour. */
  20596. PixelARGB() throw() {}
  20597. ~PixelARGB() throw() {}
  20598. /** Creates a pixel from a 32-bit argb value.
  20599. */
  20600. PixelARGB (const uint32 argb_) throw()
  20601. : argb (argb_)
  20602. {
  20603. }
  20604. forcedinline uint32 getARGB() const throw() { return argb; }
  20605. forcedinline uint32 getUnpremultipliedARGB() const throw() { PixelARGB p (argb); p.unpremultiply(); return p.getARGB(); }
  20606. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  20607. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  20608. forcedinline uint8 getAlpha() const throw() { return components.a; }
  20609. forcedinline uint8 getRed() const throw() { return components.r; }
  20610. forcedinline uint8 getGreen() const throw() { return components.g; }
  20611. forcedinline uint8 getBlue() const throw() { return components.b; }
  20612. /** Blends another pixel onto this one.
  20613. This takes into account the opacity of the pixel being overlaid, and blends
  20614. it accordingly.
  20615. */
  20616. forcedinline void blend (const PixelARGB& src) throw()
  20617. {
  20618. uint32 sargb = src.getARGB();
  20619. const uint32 alpha = 0x100 - (sargb >> 24);
  20620. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  20621. sargb += 0xff00ff00 & (getAG() * alpha);
  20622. argb = sargb;
  20623. }
  20624. /** Blends another pixel onto this one.
  20625. This takes into account the opacity of the pixel being overlaid, and blends
  20626. it accordingly.
  20627. */
  20628. forcedinline void blend (const PixelAlpha& src) throw();
  20629. /** Blends another pixel onto this one.
  20630. This takes into account the opacity of the pixel being overlaid, and blends
  20631. it accordingly.
  20632. */
  20633. forcedinline void blend (const PixelRGB& src) throw();
  20634. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  20635. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  20636. being used, so this can blend semi-transparently from a PixelRGB argument.
  20637. */
  20638. template <class Pixel>
  20639. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  20640. {
  20641. ++extraAlpha;
  20642. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  20643. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  20644. const uint32 alpha = 0x100 - (sargb >> 24);
  20645. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  20646. sargb += 0xff00ff00 & (getAG() * alpha);
  20647. argb = sargb;
  20648. }
  20649. /** Blends another pixel with this one, creating a colour that is somewhere
  20650. between the two, as specified by the amount.
  20651. */
  20652. template <class Pixel>
  20653. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  20654. {
  20655. uint32 drb = getRB();
  20656. drb += (((src.getRB() - drb) * amount) >> 8);
  20657. drb &= 0x00ff00ff;
  20658. uint32 dag = getAG();
  20659. dag += (((src.getAG() - dag) * amount) >> 8);
  20660. dag &= 0x00ff00ff;
  20661. dag <<= 8;
  20662. dag |= drb;
  20663. argb = dag;
  20664. }
  20665. /** Copies another pixel colour over this one.
  20666. This doesn't blend it - this colour is simply replaced by the other one.
  20667. */
  20668. template <class Pixel>
  20669. forcedinline void set (const Pixel& src) throw()
  20670. {
  20671. argb = src.getARGB();
  20672. }
  20673. /** Replaces the colour's alpha value with another one. */
  20674. forcedinline void setAlpha (const uint8 newAlpha) throw()
  20675. {
  20676. components.a = newAlpha;
  20677. }
  20678. /** Multiplies the colour's alpha value with another one. */
  20679. forcedinline void multiplyAlpha (int multiplier) throw()
  20680. {
  20681. ++multiplier;
  20682. argb = ((multiplier * getAG()) & 0xff00ff00)
  20683. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  20684. }
  20685. forcedinline void multiplyAlpha (const float multiplier) throw()
  20686. {
  20687. multiplyAlpha ((int) (multiplier * 256.0f));
  20688. }
  20689. /** Sets the pixel's colour from individual components. */
  20690. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  20691. {
  20692. components.b = b;
  20693. components.g = g;
  20694. components.r = r;
  20695. components.a = a;
  20696. }
  20697. /** Premultiplies the pixel's RGB values by its alpha. */
  20698. forcedinline void premultiply() throw()
  20699. {
  20700. const uint32 alpha = components.a;
  20701. if (alpha < 0xff)
  20702. {
  20703. if (alpha == 0)
  20704. {
  20705. components.b = 0;
  20706. components.g = 0;
  20707. components.r = 0;
  20708. }
  20709. else
  20710. {
  20711. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  20712. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  20713. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  20714. }
  20715. }
  20716. }
  20717. /** Unpremultiplies the pixel's RGB values. */
  20718. forcedinline void unpremultiply() throw()
  20719. {
  20720. const uint32 alpha = components.a;
  20721. if (alpha < 0xff)
  20722. {
  20723. if (alpha == 0)
  20724. {
  20725. components.b = 0;
  20726. components.g = 0;
  20727. components.r = 0;
  20728. }
  20729. else
  20730. {
  20731. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  20732. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  20733. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  20734. }
  20735. }
  20736. }
  20737. forcedinline void desaturate() throw()
  20738. {
  20739. if (components.a < 0xff && components.a > 0)
  20740. {
  20741. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  20742. components.r = components.g = components.b
  20743. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  20744. }
  20745. else
  20746. {
  20747. components.r = components.g = components.b
  20748. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  20749. }
  20750. }
  20751. /** The indexes of the different components in the byte layout of this type of colour. */
  20752. #if JUCE_BIG_ENDIAN
  20753. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  20754. #else
  20755. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  20756. #endif
  20757. private:
  20758. union
  20759. {
  20760. uint32 argb;
  20761. struct
  20762. {
  20763. #if JUCE_BIG_ENDIAN
  20764. uint8 a : 8, r : 8, g : 8, b : 8;
  20765. #else
  20766. uint8 b, g, r, a;
  20767. #endif
  20768. } PACKED components;
  20769. };
  20770. }
  20771. #ifndef DOXYGEN
  20772. PACKED
  20773. #endif
  20774. ;
  20775. /**
  20776. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  20777. This is used internally by the imaging classes.
  20778. @see PixelARGB
  20779. */
  20780. class JUCE_API PixelRGB
  20781. {
  20782. public:
  20783. /** Creates a pixel without defining its colour. */
  20784. PixelRGB() throw() {}
  20785. ~PixelRGB() throw() {}
  20786. /** Creates a pixel from a 32-bit argb value.
  20787. (The argb format is that used by PixelARGB)
  20788. */
  20789. PixelRGB (const uint32 argb) throw()
  20790. {
  20791. r = (uint8) (argb >> 16);
  20792. g = (uint8) (argb >> 8);
  20793. b = (uint8) (argb);
  20794. }
  20795. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  20796. forcedinline uint32 getUnpremultipliedARGB() const throw() { return getARGB(); }
  20797. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  20798. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  20799. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  20800. forcedinline uint8 getRed() const throw() { return r; }
  20801. forcedinline uint8 getGreen() const throw() { return g; }
  20802. forcedinline uint8 getBlue() const throw() { return b; }
  20803. /** Blends another pixel onto this one.
  20804. This takes into account the opacity of the pixel being overlaid, and blends
  20805. it accordingly.
  20806. */
  20807. forcedinline void blend (const PixelARGB& src) throw()
  20808. {
  20809. uint32 sargb = src.getARGB();
  20810. const uint32 alpha = 0x100 - (sargb >> 24);
  20811. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  20812. sargb += 0x0000ff00 & (g * alpha);
  20813. r = (uint8) (sargb >> 16);
  20814. g = (uint8) (sargb >> 8);
  20815. b = (uint8) sargb;
  20816. }
  20817. forcedinline void blend (const PixelRGB& src) throw()
  20818. {
  20819. set (src);
  20820. }
  20821. forcedinline void blend (const PixelAlpha& src) throw();
  20822. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  20823. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  20824. being used, so this can blend semi-transparently from a PixelRGB argument.
  20825. */
  20826. template <class Pixel>
  20827. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  20828. {
  20829. ++extraAlpha;
  20830. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  20831. const uint32 sag = extraAlpha * src.getAG();
  20832. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  20833. const uint32 alpha = 0x100 - (sargb >> 24);
  20834. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  20835. sargb += 0x0000ff00 & (g * alpha);
  20836. b = (uint8) sargb;
  20837. g = (uint8) (sargb >> 8);
  20838. r = (uint8) (sargb >> 16);
  20839. }
  20840. /** Blends another pixel with this one, creating a colour that is somewhere
  20841. between the two, as specified by the amount.
  20842. */
  20843. template <class Pixel>
  20844. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  20845. {
  20846. uint32 drb = getRB();
  20847. drb += (((src.getRB() - drb) * amount) >> 8);
  20848. uint32 dag = getAG();
  20849. dag += (((src.getAG() - dag) * amount) >> 8);
  20850. b = (uint8) drb;
  20851. g = (uint8) dag;
  20852. r = (uint8) (drb >> 16);
  20853. }
  20854. /** Copies another pixel colour over this one.
  20855. This doesn't blend it - this colour is simply replaced by the other one.
  20856. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  20857. is thrown away.
  20858. */
  20859. template <class Pixel>
  20860. forcedinline void set (const Pixel& src) throw()
  20861. {
  20862. b = src.getBlue();
  20863. g = src.getGreen();
  20864. r = src.getRed();
  20865. }
  20866. /** This method is included for compatibility with the PixelARGB class. */
  20867. forcedinline void setAlpha (const uint8) throw() {}
  20868. /** Multiplies the colour's alpha value with another one. */
  20869. forcedinline void multiplyAlpha (int) throw() {}
  20870. /** Sets the pixel's colour from individual components. */
  20871. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  20872. {
  20873. r = r_;
  20874. g = g_;
  20875. b = b_;
  20876. }
  20877. /** Premultiplies the pixel's RGB values by its alpha. */
  20878. forcedinline void premultiply() throw() {}
  20879. /** Unpremultiplies the pixel's RGB values. */
  20880. forcedinline void unpremultiply() throw() {}
  20881. forcedinline void desaturate() throw()
  20882. {
  20883. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  20884. }
  20885. /** The indexes of the different components in the byte layout of this type of colour. */
  20886. #if JUCE_MAC
  20887. enum { indexR = 0, indexG = 1, indexB = 2 };
  20888. #else
  20889. enum { indexR = 2, indexG = 1, indexB = 0 };
  20890. #endif
  20891. private:
  20892. #if JUCE_MAC
  20893. uint8 r, g, b;
  20894. #else
  20895. uint8 b, g, r;
  20896. #endif
  20897. }
  20898. #ifndef DOXYGEN
  20899. PACKED
  20900. #endif
  20901. ;
  20902. forcedinline void PixelARGB::blend (const PixelRGB& src) throw()
  20903. {
  20904. set (src);
  20905. }
  20906. /**
  20907. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  20908. This is used internally by the imaging classes.
  20909. @see PixelARGB, PixelRGB
  20910. */
  20911. class JUCE_API PixelAlpha
  20912. {
  20913. public:
  20914. /** Creates a pixel without defining its colour. */
  20915. PixelAlpha() throw() {}
  20916. ~PixelAlpha() throw() {}
  20917. /** Creates a pixel from a 32-bit argb value.
  20918. (The argb format is that used by PixelARGB)
  20919. */
  20920. PixelAlpha (const uint32 argb) throw()
  20921. {
  20922. a = (uint8) (argb >> 24);
  20923. }
  20924. forcedinline uint32 getARGB() const throw() { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  20925. forcedinline uint32 getUnpremultipliedARGB() const throw() { return (((uint32) a) << 24) | 0xffffff; }
  20926. forcedinline uint32 getRB() const throw() { return (((uint32) a) << 16) | a; }
  20927. forcedinline uint32 getAG() const throw() { return (((uint32) a) << 16) | a; }
  20928. forcedinline uint8 getAlpha() const throw() { return a; }
  20929. forcedinline uint8 getRed() const throw() { return 0; }
  20930. forcedinline uint8 getGreen() const throw() { return 0; }
  20931. forcedinline uint8 getBlue() const throw() { return 0; }
  20932. /** Blends another pixel onto this one.
  20933. This takes into account the opacity of the pixel being overlaid, and blends
  20934. it accordingly.
  20935. */
  20936. template <class Pixel>
  20937. forcedinline void blend (const Pixel& src) throw()
  20938. {
  20939. const int srcA = src.getAlpha();
  20940. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  20941. }
  20942. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  20943. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  20944. being used, so this can blend semi-transparently from a PixelRGB argument.
  20945. */
  20946. template <class Pixel>
  20947. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  20948. {
  20949. ++extraAlpha;
  20950. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  20951. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  20952. }
  20953. /** Blends another pixel with this one, creating a colour that is somewhere
  20954. between the two, as specified by the amount.
  20955. */
  20956. template <class Pixel>
  20957. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  20958. {
  20959. a += ((src,getAlpha() - a) * amount) >> 8;
  20960. }
  20961. /** Copies another pixel colour over this one.
  20962. This doesn't blend it - this colour is simply replaced by the other one.
  20963. */
  20964. template <class Pixel>
  20965. forcedinline void set (const Pixel& src) throw()
  20966. {
  20967. a = src.getAlpha();
  20968. }
  20969. /** Replaces the colour's alpha value with another one. */
  20970. forcedinline void setAlpha (const uint8 newAlpha) throw()
  20971. {
  20972. a = newAlpha;
  20973. }
  20974. /** Multiplies the colour's alpha value with another one. */
  20975. forcedinline void multiplyAlpha (int multiplier) throw()
  20976. {
  20977. ++multiplier;
  20978. a = (uint8) ((a * multiplier) >> 8);
  20979. }
  20980. forcedinline void multiplyAlpha (const float multiplier) throw()
  20981. {
  20982. a = (uint8) (a * multiplier);
  20983. }
  20984. /** Sets the pixel's colour from individual components. */
  20985. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) throw()
  20986. {
  20987. a = a_;
  20988. }
  20989. /** Premultiplies the pixel's RGB values by its alpha. */
  20990. forcedinline void premultiply() throw()
  20991. {
  20992. }
  20993. /** Unpremultiplies the pixel's RGB values. */
  20994. forcedinline void unpremultiply() throw()
  20995. {
  20996. }
  20997. forcedinline void desaturate() throw()
  20998. {
  20999. }
  21000. /** The indexes of the different components in the byte layout of this type of colour. */
  21001. enum { indexA = 0 };
  21002. private:
  21003. uint8 a : 8;
  21004. }
  21005. #ifndef DOXYGEN
  21006. PACKED
  21007. #endif
  21008. ;
  21009. forcedinline void PixelRGB::blend (const PixelAlpha& src) throw()
  21010. {
  21011. blend (PixelARGB (src.getARGB()));
  21012. }
  21013. forcedinline void PixelARGB::blend (const PixelAlpha& src) throw()
  21014. {
  21015. uint32 sargb = src.getARGB();
  21016. const uint32 alpha = 0x100 - (sargb >> 24);
  21017. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  21018. sargb += 0xff00ff00 & (getAG() * alpha);
  21019. argb = sargb;
  21020. }
  21021. #if JUCE_MSVC
  21022. #pragma pack (pop)
  21023. #endif
  21024. #undef PACKED
  21025. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  21026. /*** End of inlined file: juce_PixelFormats.h ***/
  21027. /**
  21028. Represents a colour, also including a transparency value.
  21029. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  21030. */
  21031. class JUCE_API Colour
  21032. {
  21033. public:
  21034. /** Creates a transparent black colour. */
  21035. Colour() throw();
  21036. /** Creates a copy of another Colour object. */
  21037. Colour (const Colour& other) throw();
  21038. /** Creates a colour from a 32-bit ARGB value.
  21039. The format of this number is:
  21040. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  21041. All components in the range 0x00 to 0xff.
  21042. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21043. @see getPixelARGB
  21044. */
  21045. explicit Colour (uint32 argb) throw();
  21046. /** Creates an opaque colour using 8-bit red, green and blue values */
  21047. Colour (uint8 red,
  21048. uint8 green,
  21049. uint8 blue) throw();
  21050. /** Creates an opaque colour using 8-bit red, green and blue values */
  21051. static const Colour fromRGB (uint8 red,
  21052. uint8 green,
  21053. uint8 blue) throw();
  21054. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21055. Colour (uint8 red,
  21056. uint8 green,
  21057. uint8 blue,
  21058. uint8 alpha) throw();
  21059. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21060. static const Colour fromRGBA (uint8 red,
  21061. uint8 green,
  21062. uint8 blue,
  21063. uint8 alpha) throw();
  21064. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  21065. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  21066. Values outside the valid range will be clipped.
  21067. */
  21068. Colour (uint8 red,
  21069. uint8 green,
  21070. uint8 blue,
  21071. float alpha) throw();
  21072. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  21073. static const Colour fromRGBAFloat (uint8 red,
  21074. uint8 green,
  21075. uint8 blue,
  21076. float alpha) throw();
  21077. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21078. The floating point values must be between 0.0 and 1.0.
  21079. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21080. Values outside the valid range will be clipped.
  21081. */
  21082. Colour (float hue,
  21083. float saturation,
  21084. float brightness,
  21085. uint8 alpha) throw();
  21086. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  21087. All values must be between 0.0 and 1.0.
  21088. Numbers outside the valid range will be clipped.
  21089. */
  21090. Colour (float hue,
  21091. float saturation,
  21092. float brightness,
  21093. float alpha) throw();
  21094. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21095. The floating point values must be between 0.0 and 1.0.
  21096. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21097. Values outside the valid range will be clipped.
  21098. */
  21099. static const Colour fromHSV (float hue,
  21100. float saturation,
  21101. float brightness,
  21102. float alpha) throw();
  21103. /** Destructor. */
  21104. ~Colour() throw();
  21105. /** Copies another Colour object. */
  21106. Colour& operator= (const Colour& other) throw();
  21107. /** Compares two colours. */
  21108. bool operator== (const Colour& other) const throw();
  21109. /** Compares two colours. */
  21110. bool operator!= (const Colour& other) const throw();
  21111. /** Returns the red component of this colour.
  21112. @returns a value between 0x00 and 0xff.
  21113. */
  21114. uint8 getRed() const throw() { return argb.getRed(); }
  21115. /** Returns the green component of this colour.
  21116. @returns a value between 0x00 and 0xff.
  21117. */
  21118. uint8 getGreen() const throw() { return argb.getGreen(); }
  21119. /** Returns the blue component of this colour.
  21120. @returns a value between 0x00 and 0xff.
  21121. */
  21122. uint8 getBlue() const throw() { return argb.getBlue(); }
  21123. /** Returns the red component of this colour as a floating point value.
  21124. @returns a value between 0.0 and 1.0
  21125. */
  21126. float getFloatRed() const throw();
  21127. /** Returns the green component of this colour as a floating point value.
  21128. @returns a value between 0.0 and 1.0
  21129. */
  21130. float getFloatGreen() const throw();
  21131. /** Returns the blue component of this colour as a floating point value.
  21132. @returns a value between 0.0 and 1.0
  21133. */
  21134. float getFloatBlue() const throw();
  21135. /** Returns a premultiplied ARGB pixel object that represents this colour.
  21136. */
  21137. const PixelARGB getPixelARGB() const throw();
  21138. /** Returns a 32-bit integer that represents this colour.
  21139. The format of this number is:
  21140. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  21141. */
  21142. uint32 getARGB() const throw();
  21143. /** Returns the colour's alpha (opacity).
  21144. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  21145. */
  21146. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  21147. /** Returns the colour's alpha (opacity) as a floating point value.
  21148. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  21149. */
  21150. float getFloatAlpha() const throw();
  21151. /** Returns true if this colour is completely opaque.
  21152. Equivalent to (getAlpha() == 0xff).
  21153. */
  21154. bool isOpaque() const throw();
  21155. /** Returns true if this colour is completely transparent.
  21156. Equivalent to (getAlpha() == 0x00).
  21157. */
  21158. bool isTransparent() const throw();
  21159. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21160. const Colour withAlpha (uint8 newAlpha) const throw();
  21161. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21162. const Colour withAlpha (float newAlpha) const throw();
  21163. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  21164. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  21165. */
  21166. const Colour withMultipliedAlpha (float alphaMultiplier) const throw();
  21167. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  21168. If the foreground colour is semi-transparent, it is blended onto this colour
  21169. accordingly.
  21170. */
  21171. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  21172. /** Returns a colour that lies somewhere between this one and another.
  21173. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  21174. is 1.0, the result is 100% of the other colour.
  21175. */
  21176. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const throw();
  21177. /** Returns the colour's hue component.
  21178. The value returned is in the range 0.0 to 1.0
  21179. */
  21180. float getHue() const throw();
  21181. /** Returns the colour's saturation component.
  21182. The value returned is in the range 0.0 to 1.0
  21183. */
  21184. float getSaturation() const throw();
  21185. /** Returns the colour's brightness component.
  21186. The value returned is in the range 0.0 to 1.0
  21187. */
  21188. float getBrightness() const throw();
  21189. /** Returns the colour's hue, saturation and brightness components all at once.
  21190. The values returned are in the range 0.0 to 1.0
  21191. */
  21192. void getHSB (float& hue,
  21193. float& saturation,
  21194. float& brightness) const throw();
  21195. /** Returns a copy of this colour with a different hue. */
  21196. const Colour withHue (float newHue) const throw();
  21197. /** Returns a copy of this colour with a different saturation. */
  21198. const Colour withSaturation (float newSaturation) const throw();
  21199. /** Returns a copy of this colour with a different brightness.
  21200. @see brighter, darker, withMultipliedBrightness
  21201. */
  21202. const Colour withBrightness (float newBrightness) const throw();
  21203. /** Returns a copy of this colour with it hue rotated.
  21204. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  21205. @see brighter, darker, withMultipliedBrightness
  21206. */
  21207. const Colour withRotatedHue (float amountToRotate) const throw();
  21208. /** Returns a copy of this colour with its saturation multiplied by the given value.
  21209. The new colour's saturation is (this->getSaturation() * multiplier)
  21210. (the result is clipped to legal limits).
  21211. */
  21212. const Colour withMultipliedSaturation (float multiplier) const throw();
  21213. /** Returns a copy of this colour with its brightness multiplied by the given value.
  21214. The new colour's saturation is (this->getBrightness() * multiplier)
  21215. (the result is clipped to legal limits).
  21216. */
  21217. const Colour withMultipliedBrightness (float amount) const throw();
  21218. /** Returns a brighter version of this colour.
  21219. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  21220. unchanged, and higher values make it brighter
  21221. @see withMultipliedBrightness
  21222. */
  21223. const Colour brighter (float amountBrighter = 0.4f) const throw();
  21224. /** Returns a darker version of this colour.
  21225. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  21226. unchanged, and higher values make it darker
  21227. @see withMultipliedBrightness
  21228. */
  21229. const Colour darker (float amountDarker = 0.4f) const throw();
  21230. /** Returns a colour that will be clearly visible against this colour.
  21231. The amount parameter indicates how contrasting the new colour should
  21232. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  21233. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  21234. return white; Colours::white.contrasting (1.0f) will return black, etc.
  21235. */
  21236. const Colour contrasting (float amount = 1.0f) const throw();
  21237. /** Returns a colour that contrasts against two colours.
  21238. Looks for a colour that contrasts with both of the colours passed-in.
  21239. Handy for things like choosing a highlight colour in text editors, etc.
  21240. */
  21241. static const Colour contrasting (const Colour& colour1,
  21242. const Colour& colour2) throw();
  21243. /** Returns an opaque shade of grey.
  21244. @param brightness the level of grey to return - 0 is black, 1.0 is white
  21245. */
  21246. static const Colour greyLevel (float brightness) throw();
  21247. /** Returns a stringified version of this colour.
  21248. The string can be turned back into a colour using the fromString() method.
  21249. */
  21250. const String toString() const;
  21251. /** Reads the colour from a string that was created with toString().
  21252. */
  21253. static const Colour fromString (const String& encodedColourString);
  21254. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  21255. const String toDisplayString (bool includeAlphaValue) const;
  21256. private:
  21257. PixelARGB argb;
  21258. };
  21259. #endif // __JUCE_COLOUR_JUCEHEADER__
  21260. /*** End of inlined file: juce_Colour.h ***/
  21261. /**
  21262. Contains a set of predefined named colours (mostly standard HTML colours)
  21263. @see Colour, Colours::greyLevel
  21264. */
  21265. class Colours
  21266. {
  21267. public:
  21268. static JUCE_API const Colour
  21269. transparentBlack, /**< ARGB = 0x00000000 */
  21270. transparentWhite, /**< ARGB = 0x00ffffff */
  21271. black, /**< ARGB = 0xff000000 */
  21272. white, /**< ARGB = 0xffffffff */
  21273. blue, /**< ARGB = 0xff0000ff */
  21274. grey, /**< ARGB = 0xff808080 */
  21275. green, /**< ARGB = 0xff008000 */
  21276. red, /**< ARGB = 0xffff0000 */
  21277. yellow, /**< ARGB = 0xffffff00 */
  21278. aliceblue, antiquewhite, aqua, aquamarine,
  21279. azure, beige, bisque, blanchedalmond,
  21280. blueviolet, brown, burlywood, cadetblue,
  21281. chartreuse, chocolate, coral, cornflowerblue,
  21282. cornsilk, crimson, cyan, darkblue,
  21283. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  21284. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  21285. darkorchid, darkred, darksalmon, darkseagreen,
  21286. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  21287. deeppink, deepskyblue, dimgrey, dodgerblue,
  21288. firebrick, floralwhite, forestgreen, fuchsia,
  21289. gainsboro, gold, goldenrod, greenyellow,
  21290. honeydew, hotpink, indianred, indigo,
  21291. ivory, khaki, lavender, lavenderblush,
  21292. lemonchiffon, lightblue, lightcoral, lightcyan,
  21293. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  21294. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  21295. lightsteelblue, lightyellow, lime, limegreen,
  21296. linen, magenta, maroon, mediumaquamarine,
  21297. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  21298. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  21299. midnightblue, mintcream, mistyrose, navajowhite,
  21300. navy, oldlace, olive, olivedrab,
  21301. orange, orangered, orchid, palegoldenrod,
  21302. palegreen, paleturquoise, palevioletred, papayawhip,
  21303. peachpuff, peru, pink, plum,
  21304. powderblue, purple, rosybrown, royalblue,
  21305. saddlebrown, salmon, sandybrown, seagreen,
  21306. seashell, sienna, silver, skyblue,
  21307. slateblue, slategrey, snow, springgreen,
  21308. steelblue, tan, teal, thistle,
  21309. tomato, turquoise, violet, wheat,
  21310. whitesmoke, yellowgreen;
  21311. /** Attempts to look up a string in the list of known colour names, and return
  21312. the appropriate colour.
  21313. A non-case-sensitive search is made of the list of predefined colours, and
  21314. if a match is found, that colour is returned. If no match is found, the
  21315. colour passed in as the defaultColour parameter is returned.
  21316. */
  21317. static JUCE_API const Colour findColourForName (const String& colourName,
  21318. const Colour& defaultColour);
  21319. private:
  21320. // this isn't a class you should ever instantiate - it's just here for the
  21321. // static values in it.
  21322. Colours();
  21323. JUCE_DECLARE_NON_COPYABLE (Colours);
  21324. };
  21325. #endif // __JUCE_COLOURS_JUCEHEADER__
  21326. /*** End of inlined file: juce_Colours.h ***/
  21327. /*** Start of inlined file: juce_ColourGradient.h ***/
  21328. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  21329. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  21330. /**
  21331. Describes the layout and colours that should be used to paint a colour gradient.
  21332. @see Graphics::setGradientFill
  21333. */
  21334. class JUCE_API ColourGradient
  21335. {
  21336. public:
  21337. /** Creates a gradient object.
  21338. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  21339. colour2 should be. In between them there's a gradient.
  21340. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  21341. its centre.
  21342. The alpha transparencies of the colours are used, so note that
  21343. if you blend from transparent to a solid colour, the RGB of the transparent
  21344. colour will become visible in parts of the gradient. e.g. blending
  21345. from Colour::transparentBlack to Colours::white will produce a
  21346. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  21347. will be white all the way across.
  21348. @see ColourGradient
  21349. */
  21350. ColourGradient (const Colour& colour1, float x1, float y1,
  21351. const Colour& colour2, float x2, float y2,
  21352. bool isRadial);
  21353. /** Creates an uninitialised gradient.
  21354. If you use this constructor instead of the other one, be sure to set all the
  21355. object's public member variables before using it!
  21356. */
  21357. ColourGradient() throw();
  21358. /** Destructor */
  21359. ~ColourGradient();
  21360. /** Removes any colours that have been added.
  21361. This will also remove any start and end colours, so the gradient won't work. You'll
  21362. need to add more colours with addColour().
  21363. */
  21364. void clearColours();
  21365. /** Adds a colour at a point along the length of the gradient.
  21366. This allows the gradient to go through a spectrum of colours, instead of just a
  21367. start and end colour.
  21368. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  21369. of the distance along the line between the two points
  21370. at which the colour should occur.
  21371. @param colour the colour that should be used at this point
  21372. @returns the index at which the new point was added
  21373. */
  21374. int addColour (double proportionAlongGradient,
  21375. const Colour& colour);
  21376. /** Removes one of the colours from the gradient. */
  21377. void removeColour (int index);
  21378. /** Multiplies the alpha value of all the colours by the given scale factor */
  21379. void multiplyOpacity (float multiplier) throw();
  21380. /** Returns the number of colour-stops that have been added. */
  21381. int getNumColours() const throw();
  21382. /** Returns the position along the length of the gradient of the colour with this index.
  21383. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  21384. */
  21385. double getColourPosition (int index) const throw();
  21386. /** Returns the colour that was added with a given index.
  21387. The index is from 0 to getNumColours() - 1.
  21388. */
  21389. const Colour getColour (int index) const throw();
  21390. /** Changes the colour at a given index.
  21391. The index is from 0 to getNumColours() - 1.
  21392. */
  21393. void setColour (int index, const Colour& newColour) throw();
  21394. /** Returns the an interpolated colour at any position along the gradient.
  21395. @param position the position along the gradient, between 0 and 1
  21396. */
  21397. const Colour getColourAtPosition (double position) const throw();
  21398. /** Creates a set of interpolated premultiplied ARGB values.
  21399. This will resize the HeapBlock, fill it with the colours, and will return the number of
  21400. colours that it added.
  21401. */
  21402. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  21403. /** Returns true if all colours are opaque. */
  21404. bool isOpaque() const throw();
  21405. /** Returns true if all colours are completely transparent. */
  21406. bool isInvisible() const throw();
  21407. Point<float> point1, point2;
  21408. /** If true, the gradient should be filled circularly, centred around
  21409. point1, with point2 defining a point on the circumference.
  21410. If false, the gradient is linear between the two points.
  21411. */
  21412. bool isRadial;
  21413. bool operator== (const ColourGradient& other) const throw();
  21414. bool operator!= (const ColourGradient& other) const throw();
  21415. private:
  21416. struct ColourPoint
  21417. {
  21418. ColourPoint() throw() {}
  21419. ColourPoint (const double position_, const Colour& colour_) throw()
  21420. : position (position_), colour (colour_)
  21421. {}
  21422. bool operator== (const ColourPoint& other) const throw();
  21423. bool operator!= (const ColourPoint& other) const throw();
  21424. double position;
  21425. Colour colour;
  21426. };
  21427. Array <ColourPoint> colours;
  21428. JUCE_LEAK_DETECTOR (ColourGradient);
  21429. };
  21430. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  21431. /*** End of inlined file: juce_ColourGradient.h ***/
  21432. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  21433. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  21434. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  21435. /**
  21436. Defines the method used to postion some kind of rectangular object within
  21437. a rectangular viewport.
  21438. Although similar to Justification, this is more specific, and has some extra
  21439. options.
  21440. */
  21441. class JUCE_API RectanglePlacement
  21442. {
  21443. public:
  21444. /** Creates a RectanglePlacement object using a combination of flags. */
  21445. inline RectanglePlacement (int flags_) throw() : flags (flags_) {}
  21446. /** Creates a copy of another RectanglePlacement object. */
  21447. RectanglePlacement (const RectanglePlacement& other) throw();
  21448. /** Copies another RectanglePlacement object. */
  21449. RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  21450. /** Flag values that can be combined and used in the constructor. */
  21451. enum
  21452. {
  21453. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  21454. xLeft = 1,
  21455. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  21456. xRight = 2,
  21457. /** Indicates that the source should be placed in the centre between the left and right
  21458. sides of the available space. */
  21459. xMid = 4,
  21460. /** Indicates that the source's top edge should be aligned with the top edge of the
  21461. destination rectangle. */
  21462. yTop = 8,
  21463. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  21464. destination rectangle. */
  21465. yBottom = 16,
  21466. /** Indicates that the source should be placed in the centre between the top and bottom
  21467. sides of the available space. */
  21468. yMid = 32,
  21469. /** If this flag is set, then the source rectangle will be resized to completely fill
  21470. the destination rectangle, and all other flags are ignored.
  21471. */
  21472. stretchToFit = 64,
  21473. /** If this flag is set, then the source rectangle will be resized so that it is the
  21474. minimum size to completely fill the destination rectangle, without changing its
  21475. aspect ratio. This means that some of the source rectangle may fall outside
  21476. the destination.
  21477. If this flag is not set, the source will be given the maximum size at which none
  21478. of it falls outside the destination rectangle.
  21479. */
  21480. fillDestination = 128,
  21481. /** Indicates that the source rectangle can be reduced in size if required, but should
  21482. never be made larger than its original size.
  21483. */
  21484. onlyReduceInSize = 256,
  21485. /** Indicates that the source rectangle can be enlarged if required, but should
  21486. never be made smaller than its original size.
  21487. */
  21488. onlyIncreaseInSize = 512,
  21489. /** Indicates that the source rectangle's size should be left unchanged.
  21490. */
  21491. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  21492. /** A shorthand value that is equivalent to (xMid | yMid). */
  21493. centred = 4 + 32
  21494. };
  21495. /** Returns the raw flags that are set for this object. */
  21496. inline int getFlags() const throw() { return flags; }
  21497. /** Tests a set of flags for this object.
  21498. @returns true if any of the flags passed in are set on this object.
  21499. */
  21500. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  21501. /** Adjusts the position and size of a rectangle to fit it into a space.
  21502. The source rectangle co-ordinates will be adjusted so that they fit into
  21503. the destination rectangle based on this object's flags.
  21504. */
  21505. void applyTo (double& sourceX,
  21506. double& sourceY,
  21507. double& sourceW,
  21508. double& sourceH,
  21509. double destinationX,
  21510. double destinationY,
  21511. double destinationW,
  21512. double destinationH) const throw();
  21513. /** Returns the transform that should be applied to these source co-ordinates to fit them
  21514. into the destination rectangle using the current flags.
  21515. */
  21516. template <typename ValueType>
  21517. const Rectangle<ValueType> appliedTo (const Rectangle<ValueType>& source,
  21518. const Rectangle<ValueType>& destination) const throw()
  21519. {
  21520. double x = source.getX(), y = source.getY(), w = source.getWidth(), h = source.getHeight();
  21521. applyTo (x, y, w, h, static_cast <double> (destination.getX()), static_cast <double> (destination.getY()),
  21522. static_cast <double> (destination.getWidth()), static_cast <double> (destination.getHeight()));
  21523. return Rectangle<ValueType> (static_cast <ValueType> (x), static_cast <ValueType> (y),
  21524. static_cast <ValueType> (w), static_cast <ValueType> (h));
  21525. }
  21526. /** Returns the transform that should be applied to these source co-ordinates to fit them
  21527. into the destination rectangle using the current flags.
  21528. */
  21529. const AffineTransform getTransformToFit (const Rectangle<float>& source,
  21530. const Rectangle<float>& destination) const throw();
  21531. private:
  21532. int flags;
  21533. };
  21534. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  21535. /*** End of inlined file: juce_RectanglePlacement.h ***/
  21536. class LowLevelGraphicsContext;
  21537. class Image;
  21538. class FillType;
  21539. class RectangleList;
  21540. /**
  21541. A graphics context, used for drawing a component or image.
  21542. When a Component needs painting, a Graphics context is passed to its
  21543. Component::paint() method, and this you then call methods within this
  21544. object to actually draw the component's content.
  21545. A Graphics can also be created from an image, to allow drawing directly onto
  21546. that image.
  21547. @see Component::paint
  21548. */
  21549. class JUCE_API Graphics
  21550. {
  21551. public:
  21552. /** Creates a Graphics object to draw directly onto the given image.
  21553. The graphics object that is created will be set up to draw onto the image,
  21554. with the context's clipping area being the entire size of the image, and its
  21555. origin being the image's origin. To draw into a subsection of an image, use the
  21556. reduceClipRegion() and setOrigin() methods.
  21557. Obviously you shouldn't delete the image before this context is deleted.
  21558. */
  21559. explicit Graphics (const Image& imageToDrawOnto);
  21560. /** Destructor. */
  21561. ~Graphics();
  21562. /** Changes the current drawing colour.
  21563. This sets the colour that will now be used for drawing operations - it also
  21564. sets the opacity to that of the colour passed-in.
  21565. If a brush is being used when this method is called, the brush will be deselected,
  21566. and any subsequent drawing will be done with a solid colour brush instead.
  21567. @see setOpacity
  21568. */
  21569. void setColour (const Colour& newColour);
  21570. /** Changes the opacity to use with the current colour.
  21571. If a solid colour is being used for drawing, this changes its opacity
  21572. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  21573. If a gradient is being used, this will have no effect on it.
  21574. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  21575. */
  21576. void setOpacity (float newOpacity);
  21577. /** Sets the context to use a gradient for its fill pattern.
  21578. */
  21579. void setGradientFill (const ColourGradient& gradient);
  21580. /** Sets the context to use a tiled image pattern for filling.
  21581. Make sure that you don't delete this image while it's still being used by
  21582. this context!
  21583. */
  21584. void setTiledImageFill (const Image& imageToUse,
  21585. int anchorX, int anchorY,
  21586. float opacity);
  21587. /** Changes the current fill settings.
  21588. @see setColour, setGradientFill, setTiledImageFill
  21589. */
  21590. void setFillType (const FillType& newFill);
  21591. /** Changes the font to use for subsequent text-drawing functions.
  21592. Note there's also a setFont (float, int) method to quickly change the size and
  21593. style of the current font.
  21594. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  21595. */
  21596. void setFont (const Font& newFont);
  21597. /** Changes the size and style of the currently-selected font.
  21598. This is a convenient shortcut that changes the context's current font to a
  21599. different size or style. The typeface won't be changed.
  21600. @see Font
  21601. */
  21602. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  21603. /** Returns the currently selected font. */
  21604. const Font getCurrentFont() const;
  21605. /** Draws a one-line text string.
  21606. This will use the current colour (or brush) to fill the text. The font is the last
  21607. one specified by setFont().
  21608. @param text the string to draw
  21609. @param startX the position to draw the left-hand edge of the text
  21610. @param baselineY the position of the text's baseline
  21611. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  21612. */
  21613. void drawSingleLineText (const String& text,
  21614. int startX, int baselineY) const;
  21615. /** Draws text across multiple lines.
  21616. This will break the text onto a new line where there's a new-line or
  21617. carriage-return character, or at a word-boundary when the text becomes wider
  21618. than the size specified by the maximumLineWidth parameter.
  21619. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  21620. */
  21621. void drawMultiLineText (const String& text,
  21622. int startX, int baselineY,
  21623. int maximumLineWidth) const;
  21624. /** Renders a string of text as a vector path.
  21625. This allows a string to be transformed with an arbitrary AffineTransform and
  21626. rendered using the current colour/brush. It's much slower than the normal text methods
  21627. but more accurate.
  21628. @see setFont
  21629. */
  21630. void drawTextAsPath (const String& text,
  21631. const AffineTransform& transform) const;
  21632. /** Draws a line of text within a specified rectangle.
  21633. The text will be positioned within the rectangle based on the justification
  21634. flags passed-in. If the string is too long to fit inside the rectangle, it will
  21635. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  21636. flag is true).
  21637. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  21638. */
  21639. void drawText (const String& text,
  21640. int x, int y, int width, int height,
  21641. const Justification& justificationType,
  21642. bool useEllipsesIfTooBig) const;
  21643. /** Tries to draw a text string inside a given space.
  21644. This does its best to make the given text readable within the specified rectangle,
  21645. so it useful for labelling things.
  21646. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  21647. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  21648. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  21649. it's been truncated.
  21650. A Justification parameter lets you specify how the text is laid out within the rectangle,
  21651. both horizontally and vertically.
  21652. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  21653. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  21654. can set this value to 1.0f.
  21655. @see GlyphArrangement::addFittedText
  21656. */
  21657. void drawFittedText (const String& text,
  21658. int x, int y, int width, int height,
  21659. const Justification& justificationFlags,
  21660. int maximumNumberOfLines,
  21661. float minimumHorizontalScale = 0.7f) const;
  21662. /** Fills the context's entire clip region with the current colour or brush.
  21663. (See also the fillAll (const Colour&) method which is a quick way of filling
  21664. it with a given colour).
  21665. */
  21666. void fillAll() const;
  21667. /** Fills the context's entire clip region with a given colour.
  21668. This leaves the context's current colour and brush unchanged, it just
  21669. uses the specified colour temporarily.
  21670. */
  21671. void fillAll (const Colour& colourToUse) const;
  21672. /** Fills a rectangle with the current colour or brush.
  21673. @see drawRect, fillRoundedRectangle
  21674. */
  21675. void fillRect (int x, int y, int width, int height) const;
  21676. /** Fills a rectangle with the current colour or brush. */
  21677. void fillRect (const Rectangle<int>& rectangle) const;
  21678. /** Fills a rectangle with the current colour or brush.
  21679. This uses sub-pixel positioning so is slower than the fillRect method which
  21680. takes integer co-ordinates.
  21681. */
  21682. void fillRect (float x, float y, float width, float height) const;
  21683. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  21684. @see drawRoundedRectangle, Path::addRoundedRectangle
  21685. */
  21686. void fillRoundedRectangle (float x, float y, float width, float height,
  21687. float cornerSize) const;
  21688. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  21689. @see drawRoundedRectangle, Path::addRoundedRectangle
  21690. */
  21691. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  21692. float cornerSize) const;
  21693. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  21694. */
  21695. void fillCheckerBoard (const Rectangle<int>& area,
  21696. int checkWidth, int checkHeight,
  21697. const Colour& colour1, const Colour& colour2) const;
  21698. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  21699. The lines are drawn inside the given rectangle, and greater line thicknesses
  21700. extend inwards.
  21701. @see fillRect
  21702. */
  21703. void drawRect (int x, int y, int width, int height,
  21704. int lineThickness = 1) const;
  21705. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  21706. The lines are drawn inside the given rectangle, and greater line thicknesses
  21707. extend inwards.
  21708. @see fillRect
  21709. */
  21710. void drawRect (float x, float y, float width, float height,
  21711. float lineThickness = 1.0f) const;
  21712. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  21713. The lines are drawn inside the given rectangle, and greater line thicknesses
  21714. extend inwards.
  21715. @see fillRect
  21716. */
  21717. void drawRect (const Rectangle<int>& rectangle,
  21718. int lineThickness = 1) const;
  21719. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  21720. @see fillRoundedRectangle, Path::addRoundedRectangle
  21721. */
  21722. void drawRoundedRectangle (float x, float y, float width, float height,
  21723. float cornerSize, float lineThickness) const;
  21724. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  21725. @see fillRoundedRectangle, Path::addRoundedRectangle
  21726. */
  21727. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  21728. float cornerSize, float lineThickness) const;
  21729. /** Draws a 3D raised (or indented) bevel using two colours.
  21730. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  21731. extend inwards.
  21732. The top-left colour is used for the top- and left-hand edges of the
  21733. bevel; the bottom-right colour is used for the bottom- and right-hand
  21734. edges.
  21735. If useGradient is true, then the bevel fades out to make it look more curved
  21736. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  21737. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  21738. the centre edges are sharp and it fades towards the outside.
  21739. */
  21740. void drawBevel (int x, int y, int width, int height,
  21741. int bevelThickness,
  21742. const Colour& topLeftColour = Colours::white,
  21743. const Colour& bottomRightColour = Colours::black,
  21744. bool useGradient = true,
  21745. bool sharpEdgeOnOutside = true) const;
  21746. /** Draws a pixel using the current colour or brush.
  21747. */
  21748. void setPixel (int x, int y) const;
  21749. /** Fills an ellipse with the current colour or brush.
  21750. The ellipse is drawn to fit inside the given rectangle.
  21751. @see drawEllipse, Path::addEllipse
  21752. */
  21753. void fillEllipse (float x, float y, float width, float height) const;
  21754. /** Draws an elliptical stroke using the current colour or brush.
  21755. @see fillEllipse, Path::addEllipse
  21756. */
  21757. void drawEllipse (float x, float y, float width, float height,
  21758. float lineThickness) const;
  21759. /** Draws a line between two points.
  21760. The line is 1 pixel wide and drawn with the current colour or brush.
  21761. */
  21762. void drawLine (float startX, float startY, float endX, float endY) const;
  21763. /** Draws a line between two points with a given thickness.
  21764. @see Path::addLineSegment
  21765. */
  21766. void drawLine (float startX, float startY, float endX, float endY,
  21767. float lineThickness) const;
  21768. /** Draws a line between two points.
  21769. The line is 1 pixel wide and drawn with the current colour or brush.
  21770. */
  21771. void drawLine (const Line<float>& line) const;
  21772. /** Draws a line between two points with a given thickness.
  21773. @see Path::addLineSegment
  21774. */
  21775. void drawLine (const Line<float>& line, float lineThickness) const;
  21776. /** Draws a dashed line using a custom set of dash-lengths.
  21777. @param line the line to draw
  21778. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  21779. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  21780. draw 6 pixels, skip 7 pixels, and then repeat.
  21781. @param numDashLengths the number of elements in the array (this must be an even number).
  21782. @param lineThickness the thickness of the line to draw
  21783. @param dashIndexToStartFrom the index in the dash-length array to use for the first segment
  21784. @see PathStrokeType::createDashedStroke
  21785. */
  21786. void drawDashedLine (const Line<float>& line,
  21787. const float* dashLengths, int numDashLengths,
  21788. float lineThickness = 1.0f,
  21789. int dashIndexToStartFrom = 0) const;
  21790. /** Draws a vertical line of pixels at a given x position.
  21791. The x position is an integer, but the top and bottom of the line can be sub-pixel
  21792. positions, and these will be anti-aliased if necessary.
  21793. */
  21794. void drawVerticalLine (int x, float top, float bottom) const;
  21795. /** Draws a horizontal line of pixels at a given y position.
  21796. The y position is an integer, but the left and right ends of the line can be sub-pixel
  21797. positions, and these will be anti-aliased if necessary.
  21798. */
  21799. void drawHorizontalLine (int y, float left, float right) const;
  21800. /** Fills a path using the currently selected colour or brush.
  21801. */
  21802. void fillPath (const Path& path,
  21803. const AffineTransform& transform = AffineTransform::identity) const;
  21804. /** Draws a path's outline using the currently selected colour or brush.
  21805. */
  21806. void strokePath (const Path& path,
  21807. const PathStrokeType& strokeType,
  21808. const AffineTransform& transform = AffineTransform::identity) const;
  21809. /** Draws a line with an arrowhead at its end.
  21810. @param line the line to draw
  21811. @param lineThickness the thickness of the line
  21812. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  21813. @param arrowheadLength the length of the arrow head (along the length of the line)
  21814. */
  21815. void drawArrow (const Line<float>& line,
  21816. float lineThickness,
  21817. float arrowheadWidth,
  21818. float arrowheadLength) const;
  21819. /** Types of rendering quality that can be specified when drawing images.
  21820. @see blendImage, Graphics::setImageResamplingQuality
  21821. */
  21822. enum ResamplingQuality
  21823. {
  21824. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  21825. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  21826. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  21827. };
  21828. /** Changes the quality that will be used when resampling images.
  21829. By default a Graphics object will be set to mediumRenderingQuality.
  21830. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  21831. */
  21832. void setImageResamplingQuality (const ResamplingQuality newQuality);
  21833. /** Draws an image.
  21834. This will draw the whole of an image, positioning its top-left corner at the
  21835. given co-ordinates, and keeping its size the same. This is the simplest image
  21836. drawing method - the others give more control over the scaling and clipping
  21837. of the images.
  21838. Images are composited using the context's current opacity, so if you
  21839. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  21840. (or setColour() with an opaque colour) before drawing images.
  21841. */
  21842. void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
  21843. bool fillAlphaChannelWithCurrentBrush = false) const;
  21844. /** Draws part of an image, rescaling it to fit in a given target region.
  21845. The specified area of the source image is rescaled and drawn to fill the
  21846. specifed destination rectangle.
  21847. Images are composited using the context's current opacity, so if you
  21848. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  21849. (or setColour() with an opaque colour) before drawing images.
  21850. @param imageToDraw the image to overlay
  21851. @param destX the left of the destination rectangle
  21852. @param destY the top of the destination rectangle
  21853. @param destWidth the width of the destination rectangle
  21854. @param destHeight the height of the destination rectangle
  21855. @param sourceX the left of the rectangle to copy from the source image
  21856. @param sourceY the top of the rectangle to copy from the source image
  21857. @param sourceWidth the width of the rectangle to copy from the source image
  21858. @param sourceHeight the height of the rectangle to copy from the source image
  21859. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  21860. the source image's alpha channel is used as a mask with
  21861. which to fill the destination using the current colour
  21862. or brush. (If the source is has no alpha channel, then
  21863. it will just fill the target with a solid rectangle)
  21864. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  21865. */
  21866. void drawImage (const Image& imageToDraw,
  21867. int destX, int destY, int destWidth, int destHeight,
  21868. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  21869. bool fillAlphaChannelWithCurrentBrush = false) const;
  21870. /** Draws an image, having applied an affine transform to it.
  21871. This lets you throw the image around in some wacky ways, rotate it, shear,
  21872. scale it, etc.
  21873. Images are composited using the context's current opacity, so if you
  21874. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  21875. (or setColour() with an opaque colour) before drawing images.
  21876. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  21877. are ignored and it is filled with the current brush, masked by its alpha channel.
  21878. If you want to render only a subsection of an image, use Image::getClippedImage() to
  21879. create the section that you need.
  21880. @see setImageResamplingQuality, drawImage
  21881. */
  21882. void drawImageTransformed (const Image& imageToDraw,
  21883. const AffineTransform& transform,
  21884. bool fillAlphaChannelWithCurrentBrush = false) const;
  21885. /** Draws an image to fit within a designated rectangle.
  21886. If the image is too big or too small for the space, it will be rescaled
  21887. to fit as nicely as it can do without affecting its aspect ratio. It will
  21888. then be placed within the target rectangle according to the justification flags
  21889. specified.
  21890. @param imageToDraw the source image to draw
  21891. @param destX top-left of the target rectangle to fit it into
  21892. @param destY top-left of the target rectangle to fit it into
  21893. @param destWidth size of the target rectangle to fit the image into
  21894. @param destHeight size of the target rectangle to fit the image into
  21895. @param placementWithinTarget this specifies how the image should be positioned
  21896. within the target rectangle - see the RectanglePlacement
  21897. class for more details about this.
  21898. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  21899. alpha channel will be used as a mask with which to
  21900. draw with the current brush or colour. This is
  21901. similar to fillAlphaMap(), and see also drawImage()
  21902. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  21903. */
  21904. void drawImageWithin (const Image& imageToDraw,
  21905. int destX, int destY, int destWidth, int destHeight,
  21906. const RectanglePlacement& placementWithinTarget,
  21907. bool fillAlphaChannelWithCurrentBrush = false) const;
  21908. /** Returns the position of the bounding box for the current clipping region.
  21909. @see getClipRegion, clipRegionIntersects
  21910. */
  21911. const Rectangle<int> getClipBounds() const;
  21912. /** Checks whether a rectangle overlaps the context's clipping region.
  21913. If this returns false, no part of the given area can be drawn onto, so this
  21914. method can be used to optimise a component's paint() method, by letting it
  21915. avoid drawing complex objects that aren't within the region being repainted.
  21916. */
  21917. bool clipRegionIntersects (const Rectangle<int>& area) const;
  21918. /** Intersects the current clipping region with another region.
  21919. @returns true if the resulting clipping region is non-zero in size
  21920. @see setOrigin, clipRegionIntersects
  21921. */
  21922. bool reduceClipRegion (int x, int y, int width, int height);
  21923. /** Intersects the current clipping region with another region.
  21924. @returns true if the resulting clipping region is non-zero in size
  21925. @see setOrigin, clipRegionIntersects
  21926. */
  21927. bool reduceClipRegion (const Rectangle<int>& area);
  21928. /** Intersects the current clipping region with a rectangle list region.
  21929. @returns true if the resulting clipping region is non-zero in size
  21930. @see setOrigin, clipRegionIntersects
  21931. */
  21932. bool reduceClipRegion (const RectangleList& clipRegion);
  21933. /** Intersects the current clipping region with a path.
  21934. @returns true if the resulting clipping region is non-zero in size
  21935. @see reduceClipRegion
  21936. */
  21937. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  21938. /** Intersects the current clipping region with an image's alpha-channel.
  21939. The current clipping path is intersected with the area covered by this image's
  21940. alpha-channel, after the image has been transformed by the specified matrix.
  21941. @param image the image whose alpha-channel should be used. If the image doesn't
  21942. have an alpha-channel, it is treated as entirely opaque.
  21943. @param transform a matrix to apply to the image
  21944. @returns true if the resulting clipping region is non-zero in size
  21945. @see reduceClipRegion
  21946. */
  21947. bool reduceClipRegion (const Image& image, const AffineTransform& transform);
  21948. /** Excludes a rectangle to stop it being drawn into. */
  21949. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  21950. /** Returns true if no drawing can be done because the clip region is zero. */
  21951. bool isClipEmpty() const;
  21952. /** Saves the current graphics state on an internal stack.
  21953. To restore the state, use restoreState().
  21954. @see ScopedSaveState
  21955. */
  21956. void saveState();
  21957. /** Restores a graphics state that was previously saved with saveState().
  21958. @see ScopedSaveState
  21959. */
  21960. void restoreState();
  21961. /** Uses RAII to save and restore the state of a graphics context.
  21962. On construction, this calls Graphics::saveState(), and on destruction it calls
  21963. Graphics::restoreState() on the Graphics object that you supply.
  21964. */
  21965. class ScopedSaveState
  21966. {
  21967. public:
  21968. ScopedSaveState (Graphics& g);
  21969. ~ScopedSaveState();
  21970. private:
  21971. Graphics& context;
  21972. JUCE_DECLARE_NON_COPYABLE (ScopedSaveState);
  21973. };
  21974. /** Begins rendering to an off-screen bitmap which will later be flattened onto the current
  21975. context with the given opacity.
  21976. The context uses an internal stack of temporary image layers to do this. When you've
  21977. finished drawing to the layer, call endTransparencyLayer() to complete the operation and
  21978. composite the finished layer. Every call to beginTransparencyLayer() MUST be matched
  21979. by a corresponding call to endTransparencyLayer()!
  21980. This call also saves the current state, and endTransparencyLayer() restores it.
  21981. */
  21982. void beginTransparencyLayer (float layerOpacity);
  21983. /** Completes a drawing operation to a temporary semi-transparent buffer.
  21984. See beginTransparencyLayer() for more details.
  21985. */
  21986. void endTransparencyLayer();
  21987. /** Moves the position of the context's origin.
  21988. This changes the position that the context considers to be (0, 0) to
  21989. the specified position.
  21990. So if you call setOrigin (100, 100), then the position that was previously
  21991. referred to as (100, 100) will subsequently be considered to be (0, 0).
  21992. @see reduceClipRegion, addTransform
  21993. */
  21994. void setOrigin (int newOriginX, int newOriginY);
  21995. /** Adds a transformation which will be performed on all the graphics operations that
  21996. the context subsequently performs.
  21997. After calling this, all the coordinates that are passed into the context will be
  21998. transformed by this matrix.
  21999. @see setOrigin
  22000. */
  22001. void addTransform (const AffineTransform& transform);
  22002. /** Resets the current colour, brush, and font to default settings. */
  22003. void resetToDefaultState();
  22004. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  22005. bool isVectorDevice() const;
  22006. /** Create a graphics that uses a given low-level renderer.
  22007. For internal use only.
  22008. NB. The context will NOT be deleted by this object when it is deleted.
  22009. */
  22010. Graphics (LowLevelGraphicsContext* internalContext) throw();
  22011. /** @internal */
  22012. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  22013. private:
  22014. LowLevelGraphicsContext* const context;
  22015. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  22016. bool saveStatePending;
  22017. void saveStateIfPending();
  22018. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Graphics);
  22019. };
  22020. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  22021. /*** End of inlined file: juce_Graphics.h ***/
  22022. /**
  22023. A graphical effect filter that can be applied to components.
  22024. An ImageEffectFilter can be applied to the image that a component
  22025. paints before it hits the screen.
  22026. This is used for adding effects like shadows, blurs, etc.
  22027. @see Component::setComponentEffect
  22028. */
  22029. class JUCE_API ImageEffectFilter
  22030. {
  22031. public:
  22032. /** Overridden to render the effect.
  22033. The implementation of this method must use the image that is passed in
  22034. as its source, and should render its output to the graphics context passed in.
  22035. @param sourceImage the image that the source component has just rendered with
  22036. its paint() method. The image may or may not have an alpha
  22037. channel, depending on whether the component is opaque.
  22038. @param destContext the graphics context to use to draw the resultant image.
  22039. @param alpha the alpha with which to draw the resultant image to the
  22040. target context
  22041. */
  22042. virtual void applyEffect (Image& sourceImage,
  22043. Graphics& destContext,
  22044. float alpha) = 0;
  22045. /** Destructor. */
  22046. virtual ~ImageEffectFilter() {}
  22047. };
  22048. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  22049. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  22050. /*** Start of inlined file: juce_Image.h ***/
  22051. #ifndef __JUCE_IMAGE_JUCEHEADER__
  22052. #define __JUCE_IMAGE_JUCEHEADER__
  22053. /**
  22054. Holds a fixed-size bitmap.
  22055. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  22056. To draw into an image, create a Graphics object for it.
  22057. e.g. @code
  22058. // create a transparent 500x500 image..
  22059. Image myImage (Image::RGB, 500, 500, true);
  22060. Graphics g (myImage);
  22061. g.setColour (Colours::red);
  22062. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  22063. @endcode
  22064. Other useful ways to create an image are with the ImageCache class, or the
  22065. ImageFileFormat, which provides a way to load common image files.
  22066. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  22067. */
  22068. class JUCE_API Image
  22069. {
  22070. public:
  22071. /**
  22072. */
  22073. enum PixelFormat
  22074. {
  22075. UnknownFormat,
  22076. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  22077. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  22078. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  22079. };
  22080. /**
  22081. */
  22082. enum ImageType
  22083. {
  22084. SoftwareImage = 0,
  22085. NativeImage
  22086. };
  22087. /** Creates a null image. */
  22088. Image();
  22089. /** Creates an image with a specified size and format.
  22090. @param format the number of colour channels in the image
  22091. @param imageWidth the desired width of the image, in pixels - this value must be
  22092. greater than zero (otherwise a width of 1 will be used)
  22093. @param imageHeight the desired width of the image, in pixels - this value must be
  22094. greater than zero (otherwise a height of 1 will be used)
  22095. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  22096. or transparent black (if it's ARGB). If false, the image may contain
  22097. junk initially, so you need to make sure you overwrite it thoroughly.
  22098. @param type the type of image - this lets you specify whether you want a purely
  22099. memory-based image, or one that may be managed by the OS if possible.
  22100. */
  22101. Image (PixelFormat format,
  22102. int imageWidth,
  22103. int imageHeight,
  22104. bool clearImage,
  22105. ImageType type = NativeImage);
  22106. /** Creates a shared reference to another image.
  22107. This won't create a duplicate of the image - when Image objects are copied, they simply
  22108. point to the same shared image data. To make sure that an Image object has its own unique,
  22109. unshared internal data, call duplicateIfShared().
  22110. */
  22111. Image (const Image& other);
  22112. /** Makes this image refer to the same underlying image as another object.
  22113. This won't create a duplicate of the image - when Image objects are copied, they simply
  22114. point to the same shared image data. To make sure that an Image object has its own unique,
  22115. unshared internal data, call duplicateIfShared().
  22116. */
  22117. Image& operator= (const Image&);
  22118. /** Destructor. */
  22119. ~Image();
  22120. /** Returns true if the two images are referring to the same internal, shared image. */
  22121. bool operator== (const Image& other) const throw() { return image == other.image; }
  22122. /** Returns true if the two images are not referring to the same internal, shared image. */
  22123. bool operator!= (const Image& other) const throw() { return image != other.image; }
  22124. /** Returns true if this image isn't null.
  22125. If you create an Image with the default constructor, it has no size or content, and is null
  22126. until you reassign it to an Image which contains some actual data.
  22127. The isNull() method is the opposite of isValid().
  22128. @see isNull
  22129. */
  22130. inline bool isValid() const throw() { return image != 0; }
  22131. /** Returns true if this image is not valid.
  22132. If you create an Image with the default constructor, it has no size or content, and is null
  22133. until you reassign it to an Image which contains some actual data.
  22134. The isNull() method is the opposite of isValid().
  22135. @see isValid
  22136. */
  22137. inline bool isNull() const throw() { return image == 0; }
  22138. /** A null Image object that can be used when you need to return an invalid image.
  22139. This object is the equivalient to an Image created with the default constructor.
  22140. */
  22141. static const Image null;
  22142. /** Returns the image's width (in pixels). */
  22143. int getWidth() const throw() { return image == 0 ? 0 : image->width; }
  22144. /** Returns the image's height (in pixels). */
  22145. int getHeight() const throw() { return image == 0 ? 0 : image->height; }
  22146. /** Returns a rectangle with the same size as this image.
  22147. The rectangle's origin is always (0, 0).
  22148. */
  22149. const Rectangle<int> getBounds() const throw() { return image == 0 ? Rectangle<int>() : Rectangle<int> (image->width, image->height); }
  22150. /** Returns the image's pixel format. */
  22151. PixelFormat getFormat() const throw() { return image == 0 ? UnknownFormat : image->format; }
  22152. /** True if the image's format is ARGB. */
  22153. bool isARGB() const throw() { return getFormat() == ARGB; }
  22154. /** True if the image's format is RGB. */
  22155. bool isRGB() const throw() { return getFormat() == RGB; }
  22156. /** True if the image's format is a single-channel alpha map. */
  22157. bool isSingleChannel() const throw() { return getFormat() == SingleChannel; }
  22158. /** True if the image contains an alpha-channel. */
  22159. bool hasAlphaChannel() const throw() { return getFormat() != RGB; }
  22160. /** Clears a section of the image with a given colour.
  22161. This won't do any alpha-blending - it just sets all pixels in the image to
  22162. the given colour (which may be non-opaque if the image has an alpha channel).
  22163. */
  22164. void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  22165. /** Returns a rescaled version of this image.
  22166. A new image is returned which is a copy of this one, rescaled to the given size.
  22167. Note that if the new size is identical to the existing image, this will just return
  22168. a reference to the original image, and won't actually create a duplicate.
  22169. */
  22170. const Image rescaled (int newWidth, int newHeight,
  22171. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  22172. /** Returns a version of this image with a different image format.
  22173. A new image is returned which has been converted to the specified format.
  22174. Note that if the new format is no different to the current one, this will just return
  22175. a reference to the original image, and won't actually create a copy.
  22176. */
  22177. const Image convertedToFormat (PixelFormat newFormat) const;
  22178. /** Makes sure that no other Image objects share the same underlying data as this one.
  22179. If no other Image objects refer to the same shared data as this one, this method has no
  22180. effect. But if there are other references to the data, this will create a new copy of
  22181. the data internally.
  22182. Call this if you want to draw onto the image, but want to make sure that this doesn't
  22183. affect any other code that may be sharing the same data.
  22184. @see getReferenceCount
  22185. */
  22186. void duplicateIfShared();
  22187. /** Returns an image which refers to a subsection of this image.
  22188. This will not make a copy of the original - the new image will keep a reference to it, so that
  22189. if the original image is changed, the contents of the subsection will also change. Likewise if you
  22190. draw into the subimage, you'll also be drawing onto that area of the original image. Note that if
  22191. you use operator= to make the original Image object refer to something else, the subsection image
  22192. won't pick up this change, it'll remain pointing at the original.
  22193. The area passed-in will be clipped to the bounds of this image, so this may return a smaller
  22194. image than the area you asked for, or even a null image if the area was out-of-bounds.
  22195. */
  22196. const Image getClippedImage (const Rectangle<int>& area) const;
  22197. /** Returns the colour of one of the pixels in the image.
  22198. If the co-ordinates given are beyond the image's boundaries, this will
  22199. return Colours::transparentBlack.
  22200. @see setPixelAt, Image::BitmapData::getPixelColour
  22201. */
  22202. const Colour getPixelAt (int x, int y) const;
  22203. /** Sets the colour of one of the image's pixels.
  22204. If the co-ordinates are beyond the image's boundaries, then nothing will happen.
  22205. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  22206. with the given one. The colour's opacity will be ignored if this image doesn't have
  22207. an alpha-channel.
  22208. @see getPixelAt, Image::BitmapData::setPixelColour
  22209. */
  22210. void setPixelAt (int x, int y, const Colour& colour);
  22211. /** Changes the opacity of a pixel.
  22212. This only has an effect if the image has an alpha channel and if the
  22213. given co-ordinates are inside the image's boundary.
  22214. The multiplier must be in the range 0 to 1.0, and the current alpha
  22215. at the given co-ordinates will be multiplied by this value.
  22216. @see setPixelAt
  22217. */
  22218. void multiplyAlphaAt (int x, int y, float multiplier);
  22219. /** Changes the overall opacity of the image.
  22220. This will multiply the alpha value of each pixel in the image by the given
  22221. amount (limiting the resulting alpha values between 0 and 255). This allows
  22222. you to make an image more or less transparent.
  22223. If the image doesn't have an alpha channel, this won't have any effect.
  22224. */
  22225. void multiplyAllAlphas (float amountToMultiplyBy);
  22226. /** Changes all the colours to be shades of grey, based on their current luminosity.
  22227. */
  22228. void desaturate();
  22229. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  22230. You should only use this class as a last resort - messing about with the internals of
  22231. an image is only recommended for people who really know what they're doing!
  22232. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  22233. hanging around while the image is being used elsewhere.
  22234. Depending on the way the image class is implemented, this may create a temporary buffer
  22235. which is copied back to the image when the object is deleted, or it may just get a pointer
  22236. directly into the image's raw data.
  22237. You can use the stride and data values in this class directly, but don't alter them!
  22238. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  22239. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  22240. */
  22241. class BitmapData
  22242. {
  22243. public:
  22244. enum ReadWriteMode
  22245. {
  22246. readOnly,
  22247. writeOnly,
  22248. readWrite
  22249. };
  22250. BitmapData (Image& image, int x, int y, int w, int h, ReadWriteMode mode);
  22251. BitmapData (const Image& image, int x, int y, int w, int h);
  22252. BitmapData (const Image& image, ReadWriteMode mode);
  22253. ~BitmapData();
  22254. /** Returns a pointer to the start of a line in the image.
  22255. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  22256. sure it's not out-of-range.
  22257. */
  22258. inline uint8* getLinePointer (int y) const throw() { return data + y * lineStride; }
  22259. /** Returns a pointer to a pixel in the image.
  22260. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  22261. not out-of-range.
  22262. */
  22263. inline uint8* getPixelPointer (int x, int y) const throw() { return data + y * lineStride + x * pixelStride; }
  22264. /** Returns the colour of a given pixel.
  22265. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  22266. repsonsibility to make sure they're within the image's size.
  22267. */
  22268. const Colour getPixelColour (int x, int y) const throw();
  22269. /** Sets the colour of a given pixel.
  22270. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  22271. repsonsibility to make sure they're within the image's size.
  22272. */
  22273. void setPixelColour (int x, int y, const Colour& colour) const throw();
  22274. uint8* data;
  22275. PixelFormat pixelFormat;
  22276. int lineStride, pixelStride, width, height;
  22277. /** Used internally by custom image types to manage pixel data lifetime. */
  22278. class BitmapDataReleaser
  22279. {
  22280. protected:
  22281. BitmapDataReleaser() {}
  22282. public:
  22283. virtual ~BitmapDataReleaser() {}
  22284. };
  22285. ScopedPointer<BitmapDataReleaser> dataReleaser;
  22286. private:
  22287. JUCE_DECLARE_NON_COPYABLE (BitmapData);
  22288. };
  22289. /** Copies some pixel values to a rectangle of the image.
  22290. The format of the pixel data must match that of the image itself, and the
  22291. rectangle supplied must be within the image's bounds.
  22292. */
  22293. void setPixelData (int destX, int destY, int destW, int destH,
  22294. const uint8* sourcePixelData, int sourceLineStride);
  22295. /** Copies a section of the image to somewhere else within itself. */
  22296. void moveImageSection (int destX, int destY,
  22297. int sourceX, int sourceY,
  22298. int width, int height);
  22299. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  22300. of the image.
  22301. @param result the list that will have the area added to it
  22302. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  22303. above this level will be considered opaque
  22304. */
  22305. void createSolidAreaMask (RectangleList& result,
  22306. float alphaThreshold = 0.5f) const;
  22307. /** Returns a NamedValueSet that is attached to the image and which can be used for
  22308. associating custom values with it.
  22309. If this is a null image, this will return a null pointer.
  22310. */
  22311. NamedValueSet* getProperties() const;
  22312. /** Creates a context suitable for drawing onto this image.
  22313. Don't call this method directly! It's used internally by the Graphics class.
  22314. */
  22315. LowLevelGraphicsContext* createLowLevelContext() const;
  22316. /** Returns the number of Image objects which are currently referring to the same internal
  22317. shared image data.
  22318. @see duplicateIfShared
  22319. */
  22320. int getReferenceCount() const throw() { return image == 0 ? 0 : image->getReferenceCount(); }
  22321. /** This is a base class for task-specific types of image.
  22322. Don't use this class directly! It's used internally by the Image class.
  22323. */
  22324. class SharedImage : public ReferenceCountedObject
  22325. {
  22326. public:
  22327. SharedImage (PixelFormat format, int width, int height);
  22328. ~SharedImage();
  22329. virtual LowLevelGraphicsContext* createLowLevelContext() = 0;
  22330. virtual SharedImage* clone() = 0;
  22331. virtual ImageType getType() const = 0;
  22332. virtual void initialiseBitmapData (BitmapData& bitmapData, int x, int y, BitmapData::ReadWriteMode mode) = 0;
  22333. static SharedImage* createNativeImage (PixelFormat format, int width, int height, bool clearImage);
  22334. static SharedImage* createSoftwareImage (PixelFormat format, int width, int height, bool clearImage);
  22335. const PixelFormat getPixelFormat() const throw() { return format; }
  22336. int getWidth() const throw() { return width; }
  22337. int getHeight() const throw() { return height; }
  22338. protected:
  22339. friend class Image;
  22340. friend class BitmapData;
  22341. const PixelFormat format;
  22342. const int width, height;
  22343. NamedValueSet userData;
  22344. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedImage);
  22345. };
  22346. /** @internal */
  22347. SharedImage* getSharedImage() const throw() { return image; }
  22348. /** @internal */
  22349. explicit Image (SharedImage* instance);
  22350. private:
  22351. friend class SharedImage;
  22352. friend class BitmapData;
  22353. ReferenceCountedObjectPtr<SharedImage> image;
  22354. JUCE_LEAK_DETECTOR (Image);
  22355. };
  22356. #endif // __JUCE_IMAGE_JUCEHEADER__
  22357. /*** End of inlined file: juce_Image.h ***/
  22358. /*** Start of inlined file: juce_RectangleList.h ***/
  22359. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  22360. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  22361. /**
  22362. Maintains a set of rectangles as a complex region.
  22363. This class allows a set of rectangles to be treated as a solid shape, and can
  22364. add and remove rectangular sections of it, and simplify overlapping or
  22365. adjacent rectangles.
  22366. @see Rectangle
  22367. */
  22368. class JUCE_API RectangleList
  22369. {
  22370. public:
  22371. /** Creates an empty RectangleList */
  22372. RectangleList() throw();
  22373. /** Creates a copy of another list */
  22374. RectangleList (const RectangleList& other);
  22375. /** Creates a list containing just one rectangle. */
  22376. RectangleList (const Rectangle<int>& rect);
  22377. /** Copies this list from another one. */
  22378. RectangleList& operator= (const RectangleList& other);
  22379. /** Destructor. */
  22380. ~RectangleList();
  22381. /** Returns true if the region is empty. */
  22382. bool isEmpty() const throw();
  22383. /** Returns the number of rectangles in the list. */
  22384. int getNumRectangles() const throw() { return rects.size(); }
  22385. /** Returns one of the rectangles at a particular index.
  22386. @returns the rectangle at the index, or an empty rectangle if the
  22387. index is out-of-range.
  22388. */
  22389. const Rectangle<int> getRectangle (int index) const throw();
  22390. /** Removes all rectangles to leave an empty region. */
  22391. void clear();
  22392. /** Merges a new rectangle into the list.
  22393. The rectangle being added will first be clipped to remove any parts of it
  22394. that overlap existing rectangles in the list.
  22395. */
  22396. void add (int x, int y, int width, int height);
  22397. /** Merges a new rectangle into the list.
  22398. The rectangle being added will first be clipped to remove any parts of it
  22399. that overlap existing rectangles in the list, and adjacent rectangles will be
  22400. merged into it.
  22401. */
  22402. void add (const Rectangle<int>& rect);
  22403. /** Dumbly adds a rectangle to the list without checking for overlaps.
  22404. This simply adds the rectangle to the end, it doesn't merge it or remove
  22405. any overlapping bits.
  22406. */
  22407. void addWithoutMerging (const Rectangle<int>& rect);
  22408. /** Merges another rectangle list into this one.
  22409. Any overlaps between the two lists will be clipped, so that the result is
  22410. the union of both lists.
  22411. */
  22412. void add (const RectangleList& other);
  22413. /** Removes a rectangular region from the list.
  22414. Any rectangles in the list which overlap this will be clipped and subdivided
  22415. if necessary.
  22416. */
  22417. void subtract (const Rectangle<int>& rect);
  22418. /** Removes all areas in another RectangleList from this one.
  22419. Any rectangles in the list which overlap this will be clipped and subdivided
  22420. if necessary.
  22421. @returns true if the resulting list is non-empty.
  22422. */
  22423. bool subtract (const RectangleList& otherList);
  22424. /** Removes any areas of the region that lie outside a given rectangle.
  22425. Any rectangles in the list which overlap this will be clipped and subdivided
  22426. if necessary.
  22427. Returns true if the resulting region is not empty, false if it is empty.
  22428. @see getIntersectionWith
  22429. */
  22430. bool clipTo (const Rectangle<int>& rect);
  22431. /** Removes any areas of the region that lie outside a given rectangle list.
  22432. Any rectangles in this object which overlap the specified list will be clipped
  22433. and subdivided if necessary.
  22434. Returns true if the resulting region is not empty, false if it is empty.
  22435. @see getIntersectionWith
  22436. */
  22437. bool clipTo (const RectangleList& other);
  22438. /** Creates a region which is the result of clipping this one to a given rectangle.
  22439. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  22440. resulting region into the list whose reference is passed-in.
  22441. Returns true if the resulting region is not empty, false if it is empty.
  22442. @see clipTo
  22443. */
  22444. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  22445. /** Swaps the contents of this and another list.
  22446. This swaps their internal pointers, so is hugely faster than using copy-by-value
  22447. to swap them.
  22448. */
  22449. void swapWith (RectangleList& otherList) throw();
  22450. /** Checks whether the region contains a given point.
  22451. @returns true if the point lies within one of the rectangles in the list
  22452. */
  22453. bool containsPoint (int x, int y) const throw();
  22454. /** Checks whether the region contains the whole of a given rectangle.
  22455. @returns true all parts of the rectangle passed in lie within the region
  22456. defined by this object
  22457. @see intersectsRectangle, containsPoint
  22458. */
  22459. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  22460. /** Checks whether the region contains any part of a given rectangle.
  22461. @returns true if any part of the rectangle passed in lies within the region
  22462. defined by this object
  22463. @see containsRectangle
  22464. */
  22465. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw();
  22466. /** Checks whether this region intersects any part of another one.
  22467. @see intersectsRectangle
  22468. */
  22469. bool intersects (const RectangleList& other) const throw();
  22470. /** Returns the smallest rectangle that can enclose the whole of this region. */
  22471. const Rectangle<int> getBounds() const throw();
  22472. /** Optimises the list into a minimum number of constituent rectangles.
  22473. This will try to combine any adjacent rectangles into larger ones where
  22474. possible, to simplify lists that might have been fragmented by repeated
  22475. add/subtract calls.
  22476. */
  22477. void consolidate();
  22478. /** Adds an x and y value to all the co-ordinates. */
  22479. void offsetAll (int dx, int dy) throw();
  22480. /** Creates a Path object to represent this region. */
  22481. const Path toPath() const;
  22482. /** An iterator for accessing all the rectangles in a RectangleList. */
  22483. class JUCE_API Iterator
  22484. {
  22485. public:
  22486. Iterator (const RectangleList& list) throw();
  22487. ~Iterator();
  22488. /** Advances to the next rectangle, and returns true if it's not finished.
  22489. Call this before using getRectangle() to find the rectangle that was returned.
  22490. */
  22491. bool next() throw();
  22492. /** Returns the current rectangle. */
  22493. const Rectangle<int>* getRectangle() const throw() { return current; }
  22494. private:
  22495. const Rectangle<int>* current;
  22496. const RectangleList& owner;
  22497. int index;
  22498. JUCE_DECLARE_NON_COPYABLE (Iterator);
  22499. };
  22500. private:
  22501. friend class Iterator;
  22502. Array <Rectangle<int> > rects;
  22503. JUCE_LEAK_DETECTOR (RectangleList);
  22504. };
  22505. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  22506. /*** End of inlined file: juce_RectangleList.h ***/
  22507. /*** Start of inlined file: juce_BorderSize.h ***/
  22508. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  22509. #define __JUCE_BORDERSIZE_JUCEHEADER__
  22510. /**
  22511. Specifies a set of gaps to be left around the sides of a rectangle.
  22512. This is basically the size of the spaces at the top, bottom, left and right of
  22513. a rectangle. It's used by various component classes to specify borders.
  22514. @see Rectangle
  22515. */
  22516. template <typename ValueType>
  22517. class BorderSize
  22518. {
  22519. public:
  22520. /** Creates a null border.
  22521. All sizes are left as 0.
  22522. */
  22523. BorderSize() throw()
  22524. : top(), left(), bottom(), right()
  22525. {
  22526. }
  22527. /** Creates a copy of another border. */
  22528. BorderSize (const BorderSize& other) throw()
  22529. : top (other.top), left (other.left), bottom (other.bottom), right (other.right)
  22530. {
  22531. }
  22532. /** Creates a border with the given gaps. */
  22533. BorderSize (ValueType topGap, ValueType leftGap, ValueType bottomGap, ValueType rightGap) throw()
  22534. : top (topGap), left (leftGap), bottom (bottomGap), right (rightGap)
  22535. {
  22536. }
  22537. /** Creates a border with the given gap on all sides. */
  22538. explicit BorderSize (ValueType allGaps) throw()
  22539. : top (allGaps), left (allGaps), bottom (allGaps), right (allGaps)
  22540. {
  22541. }
  22542. /** Returns the gap that should be left at the top of the region. */
  22543. ValueType getTop() const throw() { return top; }
  22544. /** Returns the gap that should be left at the top of the region. */
  22545. ValueType getLeft() const throw() { return left; }
  22546. /** Returns the gap that should be left at the top of the region. */
  22547. ValueType getBottom() const throw() { return bottom; }
  22548. /** Returns the gap that should be left at the top of the region. */
  22549. ValueType getRight() const throw() { return right; }
  22550. /** Returns the sum of the top and bottom gaps. */
  22551. ValueType getTopAndBottom() const throw() { return top + bottom; }
  22552. /** Returns the sum of the left and right gaps. */
  22553. ValueType getLeftAndRight() const throw() { return left + right; }
  22554. /** Returns true if this border has no thickness along any edge. */
  22555. bool isEmpty() const throw() { return left + right + top + bottom == ValueType(); }
  22556. /** Changes the top gap. */
  22557. void setTop (ValueType newTopGap) throw() { top = newTopGap; }
  22558. /** Changes the left gap. */
  22559. void setLeft (ValueType newLeftGap) throw() { left = newLeftGap; }
  22560. /** Changes the bottom gap. */
  22561. void setBottom (ValueType newBottomGap) throw() { bottom = newBottomGap; }
  22562. /** Changes the right gap. */
  22563. void setRight (ValueType newRightGap) throw() { right = newRightGap; }
  22564. /** Returns a rectangle with these borders removed from it. */
  22565. const Rectangle<ValueType> subtractedFrom (const Rectangle<ValueType>& original) const throw()
  22566. {
  22567. return Rectangle<ValueType> (original.getX() + left,
  22568. original.getY() + top,
  22569. original.getWidth() - (left + right),
  22570. original.getHeight() - (top + bottom));
  22571. }
  22572. /** Removes this border from a given rectangle. */
  22573. void subtractFrom (Rectangle<ValueType>& rectangle) const throw()
  22574. {
  22575. rectangle = subtractedFrom (rectangle);
  22576. }
  22577. /** Returns a rectangle with these borders added around it. */
  22578. const Rectangle<ValueType> addedTo (const Rectangle<ValueType>& original) const throw()
  22579. {
  22580. return Rectangle<ValueType> (original.getX() - left,
  22581. original.getY() - top,
  22582. original.getWidth() + (left + right),
  22583. original.getHeight() + (top + bottom));
  22584. }
  22585. /** Adds this border around a given rectangle. */
  22586. void addTo (Rectangle<ValueType>& rectangle) const throw()
  22587. {
  22588. rectangle = addedTo (rectangle);
  22589. }
  22590. bool operator== (const BorderSize& other) const throw()
  22591. {
  22592. return top == other.top && left == other.left && bottom == other.bottom && right == other.right;
  22593. }
  22594. bool operator!= (const BorderSize& other) const throw()
  22595. {
  22596. return ! operator== (other);
  22597. }
  22598. private:
  22599. ValueType top, left, bottom, right;
  22600. JUCE_LEAK_DETECTOR (BorderSize);
  22601. };
  22602. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  22603. /*** End of inlined file: juce_BorderSize.h ***/
  22604. /*** Start of inlined file: juce_ModalComponentManager.h ***/
  22605. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  22606. #define __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  22607. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  22608. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  22609. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  22610. /**
  22611. Classes derived from this will be automatically deleted when the application exits.
  22612. After JUCEApplication::shutdown() has been called, any objects derived from
  22613. DeletedAtShutdown which are still in existence will be deleted in the reverse
  22614. order to that in which they were created.
  22615. So if you've got a singleton and don't want to have to explicitly delete it, just
  22616. inherit from this and it'll be taken care of.
  22617. */
  22618. class JUCE_API DeletedAtShutdown
  22619. {
  22620. protected:
  22621. /** Creates a DeletedAtShutdown object. */
  22622. DeletedAtShutdown();
  22623. /** Destructor.
  22624. It's ok to delete these objects explicitly - it's only the ones left
  22625. dangling at the end that will be deleted automatically.
  22626. */
  22627. virtual ~DeletedAtShutdown();
  22628. public:
  22629. /** Deletes all extant objects.
  22630. This shouldn't be used by applications, as it's called automatically
  22631. in the shutdown code of the JUCEApplication class.
  22632. */
  22633. static void deleteAll();
  22634. private:
  22635. static CriticalSection& getLock();
  22636. static Array <DeletedAtShutdown*>& getObjects();
  22637. JUCE_DECLARE_NON_COPYABLE (DeletedAtShutdown);
  22638. };
  22639. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  22640. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  22641. /**
  22642. Manages the system's stack of modal components.
  22643. Normally you'll just use the Component methods to invoke modal states in components,
  22644. and won't have to deal with this class directly, but this is the singleton object that's
  22645. used internally to manage the stack.
  22646. @see Component::enterModalState, Component::exitModalState, Component::isCurrentlyModal,
  22647. Component::getCurrentlyModalComponent, Component::isCurrentlyBlockedByAnotherModalComponent
  22648. */
  22649. class JUCE_API ModalComponentManager : public AsyncUpdater,
  22650. public DeletedAtShutdown
  22651. {
  22652. public:
  22653. /** Receives callbacks when a modal component is dismissed.
  22654. You can register a callback using Component::enterModalState() or
  22655. ModalComponentManager::attachCallback().
  22656. For some quick ways of creating callback objects, see the ModalCallbackFunction class.
  22657. @see ModalCallbackFunction
  22658. */
  22659. class Callback
  22660. {
  22661. public:
  22662. /** */
  22663. Callback() {}
  22664. /** Destructor. */
  22665. virtual ~Callback() {}
  22666. /** Called to indicate that a modal component has been dismissed.
  22667. You can register a callback using Component::enterModalState() or
  22668. ModalComponentManager::attachCallback().
  22669. The returnValue parameter is the value that was passed to Component::exitModalState()
  22670. when the component was dismissed.
  22671. The callback object will be deleted shortly after this method is called.
  22672. */
  22673. virtual void modalStateFinished (int returnValue) = 0;
  22674. };
  22675. /** Returns the number of components currently being shown modally.
  22676. @see getModalComponent
  22677. */
  22678. int getNumModalComponents() const;
  22679. /** Returns one of the components being shown modally.
  22680. An index of 0 is the most recently-shown, topmost component.
  22681. */
  22682. Component* getModalComponent (int index) const;
  22683. /** Returns true if the specified component is in a modal state. */
  22684. bool isModal (Component* component) const;
  22685. /** Returns true if the specified component is currently the topmost modal component. */
  22686. bool isFrontModalComponent (Component* component) const;
  22687. /** Adds a new callback that will be called when the specified modal component is dismissed.
  22688. If the component is modal, then when it is dismissed, either by being hidden, or by calling
  22689. Component::exitModalState(), then the Callback::modalStateFinished() method will be
  22690. called.
  22691. Each component can have any number of callbacks associated with it, and this one is added
  22692. to that list.
  22693. The object that is passed in will be deleted by the manager when it's no longer needed. If
  22694. the given component is not currently modal, the callback object is deleted immediately and
  22695. no action is taken.
  22696. */
  22697. void attachCallback (Component* component, Callback* callback);
  22698. /** Brings any modal components to the front. */
  22699. void bringModalComponentsToFront();
  22700. #if JUCE_MODAL_LOOPS_PERMITTED
  22701. /** Runs the event loop until the currently topmost modal component is dismissed, and
  22702. returns the exit code for that component.
  22703. */
  22704. int runEventLoopForCurrentComponent();
  22705. #endif
  22706. juce_DeclareSingleton_SingleThreaded_Minimal (ModalComponentManager);
  22707. protected:
  22708. /** Creates a ModalComponentManager.
  22709. You shouldn't ever call the constructor - it's a singleton, so use ModalComponentManager::getInstance()
  22710. */
  22711. ModalComponentManager();
  22712. /** Destructor. */
  22713. ~ModalComponentManager();
  22714. /** @internal */
  22715. void handleAsyncUpdate();
  22716. private:
  22717. class ModalItem;
  22718. class ReturnValueRetriever;
  22719. friend class Component;
  22720. friend class OwnedArray <ModalItem>;
  22721. OwnedArray <ModalItem> stack;
  22722. void startModal (Component* component);
  22723. void endModal (Component* component, int returnValue);
  22724. void endModal (Component* component);
  22725. JUCE_DECLARE_NON_COPYABLE (ModalComponentManager);
  22726. };
  22727. /**
  22728. This class provides some handy utility methods for creating ModalComponentManager::Callback
  22729. objects that will invoke a static function with some parameters when a modal component is dismissed.
  22730. */
  22731. class ModalCallbackFunction
  22732. {
  22733. public:
  22734. /** This is a utility function to create a ModalComponentManager::Callback that will
  22735. call a static function with a parameter.
  22736. The function that you supply must take two parameters - the first being an int, which is
  22737. the result code that was used when the modal component was dismissed, and the second
  22738. can be a custom type. Note that this custom value will be copied and stored, so it must
  22739. be a primitive type or a class that provides copy-by-value semantics.
  22740. E.g. @code
  22741. static void myCallbackFunction (int modalResult, double customValue)
  22742. {
  22743. if (modalResult == 1)
  22744. doSomethingWith (customValue);
  22745. }
  22746. Component* someKindOfComp;
  22747. ...
  22748. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0));
  22749. @endcode
  22750. @see ModalComponentManager::Callback
  22751. */
  22752. template <typename ParamType>
  22753. static ModalComponentManager::Callback* create (void (*functionToCall) (int, ParamType),
  22754. ParamType parameterValue)
  22755. {
  22756. return new FunctionCaller1 <ParamType> (functionToCall, parameterValue);
  22757. }
  22758. /** This is a utility function to create a ModalComponentManager::Callback that will
  22759. call a static function with two custom parameters.
  22760. The function that you supply must take three parameters - the first being an int, which is
  22761. the result code that was used when the modal component was dismissed, and the next two are
  22762. your custom types. Note that these custom values will be copied and stored, so they must
  22763. be primitive types or classes that provide copy-by-value semantics.
  22764. E.g. @code
  22765. static void myCallbackFunction (int modalResult, double customValue1, String customValue2)
  22766. {
  22767. if (modalResult == 1)
  22768. doSomethingWith (customValue1, customValue2);
  22769. }
  22770. Component* someKindOfComp;
  22771. ...
  22772. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0, String ("xyz")));
  22773. @endcode
  22774. @see ModalComponentManager::Callback
  22775. */
  22776. template <typename ParamType1, typename ParamType2>
  22777. static ModalComponentManager::Callback* withParam (void (*functionToCall) (int, ParamType1, ParamType2),
  22778. ParamType1 parameterValue1,
  22779. ParamType2 parameterValue2)
  22780. {
  22781. return new FunctionCaller2 <ParamType1, ParamType2> (functionToCall, parameterValue1, parameterValue2);
  22782. }
  22783. /** This is a utility function to create a ModalComponentManager::Callback that will
  22784. call a static function with a component.
  22785. The function that you supply must take two parameters - the first being an int, which is
  22786. the result code that was used when the modal component was dismissed, and the second
  22787. can be a Component class. The component will be stored as a WeakReference, so that if it gets
  22788. deleted before this callback is invoked, the pointer that is passed to the function will be null.
  22789. E.g. @code
  22790. static void myCallbackFunction (int modalResult, Slider* mySlider)
  22791. {
  22792. if (modalResult == 1 && mySlider != 0) // (must check that mySlider isn't null in case it was deleted..)
  22793. mySlider->setValue (0.0);
  22794. }
  22795. Component* someKindOfComp;
  22796. Slider* mySlider;
  22797. ...
  22798. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider));
  22799. @endcode
  22800. @see ModalComponentManager::Callback
  22801. */
  22802. template <class ComponentType>
  22803. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*),
  22804. ComponentType* component)
  22805. {
  22806. return new ComponentCaller1 <ComponentType> (functionToCall, component);
  22807. }
  22808. /** Creates a ModalComponentManager::Callback that will call a static function with a component.
  22809. The function that you supply must take three parameters - the first being an int, which is
  22810. the result code that was used when the modal component was dismissed, the second being a Component
  22811. class, and the third being a custom type (which must be a primitive type or have copy-by-value semantics).
  22812. The component will be stored as a WeakReference, so that if it gets deleted before this callback is
  22813. invoked, the pointer that is passed into the function will be null.
  22814. E.g. @code
  22815. static void myCallbackFunction (int modalResult, Slider* mySlider, String customParam)
  22816. {
  22817. if (modalResult == 1 && mySlider != 0) // (must check that mySlider isn't null in case it was deleted..)
  22818. mySlider->setName (customParam);
  22819. }
  22820. Component* someKindOfComp;
  22821. Slider* mySlider;
  22822. ...
  22823. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider, String ("hello")));
  22824. @endcode
  22825. @see ModalComponentManager::Callback
  22826. */
  22827. template <class ComponentType, typename ParamType>
  22828. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*, ParamType),
  22829. ComponentType* component,
  22830. ParamType param)
  22831. {
  22832. return new ComponentCaller2 <ComponentType, ParamType> (functionToCall, component, param);
  22833. }
  22834. private:
  22835. template <typename ParamType>
  22836. class FunctionCaller1 : public ModalComponentManager::Callback
  22837. {
  22838. public:
  22839. typedef void (*FunctionType) (int, ParamType);
  22840. FunctionCaller1 (FunctionType& function_, ParamType& param_)
  22841. : function (function_), param (param_) {}
  22842. void modalStateFinished (int returnValue) { function (returnValue, param); }
  22843. private:
  22844. const FunctionType function;
  22845. ParamType param;
  22846. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller1);
  22847. };
  22848. template <typename ParamType1, typename ParamType2>
  22849. class FunctionCaller2 : public ModalComponentManager::Callback
  22850. {
  22851. public:
  22852. typedef void (*FunctionType) (int, ParamType1, ParamType2);
  22853. FunctionCaller2 (FunctionType& function_, ParamType1& param1_, ParamType2& param2_)
  22854. : function (function_), param1 (param1_), param2 (param2_) {}
  22855. void modalStateFinished (int returnValue) { function (returnValue, param1, param2); }
  22856. private:
  22857. const FunctionType function;
  22858. ParamType1 param1;
  22859. ParamType2 param2;
  22860. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller2);
  22861. };
  22862. template <typename ComponentType>
  22863. class ComponentCaller1 : public ModalComponentManager::Callback
  22864. {
  22865. public:
  22866. typedef void (*FunctionType) (int, ComponentType*);
  22867. ComponentCaller1 (FunctionType& function_, ComponentType* comp_)
  22868. : function (function_), comp (comp_) {}
  22869. void modalStateFinished (int returnValue)
  22870. {
  22871. function (returnValue, static_cast <ComponentType*> (comp.get()));
  22872. }
  22873. private:
  22874. const FunctionType function;
  22875. WeakReference<Component> comp;
  22876. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller1);
  22877. };
  22878. template <typename ComponentType, typename ParamType1>
  22879. class ComponentCaller2 : public ModalComponentManager::Callback
  22880. {
  22881. public:
  22882. typedef void (*FunctionType) (int, ComponentType*, ParamType1);
  22883. ComponentCaller2 (FunctionType& function_, ComponentType* comp_, ParamType1 param1_)
  22884. : function (function_), comp (comp_), param1 (param1_) {}
  22885. void modalStateFinished (int returnValue)
  22886. {
  22887. function (returnValue, static_cast <ComponentType*> (comp.get()), param1);
  22888. }
  22889. private:
  22890. const FunctionType function;
  22891. WeakReference<Component> comp;
  22892. ParamType1 param1;
  22893. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller2);
  22894. };
  22895. ModalCallbackFunction();
  22896. ~ModalCallbackFunction();
  22897. JUCE_DECLARE_NON_COPYABLE (ModalCallbackFunction);
  22898. };
  22899. #endif // __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  22900. /*** End of inlined file: juce_ModalComponentManager.h ***/
  22901. class LookAndFeel;
  22902. class MouseInputSource;
  22903. class MouseInputSourceInternal;
  22904. class ComponentPeer;
  22905. class MarkerList;
  22906. class RelativeRectangle;
  22907. /**
  22908. The base class for all JUCE user-interface objects.
  22909. */
  22910. class JUCE_API Component : public MouseListener
  22911. {
  22912. public:
  22913. /** Creates a component.
  22914. To get it to actually appear, you'll also need to:
  22915. - Either add it to a parent component or use the addToDesktop() method to
  22916. make it a desktop window
  22917. - Set its size and position to something sensible
  22918. - Use setVisible() to make it visible
  22919. And for it to serve any useful purpose, you'll need to write a
  22920. subclass of Component or use one of the other types of component from
  22921. the library.
  22922. */
  22923. Component();
  22924. /** Destructor.
  22925. Note that when a component is deleted, any child components it contains are NOT
  22926. automatically deleted. It's your responsibilty to manage their lifespan - you
  22927. may want to use helper methods like deleteAllChildren(), or less haphazard
  22928. approaches like using ScopedPointers or normal object aggregation to manage them.
  22929. If the component being deleted is currently the child of another one, then during
  22930. deletion, it will be removed from its parent, and the parent will receive a childrenChanged()
  22931. callback. Any ComponentListener objects that have registered with it will also have their
  22932. ComponentListener::componentBeingDeleted() methods called.
  22933. */
  22934. virtual ~Component();
  22935. /** Creates a component, setting its name at the same time.
  22936. @see getName, setName
  22937. */
  22938. explicit Component (const String& componentName);
  22939. /** Returns the name of this component.
  22940. @see setName
  22941. */
  22942. const String& getName() const throw() { return componentName; }
  22943. /** Sets the name of this component.
  22944. When the name changes, all registered ComponentListeners will receive a
  22945. ComponentListener::componentNameChanged() callback.
  22946. @see getName
  22947. */
  22948. virtual void setName (const String& newName);
  22949. /** Returns the ID string that was set by setComponentID().
  22950. @see setComponentID
  22951. */
  22952. const String& getComponentID() const throw() { return componentID; }
  22953. /** Sets the component's ID string.
  22954. You can retrieve the ID using getComponentID().
  22955. @see getComponentID
  22956. */
  22957. void setComponentID (const String& newID);
  22958. /** Makes the component visible or invisible.
  22959. This method will show or hide the component.
  22960. Note that components default to being non-visible when first created.
  22961. Also note that visible components won't be seen unless all their parent components
  22962. are also visible.
  22963. This method will call visibilityChanged() and also componentVisibilityChanged()
  22964. for any component listeners that are interested in this component.
  22965. @param shouldBeVisible whether to show or hide the component
  22966. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  22967. */
  22968. virtual void setVisible (bool shouldBeVisible);
  22969. /** Tests whether the component is visible or not.
  22970. this doesn't necessarily tell you whether this comp is actually on the screen
  22971. because this depends on whether all the parent components are also visible - use
  22972. isShowing() to find this out.
  22973. @see isShowing, setVisible
  22974. */
  22975. bool isVisible() const throw() { return flags.visibleFlag; }
  22976. /** Called when this component's visiblility changes.
  22977. @see setVisible, isVisible
  22978. */
  22979. virtual void visibilityChanged();
  22980. /** Tests whether this component and all its parents are visible.
  22981. @returns true only if this component and all its parents are visible.
  22982. @see isVisible
  22983. */
  22984. bool isShowing() const;
  22985. /** Makes this component appear as a window on the desktop.
  22986. Note that before calling this, you should make sure that the component's opacity is
  22987. set correctly using setOpaque(). If the component is non-opaque, the windowing
  22988. system will try to create a special transparent window for it, which will generally take
  22989. a lot more CPU to operate (and might not even be possible on some platforms).
  22990. If the component is inside a parent component at the time this method is called, it
  22991. will be first be removed from that parent. Likewise if a component on the desktop
  22992. is subsequently added to another component, it'll be removed from the desktop.
  22993. @param windowStyleFlags a combination of the flags specified in the
  22994. ComponentPeer::StyleFlags enum, which define the
  22995. window's characteristics.
  22996. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  22997. in which the juce component should place itself. On Windows,
  22998. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  22999. supported on all platforms, and best left as 0 unless you know
  23000. what you're doing
  23001. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  23002. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  23003. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  23004. */
  23005. virtual void addToDesktop (int windowStyleFlags,
  23006. void* nativeWindowToAttachTo = 0);
  23007. /** If the component is currently showing on the desktop, this will hide it.
  23008. You can also use setVisible() to hide a desktop window temporarily, but
  23009. removeFromDesktop() will free any system resources that are being used up.
  23010. @see addToDesktop, isOnDesktop
  23011. */
  23012. void removeFromDesktop();
  23013. /** Returns true if this component is currently showing on the desktop.
  23014. @see addToDesktop, removeFromDesktop
  23015. */
  23016. bool isOnDesktop() const throw();
  23017. /** Returns the heavyweight window that contains this component.
  23018. If this component is itself on the desktop, this will return the window
  23019. object that it is using. Otherwise, it will return the window of
  23020. its top-level parent component.
  23021. This may return 0 if there isn't a desktop component.
  23022. @see addToDesktop, isOnDesktop
  23023. */
  23024. ComponentPeer* getPeer() const;
  23025. /** For components on the desktop, this is called if the system wants to close the window.
  23026. This is a signal that either the user or the system wants the window to close. The
  23027. default implementation of this method will trigger an assertion to warn you that your
  23028. component should do something about it, but you can override this to ignore the event
  23029. if you want.
  23030. */
  23031. virtual void userTriedToCloseWindow();
  23032. /** Called for a desktop component which has just been minimised or un-minimised.
  23033. This will only be called for components on the desktop.
  23034. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  23035. */
  23036. virtual void minimisationStateChanged (bool isNowMinimised);
  23037. /** Brings the component to the front of its siblings.
  23038. If some of the component's siblings have had their 'always-on-top' flag set,
  23039. then they will still be kept in front of this one (unless of course this
  23040. one is also 'always-on-top').
  23041. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  23042. to the component (see grabKeyboardFocus() for more details)
  23043. @see toBack, toBehind, setAlwaysOnTop
  23044. */
  23045. void toFront (bool shouldAlsoGainFocus);
  23046. /** Changes this component's z-order to be at the back of all its siblings.
  23047. If the component is set to be 'always-on-top', it will only be moved to the
  23048. back of the other other 'always-on-top' components.
  23049. @see toFront, toBehind, setAlwaysOnTop
  23050. */
  23051. void toBack();
  23052. /** Changes this component's z-order so that it's just behind another component.
  23053. @see toFront, toBack
  23054. */
  23055. void toBehind (Component* other);
  23056. /** Sets whether the component should always be kept at the front of its siblings.
  23057. @see isAlwaysOnTop
  23058. */
  23059. void setAlwaysOnTop (bool shouldStayOnTop);
  23060. /** Returns true if this component is set to always stay in front of its siblings.
  23061. @see setAlwaysOnTop
  23062. */
  23063. bool isAlwaysOnTop() const throw();
  23064. /** Returns the x coordinate of the component's left edge.
  23065. This is a distance in pixels from the left edge of the component's parent.
  23066. Note that if you've used setTransform() to apply a transform, then the component's
  23067. bounds will no longer be a direct reflection of the position at which it appears within
  23068. its parent, as the transform will be applied to its bounding box.
  23069. */
  23070. inline int getX() const throw() { return bounds.getX(); }
  23071. /** Returns the y coordinate of the top of this component.
  23072. This is a distance in pixels from the top edge of the component's parent.
  23073. Note that if you've used setTransform() to apply a transform, then the component's
  23074. bounds will no longer be a direct reflection of the position at which it appears within
  23075. its parent, as the transform will be applied to its bounding box.
  23076. */
  23077. inline int getY() const throw() { return bounds.getY(); }
  23078. /** Returns the component's width in pixels. */
  23079. inline int getWidth() const throw() { return bounds.getWidth(); }
  23080. /** Returns the component's height in pixels. */
  23081. inline int getHeight() const throw() { return bounds.getHeight(); }
  23082. /** Returns the x coordinate of the component's right-hand edge.
  23083. This is a distance in pixels from the left edge of the component's parent.
  23084. Note that if you've used setTransform() to apply a transform, then the component's
  23085. bounds will no longer be a direct reflection of the position at which it appears within
  23086. its parent, as the transform will be applied to its bounding box.
  23087. */
  23088. int getRight() const throw() { return bounds.getRight(); }
  23089. /** Returns the component's top-left position as a Point. */
  23090. const Point<int> getPosition() const throw() { return bounds.getPosition(); }
  23091. /** Returns the y coordinate of the bottom edge of this component.
  23092. This is a distance in pixels from the top edge of the component's parent.
  23093. Note that if you've used setTransform() to apply a transform, then the component's
  23094. bounds will no longer be a direct reflection of the position at which it appears within
  23095. its parent, as the transform will be applied to its bounding box.
  23096. */
  23097. int getBottom() const throw() { return bounds.getBottom(); }
  23098. /** Returns this component's bounding box.
  23099. The rectangle returned is relative to the top-left of the component's parent.
  23100. Note that if you've used setTransform() to apply a transform, then the component's
  23101. bounds will no longer be a direct reflection of the position at which it appears within
  23102. its parent, as the transform will be applied to its bounding box.
  23103. */
  23104. const Rectangle<int>& getBounds() const throw() { return bounds; }
  23105. /** Returns the component's bounds, relative to its own origin.
  23106. This is like getBounds(), but returns the rectangle in local coordinates, In practice, it'll
  23107. return a rectangle with position (0, 0), and the same size as this component.
  23108. */
  23109. const Rectangle<int> getLocalBounds() const throw();
  23110. /** Returns the area of this component's parent which this component covers.
  23111. The returned area is relative to the parent's coordinate space.
  23112. If the component has an affine transform specified, then the resulting area will be
  23113. the smallest rectangle that fully covers the component's transformed bounding box.
  23114. If this component has no parent, the return value will simply be the same as getBounds().
  23115. */
  23116. const Rectangle<int> getBoundsInParent() const throw();
  23117. /** Returns the region of this component that's not obscured by other, opaque components.
  23118. The RectangleList that is returned represents the area of this component
  23119. which isn't covered by opaque child components.
  23120. If includeSiblings is true, it will also take into account any siblings
  23121. that may be overlapping the component.
  23122. */
  23123. void getVisibleArea (RectangleList& result,
  23124. bool includeSiblings) const;
  23125. /** Returns this component's x coordinate relative the the screen's top-left origin.
  23126. @see getX, localPointToGlobal
  23127. */
  23128. int getScreenX() const;
  23129. /** Returns this component's y coordinate relative the the screen's top-left origin.
  23130. @see getY, localPointToGlobal
  23131. */
  23132. int getScreenY() const;
  23133. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  23134. @see getScreenBounds
  23135. */
  23136. const Point<int> getScreenPosition() const;
  23137. /** Returns the bounds of this component, relative to the screen's top-left.
  23138. @see getScreenPosition
  23139. */
  23140. const Rectangle<int> getScreenBounds() const;
  23141. /** Converts a point to be relative to this component's coordinate space.
  23142. This takes a point relative to a different component, and returns its position relative to this
  23143. component. If the sourceComponent parameter is null, the source point is assumed to be a global
  23144. screen coordinate.
  23145. */
  23146. const Point<int> getLocalPoint (const Component* sourceComponent,
  23147. const Point<int>& pointRelativeToSourceComponent) const;
  23148. /** Converts a rectangle to be relative to this component's coordinate space.
  23149. This takes a rectangle that is relative to a different component, and returns its position relative
  23150. to this component. If the sourceComponent parameter is null, the source rectangle is assumed to be
  23151. a screen coordinate.
  23152. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23153. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23154. the smallest rectangle that fully contains the transformed area.
  23155. */
  23156. const Rectangle<int> getLocalArea (const Component* sourceComponent,
  23157. const Rectangle<int>& areaRelativeToSourceComponent) const;
  23158. /** Converts a point relative to this component's top-left into a screen coordinate.
  23159. @see getLocalPoint, localAreaToGlobal
  23160. */
  23161. const Point<int> localPointToGlobal (const Point<int>& localPoint) const;
  23162. /** Converts a rectangle from this component's coordinate space to a screen coordinate.
  23163. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23164. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23165. the smallest rectangle that fully contains the transformed area.
  23166. @see getLocalPoint, localPointToGlobal
  23167. */
  23168. const Rectangle<int> localAreaToGlobal (const Rectangle<int>& localArea) const;
  23169. /** Moves the component to a new position.
  23170. Changes the component's top-left position (without changing its size).
  23171. The position is relative to the top-left of the component's parent.
  23172. If the component actually moves, this method will make a synchronous call to moved().
  23173. Note that if you've used setTransform() to apply a transform, then the component's
  23174. bounds will no longer be a direct reflection of the position at which it appears within
  23175. its parent, as the transform will be applied to whatever bounds you set for it.
  23176. @see setBounds, ComponentListener::componentMovedOrResized
  23177. */
  23178. void setTopLeftPosition (int x, int y);
  23179. /** Moves the component to a new position.
  23180. Changes the position of the component's top-right corner (keeping it the same size).
  23181. The position is relative to the top-left of the component's parent.
  23182. If the component actually moves, this method will make a synchronous call to moved().
  23183. Note that if you've used setTransform() to apply a transform, then the component's
  23184. bounds will no longer be a direct reflection of the position at which it appears within
  23185. its parent, as the transform will be applied to whatever bounds you set for it.
  23186. */
  23187. void setTopRightPosition (int x, int y);
  23188. /** Changes the size of the component.
  23189. A synchronous call to resized() will be occur if the size actually changes.
  23190. Note that if you've used setTransform() to apply a transform, then the component's
  23191. bounds will no longer be a direct reflection of the position at which it appears within
  23192. its parent, as the transform will be applied to whatever bounds you set for it.
  23193. */
  23194. void setSize (int newWidth, int newHeight);
  23195. /** Changes the component's position and size.
  23196. The coordinates are relative to the top-left of the component's parent, or relative
  23197. to the origin of the screen is the component is on the desktop.
  23198. If this method changes the component's top-left position, it will make a synchronous
  23199. call to moved(). If it changes the size, it will also make a call to resized().
  23200. Note that if you've used setTransform() to apply a transform, then the component's
  23201. bounds will no longer be a direct reflection of the position at which it appears within
  23202. its parent, as the transform will be applied to whatever bounds you set for it.
  23203. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  23204. */
  23205. void setBounds (int x, int y, int width, int height);
  23206. /** Changes the component's position and size.
  23207. The coordinates are relative to the top-left of the component's parent, or relative
  23208. to the origin of the screen is the component is on the desktop.
  23209. If this method changes the component's top-left position, it will make a synchronous
  23210. call to moved(). If it changes the size, it will also make a call to resized().
  23211. Note that if you've used setTransform() to apply a transform, then the component's
  23212. bounds will no longer be a direct reflection of the position at which it appears within
  23213. its parent, as the transform will be applied to whatever bounds you set for it.
  23214. @see setBounds
  23215. */
  23216. void setBounds (const Rectangle<int>& newBounds);
  23217. /** Changes the component's position and size.
  23218. This is similar to the other setBounds() methods, but uses RelativeRectangle::applyToComponent()
  23219. to set the position, This uses a Component::Positioner to make sure that any dynamic
  23220. expressions are used in the RelativeRectangle will be automatically re-applied to the
  23221. component's bounds when the source values change. See RelativeRectangle::applyToComponent()
  23222. for more details.
  23223. When using relative expressions, the following symbols are available:
  23224. - "left", "right", "top", "bottom" refer to the position of those edges in this component, so
  23225. e.g. for a component whose width is always 100, you might set the right edge to the "left + 100".
  23226. - "[id].left", "[id].right", "[id].top", "[id].bottom", "[id].width", "[id].height", where [id] is
  23227. the identifier of one of this component's siblings. A component's identifier is set with
  23228. Component::setComponentID(). So for example if you want your component to always be 50 pixels to the
  23229. right of the one called "xyz", you could set your left edge to be "xyz.right + 50".
  23230. - Instead of an [id], you can use the name "parent" to refer to this component's parent. Like
  23231. any other component, these values are relative to their component's parent, so "parent.right" won't be
  23232. very useful for positioning a component because it refers to a position with the parent's parent.. but
  23233. "parent.width" can be used for setting positions relative to the parent's size. E.g. to make a 10x10
  23234. component which remains 1 pixel away from its parent's bottom-right, you could use
  23235. "right - 10, bottom - 10, parent.width - 1, parent.height - 1".
  23236. - The name of one of the parent component's markers can also be used as a symbol. For markers to be
  23237. used, the parent component must implement its Component::getMarkers() method, and return at least one
  23238. valid MarkerList. So if you want your component's top edge to be 10 pixels below the
  23239. marker called "foobar", you'd set it to "foobar + 10".
  23240. See the Expression class for details about the operators that are supported, but for example
  23241. if you wanted to make your component remain centred within its parent with a size of 100, 100,
  23242. you could express it as:
  23243. @code myComp.setBounds (RelativeBounds ("parent.width / 2 - 50, parent.height / 2 - 50, left + 100, top + 100"));
  23244. @endcode
  23245. ..or an alternative way to achieve the same thing:
  23246. @code myComp.setBounds (RelativeBounds ("right - 100, bottom - 100, parent.width / 2 + 50, parent.height / 2 + 50"));
  23247. @endcode
  23248. Or if you wanted a 100x100 component whose top edge is lined up to a marker called "topMarker" and
  23249. which is positioned 50 pixels to the right of another component called "otherComp", you could write:
  23250. @code myComp.setBounds (RelativeBounds ("otherComp.right + 50, topMarker, left + 100, top + 100"));
  23251. @endcode
  23252. Be careful not to make your coordinate expressions recursive, though, or exceptions and assertions will
  23253. be thrown!
  23254. @see setBounds, RelativeRectangle::applyToComponent(), Expression
  23255. */
  23256. void setBounds (const RelativeRectangle& newBounds);
  23257. /** Sets the component's bounds with an expression.
  23258. The string is parsed as a RelativeRectangle expression - see the notes for
  23259. Component::setBounds (const RelativeRectangle&) for more information. This method is
  23260. basically just a shortcut for writing setBounds (RelativeRectangle ("..."))
  23261. */
  23262. void setBounds (const String& newBoundsExpression);
  23263. /** Changes the component's position and size in terms of fractions of its parent's size.
  23264. The values are factors of the parent's size, so for example
  23265. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  23266. width and height of the parent, with its top-left position 20% of
  23267. the way across and down the parent.
  23268. @see setBounds
  23269. */
  23270. void setBoundsRelative (float proportionalX, float proportionalY,
  23271. float proportionalWidth, float proportionalHeight);
  23272. /** Changes the component's position and size based on the amount of space to leave around it.
  23273. This will position the component within its parent, leaving the specified number of
  23274. pixels around each edge.
  23275. @see setBounds
  23276. */
  23277. void setBoundsInset (const BorderSize<int>& borders);
  23278. /** Positions the component within a given rectangle, keeping its proportions
  23279. unchanged.
  23280. If onlyReduceInSize is false, the component will be resized to fill as much of the
  23281. rectangle as possible without changing its aspect ratio (the component's
  23282. current size is used to determine its aspect ratio, so a zero-size component
  23283. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  23284. too big to fit inside the rectangle.
  23285. It will then be positioned within the rectangle according to the justification flags
  23286. specified.
  23287. @see setBounds
  23288. */
  23289. void setBoundsToFit (int x, int y, int width, int height,
  23290. const Justification& justification,
  23291. bool onlyReduceInSize);
  23292. /** Changes the position of the component's centre.
  23293. Leaves the component's size unchanged, but sets the position of its centre
  23294. relative to its parent's top-left.
  23295. @see setBounds
  23296. */
  23297. void setCentrePosition (int x, int y);
  23298. /** Changes the position of the component's centre.
  23299. Leaves the position unchanged, but positions its centre relative to its
  23300. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  23301. its parent.
  23302. */
  23303. void setCentreRelative (float x, float y);
  23304. /** Changes the component's size and centres it within its parent.
  23305. After changing the size, the component will be moved so that it's
  23306. centred within its parent. If the component is on the desktop (or has no
  23307. parent component), then it'll be centred within the main monitor area.
  23308. */
  23309. void centreWithSize (int width, int height);
  23310. /** Sets a transform matrix to be applied to this component.
  23311. If you set a transform for a component, the component's position will be warped by it, relative to
  23312. the component's parent's top-left origin. This means that the values you pass into setBounds() will no
  23313. longer reflect the actual area within the parent that the component covers, as the bounds will be
  23314. transformed and the component will probably end up actually appearing somewhere else within its parent.
  23315. When using transforms you need to be extremely careful when converting coordinates between the
  23316. coordinate spaces of different components or the screen - you should always use getLocalPoint(),
  23317. getLocalArea(), etc to do this, and never just manually add a component's position to a point in order to
  23318. convert it between different components (but I'm sure you would never have done that anyway...).
  23319. Currently, transforms are not supported for desktop windows, so the transform will be ignored if you
  23320. put a component on the desktop.
  23321. To remove a component's transform, simply pass AffineTransform::identity as the parameter to this method.
  23322. */
  23323. void setTransform (const AffineTransform& transform);
  23324. /** Returns the transform that is currently being applied to this component.
  23325. For more details about transforms, see setTransform().
  23326. @see setTransform
  23327. */
  23328. const AffineTransform getTransform() const;
  23329. /** Returns true if a non-identity transform is being applied to this component.
  23330. For more details about transforms, see setTransform().
  23331. @see setTransform
  23332. */
  23333. bool isTransformed() const throw();
  23334. /** Returns a proportion of the component's width.
  23335. This is a handy equivalent of (getWidth() * proportion).
  23336. */
  23337. int proportionOfWidth (float proportion) const throw();
  23338. /** Returns a proportion of the component's height.
  23339. This is a handy equivalent of (getHeight() * proportion).
  23340. */
  23341. int proportionOfHeight (float proportion) const throw();
  23342. /** Returns the width of the component's parent.
  23343. If the component has no parent (i.e. if it's on the desktop), this will return
  23344. the width of the screen.
  23345. */
  23346. int getParentWidth() const throw();
  23347. /** Returns the height of the component's parent.
  23348. If the component has no parent (i.e. if it's on the desktop), this will return
  23349. the height of the screen.
  23350. */
  23351. int getParentHeight() const throw();
  23352. /** Returns the screen coordinates of the monitor that contains this component.
  23353. If there's only one monitor, this will return its size - if there are multiple
  23354. monitors, it will return the area of the monitor that contains the component's
  23355. centre.
  23356. */
  23357. const Rectangle<int> getParentMonitorArea() const;
  23358. /** Returns the number of child components that this component contains.
  23359. @see getChildComponent, getIndexOfChildComponent
  23360. */
  23361. int getNumChildComponents() const throw();
  23362. /** Returns one of this component's child components, by it index.
  23363. The component with index 0 is at the back of the z-order, the one at the
  23364. front will have index (getNumChildComponents() - 1).
  23365. If the index is out-of-range, this will return a null pointer.
  23366. @see getNumChildComponents, getIndexOfChildComponent
  23367. */
  23368. Component* getChildComponent (int index) const throw();
  23369. /** Returns the index of this component in the list of child components.
  23370. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  23371. values are further towards the front.
  23372. Returns -1 if the component passed-in is not a child of this component.
  23373. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  23374. */
  23375. int getIndexOfChildComponent (const Component* child) const throw();
  23376. /** Adds a child component to this one.
  23377. Adding a child component does not mean that the component will own or delete the child - it's
  23378. your responsibility to delete the component. Note that it's safe to delete a component
  23379. without first removing it from its parent - doing so will automatically remove it and
  23380. send out the appropriate notifications before the deletion completes.
  23381. If the child is already a child of this component, then no action will be taken, and its
  23382. z-order will be left unchanged.
  23383. @param child the new component to add. If the component passed-in is already
  23384. the child of another component, it'll first be removed from it current parent.
  23385. @param zOrder The index in the child-list at which this component should be inserted.
  23386. A value of -1 will insert it in front of the others, 0 is the back.
  23387. @see removeChildComponent, addAndMakeVisible, getChild, ComponentListener::componentChildrenChanged
  23388. */
  23389. void addChildComponent (Component* child, int zOrder = -1);
  23390. /** Adds a child component to this one, and also makes the child visible if it isn't.
  23391. Quite a useful function, this is just the same as calling setVisible (true) on the child
  23392. and then addChildComponent(). See addChildComponent() for more details.
  23393. */
  23394. void addAndMakeVisible (Component* child, int zOrder = -1);
  23395. /** Removes one of this component's child-components.
  23396. If the child passed-in isn't actually a child of this component (either because
  23397. it's invalid or is the child of a different parent), then no action is taken.
  23398. Note that removing a child will not delete it! But it's ok to delete a component
  23399. without first removing it - doing so will automatically remove it and send out the
  23400. appropriate notifications before the deletion completes.
  23401. @see addChildComponent, ComponentListener::componentChildrenChanged
  23402. */
  23403. void removeChildComponent (Component* childToRemove);
  23404. /** Removes one of this component's child-components by index.
  23405. This will return a pointer to the component that was removed, or null if
  23406. the index was out-of-range.
  23407. Note that removing a child will not delete it! But it's ok to delete a component
  23408. without first removing it - doing so will automatically remove it and send out the
  23409. appropriate notifications before the deletion completes.
  23410. @see addChildComponent, ComponentListener::componentChildrenChanged
  23411. */
  23412. Component* removeChildComponent (int childIndexToRemove);
  23413. /** Removes all this component's children.
  23414. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  23415. */
  23416. void removeAllChildren();
  23417. /** Removes all this component's children, and deletes them.
  23418. @see removeAllChildren
  23419. */
  23420. void deleteAllChildren();
  23421. /** Returns the component which this component is inside.
  23422. If this is the highest-level component or hasn't yet been added to
  23423. a parent, this will return null.
  23424. */
  23425. Component* getParentComponent() const throw() { return parentComponent; }
  23426. /** Searches the parent components for a component of a specified class.
  23427. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  23428. component that can be dynamically cast to a MyComp, or will return 0 if none
  23429. of the parents are suitable.
  23430. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  23431. */
  23432. template <class TargetClass>
  23433. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  23434. {
  23435. (void) dummyParameter;
  23436. Component* p = parentComponent;
  23437. while (p != 0)
  23438. {
  23439. TargetClass* target = dynamic_cast <TargetClass*> (p);
  23440. if (target != 0)
  23441. return target;
  23442. p = p->parentComponent;
  23443. }
  23444. return 0;
  23445. }
  23446. /** Returns the highest-level component which contains this one or its parents.
  23447. This will search upwards in the parent-hierarchy from this component, until it
  23448. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  23449. not yet added to a parent), and will return that.
  23450. */
  23451. Component* getTopLevelComponent() const throw();
  23452. /** Checks whether a component is anywhere inside this component or its children.
  23453. This will recursively check through this component's children to see if the
  23454. given component is anywhere inside.
  23455. */
  23456. bool isParentOf (const Component* possibleChild) const throw();
  23457. /** Called to indicate that the component's parents have changed.
  23458. When a component is added or removed from its parent, this method will
  23459. be called on all of its children (recursively - so all children of its
  23460. children will also be called as well).
  23461. Subclasses can override this if they need to react to this in some way.
  23462. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  23463. */
  23464. virtual void parentHierarchyChanged();
  23465. /** Subclasses can use this callback to be told when children are added or removed.
  23466. @see parentHierarchyChanged
  23467. */
  23468. virtual void childrenChanged();
  23469. /** Tests whether a given point inside the component.
  23470. Overriding this method allows you to create components which only intercept
  23471. mouse-clicks within a user-defined area.
  23472. This is called to find out whether a particular x, y coordinate is
  23473. considered to be inside the component or not, and is used by methods such
  23474. as contains() and getComponentAt() to work out which component
  23475. the mouse is clicked on.
  23476. Components with custom shapes will probably want to override it to perform
  23477. some more complex hit-testing.
  23478. The default implementation of this method returns either true or false,
  23479. depending on the value that was set by calling setInterceptsMouseClicks() (true
  23480. is the default return value).
  23481. Note that the hit-test region is not related to the opacity with which
  23482. areas of a component are painted.
  23483. Applications should never call hitTest() directly - instead use the
  23484. contains() method, because this will also test for occlusion by the
  23485. component's parent.
  23486. Note that for components on the desktop, this method will be ignored, because it's
  23487. not always possible to implement this behaviour on all platforms.
  23488. @param x the x coordinate to test, relative to the left hand edge of this
  23489. component. This value is guaranteed to be greater than or equal to
  23490. zero, and less than the component's width
  23491. @param y the y coordinate to test, relative to the top edge of this
  23492. component. This value is guaranteed to be greater than or equal to
  23493. zero, and less than the component's height
  23494. @returns true if the click is considered to be inside the component
  23495. @see setInterceptsMouseClicks, contains
  23496. */
  23497. virtual bool hitTest (int x, int y);
  23498. /** Changes the default return value for the hitTest() method.
  23499. Setting this to false is an easy way to make a component pass its mouse-clicks
  23500. through to the components behind it.
  23501. When a component is created, the default setting for this is true.
  23502. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  23503. return false (or true for child components if allowClicksOnChildComponents
  23504. is true)
  23505. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  23506. components can be clicked on as normal but clicks on this component pass
  23507. straight through; if this is false and allowClicksOnThisComponent
  23508. is false, then neither this component nor any child components can
  23509. be clicked on
  23510. @see hitTest, getInterceptsMouseClicks
  23511. */
  23512. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  23513. bool allowClicksOnChildComponents) throw();
  23514. /** Retrieves the current state of the mouse-click interception flags.
  23515. On return, the two parameters are set to the state used in the last call to
  23516. setInterceptsMouseClicks().
  23517. @see setInterceptsMouseClicks
  23518. */
  23519. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  23520. bool& allowsClicksOnChildComponents) const throw();
  23521. /** Returns true if a given point lies within this component or one of its children.
  23522. Never override this method! Use hitTest to create custom hit regions.
  23523. @param localPoint the coordinate to test, relative to this component's top-left.
  23524. @returns true if the point is within the component's hit-test area, but only if
  23525. that part of the component isn't clipped by its parent component. Note
  23526. that this won't take into account any overlapping sibling components
  23527. which might be in the way - for that, see reallyContains()
  23528. @see hitTest, reallyContains, getComponentAt
  23529. */
  23530. bool contains (const Point<int>& localPoint);
  23531. /** Returns true if a given point lies in this component, taking any overlapping
  23532. siblings into account.
  23533. @param localPoint the coordinate to test, relative to this component's top-left.
  23534. @param returnTrueIfWithinAChild if the point actually lies within a child of this component,
  23535. this determines whether that is counted as a hit.
  23536. @see contains, getComponentAt
  23537. */
  23538. bool reallyContains (const Point<int>& localPoint, bool returnTrueIfWithinAChild);
  23539. /** Returns the component at a certain point within this one.
  23540. @param x the x coordinate to test, relative to this component's left edge.
  23541. @param y the y coordinate to test, relative to this component's top edge.
  23542. @returns the component that is at this position - which may be 0, this component,
  23543. or one of its children. Note that overlapping siblings that might actually
  23544. be in the way are not taken into account by this method - to account for these,
  23545. instead call getComponentAt on the top-level parent of this component.
  23546. @see hitTest, contains, reallyContains
  23547. */
  23548. Component* getComponentAt (int x, int y);
  23549. /** Returns the component at a certain point within this one.
  23550. @param position the coordinate to test, relative to this component's top-left.
  23551. @returns the component that is at this position - which may be 0, this component,
  23552. or one of its children. Note that overlapping siblings that might actually
  23553. be in the way are not taken into account by this method - to account for these,
  23554. instead call getComponentAt on the top-level parent of this component.
  23555. @see hitTest, contains, reallyContains
  23556. */
  23557. Component* getComponentAt (const Point<int>& position);
  23558. /** Marks the whole component as needing to be redrawn.
  23559. Calling this will not do any repainting immediately, but will mark the component
  23560. as 'dirty'. At some point in the near future the operating system will send a paint
  23561. message, which will redraw all the dirty regions of all components.
  23562. There's no guarantee about how soon after calling repaint() the redraw will actually
  23563. happen, and other queued events may be delivered before a redraw is done.
  23564. If the setBufferedToImage() method has been used to cause this component
  23565. to use a buffer, the repaint() call will invalidate the component's buffer.
  23566. To redraw just a subsection of the component rather than the whole thing,
  23567. use the repaint (int, int, int, int) method.
  23568. @see paint
  23569. */
  23570. void repaint();
  23571. /** Marks a subsection of this component as needing to be redrawn.
  23572. Calling this will not do any repainting immediately, but will mark the given region
  23573. of the component as 'dirty'. At some point in the near future the operating system
  23574. will send a paint message, which will redraw all the dirty regions of all components.
  23575. There's no guarantee about how soon after calling repaint() the redraw will actually
  23576. happen, and other queued events may be delivered before a redraw is done.
  23577. The region that is passed in will be clipped to keep it within the bounds of this
  23578. component.
  23579. @see repaint()
  23580. */
  23581. void repaint (int x, int y, int width, int height);
  23582. /** Marks a subsection of this component as needing to be redrawn.
  23583. Calling this will not do any repainting immediately, but will mark the given region
  23584. of the component as 'dirty'. At some point in the near future the operating system
  23585. will send a paint message, which will redraw all the dirty regions of all components.
  23586. There's no guarantee about how soon after calling repaint() the redraw will actually
  23587. happen, and other queued events may be delivered before a redraw is done.
  23588. The region that is passed in will be clipped to keep it within the bounds of this
  23589. component.
  23590. @see repaint()
  23591. */
  23592. void repaint (const Rectangle<int>& area);
  23593. /** Makes the component use an internal buffer to optimise its redrawing.
  23594. Setting this flag to true will cause the component to allocate an
  23595. internal buffer into which it paints itself, so that when asked to
  23596. redraw itself, it can use this buffer rather than actually calling the
  23597. paint() method.
  23598. The buffer is kept until the repaint() method is called directly on
  23599. this component (or until it is resized), when the image is invalidated
  23600. and then redrawn the next time the component is painted.
  23601. Note that only the drawing that happens within the component's paint()
  23602. method is drawn into the buffer, it's child components are not buffered, and
  23603. nor is the paintOverChildren() method.
  23604. @see repaint, paint, createComponentSnapshot
  23605. */
  23606. void setBufferedToImage (bool shouldBeBuffered);
  23607. /** Generates a snapshot of part of this component.
  23608. This will return a new Image, the size of the rectangle specified,
  23609. containing a snapshot of the specified area of the component and all
  23610. its children.
  23611. The image may or may not have an alpha-channel, depending on whether the
  23612. image is opaque or not.
  23613. If the clipImageToComponentBounds parameter is true and the area is greater than
  23614. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  23615. then parts of the component beyond its bounds can be drawn.
  23616. @see paintEntireComponent
  23617. */
  23618. const Image createComponentSnapshot (const Rectangle<int>& areaToGrab,
  23619. bool clipImageToComponentBounds = true);
  23620. /** Draws this component and all its subcomponents onto the specified graphics
  23621. context.
  23622. You should very rarely have to use this method, it's simply there in case you need
  23623. to draw a component with a custom graphics context for some reason, e.g. for
  23624. creating a snapshot of the component.
  23625. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  23626. on its children in order to render the entire tree.
  23627. The graphics context may be left in an undefined state after this method returns,
  23628. so you may need to reset it if you're going to use it again.
  23629. If ignoreAlphaLevel is false, then the component will be drawn with the opacity level
  23630. specified by getAlpha(); if ignoreAlphaLevel is true, then this will be ignored and
  23631. an alpha of 1.0 will be used.
  23632. */
  23633. void paintEntireComponent (Graphics& context, bool ignoreAlphaLevel);
  23634. /** This allows you to indicate that this component doesn't require its graphics
  23635. context to be clipped when it is being painted.
  23636. Most people will never need to use this setting, but in situations where you have a very large
  23637. number of simple components being rendered, and where they are guaranteed never to do any drawing
  23638. beyond their own boundaries, setting this to true will reduce the overhead involved in clipping
  23639. the graphics context that gets passed to the component's paint() callback.
  23640. If you enable this mode, you'll need to make sure your paint method doesn't call anything like
  23641. Graphics::fillAll(), and doesn't draw beyond the component's bounds, because that'll produce
  23642. artifacts. Your component also can't have any child components that may be placed beyond its
  23643. bounds.
  23644. */
  23645. void setPaintingIsUnclipped (bool shouldPaintWithoutClipping) throw();
  23646. /** Adds an effect filter to alter the component's appearance.
  23647. When a component has an effect filter set, then this is applied to the
  23648. results of its paint() method. There are a few preset effects, such as
  23649. a drop-shadow or glow, but they can be user-defined as well.
  23650. The effect that is passed in will not be deleted by the component - the
  23651. caller must take care of deleting it.
  23652. To remove an effect from a component, pass a null pointer in as the parameter.
  23653. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  23654. */
  23655. void setComponentEffect (ImageEffectFilter* newEffect);
  23656. /** Returns the current component effect.
  23657. @see setComponentEffect
  23658. */
  23659. ImageEffectFilter* getComponentEffect() const throw() { return effect; }
  23660. /** Finds the appropriate look-and-feel to use for this component.
  23661. If the component hasn't had a look-and-feel explicitly set, this will
  23662. return the parent's look-and-feel, or just the default one if there's no
  23663. parent.
  23664. @see setLookAndFeel, lookAndFeelChanged
  23665. */
  23666. LookAndFeel& getLookAndFeel() const throw();
  23667. /** Sets the look and feel to use for this component.
  23668. This will also change the look and feel for any child components that haven't
  23669. had their look set explicitly.
  23670. The object passed in will not be deleted by the component, so it's the caller's
  23671. responsibility to manage it. It may be used at any time until this component
  23672. has been deleted.
  23673. Calling this method will also invoke the sendLookAndFeelChange() method.
  23674. @see getLookAndFeel, lookAndFeelChanged
  23675. */
  23676. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  23677. /** Called to let the component react to a change in the look-and-feel setting.
  23678. When the look-and-feel is changed for a component, this will be called in
  23679. all its child components, recursively.
  23680. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  23681. an application uses a LookAndFeel class that might have changed internally.
  23682. @see sendLookAndFeelChange, getLookAndFeel
  23683. */
  23684. virtual void lookAndFeelChanged();
  23685. /** Calls the lookAndFeelChanged() method in this component and all its children.
  23686. This will recurse through the children and their children, calling lookAndFeelChanged()
  23687. on them all.
  23688. @see lookAndFeelChanged
  23689. */
  23690. void sendLookAndFeelChange();
  23691. /** Indicates whether any parts of the component might be transparent.
  23692. Components that always paint all of their contents with solid colour and
  23693. thus completely cover any components behind them should use this method
  23694. to tell the repaint system that they are opaque.
  23695. This information is used to optimise drawing, because it means that
  23696. objects underneath opaque windows don't need to be painted.
  23697. By default, components are considered transparent, unless this is used to
  23698. make it otherwise.
  23699. @see isOpaque, getVisibleArea
  23700. */
  23701. void setOpaque (bool shouldBeOpaque);
  23702. /** Returns true if no parts of this component are transparent.
  23703. @returns the value that was set by setOpaque, (the default being false)
  23704. @see setOpaque
  23705. */
  23706. bool isOpaque() const throw();
  23707. /** Indicates whether the component should be brought to the front when clicked.
  23708. Setting this flag to true will cause the component to be brought to the front
  23709. when the mouse is clicked somewhere inside it or its child components.
  23710. Note that a top-level desktop window might still be brought to the front by the
  23711. operating system when it's clicked, depending on how the OS works.
  23712. By default this is set to false.
  23713. @see setMouseClickGrabsKeyboardFocus
  23714. */
  23715. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) throw();
  23716. /** Indicates whether the component should be brought to the front when clicked-on.
  23717. @see setBroughtToFrontOnMouseClick
  23718. */
  23719. bool isBroughtToFrontOnMouseClick() const throw();
  23720. // Keyboard focus methods
  23721. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  23722. By default components aren't actually interested in gaining the
  23723. focus, but this method can be used to turn this on.
  23724. See the grabKeyboardFocus() method for details about the way a component
  23725. is chosen to receive the focus.
  23726. @see grabKeyboardFocus, getWantsKeyboardFocus
  23727. */
  23728. void setWantsKeyboardFocus (bool wantsFocus) throw();
  23729. /** Returns true if the component is interested in getting keyboard focus.
  23730. This returns the flag set by setWantsKeyboardFocus(). The default
  23731. setting is false.
  23732. @see setWantsKeyboardFocus
  23733. */
  23734. bool getWantsKeyboardFocus() const throw();
  23735. /** Chooses whether a click on this component automatically grabs the focus.
  23736. By default this is set to true, but you might want a component which can
  23737. be focused, but where you don't want the user to be able to affect it directly
  23738. by clicking.
  23739. */
  23740. void setMouseClickGrabsKeyboardFocus (bool shouldGrabFocus);
  23741. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  23742. See setMouseClickGrabsKeyboardFocus() for more info.
  23743. */
  23744. bool getMouseClickGrabsKeyboardFocus() const throw();
  23745. /** Tries to give keyboard focus to this component.
  23746. When the user clicks on a component or its grabKeyboardFocus()
  23747. method is called, the following procedure is used to work out which
  23748. component should get it:
  23749. - if the component that was clicked on actually wants focus (as indicated
  23750. by calling getWantsKeyboardFocus), it gets it.
  23751. - if the component itself doesn't want focus, it will try to pass it
  23752. on to whichever of its children is the default component, as determined by
  23753. KeyboardFocusTraverser::getDefaultComponent()
  23754. - if none of its children want focus at all, it will pass it up to its
  23755. parent instead, unless it's a top-level component without a parent,
  23756. in which case it just takes the focus itself.
  23757. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  23758. getCurrentlyFocusedComponent, focusGained, focusLost,
  23759. keyPressed, keyStateChanged
  23760. */
  23761. void grabKeyboardFocus();
  23762. /** Returns true if this component currently has the keyboard focus.
  23763. @param trueIfChildIsFocused if this is true, then the method returns true if
  23764. either this component or any of its children (recursively)
  23765. have the focus. If false, the method only returns true if
  23766. this component has the focus.
  23767. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  23768. focusGained, focusLost
  23769. */
  23770. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  23771. /** Returns the component that currently has the keyboard focus.
  23772. @returns the focused component, or null if nothing is focused.
  23773. */
  23774. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  23775. /** Tries to move the keyboard focus to one of this component's siblings.
  23776. This will try to move focus to either the next or previous component. (This
  23777. is the method that is used when shifting focus by pressing the tab key).
  23778. Components for which getWantsKeyboardFocus() returns false are not looked at.
  23779. @param moveToNext if true, the focus will move forwards; if false, it will
  23780. move backwards
  23781. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  23782. */
  23783. void moveKeyboardFocusToSibling (bool moveToNext);
  23784. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  23785. which focus should be passed from this component.
  23786. The default implementation of this method will return a default
  23787. KeyboardFocusTraverser if this component is a focus container (as determined
  23788. by the setFocusContainer() method). If the component isn't a focus
  23789. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  23790. If you overrride this to return a custom KeyboardFocusTraverser, then
  23791. this component and all its sub-components will use the new object to
  23792. make their focusing decisions.
  23793. The method should return a new object, which the caller is required to
  23794. delete when no longer needed.
  23795. */
  23796. virtual KeyboardFocusTraverser* createFocusTraverser();
  23797. /** Returns the focus order of this component, if one has been specified.
  23798. By default components don't have a focus order - in that case, this
  23799. will return 0. Lower numbers indicate that the component will be
  23800. earlier in the focus traversal order.
  23801. To change the order, call setExplicitFocusOrder().
  23802. The focus order may be used by the KeyboardFocusTraverser class as part of
  23803. its algorithm for deciding the order in which components should be traversed.
  23804. See the KeyboardFocusTraverser class for more details on this.
  23805. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  23806. */
  23807. int getExplicitFocusOrder() const;
  23808. /** Sets the index used in determining the order in which focusable components
  23809. should be traversed.
  23810. A value of 0 or less is taken to mean that no explicit order is wanted, and
  23811. that traversal should use other factors, like the component's position.
  23812. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  23813. */
  23814. void setExplicitFocusOrder (int newFocusOrderIndex);
  23815. /** Indicates whether this component is a parent for components that can have
  23816. their focus traversed.
  23817. This flag is used by the default implementation of the createFocusTraverser()
  23818. method, which uses the flag to find the first parent component (of the currently
  23819. focused one) which wants to be a focus container.
  23820. So using this method to set the flag to 'true' causes this component to
  23821. act as the top level within which focus is passed around.
  23822. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  23823. */
  23824. void setFocusContainer (bool shouldBeFocusContainer) throw();
  23825. /** Returns true if this component has been marked as a focus container.
  23826. See setFocusContainer() for more details.
  23827. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  23828. */
  23829. bool isFocusContainer() const throw();
  23830. /** Returns true if the component (and all its parents) are enabled.
  23831. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  23832. what difference this makes to the component depends on the type. E.g. buttons
  23833. and sliders will choose to draw themselves differently, etc.
  23834. Note that if one of this component's parents is disabled, this will always
  23835. return false, even if this component itself is enabled.
  23836. @see setEnabled, enablementChanged
  23837. */
  23838. bool isEnabled() const throw();
  23839. /** Enables or disables this component.
  23840. Disabling a component will also cause all of its child components to become
  23841. disabled.
  23842. Similarly, enabling a component which is inside a disabled parent
  23843. component won't make any difference until the parent is re-enabled.
  23844. @see isEnabled, enablementChanged
  23845. */
  23846. void setEnabled (bool shouldBeEnabled);
  23847. /** Callback to indicate that this component has been enabled or disabled.
  23848. This can be triggered by one of the component's parent components
  23849. being enabled or disabled, as well as changes to the component itself.
  23850. The default implementation of this method does nothing; your class may
  23851. wish to repaint itself or something when this happens.
  23852. @see setEnabled, isEnabled
  23853. */
  23854. virtual void enablementChanged();
  23855. /** Changes the transparency of this component.
  23856. When painted, the entire component and all its children will be rendered
  23857. with this as the overall opacity level, where 0 is completely invisible, and
  23858. 1.0 is fully opaque (i.e. normal).
  23859. @see getAlpha
  23860. */
  23861. void setAlpha (float newAlpha);
  23862. /** Returns the component's current transparancy level.
  23863. See setAlpha() for more details.
  23864. */
  23865. float getAlpha() const;
  23866. /** Changes the mouse cursor shape to use when the mouse is over this component.
  23867. Note that the cursor set by this method can be overridden by the getMouseCursor
  23868. method.
  23869. @see MouseCursor
  23870. */
  23871. void setMouseCursor (const MouseCursor& cursorType);
  23872. /** Returns the mouse cursor shape to use when the mouse is over this component.
  23873. The default implementation will return the cursor that was set by setCursor()
  23874. but can be overridden for more specialised purposes, e.g. returning different
  23875. cursors depending on the mouse position.
  23876. @see MouseCursor
  23877. */
  23878. virtual const MouseCursor getMouseCursor();
  23879. /** Forces the current mouse cursor to be updated.
  23880. If you're overriding the getMouseCursor() method to control which cursor is
  23881. displayed, then this will only be checked each time the user moves the mouse. So
  23882. if you want to force the system to check that the cursor being displayed is
  23883. up-to-date (even if the mouse is just sitting there), call this method.
  23884. (If you're changing the cursor using setMouseCursor(), you don't need to bother
  23885. calling this).
  23886. */
  23887. void updateMouseCursor() const;
  23888. /** Components can override this method to draw their content.
  23889. The paint() method gets called when a region of a component needs redrawing,
  23890. either because the component's repaint() method has been called, or because
  23891. something has happened on the screen that means a section of a window needs
  23892. to be redrawn.
  23893. Any child components will draw themselves over whatever this method draws. If
  23894. you need to paint over the top of your child components, you can also implement
  23895. the paintOverChildren() method to do this.
  23896. If you want to cause a component to redraw itself, this is done asynchronously -
  23897. calling the repaint() method marks a region of the component as "dirty", and the
  23898. paint() method will automatically be called sometime later, by the message thread,
  23899. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  23900. you never redraw something synchronously.
  23901. You should never need to call this method directly - to take a snapshot of the
  23902. component you could use createComponentSnapshot() or paintEntireComponent().
  23903. @param g the graphics context that must be used to do the drawing operations.
  23904. @see repaint, paintOverChildren, Graphics
  23905. */
  23906. virtual void paint (Graphics& g);
  23907. /** Components can override this method to draw over the top of their children.
  23908. For most drawing operations, it's better to use the normal paint() method,
  23909. but if you need to overlay something on top of the children, this can be
  23910. used.
  23911. @see paint, Graphics
  23912. */
  23913. virtual void paintOverChildren (Graphics& g);
  23914. /** Called when the mouse moves inside this component.
  23915. If the mouse button isn't pressed and the mouse moves over a component,
  23916. this will be called to let the component react to this.
  23917. A component will always get a mouseEnter callback before a mouseMove.
  23918. @param e details about the position and status of the mouse event
  23919. @see mouseEnter, mouseExit, mouseDrag, contains
  23920. */
  23921. virtual void mouseMove (const MouseEvent& e);
  23922. /** Called when the mouse first enters this component.
  23923. If the mouse button isn't pressed and the mouse moves into a component,
  23924. this will be called to let the component react to this.
  23925. When the mouse button is pressed and held down while being moved in
  23926. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  23927. mouseDrag messages are sent to the component that the mouse was originally
  23928. clicked on, until the button is released.
  23929. If you're writing a component that needs to repaint itself when the mouse
  23930. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  23931. method.
  23932. @param e details about the position and status of the mouse event
  23933. @see mouseExit, mouseDrag, mouseMove, contains
  23934. */
  23935. virtual void mouseEnter (const MouseEvent& e);
  23936. /** Called when the mouse moves out of this component.
  23937. This will be called when the mouse moves off the edge of this
  23938. component.
  23939. If the mouse button was pressed, and it was then dragged off the
  23940. edge of the component and released, then this callback will happen
  23941. when the button is released, after the mouseUp callback.
  23942. If you're writing a component that needs to repaint itself when the mouse
  23943. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  23944. method.
  23945. @param e details about the position and status of the mouse event
  23946. @see mouseEnter, mouseDrag, mouseMove, contains
  23947. */
  23948. virtual void mouseExit (const MouseEvent& e);
  23949. /** Called when a mouse button is pressed while it's over this component.
  23950. The MouseEvent object passed in contains lots of methods for finding out
  23951. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  23952. were held down at the time.
  23953. Once a button is held down, the mouseDrag method will be called when the
  23954. mouse moves, until the button is released.
  23955. @param e details about the position and status of the mouse event
  23956. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  23957. */
  23958. virtual void mouseDown (const MouseEvent& e);
  23959. /** Called when the mouse is moved while a button is held down.
  23960. When a mouse button is pressed inside a component, that component
  23961. receives mouseDrag callbacks each time the mouse moves, even if the
  23962. mouse strays outside the component's bounds.
  23963. If you want to be able to drag things off the edge of a component
  23964. and have the component scroll when you get to the edges, the
  23965. beginDragAutoRepeat() method might be useful.
  23966. @param e details about the position and status of the mouse event
  23967. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  23968. */
  23969. virtual void mouseDrag (const MouseEvent& e);
  23970. /** Called when a mouse button is released.
  23971. A mouseUp callback is sent to the component in which a button was pressed
  23972. even if the mouse is actually over a different component when the
  23973. button is released.
  23974. The MouseEvent object passed in contains lots of methods for finding out
  23975. which buttons were down just before they were released.
  23976. @param e details about the position and status of the mouse event
  23977. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  23978. */
  23979. virtual void mouseUp (const MouseEvent& e);
  23980. /** Called when a mouse button has been double-clicked in this component.
  23981. The MouseEvent object passed in contains lots of methods for finding out
  23982. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  23983. were held down at the time.
  23984. For altering the time limit used to detect double-clicks,
  23985. see MouseEvent::setDoubleClickTimeout.
  23986. @param e details about the position and status of the mouse event
  23987. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  23988. MouseEvent::getDoubleClickTimeout
  23989. */
  23990. virtual void mouseDoubleClick (const MouseEvent& e);
  23991. /** Called when the mouse-wheel is moved.
  23992. This callback is sent to the component that the mouse is over when the
  23993. wheel is moved.
  23994. If not overridden, the component will forward this message to its parent, so
  23995. that parent components can collect mouse-wheel messages that happen to
  23996. child components which aren't interested in them.
  23997. @param e details about the position and status of the mouse event
  23998. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  23999. value means the wheel has been pushed to the right, negative means it
  24000. was pushed to the left
  24001. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  24002. value means the wheel has been pushed upwards, negative means it
  24003. was pushed downwards
  24004. */
  24005. virtual void mouseWheelMove (const MouseEvent& e,
  24006. float wheelIncrementX,
  24007. float wheelIncrementY);
  24008. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  24009. current mouse-drag operation.
  24010. This allows you to make sure that mouseDrag() events are sent continuously, even
  24011. when the mouse isn't moving. This can be useful for things like auto-scrolling
  24012. components when the mouse is near an edge.
  24013. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  24014. minimum interval between consecutive mouse drag callbacks. The callbacks
  24015. will continue until the mouse is released, and then the interval will be reset,
  24016. so you need to make sure it's called every time you begin a drag event.
  24017. Passing an interval of 0 or less will cancel the auto-repeat.
  24018. @see mouseDrag, Desktop::beginDragAutoRepeat
  24019. */
  24020. static void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  24021. /** Causes automatic repaints when the mouse enters or exits this component.
  24022. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  24023. on the component, it will trigger a repaint.
  24024. This is handy for things like buttons that need to draw themselves differently when
  24025. the mouse moves over them, and it avoids having to override all the different mouse
  24026. callbacks and call repaint().
  24027. @see mouseEnter, mouseExit, mouseDown, mouseUp
  24028. */
  24029. void setRepaintsOnMouseActivity (bool shouldRepaint) throw();
  24030. /** Registers a listener to be told when mouse events occur in this component.
  24031. If you need to get informed about mouse events in a component but can't or
  24032. don't want to override its methods, you can attach any number of listeners
  24033. to the component, and these will get told about the events in addition to
  24034. the component's own callbacks being called.
  24035. Note that a MouseListener can also be attached to more than one component.
  24036. @param newListener the listener to register
  24037. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  24038. for events that happen to any child component
  24039. within this component, including deeply-nested
  24040. child components. If false, it will only be
  24041. told about events that this component handles.
  24042. @see MouseListener, removeMouseListener
  24043. */
  24044. void addMouseListener (MouseListener* newListener,
  24045. bool wantsEventsForAllNestedChildComponents);
  24046. /** Deregisters a mouse listener.
  24047. @see addMouseListener, MouseListener
  24048. */
  24049. void removeMouseListener (MouseListener* listenerToRemove);
  24050. /** Adds a listener that wants to hear about keypresses that this component receives.
  24051. The listeners that are registered with a component are called by its keyPressed() or
  24052. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  24053. If you add an object as a key listener, be careful to remove it when the object
  24054. is deleted, or the component will be left with a dangling pointer.
  24055. @see keyPressed, keyStateChanged, removeKeyListener
  24056. */
  24057. void addKeyListener (KeyListener* newListener);
  24058. /** Removes a previously-registered key listener.
  24059. @see addKeyListener
  24060. */
  24061. void removeKeyListener (KeyListener* listenerToRemove);
  24062. /** Called when a key is pressed.
  24063. When a key is pressed, the component that has the keyboard focus will have this
  24064. method called. Remember that a component will only be given the focus if its
  24065. setWantsKeyboardFocus() method has been used to enable this.
  24066. If your implementation returns true, the event will be consumed and not passed
  24067. on to any other listeners. If it returns false, the key will be passed to any
  24068. KeyListeners that have been registered with this component. As soon as one of these
  24069. returns true, the process will stop, but if they all return false, the event will
  24070. be passed upwards to this component's parent, and so on.
  24071. The default implementation of this method does nothing and returns false.
  24072. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  24073. */
  24074. virtual bool keyPressed (const KeyPress& key);
  24075. /** Called when a key is pressed or released.
  24076. Whenever a key on the keyboard is pressed or released (including modifier keys
  24077. like shift and ctrl), this method will be called on the component that currently
  24078. has the keyboard focus. Remember that a component will only be given the focus if
  24079. its setWantsKeyboardFocus() method has been used to enable this.
  24080. If your implementation returns true, the event will be consumed and not passed
  24081. on to any other listeners. If it returns false, then any KeyListeners that have
  24082. been registered with this component will have their keyStateChanged methods called.
  24083. As soon as one of these returns true, the process will stop, but if they all return
  24084. false, the event will be passed upwards to this component's parent, and so on.
  24085. The default implementation of this method does nothing and returns false.
  24086. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  24087. method.
  24088. @param isKeyDown true if a key has been pressed; false if it has been released
  24089. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  24090. */
  24091. virtual bool keyStateChanged (bool isKeyDown);
  24092. /** Called when a modifier key is pressed or released.
  24093. Whenever the shift, control, alt or command keys are pressed or released,
  24094. this method will be called on the component that currently has the keyboard focus.
  24095. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  24096. method has been used to enable this.
  24097. The default implementation of this method actually calls its parent's modifierKeysChanged
  24098. method, so that focused components which aren't interested in this will give their
  24099. parents a chance to act on the event instead.
  24100. @see keyStateChanged, ModifierKeys
  24101. */
  24102. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  24103. /** Enumeration used by the focusChanged() and focusLost() methods. */
  24104. enum FocusChangeType
  24105. {
  24106. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  24107. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  24108. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  24109. };
  24110. /** Called to indicate that this component has just acquired the keyboard focus.
  24111. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24112. */
  24113. virtual void focusGained (FocusChangeType cause);
  24114. /** Called to indicate that this component has just lost the keyboard focus.
  24115. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24116. */
  24117. virtual void focusLost (FocusChangeType cause);
  24118. /** Called to indicate that one of this component's children has been focused or unfocused.
  24119. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  24120. changed. It happens when focus moves from one of this component's children (at any depth)
  24121. to a component that isn't contained in this one, (or vice-versa).
  24122. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24123. */
  24124. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  24125. /** Returns true if the mouse is currently over this component.
  24126. If the mouse isn't over the component, this will return false, even if the
  24127. mouse is currently being dragged - so you can use this in your mouseDrag
  24128. method to find out whether it's really over the component or not.
  24129. Note that when the mouse button is being held down, then the only component
  24130. for which this method will return true is the one that was originally
  24131. clicked on.
  24132. If includeChildren is true, then this will also return true if the mouse is over
  24133. any of the component's children (recursively) as well as the component itself.
  24134. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  24135. */
  24136. bool isMouseOver (bool includeChildren = false) const;
  24137. /** Returns true if the mouse button is currently held down in this component.
  24138. Note that this is a test to see whether the mouse is being pressed in this
  24139. component, so it'll return false if called on component A when the mouse
  24140. is actually being dragged in component B.
  24141. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  24142. */
  24143. bool isMouseButtonDown() const throw();
  24144. /** True if the mouse is over this component, or if it's being dragged in this component.
  24145. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  24146. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  24147. */
  24148. bool isMouseOverOrDragging() const throw();
  24149. /** Returns true if a mouse button is currently down.
  24150. Unlike isMouseButtonDown, this will test the current state of the
  24151. buttons without regard to which component (if any) it has been
  24152. pressed in.
  24153. @see isMouseButtonDown, ModifierKeys
  24154. */
  24155. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  24156. /** Returns the mouse's current position, relative to this component.
  24157. The return value is relative to the component's top-left corner.
  24158. */
  24159. const Point<int> getMouseXYRelative() const;
  24160. /** Called when this component's size has been changed.
  24161. A component can implement this method to do things such as laying out its
  24162. child components when its width or height changes.
  24163. The method is called synchronously as a result of the setBounds or setSize
  24164. methods, so repeatedly changing a components size will repeatedly call its
  24165. resized method (unlike things like repainting, where multiple calls to repaint
  24166. are coalesced together).
  24167. If the component is a top-level window on the desktop, its size could also
  24168. be changed by operating-system factors beyond the application's control.
  24169. @see moved, setSize
  24170. */
  24171. virtual void resized();
  24172. /** Called when this component's position has been changed.
  24173. This is called when the position relative to its parent changes, not when
  24174. its absolute position on the screen changes (so it won't be called for
  24175. all child components when a parent component is moved).
  24176. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  24177. or any of the other repositioning methods, and like resized(), it will be
  24178. called each time those methods are called.
  24179. If the component is a top-level window on the desktop, its position could also
  24180. be changed by operating-system factors beyond the application's control.
  24181. @see resized, setBounds
  24182. */
  24183. virtual void moved();
  24184. /** Called when one of this component's children is moved or resized.
  24185. If the parent wants to know about changes to its immediate children (not
  24186. to children of its children), this is the method to override.
  24187. @see moved, resized, parentSizeChanged
  24188. */
  24189. virtual void childBoundsChanged (Component* child);
  24190. /** Called when this component's immediate parent has been resized.
  24191. If the component is a top-level window, this indicates that the screen size
  24192. has changed.
  24193. @see childBoundsChanged, moved, resized
  24194. */
  24195. virtual void parentSizeChanged();
  24196. /** Called when this component has been moved to the front of its siblings.
  24197. The component may have been brought to the front by the toFront() method, or
  24198. by the operating system if it's a top-level window.
  24199. @see toFront
  24200. */
  24201. virtual void broughtToFront();
  24202. /** Adds a listener to be told about changes to the component hierarchy or position.
  24203. Component listeners get called when this component's size, position or children
  24204. change - see the ComponentListener class for more details.
  24205. @param newListener the listener to register - if this is already registered, it
  24206. will be ignored.
  24207. @see ComponentListener, removeComponentListener
  24208. */
  24209. void addComponentListener (ComponentListener* newListener);
  24210. /** Removes a component listener.
  24211. @see addComponentListener
  24212. */
  24213. void removeComponentListener (ComponentListener* listenerToRemove);
  24214. /** Dispatches a numbered message to this component.
  24215. This is a quick and cheap way of allowing simple asynchronous messages to
  24216. be sent to components. It's also safe, because if the component that you
  24217. send the message to is a null or dangling pointer, this won't cause an error.
  24218. The command ID is later delivered to the component's handleCommandMessage() method by
  24219. the application's message queue.
  24220. @see handleCommandMessage
  24221. */
  24222. void postCommandMessage (int commandId);
  24223. /** Called to handle a command that was sent by postCommandMessage().
  24224. This is called by the message thread when a command message arrives, and
  24225. the component can override this method to process it in any way it needs to.
  24226. @see postCommandMessage
  24227. */
  24228. virtual void handleCommandMessage (int commandId);
  24229. /** Runs a component modally, waiting until the loop terminates.
  24230. This method first makes the component visible, brings it to the front and
  24231. gives it the keyboard focus.
  24232. It then runs a loop, dispatching messages from the system message queue, but
  24233. blocking all mouse or keyboard messages from reaching any components other
  24234. than this one and its children.
  24235. This loop continues until the component's exitModalState() method is called (or
  24236. the component is deleted), and then this method returns, returning the value
  24237. passed into exitModalState().
  24238. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  24239. isCurrentlyBlockedByAnotherModalComponent, ModalComponentManager
  24240. */
  24241. #if JUCE_MODAL_LOOPS_PERMITTED
  24242. int runModalLoop();
  24243. #endif
  24244. /** Puts the component into a modal state.
  24245. This makes the component modal, so that messages are blocked from reaching
  24246. any components other than this one and its children, but unlike runModalLoop(),
  24247. this method returns immediately.
  24248. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  24249. get the focus, which is usually what you'll want it to do. If not, it will leave
  24250. the focus unchanged.
  24251. The callback is an optional object which will receive a callback when the modal
  24252. component loses its modal status, either by being hidden or when exitModalState()
  24253. is called. If you pass an object in here, the system will take care of deleting it
  24254. later, after making the callback
  24255. If deleteWhenDismissed is true, then when it is dismissed, the component will be
  24256. deleted and then the callback will be called. (This will safely handle the situation
  24257. where the component is deleted before its exitModalState() method is called).
  24258. @see exitModalState, runModalLoop, ModalComponentManager::attachCallback
  24259. */
  24260. void enterModalState (bool takeKeyboardFocus = true,
  24261. ModalComponentManager::Callback* callback = 0,
  24262. bool deleteWhenDismissed = false);
  24263. /** Ends a component's modal state.
  24264. If this component is currently modal, this will turn of its modalness, and return
  24265. a value to the runModalLoop() method that might have be running its modal loop.
  24266. @see runModalLoop, enterModalState, isCurrentlyModal
  24267. */
  24268. void exitModalState (int returnValue);
  24269. /** Returns true if this component is the modal one.
  24270. It's possible to have nested modal components, e.g. a pop-up dialog box
  24271. that launches another pop-up, but this will only return true for
  24272. the one at the top of the stack.
  24273. @see getCurrentlyModalComponent
  24274. */
  24275. bool isCurrentlyModal() const throw();
  24276. /** Returns the number of components that are currently in a modal state.
  24277. @see getCurrentlyModalComponent
  24278. */
  24279. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  24280. /** Returns one of the components that are currently modal.
  24281. The index specifies which of the possible modal components to return. The order
  24282. of the components in this list is the reverse of the order in which they became
  24283. modal - so the component at index 0 is always the active component, and the others
  24284. are progressively earlier ones that are themselves now blocked by later ones.
  24285. @returns the modal component, or null if no components are modal (or if the
  24286. index is out of range)
  24287. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  24288. */
  24289. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  24290. /** Checks whether there's a modal component somewhere that's stopping this one
  24291. from receiving messages.
  24292. If there is a modal component, its canModalEventBeSentToComponent() method
  24293. will be called to see if it will still allow this component to receive events.
  24294. @see runModalLoop, getCurrentlyModalComponent
  24295. */
  24296. bool isCurrentlyBlockedByAnotherModalComponent() const;
  24297. /** When a component is modal, this callback allows it to choose which other
  24298. components can still receive events.
  24299. When a modal component is active and the user clicks on a non-modal component,
  24300. this method is called on the modal component, and if it returns true, the
  24301. event is allowed to reach its target. If it returns false, the event is blocked
  24302. and the inputAttemptWhenModal() callback is made.
  24303. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  24304. implementation just returns false in all cases.
  24305. */
  24306. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  24307. /** Called when the user tries to click on a component that is blocked by another
  24308. modal component.
  24309. When a component is modal and the user clicks on one of the other components,
  24310. the modal component will receive this callback.
  24311. The default implementation of this method will play a beep, and bring the currently
  24312. modal component to the front, but it can be overridden to do other tasks.
  24313. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  24314. */
  24315. virtual void inputAttemptWhenModal();
  24316. /** Returns the set of properties that belong to this component.
  24317. Each component has a NamedValueSet object which you can use to attach arbitrary
  24318. items of data to it.
  24319. */
  24320. NamedValueSet& getProperties() throw() { return properties; }
  24321. /** Returns the set of properties that belong to this component.
  24322. Each component has a NamedValueSet object which you can use to attach arbitrary
  24323. items of data to it.
  24324. */
  24325. const NamedValueSet& getProperties() const throw() { return properties; }
  24326. /** Looks for a colour that has been registered with the given colour ID number.
  24327. If a colour has been set for this ID number using setColour(), then it is
  24328. returned. If none has been set, the method will try calling the component's
  24329. LookAndFeel class's findColour() method. If none has been registered with the
  24330. look-and-feel either, it will just return black.
  24331. The colour IDs for various purposes are stored as enums in the components that
  24332. they are relevent to - for an example, see Slider::ColourIds,
  24333. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  24334. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  24335. */
  24336. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  24337. /** Registers a colour to be used for a particular purpose.
  24338. Changing a colour will cause a synchronous callback to the colourChanged()
  24339. method, which your component can override if it needs to do something when
  24340. colours are altered.
  24341. For more details about colour IDs, see the comments for findColour().
  24342. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  24343. */
  24344. void setColour (int colourId, const Colour& colour);
  24345. /** If a colour has been set with setColour(), this will remove it.
  24346. This allows you to make a colour revert to its default state.
  24347. */
  24348. void removeColour (int colourId);
  24349. /** Returns true if the specified colour ID has been explicitly set for this
  24350. component using the setColour() method.
  24351. */
  24352. bool isColourSpecified (int colourId) const;
  24353. /** This looks for any colours that have been specified for this component,
  24354. and copies them to the specified target component.
  24355. */
  24356. void copyAllExplicitColoursTo (Component& target) const;
  24357. /** This method is called when a colour is changed by the setColour() method.
  24358. @see setColour, findColour
  24359. */
  24360. virtual void colourChanged();
  24361. /** Components can implement this method to provide a MarkerList.
  24362. The default implementation of this method returns 0, but you can override it to
  24363. return a pointer to the component's marker list. If xAxis is true, it should
  24364. return the X marker list; if false, it should return the Y markers.
  24365. */
  24366. virtual MarkerList* getMarkers (bool xAxis);
  24367. /** Returns the underlying native window handle for this component.
  24368. This is platform-dependent and strictly for power-users only!
  24369. */
  24370. void* getWindowHandle() const;
  24371. /** Holds a pointer to some type of Component, which automatically becomes null if
  24372. the component is deleted.
  24373. If you're using a component which may be deleted by another event that's outside
  24374. of your control, use a SafePointer instead of a normal pointer to refer to it,
  24375. and you can test whether it's null before using it to see if something has deleted
  24376. it.
  24377. The ComponentType typedef must be Component, or some subclass of Component.
  24378. You may also want to use a WeakReference<Component> object for the same purpose.
  24379. */
  24380. template <class ComponentType>
  24381. class SafePointer
  24382. {
  24383. public:
  24384. /** Creates a null SafePointer. */
  24385. SafePointer() throw() {}
  24386. /** Creates a SafePointer that points at the given component. */
  24387. SafePointer (ComponentType* const component) : weakRef (component) {}
  24388. /** Creates a copy of another SafePointer. */
  24389. SafePointer (const SafePointer& other) throw() : weakRef (other.weakRef) {}
  24390. /** Copies another pointer to this one. */
  24391. SafePointer& operator= (const SafePointer& other) { weakRef = other.weakRef; return *this; }
  24392. /** Copies another pointer to this one. */
  24393. SafePointer& operator= (ComponentType* const newComponent) { weakRef = newComponent; return *this; }
  24394. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24395. ComponentType* getComponent() const throw() { return dynamic_cast <ComponentType*> (weakRef.get()); }
  24396. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24397. operator ComponentType*() const throw() { return getComponent(); }
  24398. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24399. ComponentType* operator->() throw() { return getComponent(); }
  24400. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24401. const ComponentType* operator->() const throw() { return getComponent(); }
  24402. /** If the component is valid, this deletes it and sets this pointer to null. */
  24403. void deleteAndZero() { delete getComponent(); jassert (getComponent() == 0); }
  24404. bool operator== (ComponentType* component) const throw() { return weakRef == component; }
  24405. bool operator!= (ComponentType* component) const throw() { return weakRef != component; }
  24406. private:
  24407. WeakReference<Component> weakRef;
  24408. };
  24409. /** A class to keep an eye on a component and check for it being deleted.
  24410. This is designed for use with the ListenerList::callChecked() methods, to allow
  24411. the list iterator to stop cleanly if the component is deleted by a listener callback
  24412. while the list is still being iterated.
  24413. */
  24414. class JUCE_API BailOutChecker
  24415. {
  24416. public:
  24417. /** Creates a checker that watches one component. */
  24418. BailOutChecker (Component* component);
  24419. /** Returns true if either of the two components have been deleted since this object was created. */
  24420. bool shouldBailOut() const throw();
  24421. private:
  24422. const WeakReference<Component> safePointer;
  24423. JUCE_DECLARE_NON_COPYABLE (BailOutChecker);
  24424. };
  24425. /**
  24426. Base class for objects that can be used to automatically position a component according to
  24427. some kind of algorithm.
  24428. The component class simply holds onto a reference to a Positioner, but doesn't actually do
  24429. anything with it - all the functionality must be implemented by the positioner itself (e.g.
  24430. it might choose to watch some kind of value and move the component when the value changes).
  24431. */
  24432. class JUCE_API Positioner
  24433. {
  24434. public:
  24435. /** Creates a Positioner which can control the specified component. */
  24436. explicit Positioner (Component& component) throw();
  24437. /** Destructor. */
  24438. virtual ~Positioner() {}
  24439. /** Returns the component that this positioner controls. */
  24440. Component& getComponent() const throw() { return component; }
  24441. /** Attempts to set the component's position to the given rectangle.
  24442. Unlike simply calling Component::setBounds(), this may involve the positioner
  24443. being smart enough to adjust itself to fit the new bounds, e.g. a RelativeRectangle's
  24444. positioner may try to reverse the expressions used to make them fit these new coordinates.
  24445. */
  24446. virtual void applyNewBounds (const Rectangle<int>& newBounds) = 0;
  24447. private:
  24448. Component& component;
  24449. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  24450. };
  24451. /** Returns the Positioner object that has been set for this component.
  24452. @see setPositioner()
  24453. */
  24454. Positioner* getPositioner() const throw();
  24455. /** Sets a new Positioner object for this component.
  24456. If there's currently another positioner set, it will be deleted. The object that is passed in
  24457. will be deleted automatically by this component when it's no longer required. Pass a null pointer
  24458. to clear the current positioner.
  24459. @see getPositioner()
  24460. */
  24461. void setPositioner (Positioner* newPositioner);
  24462. #ifndef DOXYGEN
  24463. // These methods are deprecated - use localPointToGlobal, getLocalPoint, getLocalPoint, etc instead.
  24464. JUCE_DEPRECATED (const Point<int> relativePositionToGlobal (const Point<int>&) const);
  24465. JUCE_DEPRECATED (const Point<int> globalPositionToRelative (const Point<int>&) const);
  24466. JUCE_DEPRECATED (const Point<int> relativePositionToOtherComponent (const Component*, const Point<int>&) const);
  24467. #endif
  24468. private:
  24469. friend class ComponentPeer;
  24470. friend class MouseInputSource;
  24471. friend class MouseInputSourceInternal;
  24472. #ifndef DOXYGEN
  24473. static Component* currentlyFocusedComponent;
  24474. String componentName, componentID;
  24475. Component* parentComponent;
  24476. Rectangle<int> bounds;
  24477. ScopedPointer <Positioner> positioner;
  24478. ScopedPointer <AffineTransform> affineTransform;
  24479. Array <Component*> childComponentList;
  24480. LookAndFeel* lookAndFeel;
  24481. MouseCursor cursor;
  24482. ImageEffectFilter* effect;
  24483. Image bufferedImage;
  24484. class MouseListenerList;
  24485. friend class MouseListenerList;
  24486. friend class ScopedPointer <MouseListenerList>;
  24487. ScopedPointer <MouseListenerList> mouseListeners;
  24488. ScopedPointer <Array <KeyListener*> > keyListeners;
  24489. ListenerList <ComponentListener> componentListeners;
  24490. NamedValueSet properties;
  24491. friend class WeakReference<Component>;
  24492. WeakReference<Component>::Master weakReferenceMaster;
  24493. const WeakReference<Component>::SharedRef& getWeakReference();
  24494. struct ComponentFlags
  24495. {
  24496. bool hasHeavyweightPeerFlag : 1;
  24497. bool visibleFlag : 1;
  24498. bool opaqueFlag : 1;
  24499. bool ignoresMouseClicksFlag : 1;
  24500. bool allowChildMouseClicksFlag : 1;
  24501. bool wantsFocusFlag : 1;
  24502. bool isFocusContainerFlag : 1;
  24503. bool dontFocusOnMouseClickFlag : 1;
  24504. bool alwaysOnTopFlag : 1;
  24505. bool bufferToImageFlag : 1;
  24506. bool bringToFrontOnClickFlag : 1;
  24507. bool repaintOnMouseActivityFlag : 1;
  24508. bool mouseDownFlag : 1;
  24509. bool mouseOverFlag : 1;
  24510. bool mouseInsideFlag : 1;
  24511. bool currentlyModalFlag : 1;
  24512. bool isDisabledFlag : 1;
  24513. bool childCompFocusedFlag : 1;
  24514. bool dontClipGraphicsFlag : 1;
  24515. #if JUCE_DEBUG
  24516. bool isInsidePaintCall : 1;
  24517. #endif
  24518. };
  24519. union
  24520. {
  24521. uint32 componentFlags;
  24522. ComponentFlags flags;
  24523. };
  24524. uint8 componentTransparency;
  24525. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24526. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24527. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24528. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  24529. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24530. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24531. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  24532. void internalBroughtToFront();
  24533. void internalFocusGain (const FocusChangeType cause, const WeakReference<Component>&);
  24534. void internalFocusGain (const FocusChangeType cause);
  24535. void internalFocusLoss (const FocusChangeType cause);
  24536. void internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>&);
  24537. void internalModalInputAttempt();
  24538. void internalModifierKeysChanged();
  24539. void internalChildrenChanged();
  24540. void internalHierarchyChanged();
  24541. Component* removeChildComponent (int index, bool sendParentEvents, bool sendChildEvents);
  24542. void moveChildInternal (int sourceIndex, int destIndex);
  24543. void paintComponentAndChildren (Graphics& g);
  24544. void paintComponent (Graphics& g);
  24545. void paintWithinParentContext (Graphics& g);
  24546. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  24547. void repaintParent();
  24548. void sendFakeMouseMove() const;
  24549. void takeKeyboardFocus (const FocusChangeType cause);
  24550. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  24551. static void giveAwayFocus (bool sendFocusLossEvent);
  24552. void sendEnablementChangeMessage();
  24553. void sendVisibilityChangeMessage();
  24554. class ComponentHelpers;
  24555. friend class ComponentHelpers;
  24556. /* Components aren't allowed to have copy constructors, as this would mess up parent hierarchies.
  24557. You might need to give your subclasses a private dummy constructor to avoid compiler warnings.
  24558. */
  24559. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Component);
  24560. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  24561. // This is included here just to cause a compile error if your code is still handling
  24562. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  24563. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  24564. // implement its methods instead of this Component method).
  24565. virtual void filesDropped (const StringArray&, int, int) {}
  24566. // This is included here to cause an error if you use or overload it - it has been deprecated in
  24567. // favour of contains (const Point<int>&)
  24568. void contains (int, int);
  24569. #endif
  24570. protected:
  24571. /** @internal */
  24572. virtual void internalRepaint (int x, int y, int w, int h);
  24573. /** @internal */
  24574. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  24575. #endif
  24576. };
  24577. #endif // __JUCE_COMPONENT_JUCEHEADER__
  24578. /*** End of inlined file: juce_Component.h ***/
  24579. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  24580. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  24581. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  24582. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  24583. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  24584. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  24585. /** A type used to hold the unique ID for an application command.
  24586. This is a numeric type, so it can be stored as an integer.
  24587. @see ApplicationCommandInfo, ApplicationCommandManager,
  24588. ApplicationCommandTarget, KeyPressMappingSet
  24589. */
  24590. typedef int CommandID;
  24591. /** A set of general-purpose application command IDs.
  24592. Because these commands are likely to be used in most apps, they're defined
  24593. here to help different apps to use the same numeric values for them.
  24594. Of course you don't have to use these, but some of them are used internally by
  24595. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  24596. @see ApplicationCommandInfo, ApplicationCommandManager,
  24597. ApplicationCommandTarget, KeyPressMappingSet
  24598. */
  24599. namespace StandardApplicationCommandIDs
  24600. {
  24601. /** This command ID should be used to send a "Quit the App" command.
  24602. This command is recognised by the JUCEApplication class, so if it is invoked
  24603. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  24604. object will catch it and call JUCEApplication::systemRequestedQuit().
  24605. */
  24606. static const CommandID quit = 0x1001;
  24607. /** The command ID that should be used to send a "Delete" command. */
  24608. static const CommandID del = 0x1002;
  24609. /** The command ID that should be used to send a "Cut" command. */
  24610. static const CommandID cut = 0x1003;
  24611. /** The command ID that should be used to send a "Copy to clipboard" command. */
  24612. static const CommandID copy = 0x1004;
  24613. /** The command ID that should be used to send a "Paste from clipboard" command. */
  24614. static const CommandID paste = 0x1005;
  24615. /** The command ID that should be used to send a "Select all" command. */
  24616. static const CommandID selectAll = 0x1006;
  24617. /** The command ID that should be used to send a "Deselect all" command. */
  24618. static const CommandID deselectAll = 0x1007;
  24619. }
  24620. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  24621. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  24622. /**
  24623. Holds information describing an application command.
  24624. This object is used to pass information about a particular command, such as its
  24625. name, description and other usage flags.
  24626. When an ApplicationCommandTarget is asked to provide information about the commands
  24627. it can perform, this is the structure gets filled-in to describe each one.
  24628. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  24629. ApplicationCommandManager
  24630. */
  24631. struct JUCE_API ApplicationCommandInfo
  24632. {
  24633. explicit ApplicationCommandInfo (CommandID commandID) throw();
  24634. /** Sets a number of the structures values at once.
  24635. The meanings of each of the parameters is described below, in the appropriate
  24636. member variable's description.
  24637. */
  24638. void setInfo (const String& shortName,
  24639. const String& description,
  24640. const String& categoryName,
  24641. int flags) throw();
  24642. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  24643. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  24644. is false, the bit is set.
  24645. */
  24646. void setActive (bool isActive) throw();
  24647. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  24648. */
  24649. void setTicked (bool isTicked) throw();
  24650. /** Handy method for adding a keypress to the defaultKeypresses array.
  24651. This is just so you can write things like:
  24652. @code
  24653. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  24654. @endcode
  24655. instead of
  24656. @code
  24657. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  24658. @endcode
  24659. */
  24660. void addDefaultKeypress (int keyCode,
  24661. const ModifierKeys& modifiers) throw();
  24662. /** The command's unique ID number.
  24663. */
  24664. CommandID commandID;
  24665. /** A short name to describe the command.
  24666. This should be suitable for use in menus, on buttons that trigger the command, etc.
  24667. You can use the setInfo() method to quickly set this and some of the command's
  24668. other properties.
  24669. */
  24670. String shortName;
  24671. /** A longer description of the command.
  24672. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  24673. pop-up tooltip describing what the command does.
  24674. You can use the setInfo() method to quickly set this and some of the command's
  24675. other properties.
  24676. */
  24677. String description;
  24678. /** A named category that the command fits into.
  24679. You can give your commands any category you like, and these will be displayed in
  24680. contexts such as the KeyMappingEditorComponent, where the category is used to group
  24681. commands together.
  24682. You can use the setInfo() method to quickly set this and some of the command's
  24683. other properties.
  24684. */
  24685. String categoryName;
  24686. /** A list of zero or more keypresses that should be used as the default keys for
  24687. this command.
  24688. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  24689. this list to initialise the default set of key-to-command mappings.
  24690. @see addDefaultKeypress
  24691. */
  24692. Array <KeyPress> defaultKeypresses;
  24693. /** Flags describing the ways in which this command should be used.
  24694. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  24695. variable.
  24696. */
  24697. enum CommandFlags
  24698. {
  24699. /** Indicates that the command can't currently be performed.
  24700. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  24701. not currently permissable to perform the command. If the flag is set, then
  24702. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  24703. command or show themselves as not being enabled.
  24704. @see ApplicationCommandInfo::setActive
  24705. */
  24706. isDisabled = 1 << 0,
  24707. /** Indicates that the command should have a tick next to it on a menu.
  24708. If your command is shown on a menu and this is set, it'll show a tick next to
  24709. it. Other components such as buttons may also use this flag to indicate that it
  24710. is a value that can be toggled, and is currently in the 'on' state.
  24711. @see ApplicationCommandInfo::setTicked
  24712. */
  24713. isTicked = 1 << 1,
  24714. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  24715. it will call the command twice, once on key-down and again on key-up.
  24716. @see ApplicationCommandTarget::InvocationInfo
  24717. */
  24718. wantsKeyUpDownCallbacks = 1 << 2,
  24719. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  24720. command in its list.
  24721. */
  24722. hiddenFromKeyEditor = 1 << 3,
  24723. /** If this flag is present, then a KeyMappingEditorComponent will display the
  24724. command in its list, but won't allow the assigned keypress to be changed.
  24725. */
  24726. readOnlyInKeyEditor = 1 << 4,
  24727. /** If this flag is present and the command is invoked from a keypress, then any
  24728. buttons or menus that are also connected to the command will not flash to
  24729. indicate that they've been triggered.
  24730. */
  24731. dontTriggerVisualFeedback = 1 << 5
  24732. };
  24733. /** A bitwise-OR of the values specified in the CommandFlags enum.
  24734. You can use the setInfo() method to quickly set this and some of the command's
  24735. other properties.
  24736. */
  24737. int flags;
  24738. };
  24739. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  24740. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  24741. /*** Start of inlined file: juce_MessageListener.h ***/
  24742. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  24743. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  24744. /**
  24745. MessageListener subclasses can post and receive Message objects.
  24746. @see Message, MessageManager, ActionListener, ChangeListener
  24747. */
  24748. class JUCE_API MessageListener
  24749. {
  24750. protected:
  24751. /** Creates a MessageListener. */
  24752. MessageListener() throw();
  24753. public:
  24754. /** Destructor.
  24755. When a MessageListener is deleted, it removes itself from a global list
  24756. of registered listeners, so that the isValidMessageListener() method
  24757. will no longer return true.
  24758. */
  24759. virtual ~MessageListener();
  24760. /** This is the callback method that receives incoming messages.
  24761. This is called by the MessageManager from its dispatch loop.
  24762. @see postMessage
  24763. */
  24764. virtual void handleMessage (const Message& message) = 0;
  24765. /** Sends a message to the message queue, for asynchronous delivery to this listener
  24766. later on.
  24767. This method can be called safely by any thread.
  24768. @param message the message object to send - this will be deleted
  24769. automatically by the message queue, so don't keep any
  24770. references to it after calling this method.
  24771. @see handleMessage
  24772. */
  24773. void postMessage (Message* message) const throw();
  24774. /** Checks whether this MessageListener has been deleted.
  24775. Although not foolproof, this method is safe to call on dangling or null
  24776. pointers. A list of active MessageListeners is kept internally, so this
  24777. checks whether the object is on this list or not.
  24778. Note that it's possible to get a false-positive here, if an object is
  24779. deleted and another is subsequently created that happens to be at the
  24780. exact same memory location, but I can't think of a good way of avoiding
  24781. this.
  24782. */
  24783. bool isValidMessageListener() const throw();
  24784. };
  24785. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  24786. /*** End of inlined file: juce_MessageListener.h ***/
  24787. /**
  24788. A command target publishes a list of command IDs that it can perform.
  24789. An ApplicationCommandManager despatches commands to targets, which must be
  24790. able to provide information about what commands they can handle.
  24791. To create a target, you'll need to inherit from this class, implementing all of
  24792. its pure virtual methods.
  24793. For info about how a target is chosen to receive a command, see
  24794. ApplicationCommandManager::getFirstCommandTarget().
  24795. @see ApplicationCommandManager, ApplicationCommandInfo
  24796. */
  24797. class JUCE_API ApplicationCommandTarget
  24798. {
  24799. public:
  24800. /** Creates a command target. */
  24801. ApplicationCommandTarget();
  24802. /** Destructor. */
  24803. virtual ~ApplicationCommandTarget();
  24804. /**
  24805. */
  24806. struct JUCE_API InvocationInfo
  24807. {
  24808. InvocationInfo (const CommandID commandID);
  24809. /** The UID of the command that should be performed. */
  24810. CommandID commandID;
  24811. /** The command's flags.
  24812. See ApplicationCommandInfo for a description of these flag values.
  24813. */
  24814. int commandFlags;
  24815. /** The types of context in which the command might be called. */
  24816. enum InvocationMethod
  24817. {
  24818. direct = 0, /**< The command is being invoked directly by a piece of code. */
  24819. fromKeyPress, /**< The command is being invoked by a key-press. */
  24820. fromMenu, /**< The command is being invoked by a menu selection. */
  24821. fromButton /**< The command is being invoked by a button click. */
  24822. };
  24823. /** The type of event that triggered this command. */
  24824. InvocationMethod invocationMethod;
  24825. /** If triggered by a keypress or menu, this will be the component that had the
  24826. keyboard focus at the time.
  24827. If triggered by a button, it may be set to that component, or it may be null.
  24828. */
  24829. Component* originatingComponent;
  24830. /** The keypress that was used to invoke it.
  24831. Note that this will be an invalid keypress if the command was invoked
  24832. by some other means than a keyboard shortcut.
  24833. */
  24834. KeyPress keyPress;
  24835. /** True if the callback is being invoked when the key is pressed,
  24836. false if the key is being released.
  24837. @see KeyPressMappingSet::addCommand()
  24838. */
  24839. bool isKeyDown;
  24840. /** If the key is being released, this indicates how long it had been held
  24841. down for.
  24842. (Only relevant if isKeyDown is false.)
  24843. */
  24844. int millisecsSinceKeyPressed;
  24845. };
  24846. /** This must return the next target to try after this one.
  24847. When a command is being sent, and the first target can't handle
  24848. that command, this method is used to determine the next target that should
  24849. be tried.
  24850. It may return 0 if it doesn't know of another target.
  24851. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  24852. method to return a parent component that might want to handle it.
  24853. @see invoke
  24854. */
  24855. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  24856. /** This must return a complete list of commands that this target can handle.
  24857. Your target should add all the command IDs that it handles to the array that is
  24858. passed-in.
  24859. */
  24860. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  24861. /** This must provide details about one of the commands that this target can perform.
  24862. This will be called with one of the command IDs that the target provided in its
  24863. getAllCommands() methods.
  24864. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  24865. suitable information about the command. (The commandID field will already have been filled-in
  24866. by the caller).
  24867. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  24868. set all the fields at once.
  24869. If the command is currently inactive for some reason, this method must use
  24870. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  24871. bit of the ApplicationCommandInfo::flags field).
  24872. Any default key-presses for the command should be appended to the
  24873. ApplicationCommandInfo::defaultKeypresses field.
  24874. Note that if you change something that affects the status of the commands
  24875. that would be returned by this method (e.g. something that makes some commands
  24876. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  24877. to cause the manager to refresh its status.
  24878. */
  24879. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  24880. /** This must actually perform the specified command.
  24881. If this target is able to perform the command specified by the commandID field of the
  24882. InvocationInfo structure, then it should do so, and must return true.
  24883. If it can't handle this command, it should return false, which tells the caller to pass
  24884. the command on to the next target in line.
  24885. @see invoke, ApplicationCommandManager::invoke
  24886. */
  24887. virtual bool perform (const InvocationInfo& info) = 0;
  24888. /** Makes this target invoke a command.
  24889. Your code can call this method to invoke a command on this target, but normally
  24890. you'd call it indirectly via ApplicationCommandManager::invoke() or
  24891. ApplicationCommandManager::invokeDirectly().
  24892. If this target can perform the given command, it will call its perform() method to
  24893. do so. If not, then getNextCommandTarget() will be used to determine the next target
  24894. to try, and the command will be passed along to it.
  24895. @param invocationInfo this must be correctly filled-in, describing the context for
  24896. the invocation.
  24897. @param asynchronously if false, the command will be performed before this method returns.
  24898. If true, a message will be posted so that the command will be performed
  24899. later on the message thread, and this method will return immediately.
  24900. @see perform, ApplicationCommandManager::invoke
  24901. */
  24902. bool invoke (const InvocationInfo& invocationInfo,
  24903. const bool asynchronously);
  24904. /** Invokes a given command directly on this target.
  24905. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  24906. structure.
  24907. */
  24908. bool invokeDirectly (const CommandID commandID,
  24909. const bool asynchronously);
  24910. /** Searches this target and all subsequent ones for the first one that can handle
  24911. the specified command.
  24912. This will use getNextCommandTarget() to determine the chain of targets to try
  24913. after this one.
  24914. */
  24915. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  24916. /** Checks whether this command can currently be performed by this target.
  24917. This will return true only if a call to getCommandInfo() doesn't set the
  24918. isDisabled flag to indicate that the command is inactive.
  24919. */
  24920. bool isCommandActive (const CommandID commandID);
  24921. /** If this object is a Component, this method will seach upwards in its current
  24922. UI hierarchy for the next parent component that implements the
  24923. ApplicationCommandTarget class.
  24924. If your target is a Component, this is a very handy method to use in your
  24925. getNextCommandTarget() implementation.
  24926. */
  24927. ApplicationCommandTarget* findFirstTargetParentComponent();
  24928. private:
  24929. // (for async invocation of commands)
  24930. class CommandTargetMessageInvoker : public MessageListener
  24931. {
  24932. public:
  24933. CommandTargetMessageInvoker (ApplicationCommandTarget* owner);
  24934. ~CommandTargetMessageInvoker();
  24935. void handleMessage (const Message& message);
  24936. private:
  24937. ApplicationCommandTarget* const owner;
  24938. JUCE_DECLARE_NON_COPYABLE (CommandTargetMessageInvoker);
  24939. };
  24940. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  24941. friend class CommandTargetMessageInvoker;
  24942. bool tryToInvoke (const InvocationInfo& info, bool async);
  24943. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandTarget);
  24944. };
  24945. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  24946. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  24947. /*** Start of inlined file: juce_ActionListener.h ***/
  24948. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  24949. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  24950. /**
  24951. Receives callbacks to indicate that some kind of event has occurred.
  24952. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  24953. about something that's happened.
  24954. @see ActionBroadcaster, ChangeListener
  24955. */
  24956. class JUCE_API ActionListener
  24957. {
  24958. public:
  24959. /** Destructor. */
  24960. virtual ~ActionListener() {}
  24961. /** Overridden by your subclass to receive the callback.
  24962. @param message the string that was specified when the event was triggered
  24963. by a call to ActionBroadcaster::sendActionMessage()
  24964. */
  24965. virtual void actionListenerCallback (const String& message) = 0;
  24966. };
  24967. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  24968. /*** End of inlined file: juce_ActionListener.h ***/
  24969. /**
  24970. An instance of this class is used to specify initialisation and shutdown
  24971. code for the application.
  24972. An application that wants to run in the JUCE framework needs to declare a
  24973. subclass of JUCEApplication and implement its various pure virtual methods.
  24974. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  24975. to declare an instance of this class and generate a suitable platform-specific
  24976. main() function.
  24977. e.g. @code
  24978. class MyJUCEApp : public JUCEApplication
  24979. {
  24980. public:
  24981. MyJUCEApp()
  24982. {
  24983. }
  24984. ~MyJUCEApp()
  24985. {
  24986. }
  24987. void initialise (const String& commandLine)
  24988. {
  24989. myMainWindow = new MyApplicationWindow();
  24990. myMainWindow->setBounds (100, 100, 400, 500);
  24991. myMainWindow->setVisible (true);
  24992. }
  24993. void shutdown()
  24994. {
  24995. myMainWindow = 0;
  24996. }
  24997. const String getApplicationName()
  24998. {
  24999. return "Super JUCE-o-matic";
  25000. }
  25001. const String getApplicationVersion()
  25002. {
  25003. return "1.0";
  25004. }
  25005. private:
  25006. ScopedPointer <MyApplicationWindow> myMainWindow;
  25007. };
  25008. // this creates wrapper code to actually launch the app properly.
  25009. START_JUCE_APPLICATION (MyJUCEApp)
  25010. @endcode
  25011. @see MessageManager, DeletedAtShutdown
  25012. */
  25013. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  25014. private ActionListener
  25015. {
  25016. protected:
  25017. /** Constructs a JUCE app object.
  25018. If subclasses implement a constructor or destructor, they shouldn't call any
  25019. JUCE code in there - put your startup/shutdown code in initialise() and
  25020. shutdown() instead.
  25021. */
  25022. JUCEApplication();
  25023. public:
  25024. /** Destructor.
  25025. If subclasses implement a constructor or destructor, they shouldn't call any
  25026. JUCE code in there - put your startup/shutdown code in initialise() and
  25027. shutdown() instead.
  25028. */
  25029. virtual ~JUCEApplication();
  25030. /** Returns the global instance of the application object being run. */
  25031. static JUCEApplication* getInstance() throw() { return appInstance; }
  25032. /** Called when the application starts.
  25033. This will be called once to let the application do whatever initialisation
  25034. it needs, create its windows, etc.
  25035. After the method returns, the normal event-dispatch loop will be run,
  25036. until the quit() method is called, at which point the shutdown()
  25037. method will be called to let the application clear up anything it needs
  25038. to delete.
  25039. If during the initialise() method, the application decides not to start-up
  25040. after all, it can just call the quit() method and the event loop won't be run.
  25041. @param commandLineParameters the line passed in does not include the
  25042. name of the executable, just the parameter list.
  25043. @see shutdown, quit
  25044. */
  25045. virtual void initialise (const String& commandLineParameters) = 0;
  25046. /** Returns true if the application hasn't yet completed its initialise() method
  25047. and entered the main event loop.
  25048. This is handy for things like splash screens to know when the app's up-and-running
  25049. properly.
  25050. */
  25051. bool isInitialising() const throw() { return stillInitialising; }
  25052. /* Called to allow the application to clear up before exiting.
  25053. After JUCEApplication::quit() has been called, the event-dispatch loop will
  25054. terminate, and this method will get called to allow the app to sort itself
  25055. out.
  25056. Be careful that nothing happens in this method that might rely on messages
  25057. being sent, or any kind of window activity, because the message loop is no
  25058. longer running at this point.
  25059. @see DeletedAtShutdown
  25060. */
  25061. virtual void shutdown() = 0;
  25062. /** Returns the application's name.
  25063. An application must implement this to name itself.
  25064. */
  25065. virtual const String getApplicationName() = 0;
  25066. /** Returns the application's version number.
  25067. */
  25068. virtual const String getApplicationVersion() = 0;
  25069. /** Checks whether multiple instances of the app are allowed.
  25070. If you application class returns true for this, more than one instance is
  25071. permitted to run (except on the Mac where this isn't possible).
  25072. If it's false, the second instance won't start, but it you will still get a
  25073. callback to anotherInstanceStarted() to tell you about this - which
  25074. gives you a chance to react to what the user was trying to do.
  25075. */
  25076. virtual bool moreThanOneInstanceAllowed();
  25077. /** Indicates that the user has tried to start up another instance of the app.
  25078. This will get called even if moreThanOneInstanceAllowed() is false.
  25079. */
  25080. virtual void anotherInstanceStarted (const String& commandLine);
  25081. /** Called when the operating system is trying to close the application.
  25082. The default implementation of this method is to call quit(), but it may
  25083. be overloaded to ignore the request or do some other special behaviour
  25084. instead. For example, you might want to offer the user the chance to save
  25085. their changes before quitting, and give them the chance to cancel.
  25086. If you want to send a quit signal to your app, this is the correct method
  25087. to call, because it means that requests that come from the system get handled
  25088. in the same way as those from your own application code. So e.g. you'd
  25089. call this method from a "quit" item on a menu bar.
  25090. */
  25091. virtual void systemRequestedQuit();
  25092. /** If any unhandled exceptions make it through to the message dispatch loop, this
  25093. callback will be triggered, in case you want to log them or do some other
  25094. type of error-handling.
  25095. If the type of exception is derived from the std::exception class, the pointer
  25096. passed-in will be valid. If the exception is of unknown type, this pointer
  25097. will be null.
  25098. */
  25099. virtual void unhandledException (const std::exception* e,
  25100. const String& sourceFilename,
  25101. int lineNumber);
  25102. /** Signals that the main message loop should stop and the application should terminate.
  25103. This isn't synchronous, it just posts a quit message to the main queue, and
  25104. when this message arrives, the message loop will stop, the shutdown() method
  25105. will be called, and the app will exit.
  25106. Note that this will cause an unconditional quit to happen, so if you need an
  25107. extra level before this, e.g. to give the user the chance to save their work
  25108. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  25109. method - see that method's help for more info.
  25110. @see MessageManager, DeletedAtShutdown
  25111. */
  25112. static void quit();
  25113. /** Sets the value that should be returned as the application's exit code when the
  25114. app quits.
  25115. This is the value that's returned by the main() function. Normally you'd leave this
  25116. as 0 unless you want to indicate an error code.
  25117. @see getApplicationReturnValue
  25118. */
  25119. void setApplicationReturnValue (int newReturnValue) throw();
  25120. /** Returns the value that has been set as the application's exit code.
  25121. @see setApplicationReturnValue
  25122. */
  25123. int getApplicationReturnValue() const throw() { return appReturnValue; }
  25124. /** Returns the application's command line params.
  25125. */
  25126. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  25127. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  25128. /** @internal */
  25129. static int main (const String& commandLine);
  25130. /** @internal */
  25131. static int main (int argc, const char* argv[]);
  25132. /** @internal */
  25133. static void sendUnhandledException (const std::exception* e, const char* sourceFile, int lineNumber);
  25134. /** Returns true if this executable is running as an app (as opposed to being a plugin
  25135. or other kind of shared library. */
  25136. static inline bool isStandaloneApp() throw() { return createInstance != 0; }
  25137. /** @internal */
  25138. ApplicationCommandTarget* getNextCommandTarget();
  25139. /** @internal */
  25140. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  25141. /** @internal */
  25142. void getAllCommands (Array <CommandID>& commands);
  25143. /** @internal */
  25144. bool perform (const InvocationInfo& info);
  25145. /** @internal */
  25146. void actionListenerCallback (const String& message);
  25147. /** @internal */
  25148. bool initialiseApp (const String& commandLine);
  25149. /** @internal */
  25150. int shutdownApp();
  25151. /** @internal */
  25152. static void appWillTerminateByForce();
  25153. /** @internal */
  25154. typedef JUCEApplication* (*CreateInstanceFunction)();
  25155. /** @internal */
  25156. static CreateInstanceFunction createInstance;
  25157. private:
  25158. String commandLineParameters;
  25159. int appReturnValue;
  25160. bool stillInitialising;
  25161. ScopedPointer<InterProcessLock> appLock;
  25162. static JUCEApplication* appInstance;
  25163. JUCE_DECLARE_NON_COPYABLE (JUCEApplication);
  25164. };
  25165. #endif // __JUCE_APPLICATION_JUCEHEADER__
  25166. /*** End of inlined file: juce_Application.h ***/
  25167. #endif
  25168. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25169. #endif
  25170. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25171. #endif
  25172. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25173. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  25174. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25175. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25176. /*** Start of inlined file: juce_Desktop.h ***/
  25177. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  25178. #define __JUCE_DESKTOP_JUCEHEADER__
  25179. /*** Start of inlined file: juce_Timer.h ***/
  25180. #ifndef __JUCE_TIMER_JUCEHEADER__
  25181. #define __JUCE_TIMER_JUCEHEADER__
  25182. class InternalTimerThread;
  25183. /**
  25184. Makes repeated callbacks to a virtual method at a specified time interval.
  25185. A Timer's timerCallback() method will be repeatedly called at a given
  25186. interval. When you create a Timer object, it will do nothing until the
  25187. startTimer() method is called, which will cause the message thread to
  25188. start making callbacks at the specified interval, until stopTimer() is called
  25189. or the object is deleted.
  25190. The time interval isn't guaranteed to be precise to any more than maybe
  25191. 10-20ms, and the intervals may end up being much longer than requested if the
  25192. system is busy. Because the callbacks are made by the main message thread,
  25193. anything that blocks the message queue for a period of time will also prevent
  25194. any timers from running until it can carry on.
  25195. If you need to have a single callback that is shared by multiple timers with
  25196. different frequencies, then the MultiTimer class allows you to do that - its
  25197. structure is very similar to the Timer class, but contains multiple timers
  25198. internally, each one identified by an ID number.
  25199. @see MultiTimer
  25200. */
  25201. class JUCE_API Timer
  25202. {
  25203. protected:
  25204. /** Creates a Timer.
  25205. When created, the timer is stopped, so use startTimer() to get it going.
  25206. */
  25207. Timer() throw();
  25208. /** Creates a copy of another timer.
  25209. Note that this timer won't be started, even if the one you're copying
  25210. is running.
  25211. */
  25212. Timer (const Timer& other) throw();
  25213. public:
  25214. /** Destructor. */
  25215. virtual ~Timer();
  25216. /** The user-defined callback routine that actually gets called periodically.
  25217. It's perfectly ok to call startTimer() or stopTimer() from within this
  25218. callback to change the subsequent intervals.
  25219. */
  25220. virtual void timerCallback() = 0;
  25221. /** Starts the timer and sets the length of interval required.
  25222. If the timer is already started, this will reset it, so the
  25223. time between calling this method and the next timer callback
  25224. will not be less than the interval length passed in.
  25225. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  25226. rounded up to 1)
  25227. */
  25228. void startTimer (int intervalInMilliseconds) throw();
  25229. /** Stops the timer.
  25230. No more callbacks will be made after this method returns.
  25231. If this is called from a different thread, any callbacks that may
  25232. be currently executing may be allowed to finish before the method
  25233. returns.
  25234. */
  25235. void stopTimer() throw();
  25236. /** Checks if the timer has been started.
  25237. @returns true if the timer is running.
  25238. */
  25239. bool isTimerRunning() const throw() { return periodMs > 0; }
  25240. /** Returns the timer's interval.
  25241. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  25242. */
  25243. int getTimerInterval() const throw() { return periodMs; }
  25244. private:
  25245. friend class InternalTimerThread;
  25246. int countdownMs, periodMs;
  25247. Timer* previous;
  25248. Timer* next;
  25249. Timer& operator= (const Timer&);
  25250. };
  25251. #endif // __JUCE_TIMER_JUCEHEADER__
  25252. /*** End of inlined file: juce_Timer.h ***/
  25253. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  25254. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25255. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25256. /**
  25257. Animates a set of components, moving them to a new position and/or fading their
  25258. alpha levels.
  25259. To animate a component, create a ComponentAnimator instance or (preferably) use the
  25260. global animator object provided by Desktop::getAnimator(), and call its animateComponent()
  25261. method to commence the movement.
  25262. If you're using your own ComponentAnimator instance, you'll need to make sure it isn't
  25263. deleted before it finishes moving the components, or they'll be abandoned before reaching their
  25264. destinations.
  25265. It's ok to delete components while they're being animated - the animator will detect this
  25266. and safely stop using them.
  25267. The class is a ChangeBroadcaster and sends a notification when any components
  25268. start or finish being animated.
  25269. @see Desktop::getAnimator
  25270. */
  25271. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  25272. private Timer
  25273. {
  25274. public:
  25275. /** Creates a ComponentAnimator. */
  25276. ComponentAnimator();
  25277. /** Destructor. */
  25278. ~ComponentAnimator();
  25279. /** Starts a component moving from its current position to a specified position.
  25280. If the component is already in the middle of an animation, that will be abandoned,
  25281. and a new animation will begin, moving the component from its current location.
  25282. The start and end speed parameters let you apply some acceleration to the component's
  25283. movement.
  25284. @param component the component to move
  25285. @param finalBounds the destination bounds to which the component should move. To leave the
  25286. component in the same place, just pass component->getBounds() for this value
  25287. @param finalAlpha the alpha value that the component should have at the end of the animation
  25288. @param animationDurationMilliseconds how long the animation should last, in milliseconds
  25289. @param useProxyComponent if true, this means the component should be replaced by an internally
  25290. managed temporary component which is a snapshot of the original component.
  25291. This avoids the component having to paint itself as it moves, so may
  25292. be more efficient. This option also allows you to delete the original
  25293. component immediately after starting the animation, because the animation
  25294. can proceed without it. If you use a proxy, the original component will be
  25295. made invisible by this call, and then will become visible again at the end
  25296. of the animation. It'll also mean that the proxy component will be temporarily
  25297. added to the component's parent, so avoid it if this might confuse the parent
  25298. component, or if there's a chance the parent might decide to delete its children.
  25299. @param startSpeed a value to indicate the relative start speed of the animation. If this is 0,
  25300. the component will start by accelerating from rest; higher values mean that it
  25301. will have an initial speed greater than zero. If the value if greater than 1, it
  25302. will decelerate towards the middle of its journey. To move the component at a
  25303. constant rate for its entire animation, set both the start and end speeds to 1.0
  25304. @param endSpeed a relative speed at which the component should be moving when the animation finishes.
  25305. If this is 0, the component will decelerate to a standstill at its final position;
  25306. higher values mean the component will still be moving when it stops. To move the component
  25307. at a constant rate for its entire animation, set both the start and end speeds to 1.0
  25308. */
  25309. void animateComponent (Component* component,
  25310. const Rectangle<int>& finalBounds,
  25311. float finalAlpha,
  25312. int animationDurationMilliseconds,
  25313. bool useProxyComponent,
  25314. double startSpeed,
  25315. double endSpeed);
  25316. /** Begins a fade-out of this components alpha level.
  25317. This is a quick way of invoking animateComponent() with a target alpha value of 0.0f, using
  25318. a proxy. You're safe to delete the component after calling this method, and this won't
  25319. interfere with the animation's progress.
  25320. */
  25321. void fadeOut (Component* component, int millisecondsToTake);
  25322. /** Begins a fade-in of a component.
  25323. This is a quick way of invoking animateComponent() with a target alpha value of 1.0f.
  25324. */
  25325. void fadeIn (Component* component, int millisecondsToTake);
  25326. /** Stops a component if it's currently being animated.
  25327. If moveComponentToItsFinalPosition is true, then the component will
  25328. be immediately moved to its destination position and size. If false, it will be
  25329. left in whatever location it currently occupies.
  25330. */
  25331. void cancelAnimation (Component* component,
  25332. bool moveComponentToItsFinalPosition);
  25333. /** Clears all of the active animations.
  25334. If moveComponentsToTheirFinalPositions is true, all the components will
  25335. be immediately set to their final positions. If false, they will be
  25336. left in whatever locations they currently occupy.
  25337. */
  25338. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  25339. /** Returns the destination position for a component.
  25340. If the component is being animated, this will return the target position that
  25341. was specified when animateComponent() was called.
  25342. If the specified component isn't currently being animated, this method will just
  25343. return its current position.
  25344. */
  25345. const Rectangle<int> getComponentDestination (Component* component);
  25346. /** Returns true if the specified component is currently being animated. */
  25347. bool isAnimating (Component* component) const;
  25348. private:
  25349. class AnimationTask;
  25350. OwnedArray <AnimationTask> tasks;
  25351. uint32 lastTime;
  25352. AnimationTask* findTaskFor (Component* component) const;
  25353. void timerCallback();
  25354. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentAnimator);
  25355. };
  25356. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25357. /*** End of inlined file: juce_ComponentAnimator.h ***/
  25358. class MouseInputSource;
  25359. class MouseInputSourceInternal;
  25360. class MouseListener;
  25361. /**
  25362. Classes can implement this interface and register themselves with the Desktop class
  25363. to receive callbacks when the currently focused component changes.
  25364. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  25365. */
  25366. class JUCE_API FocusChangeListener
  25367. {
  25368. public:
  25369. /** Destructor. */
  25370. virtual ~FocusChangeListener() {}
  25371. /** Callback to indicate that the currently focused component has changed. */
  25372. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  25373. };
  25374. /**
  25375. Describes and controls aspects of the computer's desktop.
  25376. */
  25377. class JUCE_API Desktop : private DeletedAtShutdown,
  25378. private Timer,
  25379. private AsyncUpdater
  25380. {
  25381. public:
  25382. /** There's only one dektop object, and this method will return it.
  25383. */
  25384. static Desktop& JUCE_CALLTYPE getInstance();
  25385. /** Returns a list of the positions of all the monitors available.
  25386. The first rectangle in the list will be the main monitor area.
  25387. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  25388. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  25389. */
  25390. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const throw();
  25391. /** Returns the position and size of the main monitor.
  25392. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  25393. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  25394. */
  25395. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const throw();
  25396. /** Returns the position and size of the monitor which contains this co-ordinate.
  25397. If none of the monitors contains the point, this will just return the
  25398. main monitor.
  25399. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  25400. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  25401. */
  25402. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  25403. /** Returns the mouse position.
  25404. The co-ordinates are relative to the top-left of the main monitor.
  25405. Note that this is just a shortcut for calling getMainMouseSource().getScreenPosition(), and
  25406. you should only resort to grabbing the global mouse position if there's really no
  25407. way to get the coordinates via a mouse event callback instead.
  25408. */
  25409. static const Point<int> getMousePosition();
  25410. /** Makes the mouse pointer jump to a given location.
  25411. The co-ordinates are relative to the top-left of the main monitor.
  25412. */
  25413. static void setMousePosition (const Point<int>& newPosition);
  25414. /** Returns the last position at which a mouse button was pressed.
  25415. Note that this is just a shortcut for calling getMainMouseSource().getLastMouseDownPosition(),
  25416. and in a multi-touch environment, it doesn't make much sense. ALWAYS prefer to
  25417. get this information via other means, such as MouseEvent::getMouseDownScreenPosition()
  25418. if possible, and only ever call this as a last resort.
  25419. */
  25420. static const Point<int> getLastMouseDownPosition();
  25421. /** Returns the number of times the mouse button has been clicked since the
  25422. app started.
  25423. Each mouse-down event increments this number by 1.
  25424. */
  25425. static int getMouseButtonClickCounter();
  25426. /** This lets you prevent the screensaver from becoming active.
  25427. Handy if you're running some sort of presentation app where having a screensaver
  25428. appear would be annoying.
  25429. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  25430. won't enable a screensaver unless the user has actually set one up).
  25431. The disablement will only happen while the Juce application is the foreground
  25432. process - if another task is running in front of it, then the screensaver will
  25433. be unaffected.
  25434. @see isScreenSaverEnabled
  25435. */
  25436. static void setScreenSaverEnabled (bool isEnabled);
  25437. /** Returns true if the screensaver has not been turned off.
  25438. This will return the last value passed into setScreenSaverEnabled(). Note that
  25439. it won't tell you whether the user is actually using a screen saver, just
  25440. whether this app is deliberately preventing one from running.
  25441. @see setScreenSaverEnabled
  25442. */
  25443. static bool isScreenSaverEnabled();
  25444. /** Registers a MouseListener that will receive all mouse events that occur on
  25445. any component.
  25446. @see removeGlobalMouseListener
  25447. */
  25448. void addGlobalMouseListener (MouseListener* listener);
  25449. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  25450. method.
  25451. @see addGlobalMouseListener
  25452. */
  25453. void removeGlobalMouseListener (MouseListener* listener);
  25454. /** Registers a MouseListener that will receive a callback whenever the focused
  25455. component changes.
  25456. */
  25457. void addFocusChangeListener (FocusChangeListener* listener);
  25458. /** Unregisters a listener that was added with addFocusChangeListener(). */
  25459. void removeFocusChangeListener (FocusChangeListener* listener);
  25460. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  25461. The component must already be on the desktop for this method to work. It will
  25462. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  25463. etc will be hidden.
  25464. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  25465. the component that's currently being used will be resized back to the size
  25466. and position it was in before being put into this mode.
  25467. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  25468. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  25469. to hide as much on-screen paraphenalia as possible.
  25470. */
  25471. void setKioskModeComponent (Component* componentToUse,
  25472. bool allowMenusAndBars = true);
  25473. /** Returns the component that is currently being used in kiosk-mode.
  25474. This is the component that was last set by setKioskModeComponent(). If none
  25475. has been set, this returns 0.
  25476. */
  25477. Component* getKioskModeComponent() const throw() { return kioskModeComponent; }
  25478. /** Returns the number of components that are currently active as top-level
  25479. desktop windows.
  25480. @see getComponent, Component::addToDesktop
  25481. */
  25482. int getNumComponents() const throw();
  25483. /** Returns one of the top-level desktop window components.
  25484. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  25485. index is out-of-range.
  25486. @see getNumComponents, Component::addToDesktop
  25487. */
  25488. Component* getComponent (int index) const throw();
  25489. /** Finds the component at a given screen location.
  25490. This will drill down into top-level windows to find the child component at
  25491. the given position.
  25492. Returns 0 if the co-ordinates are inside a non-Juce window.
  25493. */
  25494. Component* findComponentAt (const Point<int>& screenPosition) const;
  25495. /** The Desktop object has a ComponentAnimator instance which can be used for performing
  25496. your animations.
  25497. Having a single shared ComponentAnimator object makes it more efficient when multiple
  25498. components are being moved around simultaneously. It's also more convenient than having
  25499. to manage your own instance of one.
  25500. @see ComponentAnimator
  25501. */
  25502. ComponentAnimator& getAnimator() throw() { return animator; }
  25503. /** Returns the number of MouseInputSource objects the system has at its disposal.
  25504. In a traditional single-mouse system, there might be only one object. On a multi-touch
  25505. system, there could be one input source per potential finger.
  25506. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  25507. @see getMouseSource
  25508. */
  25509. int getNumMouseSources() const throw() { return mouseSources.size(); }
  25510. /** Returns one of the system's MouseInputSource objects.
  25511. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  25512. a null pointer.
  25513. In a traditional single-mouse system, there might be only one object. On a multi-touch
  25514. system, there could be one input source per potential finger.
  25515. */
  25516. MouseInputSource* getMouseSource (int index) const throw() { return mouseSources [index]; }
  25517. /** Returns the main mouse input device that the system is using.
  25518. @see getNumMouseSources()
  25519. */
  25520. MouseInputSource& getMainMouseSource() const throw() { return *mouseSources.getUnchecked(0); }
  25521. /** Returns the number of mouse-sources that are currently being dragged.
  25522. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  25523. juce component has the button down on it. In a multi-touch system, this could
  25524. be any number from 0 to the number of simultaneous touches that can be detected.
  25525. */
  25526. int getNumDraggingMouseSources() const throw();
  25527. /** Returns one of the mouse sources that's currently being dragged.
  25528. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  25529. out of range, or if no mice or fingers are down, this will return a null pointer.
  25530. */
  25531. MouseInputSource* getDraggingMouseSource (int index) const throw();
  25532. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  25533. current mouse-drag operation.
  25534. This allows you to make sure that mouseDrag() events are sent continuously, even
  25535. when the mouse isn't moving. This can be useful for things like auto-scrolling
  25536. components when the mouse is near an edge.
  25537. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  25538. minimum interval between consecutive mouse drag callbacks. The callbacks
  25539. will continue until the mouse is released, and then the interval will be reset,
  25540. so you need to make sure it's called every time you begin a drag event.
  25541. Passing an interval of 0 or less will cancel the auto-repeat.
  25542. @see mouseDrag
  25543. */
  25544. void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  25545. /** In a tablet device which can be turned around, this is used to inidicate the orientation. */
  25546. enum DisplayOrientation
  25547. {
  25548. upright = 1, /**< Indicates that the display is the normal way up. */
  25549. upsideDown = 2, /**< Indicates that the display is upside-down. */
  25550. rotatedClockwise = 4, /**< Indicates that the display is turned 90 degrees clockwise from its upright position. */
  25551. rotatedAntiClockwise = 8, /**< Indicates that the display is turned 90 degrees anti-clockwise from its upright position. */
  25552. allOrientations = 1 + 2 + 4 + 8 /**< A combination of all the orientation values */
  25553. };
  25554. /** In a tablet device which can be turned around, this returns the current orientation. */
  25555. DisplayOrientation getCurrentOrientation() const;
  25556. /** Sets which orientations the display is allowed to auto-rotate to.
  25557. For devices that support rotating desktops, this lets you specify which of the orientations your app can use.
  25558. The parameter is a bitwise or-ed combination of the values in DisplayOrientation, and must contain at least one
  25559. set bit.
  25560. */
  25561. void setOrientationsEnabled (int allowedOrientations);
  25562. /** Returns whether the display is allowed to auto-rotate to the given orientation.
  25563. Each orientation can be enabled using setOrientationEnabled(). By default, all orientations are allowed.
  25564. */
  25565. bool isOrientationEnabled (DisplayOrientation orientation) const throw();
  25566. /** Tells this object to refresh its idea of what the screen resolution is.
  25567. (Called internally by the native code).
  25568. */
  25569. void refreshMonitorSizes();
  25570. /** True if the OS supports semitransparent windows */
  25571. static bool canUseSemiTransparentWindows() throw();
  25572. private:
  25573. static Desktop* instance;
  25574. friend class Component;
  25575. friend class ComponentPeer;
  25576. friend class MouseInputSource;
  25577. friend class MouseInputSourceInternal;
  25578. friend class DeletedAtShutdown;
  25579. friend class TopLevelWindowManager;
  25580. OwnedArray <MouseInputSource> mouseSources;
  25581. void createMouseInputSources();
  25582. ListenerList <MouseListener> mouseListeners;
  25583. ListenerList <FocusChangeListener> focusListeners;
  25584. Array <Component*> desktopComponents;
  25585. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  25586. Point<int> lastFakeMouseMove;
  25587. void sendMouseMove();
  25588. int mouseClickCounter;
  25589. void incrementMouseClickCounter() throw();
  25590. ScopedPointer<Timer> dragRepeater;
  25591. Component* kioskModeComponent;
  25592. Rectangle<int> kioskComponentOriginalBounds;
  25593. int allowedOrientations;
  25594. ComponentAnimator animator;
  25595. void timerCallback();
  25596. void resetTimer();
  25597. int getNumDisplayMonitors() const throw();
  25598. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const throw();
  25599. static void getCurrentMonitorPositions (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea);
  25600. void addDesktopComponent (Component* c);
  25601. void removeDesktopComponent (Component* c);
  25602. void componentBroughtToFront (Component* c);
  25603. static void setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  25604. void triggerFocusCallback();
  25605. void handleAsyncUpdate();
  25606. Desktop();
  25607. ~Desktop();
  25608. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Desktop);
  25609. };
  25610. #endif // __JUCE_DESKTOP_JUCEHEADER__
  25611. /*** End of inlined file: juce_Desktop.h ***/
  25612. class KeyPressMappingSet;
  25613. class ApplicationCommandManagerListener;
  25614. /**
  25615. One of these objects holds a list of all the commands your app can perform,
  25616. and despatches these commands when needed.
  25617. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  25618. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  25619. to invoke automatically, which means you don't have to handle the result of a menu
  25620. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  25621. which can choose which events they want to handle.
  25622. This architecture also allows for nested ApplicationCommandTargets, so that for example
  25623. you could have two different objects, one inside the other, both of which can respond to
  25624. a "delete" command. Depending on which one has focus, the command will be sent to the
  25625. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  25626. method.
  25627. To set up your app to use commands, you'll need to do the following:
  25628. - Create a global ApplicationCommandManager to hold the list of all possible
  25629. commands. (This will also manage a set of key-mappings for them).
  25630. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  25631. This allows the object to provide a list of commands that it can perform, and
  25632. to handle them.
  25633. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  25634. or ApplicationCommandManager::registerCommand().
  25635. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  25636. method to access the key-mapper object, which you will need to register as a key-listener
  25637. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  25638. about setting this up.
  25639. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  25640. cause these commands to be invoked automatically.
  25641. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  25642. When a command is invoked, the ApplicationCommandManager will try to choose the best
  25643. ApplicationCommandTarget to receive the specified command. To do this it will use the
  25644. current keyboard focus to see which component might be interested, and will search the
  25645. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  25646. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  25647. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  25648. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  25649. point if the command still hasn't been performed, it will be passed to the current
  25650. JUCEApplication object (which is itself an ApplicationCommandTarget).
  25651. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  25652. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  25653. the object yourself.
  25654. @see ApplicationCommandTarget, ApplicationCommandInfo
  25655. */
  25656. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  25657. private FocusChangeListener
  25658. {
  25659. public:
  25660. /** Creates an ApplicationCommandManager.
  25661. Once created, you'll need to register all your app's commands with it, using
  25662. ApplicationCommandManager::registerAllCommandsForTarget() or
  25663. ApplicationCommandManager::registerCommand().
  25664. */
  25665. ApplicationCommandManager();
  25666. /** Destructor.
  25667. Make sure that you don't delete this if pointers to it are still being used by
  25668. objects such as PopupMenus or Buttons.
  25669. */
  25670. virtual ~ApplicationCommandManager();
  25671. /** Clears the current list of all commands.
  25672. Note that this will also clear the contents of the KeyPressMappingSet.
  25673. */
  25674. void clearCommands();
  25675. /** Adds a command to the list of registered commands.
  25676. @see registerAllCommandsForTarget
  25677. */
  25678. void registerCommand (const ApplicationCommandInfo& newCommand);
  25679. /** Adds all the commands that this target publishes to the manager's list.
  25680. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  25681. to get details about all the commands that this target can do, and will call
  25682. registerCommand() to add each one to the manger's list.
  25683. @see registerCommand
  25684. */
  25685. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  25686. /** Removes the command with a specified ID.
  25687. Note that this will also remove any key mappings that are mapped to the command.
  25688. */
  25689. void removeCommand (CommandID commandID);
  25690. /** This should be called to tell the manager that one of its registered commands may have changed
  25691. its active status.
  25692. Because the command manager only finds out whether a command is active or inactive by querying
  25693. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  25694. allows things like buttons to update their enablement, etc.
  25695. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  25696. for any registered listeners.
  25697. */
  25698. void commandStatusChanged();
  25699. /** Returns the number of commands that have been registered.
  25700. @see registerCommand
  25701. */
  25702. int getNumCommands() const throw() { return commands.size(); }
  25703. /** Returns the details about one of the registered commands.
  25704. The index is between 0 and (getNumCommands() - 1).
  25705. */
  25706. const ApplicationCommandInfo* getCommandForIndex (int index) const throw() { return commands [index]; }
  25707. /** Returns the details about a given command ID.
  25708. This will search the list of registered commands for one with the given command
  25709. ID number, and return its associated info. If no matching command is found, this
  25710. will return 0.
  25711. */
  25712. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const throw();
  25713. /** Returns the name field for a command.
  25714. An empty string is returned if no command with this ID has been registered.
  25715. @see getDescriptionOfCommand
  25716. */
  25717. const String getNameOfCommand (CommandID commandID) const throw();
  25718. /** Returns the description field for a command.
  25719. An empty string is returned if no command with this ID has been registered. If the
  25720. command has no description, this will return its short name field instead.
  25721. @see getNameOfCommand
  25722. */
  25723. const String getDescriptionOfCommand (CommandID commandID) const throw();
  25724. /** Returns the list of categories.
  25725. This will go through all registered commands, and return a list of all the distict
  25726. categoryName values from their ApplicationCommandInfo structure.
  25727. @see getCommandsInCategory()
  25728. */
  25729. const StringArray getCommandCategories() const;
  25730. /** Returns a list of all the command UIDs in a particular category.
  25731. @see getCommandCategories()
  25732. */
  25733. const Array <CommandID> getCommandsInCategory (const String& categoryName) const;
  25734. /** Returns the manager's internal set of key mappings.
  25735. This object can be used to edit the keypresses. To actually link this object up
  25736. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  25737. class.
  25738. @see KeyPressMappingSet
  25739. */
  25740. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  25741. /** Invokes the given command directly, sending it to the default target.
  25742. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  25743. structure.
  25744. */
  25745. bool invokeDirectly (CommandID commandID, bool asynchronously);
  25746. /** Sends a command to the default target.
  25747. This will choose a target using getFirstCommandTarget(), and send the specified command
  25748. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  25749. first target can't handle the command, it will be passed on to targets further down the
  25750. chain (see ApplicationCommandTarget::invoke() for more info).
  25751. @param invocationInfo this must be correctly filled-in, describing the context for
  25752. the invocation.
  25753. @param asynchronously if false, the command will be performed before this method returns.
  25754. If true, a message will be posted so that the command will be performed
  25755. later on the message thread, and this method will return immediately.
  25756. @see ApplicationCommandTarget::invoke
  25757. */
  25758. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  25759. bool asynchronously);
  25760. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  25761. Whenever the manager needs to know which target a command should be sent to, it calls
  25762. this method to determine the first one to try.
  25763. By default, this method will return the target that was set by calling setFirstCommandTarget().
  25764. If no target is set, it will return the result of findDefaultComponentTarget().
  25765. If you need to make sure all commands go via your own custom target, then you can
  25766. either use setFirstCommandTarget() to specify a single target, or override this method
  25767. if you need more complex logic to choose one.
  25768. It may return 0 if no targets are available.
  25769. @see getTargetForCommand, invoke, invokeDirectly
  25770. */
  25771. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  25772. /** Sets a target to be returned by getFirstCommandTarget().
  25773. If this is set to 0, then getFirstCommandTarget() will by default return the
  25774. result of findDefaultComponentTarget().
  25775. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  25776. deleting the target object.
  25777. */
  25778. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) throw();
  25779. /** Tries to find the best target to use to perform a given command.
  25780. This will call getFirstCommandTarget() to find the preferred target, and will
  25781. check whether that target can handle the given command. If it can't, then it'll use
  25782. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  25783. so on until no more are available.
  25784. If no targets are found that can perform the command, this method will return 0.
  25785. If a target is found, then it will get the target to fill-in the upToDateInfo
  25786. structure with the latest info about that command, so that the caller can see
  25787. whether the command is disabled, ticked, etc.
  25788. */
  25789. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  25790. ApplicationCommandInfo& upToDateInfo);
  25791. /** Registers a listener that will be called when various events occur. */
  25792. void addListener (ApplicationCommandManagerListener* listener);
  25793. /** Deregisters a previously-added listener. */
  25794. void removeListener (ApplicationCommandManagerListener* listener);
  25795. /** Looks for a suitable command target based on which Components have the keyboard focus.
  25796. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  25797. but is exposed here in case it's useful.
  25798. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  25799. windows, etc., and using the findTargetForComponent() method.
  25800. */
  25801. static ApplicationCommandTarget* findDefaultComponentTarget();
  25802. /** Examines this component and all its parents in turn, looking for the first one
  25803. which is a ApplicationCommandTarget.
  25804. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  25805. that class.
  25806. */
  25807. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  25808. private:
  25809. OwnedArray <ApplicationCommandInfo> commands;
  25810. ListenerList <ApplicationCommandManagerListener> listeners;
  25811. ScopedPointer <KeyPressMappingSet> keyMappings;
  25812. ApplicationCommandTarget* firstTarget;
  25813. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  25814. void handleAsyncUpdate();
  25815. void globalFocusChanged (Component*);
  25816. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  25817. // This is just here to cause a compile error in old code that hasn't been changed to use the new
  25818. // version of this method.
  25819. virtual short getFirstCommandTarget() { return 0; }
  25820. #endif
  25821. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandManager);
  25822. };
  25823. /**
  25824. A listener that receives callbacks from an ApplicationCommandManager when
  25825. commands are invoked or the command list is changed.
  25826. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  25827. */
  25828. class JUCE_API ApplicationCommandManagerListener
  25829. {
  25830. public:
  25831. /** Destructor. */
  25832. virtual ~ApplicationCommandManagerListener() {}
  25833. /** Called when an app command is about to be invoked. */
  25834. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  25835. /** Called when commands are registered or deregistered from the
  25836. command manager, or when commands are made active or inactive.
  25837. Note that if you're using this to watch for changes to whether a command is disabled,
  25838. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  25839. whenever the status of your command might have changed.
  25840. */
  25841. virtual void applicationCommandListChanged() = 0;
  25842. };
  25843. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25844. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  25845. #endif
  25846. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  25847. #endif
  25848. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  25849. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  25850. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  25851. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  25852. /*** Start of inlined file: juce_PropertiesFile.h ***/
  25853. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  25854. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  25855. /** Wrapper on a file that stores a list of key/value data pairs.
  25856. Useful for storing application settings, etc. See the PropertySet class for
  25857. the interfaces that read and write values.
  25858. Not designed for very large amounts of data, as it keeps all the values in
  25859. memory and writes them out to disk lazily when they are changed.
  25860. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  25861. with it, and these will be signalled when a value changes.
  25862. @see PropertySet
  25863. */
  25864. class JUCE_API PropertiesFile : public PropertySet,
  25865. public ChangeBroadcaster,
  25866. private Timer
  25867. {
  25868. public:
  25869. enum FileFormatOptions
  25870. {
  25871. ignoreCaseOfKeyNames = 1,
  25872. storeAsBinary = 2,
  25873. storeAsCompressedBinary = 4,
  25874. storeAsXML = 8
  25875. };
  25876. /**
  25877. Creates a PropertiesFile object.
  25878. @param file the file to use
  25879. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  25880. is changed, the object will wait for this amount
  25881. of time and then save the file. If zero, the file
  25882. will be written to disk immediately on being changed
  25883. (which might be slow, as it'll re-write synchronously
  25884. each time a value-change method is called). If it is
  25885. less than zero, the file won't be saved until
  25886. save() or saveIfNeeded() are explicitly called.
  25887. @param optionFlags a combination of the flags in the FileFormatOptions
  25888. enum, which specify the type of file to save, and other
  25889. options.
  25890. @param processLock an optional InterprocessLock object that will be used to
  25891. prevent multiple threads or processes from writing to the file
  25892. at the same time. The PropertiesFile will keep a pointer to
  25893. this object but will not take ownership of it - the caller is
  25894. responsible for making sure that the lock doesn't get deleted
  25895. before the PropertiesFile has been deleted.
  25896. */
  25897. PropertiesFile (const File& file,
  25898. int millisecondsBeforeSaving,
  25899. int optionFlags,
  25900. InterProcessLock* processLock = 0);
  25901. /** Destructor.
  25902. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  25903. */
  25904. ~PropertiesFile();
  25905. /** Returns true if this file was created from a valid (or non-existent) file.
  25906. If the file failed to load correctly because it was corrupt or had insufficient
  25907. access, this will be false.
  25908. */
  25909. bool isValidFile() const throw() { return loadedOk; }
  25910. /** This will flush all the values to disk if they've changed since the last
  25911. time they were saved.
  25912. Returns false if it fails to write to the file for some reason (maybe because
  25913. it's read-only or the directory doesn't exist or something).
  25914. @see save
  25915. */
  25916. bool saveIfNeeded();
  25917. /** This will force a write-to-disk of the current values, regardless of whether
  25918. anything has changed since the last save.
  25919. Returns false if it fails to write to the file for some reason (maybe because
  25920. it's read-only or the directory doesn't exist or something).
  25921. @see saveIfNeeded
  25922. */
  25923. bool save();
  25924. /** Returns true if the properties have been altered since the last time they were saved.
  25925. The file is flagged as needing to be saved when you change a value, but you can
  25926. explicitly set this flag with setNeedsToBeSaved().
  25927. */
  25928. bool needsToBeSaved() const;
  25929. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  25930. @see needsToBeSaved
  25931. */
  25932. void setNeedsToBeSaved (bool needsToBeSaved);
  25933. /** Returns the file that's being used. */
  25934. const File getFile() const { return file; }
  25935. /** Handy utility to create a properties file in whatever the standard OS-specific
  25936. location is for these things.
  25937. This uses getDefaultAppSettingsFile() to decide what file to create, then
  25938. creates a PropertiesFile object with the specified properties. See
  25939. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  25940. what the parameters do.
  25941. @see getDefaultAppSettingsFile
  25942. */
  25943. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  25944. const String& fileNameSuffix,
  25945. const String& folderName,
  25946. bool commonToAllUsers,
  25947. int millisecondsBeforeSaving,
  25948. int propertiesFileOptions,
  25949. InterProcessLock* processLock = 0);
  25950. /** Handy utility to choose a file in the standard OS-dependent location for application
  25951. settings files.
  25952. So on a Mac, this will return a file called:
  25953. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  25954. On Windows it'll return something like:
  25955. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  25956. On Linux it'll return
  25957. ~/.[folderName]/[applicationName].[fileNameSuffix]
  25958. If you pass an empty string as the folder name, it'll use the app name for this (or
  25959. omit the folder name on the Mac).
  25960. If commonToAllUsers is true, then this will return the same file for all users of the
  25961. computer, regardless of the current user. If it is false, the file will be specific to
  25962. only the current user. Use this to choose whether you're saving settings that are common
  25963. or user-specific.
  25964. */
  25965. static const File getDefaultAppSettingsFile (const String& applicationName,
  25966. const String& fileNameSuffix,
  25967. const String& folderName,
  25968. bool commonToAllUsers);
  25969. protected:
  25970. virtual void propertyChanged();
  25971. private:
  25972. File file;
  25973. int timerInterval;
  25974. const int options;
  25975. bool loadedOk, needsWriting;
  25976. InterProcessLock* processLock;
  25977. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  25978. InterProcessLock::ScopedLockType* createProcessLock() const;
  25979. void timerCallback();
  25980. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertiesFile);
  25981. };
  25982. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  25983. /*** End of inlined file: juce_PropertiesFile.h ***/
  25984. /**
  25985. Manages a collection of properties.
  25986. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  25987. as a singleton.
  25988. It holds two different PropertiesFile objects internally, one for user-specific
  25989. settings (stored in your user directory), and one for settings that are common to
  25990. all users (stored in a folder accessible to all users).
  25991. The class manages the creation of these files on-demand, allowing access via the
  25992. getUserSettings() and getCommonSettings() methods. It also has a few handy
  25993. methods like testWriteAccess() to check that the files can be saved.
  25994. If you're using one of these as a singleton, then your app's start-up code should
  25995. first of all call setStorageParameters() to tell it the parameters to use to create
  25996. the properties files.
  25997. @see PropertiesFile
  25998. */
  25999. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  26000. {
  26001. public:
  26002. /**
  26003. Creates an ApplicationProperties object.
  26004. Before using it, you must call setStorageParameters() to give it the info
  26005. it needs to create the property files.
  26006. */
  26007. ApplicationProperties();
  26008. /** Destructor. */
  26009. ~ApplicationProperties();
  26010. juce_DeclareSingleton (ApplicationProperties, false)
  26011. /** Gives the object the information it needs to create the appropriate properties files.
  26012. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  26013. info about how these parameters are used.
  26014. */
  26015. void setStorageParameters (const String& applicationName,
  26016. const String& fileNameSuffix,
  26017. const String& folderName,
  26018. int millisecondsBeforeSaving,
  26019. int propertiesFileOptions,
  26020. InterProcessLock* processLock = 0);
  26021. /** Tests whether the files can be successfully written to, and can show
  26022. an error message if not.
  26023. Returns true if none of the tests fail.
  26024. @param testUserSettings if true, the user settings file will be tested
  26025. @param testCommonSettings if true, the common settings file will be tested
  26026. @param showWarningDialogOnFailure if true, the method will show a helpful error
  26027. message box if either of the tests fail
  26028. */
  26029. bool testWriteAccess (bool testUserSettings,
  26030. bool testCommonSettings,
  26031. bool showWarningDialogOnFailure);
  26032. /** Returns the user settings file.
  26033. The first time this is called, it will create and load the properties file.
  26034. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  26035. the common settings are used as a second-chance place to look. This is done via the
  26036. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  26037. to the fallback for the user settings.
  26038. @see getCommonSettings
  26039. */
  26040. PropertiesFile* getUserSettings();
  26041. /** Returns the common settings file.
  26042. The first time this is called, it will create and load the properties file.
  26043. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  26044. read-only (e.g. because the user doesn't have permission to write
  26045. to shared files), then this will return the user settings instead,
  26046. (like getUserSettings() would do). This is handy if you'd like to
  26047. write a value to the common settings, but if that's no possible,
  26048. then you'd rather write to the user settings than none at all.
  26049. If returnUserPropsIfReadOnly is false, this method will always return
  26050. the common settings, even if any changes to them can't be saved.
  26051. @see getUserSettings
  26052. */
  26053. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly);
  26054. /** Saves both files if they need to be saved.
  26055. @see PropertiesFile::saveIfNeeded
  26056. */
  26057. bool saveIfNeeded();
  26058. /** Flushes and closes both files if they are open.
  26059. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  26060. and closes both files. They will then be re-opened the next time getUserSettings()
  26061. or getCommonSettings() is called.
  26062. */
  26063. void closeFiles();
  26064. private:
  26065. ScopedPointer <PropertiesFile> userProps, commonProps;
  26066. String appName, fileSuffix, folderName;
  26067. int msBeforeSaving, options;
  26068. int commonSettingsAreReadOnly;
  26069. InterProcessLock* processLock;
  26070. void openFiles();
  26071. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationProperties);
  26072. };
  26073. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26074. /*** End of inlined file: juce_ApplicationProperties.h ***/
  26075. #endif
  26076. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26077. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  26078. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26079. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26080. /*** Start of inlined file: juce_AudioFormat.h ***/
  26081. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  26082. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  26083. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  26084. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26085. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26086. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  26087. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26088. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26089. /**
  26090. This class a container which holds all the classes pertaining to the AudioData::Pointer
  26091. audio sample format class.
  26092. @see AudioData::Pointer.
  26093. */
  26094. class JUCE_API AudioData
  26095. {
  26096. public:
  26097. // These types can be used as the SampleFormat template parameter for the AudioData::Pointer class.
  26098. class Int8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit integer packed data format. */
  26099. class UInt8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit unsigned integer packed data format. */
  26100. class Int16; /**< Used as a template parameter for AudioData::Pointer. Indicates an 16-bit integer packed data format. */
  26101. class Int24; /**< Used as a template parameter for AudioData::Pointer. Indicates an 24-bit integer packed data format. */
  26102. class Int32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit integer packed data format. */
  26103. class Float32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit float data format. */
  26104. // These types can be used as the Endianness template parameter for the AudioData::Pointer class.
  26105. class BigEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in big-endian order. */
  26106. class LittleEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in little-endian order. */
  26107. class NativeEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in the CPU's native endianness. */
  26108. // These types can be used as the InterleavingType template parameter for the AudioData::Pointer class.
  26109. class NonInterleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored contiguously. */
  26110. class Interleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are interleaved with a number of other channels. */
  26111. // These types can be used as the Constness template parameter for the AudioData::Pointer class.
  26112. class NonConst; /**< Used as a template parameter for AudioData::Pointer. Indicates that the pointer can be used for non-const data. */
  26113. class Const; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples can only be used for const data.. */
  26114. #ifndef DOXYGEN
  26115. class BigEndian
  26116. {
  26117. public:
  26118. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) throw() { return s.getAsFloatBE(); }
  26119. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) throw() { s.setAsFloatBE (newValue); }
  26120. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) throw() { return s.getAsInt32BE(); }
  26121. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) throw() { s.setAsInt32BE (newValue); }
  26122. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) throw() { dest.copyFromBE (source); }
  26123. enum { isBigEndian = 1 };
  26124. };
  26125. class LittleEndian
  26126. {
  26127. public:
  26128. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) throw() { return s.getAsFloatLE(); }
  26129. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) throw() { s.setAsFloatLE (newValue); }
  26130. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) throw() { return s.getAsInt32LE(); }
  26131. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) throw() { s.setAsInt32LE (newValue); }
  26132. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) throw() { dest.copyFromLE (source); }
  26133. enum { isBigEndian = 0 };
  26134. };
  26135. #if JUCE_BIG_ENDIAN
  26136. class NativeEndian : public BigEndian {};
  26137. #else
  26138. class NativeEndian : public LittleEndian {};
  26139. #endif
  26140. class Int8
  26141. {
  26142. public:
  26143. inline Int8 (void* data_) throw() : data (static_cast <int8*> (data_)) {}
  26144. inline void advance() throw() { ++data; }
  26145. inline void skip (int numSamples) throw() { data += numSamples; }
  26146. inline float getAsFloatLE() const throw() { return (float) (*data * (1.0 / (1.0 + maxValue))); }
  26147. inline float getAsFloatBE() const throw() { return getAsFloatLE(); }
  26148. inline void setAsFloatLE (float newValue) throw() { *data = (int8) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))); }
  26149. inline void setAsFloatBE (float newValue) throw() { setAsFloatLE (newValue); }
  26150. inline int32 getAsInt32LE() const throw() { return (int) (*data << 24); }
  26151. inline int32 getAsInt32BE() const throw() { return getAsInt32LE(); }
  26152. inline void setAsInt32LE (int newValue) throw() { *data = (int8) (newValue >> 24); }
  26153. inline void setAsInt32BE (int newValue) throw() { setAsInt32LE (newValue); }
  26154. inline void clear() throw() { *data = 0; }
  26155. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  26156. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  26157. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  26158. inline void copyFromSameType (Int8& source) throw() { *data = *source.data; }
  26159. int8* data;
  26160. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  26161. };
  26162. class UInt8
  26163. {
  26164. public:
  26165. inline UInt8 (void* data_) throw() : data (static_cast <uint8*> (data_)) {}
  26166. inline void advance() throw() { ++data; }
  26167. inline void skip (int numSamples) throw() { data += numSamples; }
  26168. inline float getAsFloatLE() const throw() { return (float) ((*data - 128) * (1.0 / (1.0 + maxValue))); }
  26169. inline float getAsFloatBE() const throw() { return getAsFloatLE(); }
  26170. inline void setAsFloatLE (float newValue) throw() { *data = (uint8) jlimit (0, 255, 128 + roundToInt (newValue * (1.0 + maxValue))); }
  26171. inline void setAsFloatBE (float newValue) throw() { setAsFloatLE (newValue); }
  26172. inline int32 getAsInt32LE() const throw() { return (int) ((*data - 128) << 24); }
  26173. inline int32 getAsInt32BE() const throw() { return getAsInt32LE(); }
  26174. inline void setAsInt32LE (int newValue) throw() { *data = (uint8) (128 + (newValue >> 24)); }
  26175. inline void setAsInt32BE (int newValue) throw() { setAsInt32LE (newValue); }
  26176. inline void clear() throw() { *data = 128; }
  26177. inline void clearMultiple (int num) throw() { memset (data, 128, num) ;}
  26178. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  26179. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  26180. inline void copyFromSameType (UInt8& source) throw() { *data = *source.data; }
  26181. uint8* data;
  26182. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  26183. };
  26184. class Int16
  26185. {
  26186. public:
  26187. inline Int16 (void* data_) throw() : data (static_cast <uint16*> (data_)) {}
  26188. inline void advance() throw() { ++data; }
  26189. inline void skip (int numSamples) throw() { data += numSamples; }
  26190. inline float getAsFloatLE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfBigEndian (*data)); }
  26191. inline float getAsFloatBE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfLittleEndian (*data)); }
  26192. inline void setAsFloatLE (float newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26193. inline void setAsFloatBE (float newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint16) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26194. inline int32 getAsInt32LE() const throw() { return (int32) (ByteOrder::swapIfBigEndian ((uint16) *data) << 16); }
  26195. inline int32 getAsInt32BE() const throw() { return (int32) (ByteOrder::swapIfLittleEndian ((uint16) *data) << 16); }
  26196. inline void setAsInt32LE (int32 newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint16) (newValue >> 16)); }
  26197. inline void setAsInt32BE (int32 newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint16) (newValue >> 16)); }
  26198. inline void clear() throw() { *data = 0; }
  26199. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  26200. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  26201. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  26202. inline void copyFromSameType (Int16& source) throw() { *data = *source.data; }
  26203. uint16* data;
  26204. enum { bytesPerSample = 2, maxValue = 0x7fff, resolution = (1 << 16), isFloat = 0 };
  26205. };
  26206. class Int24
  26207. {
  26208. public:
  26209. inline Int24 (void* data_) throw() : data (static_cast <char*> (data_)) {}
  26210. inline void advance() throw() { data += 3; }
  26211. inline void skip (int numSamples) throw() { data += 3 * numSamples; }
  26212. inline float getAsFloatLE() const throw() { return (float) (ByteOrder::littleEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  26213. inline float getAsFloatBE() const throw() { return (float) (ByteOrder::bigEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  26214. inline void setAsFloatLE (float newValue) throw() { ByteOrder::littleEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  26215. inline void setAsFloatBE (float newValue) throw() { ByteOrder::bigEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  26216. inline int32 getAsInt32LE() const throw() { return (int32) ByteOrder::littleEndian24Bit (data) << 8; }
  26217. inline int32 getAsInt32BE() const throw() { return (int32) ByteOrder::bigEndian24Bit (data) << 8; }
  26218. inline void setAsInt32LE (int32 newValue) throw() { ByteOrder::littleEndian24BitToChars (newValue >> 8, data); }
  26219. inline void setAsInt32BE (int32 newValue) throw() { ByteOrder::bigEndian24BitToChars (newValue >> 8, data); }
  26220. inline void clear() throw() { data[0] = 0; data[1] = 0; data[2] = 0; }
  26221. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  26222. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  26223. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  26224. inline void copyFromSameType (Int24& source) throw() { data[0] = source.data[0]; data[1] = source.data[1]; data[2] = source.data[2]; }
  26225. char* data;
  26226. enum { bytesPerSample = 3, maxValue = 0x7fffff, resolution = (1 << 8), isFloat = 0 };
  26227. };
  26228. class Int32
  26229. {
  26230. public:
  26231. inline Int32 (void* data_) throw() : data (static_cast <uint32*> (data_)) {}
  26232. inline void advance() throw() { ++data; }
  26233. inline void skip (int numSamples) throw() { data += numSamples; }
  26234. inline float getAsFloatLE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfBigEndian (*data)); }
  26235. inline float getAsFloatBE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfLittleEndian (*data)); }
  26236. inline void setAsFloatLE (float newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint32) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26237. inline void setAsFloatBE (float newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint32) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26238. inline int32 getAsInt32LE() const throw() { return (int32) ByteOrder::swapIfBigEndian (*data); }
  26239. inline int32 getAsInt32BE() const throw() { return (int32) ByteOrder::swapIfLittleEndian (*data); }
  26240. inline void setAsInt32LE (int32 newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint32) newValue); }
  26241. inline void setAsInt32BE (int32 newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint32) newValue); }
  26242. inline void clear() throw() { *data = 0; }
  26243. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  26244. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  26245. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  26246. inline void copyFromSameType (Int32& source) throw() { *data = *source.data; }
  26247. uint32* data;
  26248. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = 1, isFloat = 0 };
  26249. };
  26250. class Float32
  26251. {
  26252. public:
  26253. inline Float32 (void* data_) throw() : data (static_cast <float*> (data_)) {}
  26254. inline void advance() throw() { ++data; }
  26255. inline void skip (int numSamples) throw() { data += numSamples; }
  26256. #if JUCE_BIG_ENDIAN
  26257. inline float getAsFloatBE() const throw() { return *data; }
  26258. inline void setAsFloatBE (float newValue) throw() { *data = newValue; }
  26259. inline float getAsFloatLE() const throw() { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  26260. inline void setAsFloatLE (float newValue) throw() { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  26261. #else
  26262. inline float getAsFloatLE() const throw() { return *data; }
  26263. inline void setAsFloatLE (float newValue) throw() { *data = newValue; }
  26264. inline float getAsFloatBE() const throw() { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  26265. inline void setAsFloatBE (float newValue) throw() { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  26266. #endif
  26267. inline int32 getAsInt32LE() const throw() { return (int32) roundToInt (jlimit (-1.0f, 1.0f, getAsFloatLE()) * (1.0 + maxValue)); }
  26268. inline int32 getAsInt32BE() const throw() { return (int32) roundToInt (jlimit (-1.0f, 1.0f, getAsFloatBE()) * (1.0 + maxValue)); }
  26269. inline void setAsInt32LE (int32 newValue) throw() { setAsFloatLE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  26270. inline void setAsInt32BE (int32 newValue) throw() { setAsFloatBE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  26271. inline void clear() throw() { *data = 0; }
  26272. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  26273. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsFloatLE (source.getAsFloat()); }
  26274. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsFloatBE (source.getAsFloat()); }
  26275. inline void copyFromSameType (Float32& source) throw() { *data = *source.data; }
  26276. float* data;
  26277. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = (1 << 8), isFloat = 1 };
  26278. };
  26279. class NonInterleaved
  26280. {
  26281. public:
  26282. inline NonInterleaved() throw() {}
  26283. inline NonInterleaved (const NonInterleaved&) throw() {}
  26284. inline NonInterleaved (const int) throw() {}
  26285. inline void copyFrom (const NonInterleaved&) throw() {}
  26286. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) throw() { s.advance(); }
  26287. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) throw() { s.skip (numSamples); }
  26288. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) throw() { s.clearMultiple (numSamples); }
  26289. template <class SampleFormatType> inline static int getNumBytesBetweenSamples (const SampleFormatType&) throw() { return SampleFormatType::bytesPerSample; }
  26290. enum { isInterleavedType = 0, numInterleavedChannels = 1 };
  26291. };
  26292. class Interleaved
  26293. {
  26294. public:
  26295. inline Interleaved() throw() : numInterleavedChannels (1) {}
  26296. inline Interleaved (const Interleaved& other) throw() : numInterleavedChannels (other.numInterleavedChannels) {}
  26297. inline Interleaved (const int numInterleavedChannels_) throw() : numInterleavedChannels (numInterleavedChannels_) {}
  26298. inline void copyFrom (const Interleaved& other) throw() { numInterleavedChannels = other.numInterleavedChannels; }
  26299. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) throw() { s.skip (numInterleavedChannels); }
  26300. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) throw() { s.skip (numInterleavedChannels * numSamples); }
  26301. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) throw() { while (--numSamples >= 0) { s.clear(); s.skip (numInterleavedChannels); } }
  26302. template <class SampleFormatType> inline int getNumBytesBetweenSamples (const SampleFormatType&) const throw() { return numInterleavedChannels * SampleFormatType::bytesPerSample; }
  26303. int numInterleavedChannels;
  26304. enum { isInterleavedType = 1 };
  26305. };
  26306. class NonConst
  26307. {
  26308. public:
  26309. typedef void VoidType;
  26310. static inline void* toVoidPtr (VoidType* v) throw() { return v; }
  26311. enum { isConst = 0 };
  26312. };
  26313. class Const
  26314. {
  26315. public:
  26316. typedef const void VoidType;
  26317. static inline void* toVoidPtr (VoidType* v) throw() { return const_cast<void*> (v); }
  26318. enum { isConst = 1 };
  26319. };
  26320. #endif
  26321. /**
  26322. A pointer to a block of audio data with a particular encoding.
  26323. This object can be used to read and write from blocks of encoded audio samples. To create one, you specify
  26324. the audio format as a series of template parameters, e.g.
  26325. @code
  26326. // this creates a pointer for reading from a const array of 16-bit little-endian packed samples.
  26327. AudioData::Pointer <AudioData::Int16,
  26328. AudioData::LittleEndian,
  26329. AudioData::NonInterleaved,
  26330. AudioData::Const> pointer (someRawAudioData);
  26331. // These methods read the sample that is being pointed to
  26332. float firstSampleAsFloat = pointer.getAsFloat();
  26333. int32 firstSampleAsInt = pointer.getAsInt32();
  26334. ++pointer; // moves the pointer to the next sample.
  26335. pointer += 3; // skips the next 3 samples.
  26336. @endcode
  26337. The convertSamples() method lets you copy a range of samples from one format to another, automatically
  26338. converting its format.
  26339. @see AudioData::Converter
  26340. */
  26341. template <typename SampleFormat,
  26342. typename Endianness,
  26343. typename InterleavingType,
  26344. typename Constness>
  26345. class Pointer
  26346. {
  26347. public:
  26348. /** Creates a non-interleaved pointer from some raw data in the appropriate format.
  26349. This constructor is only used if you've specified the AudioData::NonInterleaved option -
  26350. for interleaved formats, use the constructor that also takes a number of channels.
  26351. */
  26352. Pointer (typename Constness::VoidType* sourceData) throw()
  26353. : data (Constness::toVoidPtr (sourceData))
  26354. {
  26355. // If you're using interleaved data, call the other constructor! If you're using non-interleaved data,
  26356. // you should pass NonInterleaved as the template parameter for the interleaving type!
  26357. static_jassert (InterleavingType::isInterleavedType == 0);
  26358. }
  26359. /** Creates a pointer from some raw data in the appropriate format with the specified number of interleaved channels.
  26360. For non-interleaved data, use the other constructor.
  26361. */
  26362. Pointer (typename Constness::VoidType* sourceData, int numInterleavedChannels) throw()
  26363. : data (Constness::toVoidPtr (sourceData)),
  26364. interleaving (numInterleavedChannels)
  26365. {
  26366. }
  26367. /** Creates a copy of another pointer. */
  26368. Pointer (const Pointer& other) throw()
  26369. : data (other.data),
  26370. interleaving (other.interleaving)
  26371. {
  26372. }
  26373. Pointer& operator= (const Pointer& other) throw()
  26374. {
  26375. data = other.data;
  26376. interleaving.copyFrom (other.interleaving);
  26377. return *this;
  26378. }
  26379. /** Returns the value of the first sample as a floating point value.
  26380. The value will be in the range -1.0 to 1.0 for integer formats. For floating point
  26381. formats, the value could be outside that range, although -1 to 1 is the standard range.
  26382. */
  26383. inline float getAsFloat() const throw() { return Endianness::getAsFloat (data); }
  26384. /** Sets the value of the first sample as a floating point value.
  26385. (This method can only be used if the AudioData::NonConst option was used).
  26386. The value should be in the range -1.0 to 1.0 - for integer formats, values outside that
  26387. range will be clipped. For floating point formats, any value passed in here will be
  26388. written directly, although -1 to 1 is the standard range.
  26389. */
  26390. inline void setAsFloat (float newValue) throw()
  26391. {
  26392. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26393. Endianness::setAsFloat (data, newValue);
  26394. }
  26395. /** Returns the value of the first sample as a 32-bit integer.
  26396. The value returned will be in the range 0x80000000 to 0x7fffffff, and shorter values will be
  26397. shifted to fill this range (e.g. if you're reading from 24-bit data, the values will be shifted up
  26398. by 8 bits when returned here). If the source data is floating point, values beyond -1.0 to 1.0 will
  26399. be clipped so that -1.0 maps onto -0x7fffffff and 1.0 maps to 0x7fffffff.
  26400. */
  26401. inline int32 getAsInt32() const throw() { return Endianness::getAsInt32 (data); }
  26402. /** Sets the value of the first sample as a 32-bit integer.
  26403. This will be mapped to the range of the format that is being written - see getAsInt32().
  26404. */
  26405. inline void setAsInt32 (int32 newValue) throw()
  26406. {
  26407. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26408. Endianness::setAsInt32 (data, newValue);
  26409. }
  26410. /** Moves the pointer along to the next sample. */
  26411. inline Pointer& operator++() throw() { advance(); return *this; }
  26412. /** Moves the pointer back to the previous sample. */
  26413. inline Pointer& operator--() throw() { interleaving.advanceDataBy (data, -1); return *this; }
  26414. /** Adds a number of samples to the pointer's position. */
  26415. Pointer& operator+= (int samplesToJump) throw() { interleaving.advanceDataBy (data, samplesToJump); return *this; }
  26416. /** Writes a stream of samples into this pointer from another pointer.
  26417. This will copy the specified number of samples, converting between formats appropriately.
  26418. */
  26419. void convertSamples (Pointer source, int numSamples) const throw()
  26420. {
  26421. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26422. Pointer dest (*this);
  26423. while (--numSamples >= 0)
  26424. {
  26425. dest.data.copyFromSameType (source.data);
  26426. dest.advance();
  26427. source.advance();
  26428. }
  26429. }
  26430. /** Writes a stream of samples into this pointer from another pointer.
  26431. This will copy the specified number of samples, converting between formats appropriately.
  26432. */
  26433. template <class OtherPointerType>
  26434. void convertSamples (OtherPointerType source, int numSamples) const throw()
  26435. {
  26436. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26437. Pointer dest (*this);
  26438. if (source.getRawData() != getRawData() || source.getNumBytesBetweenSamples() >= getNumBytesBetweenSamples())
  26439. {
  26440. while (--numSamples >= 0)
  26441. {
  26442. Endianness::copyFrom (dest.data, source);
  26443. dest.advance();
  26444. ++source;
  26445. }
  26446. }
  26447. else // copy backwards if we're increasing the sample width..
  26448. {
  26449. dest += numSamples;
  26450. source += numSamples;
  26451. while (--numSamples >= 0)
  26452. Endianness::copyFrom ((--dest).data, --source);
  26453. }
  26454. }
  26455. /** Sets a number of samples to zero. */
  26456. void clearSamples (int numSamples) const throw()
  26457. {
  26458. Pointer dest (*this);
  26459. dest.interleaving.clear (dest.data, numSamples);
  26460. }
  26461. /** Returns true if the pointer is using a floating-point format. */
  26462. static bool isFloatingPoint() throw() { return (bool) SampleFormat::isFloat; }
  26463. /** Returns true if the format is big-endian. */
  26464. static bool isBigEndian() throw() { return (bool) Endianness::isBigEndian; }
  26465. /** Returns the number of bytes in each sample (ignoring the number of interleaved channels). */
  26466. static int getBytesPerSample() throw() { return (int) SampleFormat::bytesPerSample; }
  26467. /** Returns the number of interleaved channels in the format. */
  26468. int getNumInterleavedChannels() const throw() { return (int) this->numInterleavedChannels; }
  26469. /** Returns the number of bytes between the start address of each sample. */
  26470. int getNumBytesBetweenSamples() const throw() { return interleaving.getNumBytesBetweenSamples (data); }
  26471. /** Returns the accuracy of this format when represented as a 32-bit integer.
  26472. This is the smallest number above 0 that can be represented in the sample format, converted to
  26473. a 32-bit range. E,g. if the format is 8-bit, its resolution is 0x01000000; if the format is 24-bit,
  26474. its resolution is 0x100.
  26475. */
  26476. static int get32BitResolution() throw() { return (int) SampleFormat::resolution; }
  26477. /** Returns a pointer to the underlying data. */
  26478. const void* getRawData() const throw() { return data.data; }
  26479. private:
  26480. SampleFormat data;
  26481. InterleavingType interleaving; // annoyingly, making the interleaving type a superclass to take
  26482. // advantage of EBCO causes an internal compiler error in VC6..
  26483. inline void advance() throw() { interleaving.advanceData (data); }
  26484. Pointer operator++ (int); // private to force you to use the more efficient pre-increment!
  26485. Pointer operator-- (int);
  26486. };
  26487. /** A base class for objects that are used to convert between two different sample formats.
  26488. The AudioData::ConverterInstance implements this base class and can be templated, so
  26489. you can create an instance that converts between two particular formats, and then
  26490. store this in the abstract base class.
  26491. @see AudioData::ConverterInstance
  26492. */
  26493. class Converter
  26494. {
  26495. public:
  26496. virtual ~Converter() {}
  26497. /** Converts a sequence of samples from the converter's source format into the dest format. */
  26498. virtual void convertSamples (void* destSamples, const void* sourceSamples, int numSamples) const = 0;
  26499. /** Converts a sequence of samples from the converter's source format into the dest format.
  26500. This method takes sub-channel indexes, which can be used with interleaved formats in order to choose a
  26501. particular sub-channel of the data to be used.
  26502. */
  26503. virtual void convertSamples (void* destSamples, int destSubChannel,
  26504. const void* sourceSamples, int sourceSubChannel, int numSamples) const = 0;
  26505. };
  26506. /**
  26507. A class that converts between two templated AudioData::Pointer types, and which
  26508. implements the AudioData::Converter interface.
  26509. This can be used as a concrete instance of the AudioData::Converter abstract class.
  26510. @see AudioData::Converter
  26511. */
  26512. template <class SourceSampleType, class DestSampleType>
  26513. class ConverterInstance : public Converter
  26514. {
  26515. public:
  26516. ConverterInstance (int numSourceChannels = 1, int numDestChannels = 1)
  26517. : sourceChannels (numSourceChannels), destChannels (numDestChannels)
  26518. {}
  26519. ~ConverterInstance() {}
  26520. void convertSamples (void* dest, const void* source, int numSamples) const
  26521. {
  26522. SourceSampleType s (source, sourceChannels);
  26523. DestSampleType d (dest, destChannels);
  26524. d.convertSamples (s, numSamples);
  26525. }
  26526. void convertSamples (void* dest, int destSubChannel,
  26527. const void* source, int sourceSubChannel, int numSamples) const
  26528. {
  26529. jassert (destSubChannel < destChannels && sourceSubChannel < sourceChannels);
  26530. SourceSampleType s (addBytesToPointer (source, sourceSubChannel * SourceSampleType::getBytesPerSample()), sourceChannels);
  26531. DestSampleType d (addBytesToPointer (dest, destSubChannel * DestSampleType::getBytesPerSample()), destChannels);
  26532. d.convertSamples (s, numSamples);
  26533. }
  26534. private:
  26535. JUCE_DECLARE_NON_COPYABLE (ConverterInstance);
  26536. const int sourceChannels, destChannels;
  26537. };
  26538. };
  26539. /**
  26540. A set of routines to convert buffers of 32-bit floating point data to and from
  26541. various integer formats.
  26542. Note that these functions are deprecated - the AudioData class provides a much more
  26543. flexible set of conversion classes now.
  26544. */
  26545. class JUCE_API AudioDataConverters
  26546. {
  26547. public:
  26548. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  26549. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  26550. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  26551. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  26552. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  26553. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  26554. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  26555. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  26556. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  26557. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  26558. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  26559. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  26560. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  26561. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  26562. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  26563. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  26564. enum DataFormat
  26565. {
  26566. int16LE,
  26567. int16BE,
  26568. int24LE,
  26569. int24BE,
  26570. int32LE,
  26571. int32BE,
  26572. float32LE,
  26573. float32BE,
  26574. };
  26575. static void convertFloatToFormat (DataFormat destFormat,
  26576. const float* source, void* dest, int numSamples);
  26577. static void convertFormatToFloat (DataFormat sourceFormat,
  26578. const void* source, float* dest, int numSamples);
  26579. static void interleaveSamples (const float** source, float* dest,
  26580. int numSamples, int numChannels);
  26581. static void deinterleaveSamples (const float* source, float** dest,
  26582. int numSamples, int numChannels);
  26583. private:
  26584. AudioDataConverters();
  26585. JUCE_DECLARE_NON_COPYABLE (AudioDataConverters);
  26586. };
  26587. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26588. /*** End of inlined file: juce_AudioDataConverters.h ***/
  26589. class AudioFormat;
  26590. /**
  26591. Reads samples from an audio file stream.
  26592. A subclass that reads a specific type of audio format will be created by
  26593. an AudioFormat object.
  26594. @see AudioFormat, AudioFormatWriter
  26595. */
  26596. class JUCE_API AudioFormatReader
  26597. {
  26598. protected:
  26599. /** Creates an AudioFormatReader object.
  26600. @param sourceStream the stream to read from - this will be deleted
  26601. by this object when it is no longer needed. (Some
  26602. specialised readers might not use this parameter and
  26603. can leave it as 0).
  26604. @param formatName the description that will be returned by the getFormatName()
  26605. method
  26606. */
  26607. AudioFormatReader (InputStream* sourceStream,
  26608. const String& formatName);
  26609. public:
  26610. /** Destructor. */
  26611. virtual ~AudioFormatReader();
  26612. /** Returns a description of what type of format this is.
  26613. E.g. "AIFF"
  26614. */
  26615. const String getFormatName() const throw() { return formatName; }
  26616. /** Reads samples from the stream.
  26617. @param destSamples an array of buffers into which the sample data for each
  26618. channel will be written.
  26619. If the format is fixed-point, each channel will be written
  26620. as an array of 32-bit signed integers using the full
  26621. range -0x80000000 to 0x7fffffff, regardless of the source's
  26622. bit-depth. If it is a floating-point format, you should cast
  26623. the resulting array to a (float**) to get the values (in the
  26624. range -1.0 to 1.0 or beyond)
  26625. If the format is stereo, then destSamples[0] is the left channel
  26626. data, and destSamples[1] is the right channel.
  26627. The numDestChannels parameter indicates how many pointers this array
  26628. contains, but some of these pointers can be null if you don't want to
  26629. read data for some of the channels
  26630. @param numDestChannels the number of array elements in the destChannels array
  26631. @param startSampleInSource the position in the audio file or stream at which the samples
  26632. should be read, as a number of samples from the start of the
  26633. stream. It's ok for this to be beyond the start or end of the
  26634. available data - any samples that are out-of-range will be returned
  26635. as zeros.
  26636. @param numSamplesToRead the number of samples to read. If this is greater than the number
  26637. of samples that the file or stream contains. the result will be padded
  26638. with zeros
  26639. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  26640. for some of the channels that you pass in, then they should be filled with
  26641. copies of valid source channels.
  26642. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  26643. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  26644. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  26645. was false, then only the first channel would be filled with the file's contents, and
  26646. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  26647. from a stereo file, then the last 3 would all end up with copies of the same data.
  26648. @returns true if the operation succeeded, false if there was an error. Note
  26649. that reading sections of data beyond the extent of the stream isn't an
  26650. error - the reader should just return zeros for these regions
  26651. @see readMaxLevels
  26652. */
  26653. bool read (int* const* destSamples,
  26654. int numDestChannels,
  26655. int64 startSampleInSource,
  26656. int numSamplesToRead,
  26657. bool fillLeftoverChannelsWithCopies);
  26658. /** Finds the highest and lowest sample levels from a section of the audio stream.
  26659. This will read a block of samples from the stream, and measure the
  26660. highest and lowest sample levels from the channels in that section, returning
  26661. these as normalised floating-point levels.
  26662. @param startSample the offset into the audio stream to start reading from. It's
  26663. ok for this to be beyond the start or end of the stream.
  26664. @param numSamples how many samples to read
  26665. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  26666. @param highestLeft on return, this is the highest absolute sample from the left channel
  26667. @param lowestRight on return, this is the lowest absolute sample from the right
  26668. channel (if there is one)
  26669. @param highestRight on return, this is the highest absolute sample from the right
  26670. channel (if there is one)
  26671. @see read
  26672. */
  26673. virtual void readMaxLevels (int64 startSample,
  26674. int64 numSamples,
  26675. float& lowestLeft,
  26676. float& highestLeft,
  26677. float& lowestRight,
  26678. float& highestRight);
  26679. /** Scans the source looking for a sample whose magnitude is in a specified range.
  26680. This will read from the source, either forwards or backwards between two sample
  26681. positions, until it finds a sample whose magnitude lies between two specified levels.
  26682. If it finds a suitable sample, it returns its position; if not, it will return -1.
  26683. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  26684. points when you're searching for a continuous range of samples
  26685. @param startSample the first sample to look at
  26686. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  26687. the search will go backwards
  26688. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  26689. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  26690. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  26691. of this many consecutive samples, all of which lie
  26692. within the target range. When it finds such a sequence,
  26693. it returns the position of the first in-range sample
  26694. it found (i.e. the earliest one if scanning forwards, the
  26695. latest one if scanning backwards)
  26696. */
  26697. int64 searchForLevel (int64 startSample,
  26698. int64 numSamplesToSearch,
  26699. double magnitudeRangeMinimum,
  26700. double magnitudeRangeMaximum,
  26701. int minimumConsecutiveSamples);
  26702. /** The sample-rate of the stream. */
  26703. double sampleRate;
  26704. /** The number of bits per sample, e.g. 16, 24, 32. */
  26705. unsigned int bitsPerSample;
  26706. /** The total number of samples in the audio stream. */
  26707. int64 lengthInSamples;
  26708. /** The total number of channels in the audio stream. */
  26709. unsigned int numChannels;
  26710. /** Indicates whether the data is floating-point or fixed. */
  26711. bool usesFloatingPointData;
  26712. /** A set of metadata values that the reader has pulled out of the stream.
  26713. Exactly what these values are depends on the format, so you can
  26714. check out the format implementation code to see what kind of stuff
  26715. they understand.
  26716. */
  26717. StringPairArray metadataValues;
  26718. /** The input stream, for use by subclasses. */
  26719. InputStream* input;
  26720. /** Subclasses must implement this method to perform the low-level read operation.
  26721. Callers should use read() instead of calling this directly.
  26722. @param destSamples the array of destination buffers to fill. Some of these
  26723. pointers may be null
  26724. @param numDestChannels the number of items in the destSamples array. This
  26725. value is guaranteed not to be greater than the number of
  26726. channels that this reader object contains
  26727. @param startOffsetInDestBuffer the number of samples from the start of the
  26728. dest data at which to begin writing
  26729. @param startSampleInFile the number of samples into the source data at which
  26730. to begin reading. This value is guaranteed to be >= 0.
  26731. @param numSamples the number of samples to read
  26732. */
  26733. virtual bool readSamples (int** destSamples,
  26734. int numDestChannels,
  26735. int startOffsetInDestBuffer,
  26736. int64 startSampleInFile,
  26737. int numSamples) = 0;
  26738. protected:
  26739. /** Used by AudioFormatReader subclasses to copy data to different formats. */
  26740. template <class DestSampleType, class SourceSampleType, class SourceEndianness>
  26741. struct ReadHelper
  26742. {
  26743. typedef AudioData::Pointer <DestSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  26744. typedef AudioData::Pointer <SourceSampleType, SourceEndianness, AudioData::Interleaved, AudioData::Const> SourceType;
  26745. static void read (int** destData, int destOffset, int numDestChannels, const void* sourceData, int numSourceChannels, int numSamples) throw()
  26746. {
  26747. for (int i = 0; i < numDestChannels; ++i)
  26748. {
  26749. if (destData[i] != 0)
  26750. {
  26751. DestType dest (destData[i]);
  26752. dest += destOffset;
  26753. if (i < numSourceChannels)
  26754. dest.convertSamples (SourceType (addBytesToPointer (sourceData, i * SourceType::getBytesPerSample()), numSourceChannels), numSamples);
  26755. else
  26756. dest.clearSamples (numSamples);
  26757. }
  26758. }
  26759. }
  26760. };
  26761. private:
  26762. String formatName;
  26763. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReader);
  26764. };
  26765. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26766. /*** End of inlined file: juce_AudioFormatReader.h ***/
  26767. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  26768. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26769. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26770. /*** Start of inlined file: juce_AudioSource.h ***/
  26771. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  26772. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  26773. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  26774. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  26775. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  26776. class AudioFormatReader;
  26777. class AudioFormatWriter;
  26778. /**
  26779. A multi-channel buffer of 32-bit floating point audio samples.
  26780. */
  26781. class JUCE_API AudioSampleBuffer
  26782. {
  26783. public:
  26784. /** Creates a buffer with a specified number of channels and samples.
  26785. The contents of the buffer will initially be undefined, so use clear() to
  26786. set all the samples to zero.
  26787. The buffer will allocate its memory internally, and this will be released
  26788. when the buffer is deleted.
  26789. */
  26790. AudioSampleBuffer (int numChannels,
  26791. int numSamples) throw();
  26792. /** Creates a buffer using a pre-allocated block of memory.
  26793. Note that if the buffer is resized or its number of channels is changed, it
  26794. will re-allocate memory internally and copy the existing data to this new area,
  26795. so it will then stop directly addressing this memory.
  26796. @param dataToReferTo a pre-allocated array containing pointers to the data
  26797. for each channel that should be used by this buffer. The
  26798. buffer will only refer to this memory, it won't try to delete
  26799. it when the buffer is deleted or resized.
  26800. @param numChannels the number of channels to use - this must correspond to the
  26801. number of elements in the array passed in
  26802. @param numSamples the number of samples to use - this must correspond to the
  26803. size of the arrays passed in
  26804. */
  26805. AudioSampleBuffer (float** dataToReferTo,
  26806. int numChannels,
  26807. int numSamples) throw();
  26808. /** Creates a buffer using a pre-allocated block of memory.
  26809. Note that if the buffer is resized or its number of channels is changed, it
  26810. will re-allocate memory internally and copy the existing data to this new area,
  26811. so it will then stop directly addressing this memory.
  26812. @param dataToReferTo a pre-allocated array containing pointers to the data
  26813. for each channel that should be used by this buffer. The
  26814. buffer will only refer to this memory, it won't try to delete
  26815. it when the buffer is deleted or resized.
  26816. @param numChannels the number of channels to use - this must correspond to the
  26817. number of elements in the array passed in
  26818. @param startSample the offset within the arrays at which the data begins
  26819. @param numSamples the number of samples to use - this must correspond to the
  26820. size of the arrays passed in
  26821. */
  26822. AudioSampleBuffer (float** dataToReferTo,
  26823. int numChannels,
  26824. int startSample,
  26825. int numSamples) throw();
  26826. /** Copies another buffer.
  26827. This buffer will make its own copy of the other's data, unless the buffer was created
  26828. using an external data buffer, in which case boths buffers will just point to the same
  26829. shared block of data.
  26830. */
  26831. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  26832. /** Copies another buffer onto this one.
  26833. This buffer's size will be changed to that of the other buffer.
  26834. */
  26835. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  26836. /** Destructor.
  26837. This will free any memory allocated by the buffer.
  26838. */
  26839. virtual ~AudioSampleBuffer() throw();
  26840. /** Returns the number of channels of audio data that this buffer contains.
  26841. @see getSampleData
  26842. */
  26843. int getNumChannels() const throw() { return numChannels; }
  26844. /** Returns the number of samples allocated in each of the buffer's channels.
  26845. @see getSampleData
  26846. */
  26847. int getNumSamples() const throw() { return size; }
  26848. /** Returns a pointer one of the buffer's channels.
  26849. For speed, this doesn't check whether the channel number is out of range,
  26850. so be careful when using it!
  26851. */
  26852. float* getSampleData (const int channelNumber) const throw()
  26853. {
  26854. jassert (isPositiveAndBelow (channelNumber, numChannels));
  26855. return channels [channelNumber];
  26856. }
  26857. /** Returns a pointer to a sample in one of the buffer's channels.
  26858. For speed, this doesn't check whether the channel and sample number
  26859. are out-of-range, so be careful when using it!
  26860. */
  26861. float* getSampleData (const int channelNumber,
  26862. const int sampleOffset) const throw()
  26863. {
  26864. jassert (isPositiveAndBelow (channelNumber, numChannels));
  26865. jassert (isPositiveAndBelow (sampleOffset, size));
  26866. return channels [channelNumber] + sampleOffset;
  26867. }
  26868. /** Returns an array of pointers to the channels in the buffer.
  26869. Don't modify any of the pointers that are returned, and bear in mind that
  26870. these will become invalid if the buffer is resized.
  26871. */
  26872. float** getArrayOfChannels() const throw() { return channels; }
  26873. /** Changes the buffer's size or number of channels.
  26874. This can expand or contract the buffer's length, and add or remove channels.
  26875. If keepExistingContent is true, it will try to preserve as much of the
  26876. old data as it can in the new buffer.
  26877. If clearExtraSpace is true, then any extra channels or space that is
  26878. allocated will be also be cleared. If false, then this space is left
  26879. uninitialised.
  26880. If avoidReallocating is true, then changing the buffer's size won't reduce the
  26881. amount of memory that is currently allocated (but it will still increase it if
  26882. the new size is bigger than the amount it currently has). If this is false, then
  26883. a new allocation will be done so that the buffer uses takes up the minimum amount
  26884. of memory that it needs.
  26885. */
  26886. void setSize (int newNumChannels,
  26887. int newNumSamples,
  26888. bool keepExistingContent = false,
  26889. bool clearExtraSpace = false,
  26890. bool avoidReallocating = false) throw();
  26891. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  26892. There's also a constructor that lets you specify arrays like this, but this
  26893. lets you change the channels dynamically.
  26894. Note that if the buffer is resized or its number of channels is changed, it
  26895. will re-allocate memory internally and copy the existing data to this new area,
  26896. so it will then stop directly addressing this memory.
  26897. @param dataToReferTo a pre-allocated array containing pointers to the data
  26898. for each channel that should be used by this buffer. The
  26899. buffer will only refer to this memory, it won't try to delete
  26900. it when the buffer is deleted or resized.
  26901. @param numChannels the number of channels to use - this must correspond to the
  26902. number of elements in the array passed in
  26903. @param numSamples the number of samples to use - this must correspond to the
  26904. size of the arrays passed in
  26905. */
  26906. void setDataToReferTo (float** dataToReferTo,
  26907. int numChannels,
  26908. int numSamples) throw();
  26909. /** Clears all the samples in all channels. */
  26910. void clear() throw();
  26911. /** Clears a specified region of all the channels.
  26912. For speed, this doesn't check whether the channel and sample number
  26913. are in-range, so be careful!
  26914. */
  26915. void clear (int startSample,
  26916. int numSamples) throw();
  26917. /** Clears a specified region of just one channel.
  26918. For speed, this doesn't check whether the channel and sample number
  26919. are in-range, so be careful!
  26920. */
  26921. void clear (int channel,
  26922. int startSample,
  26923. int numSamples) throw();
  26924. /** Applies a gain multiple to a region of one channel.
  26925. For speed, this doesn't check whether the channel and sample number
  26926. are in-range, so be careful!
  26927. */
  26928. void applyGain (int channel,
  26929. int startSample,
  26930. int numSamples,
  26931. float gain) throw();
  26932. /** Applies a gain multiple to a region of all the channels.
  26933. For speed, this doesn't check whether the sample numbers
  26934. are in-range, so be careful!
  26935. */
  26936. void applyGain (int startSample,
  26937. int numSamples,
  26938. float gain) throw();
  26939. /** Applies a range of gains to a region of a channel.
  26940. The gain that is applied to each sample will vary from
  26941. startGain on the first sample to endGain on the last Sample,
  26942. so it can be used to do basic fades.
  26943. For speed, this doesn't check whether the sample numbers
  26944. are in-range, so be careful!
  26945. */
  26946. void applyGainRamp (int channel,
  26947. int startSample,
  26948. int numSamples,
  26949. float startGain,
  26950. float endGain) throw();
  26951. /** Adds samples from another buffer to this one.
  26952. @param destChannel the channel within this buffer to add the samples to
  26953. @param destStartSample the start sample within this buffer's channel
  26954. @param source the source buffer to add from
  26955. @param sourceChannel the channel within the source buffer to read from
  26956. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  26957. @param numSamples the number of samples to process
  26958. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  26959. added to this buffer's samples
  26960. @see copyFrom
  26961. */
  26962. void addFrom (int destChannel,
  26963. int destStartSample,
  26964. const AudioSampleBuffer& source,
  26965. int sourceChannel,
  26966. int sourceStartSample,
  26967. int numSamples,
  26968. float gainToApplyToSource = 1.0f) throw();
  26969. /** Adds samples from an array of floats to one of the channels.
  26970. @param destChannel the channel within this buffer to add the samples to
  26971. @param destStartSample the start sample within this buffer's channel
  26972. @param source the source data to use
  26973. @param numSamples the number of samples to process
  26974. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  26975. added to this buffer's samples
  26976. @see copyFrom
  26977. */
  26978. void addFrom (int destChannel,
  26979. int destStartSample,
  26980. const float* source,
  26981. int numSamples,
  26982. float gainToApplyToSource = 1.0f) throw();
  26983. /** Adds samples from an array of floats, applying a gain ramp to them.
  26984. @param destChannel the channel within this buffer to add the samples to
  26985. @param destStartSample the start sample within this buffer's channel
  26986. @param source the source data to use
  26987. @param numSamples the number of samples to process
  26988. @param startGain the gain to apply to the first sample (this is multiplied with
  26989. the source samples before they are added to this buffer)
  26990. @param endGain the gain to apply to the final sample. The gain is linearly
  26991. interpolated between the first and last samples.
  26992. */
  26993. void addFromWithRamp (int destChannel,
  26994. int destStartSample,
  26995. const float* source,
  26996. int numSamples,
  26997. float startGain,
  26998. float endGain) throw();
  26999. /** Copies samples from another buffer to this one.
  27000. @param destChannel the channel within this buffer to copy the samples to
  27001. @param destStartSample the start sample within this buffer's channel
  27002. @param source the source buffer to read from
  27003. @param sourceChannel the channel within the source buffer to read from
  27004. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  27005. @param numSamples the number of samples to process
  27006. @see addFrom
  27007. */
  27008. void copyFrom (int destChannel,
  27009. int destStartSample,
  27010. const AudioSampleBuffer& source,
  27011. int sourceChannel,
  27012. int sourceStartSample,
  27013. int numSamples) throw();
  27014. /** Copies samples from an array of floats into one of the channels.
  27015. @param destChannel the channel within this buffer to copy the samples to
  27016. @param destStartSample the start sample within this buffer's channel
  27017. @param source the source buffer to read from
  27018. @param numSamples the number of samples to process
  27019. @see addFrom
  27020. */
  27021. void copyFrom (int destChannel,
  27022. int destStartSample,
  27023. const float* source,
  27024. int numSamples) throw();
  27025. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  27026. @param destChannel the channel within this buffer to copy the samples to
  27027. @param destStartSample the start sample within this buffer's channel
  27028. @param source the source buffer to read from
  27029. @param numSamples the number of samples to process
  27030. @param gain the gain to apply
  27031. @see addFrom
  27032. */
  27033. void copyFrom (int destChannel,
  27034. int destStartSample,
  27035. const float* source,
  27036. int numSamples,
  27037. float gain) throw();
  27038. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  27039. @param destChannel the channel within this buffer to copy the samples to
  27040. @param destStartSample the start sample within this buffer's channel
  27041. @param source the source buffer to read from
  27042. @param numSamples the number of samples to process
  27043. @param startGain the gain to apply to the first sample (this is multiplied with
  27044. the source samples before they are copied to this buffer)
  27045. @param endGain the gain to apply to the final sample. The gain is linearly
  27046. interpolated between the first and last samples.
  27047. @see addFrom
  27048. */
  27049. void copyFromWithRamp (int destChannel,
  27050. int destStartSample,
  27051. const float* source,
  27052. int numSamples,
  27053. float startGain,
  27054. float endGain) throw();
  27055. /** Finds the highest and lowest sample values in a given range.
  27056. @param channel the channel to read from
  27057. @param startSample the start sample within the channel
  27058. @param numSamples the number of samples to check
  27059. @param minVal on return, the lowest value that was found
  27060. @param maxVal on return, the highest value that was found
  27061. */
  27062. void findMinMax (int channel,
  27063. int startSample,
  27064. int numSamples,
  27065. float& minVal,
  27066. float& maxVal) const throw();
  27067. /** Finds the highest absolute sample value within a region of a channel.
  27068. */
  27069. float getMagnitude (int channel,
  27070. int startSample,
  27071. int numSamples) const throw();
  27072. /** Finds the highest absolute sample value within a region on all channels.
  27073. */
  27074. float getMagnitude (int startSample,
  27075. int numSamples) const throw();
  27076. /** Returns the root mean squared level for a region of a channel.
  27077. */
  27078. float getRMSLevel (int channel,
  27079. int startSample,
  27080. int numSamples) const throw();
  27081. /** Fills a section of the buffer using an AudioReader as its source.
  27082. This will convert the reader's fixed- or floating-point data to
  27083. the buffer's floating-point format, and will try to intelligently
  27084. cope with mismatches between the number of channels in the reader
  27085. and the buffer.
  27086. @see writeToAudioWriter
  27087. */
  27088. void readFromAudioReader (AudioFormatReader* reader,
  27089. int startSample,
  27090. int numSamples,
  27091. int64 readerStartSample,
  27092. bool useReaderLeftChan,
  27093. bool useReaderRightChan);
  27094. /** Writes a section of this buffer to an audio writer.
  27095. This saves you having to mess about with channels or floating/fixed
  27096. point conversion.
  27097. @see readFromAudioReader
  27098. */
  27099. void writeToAudioWriter (AudioFormatWriter* writer,
  27100. int startSample,
  27101. int numSamples) const;
  27102. private:
  27103. int numChannels, size;
  27104. size_t allocatedBytes;
  27105. float** channels;
  27106. HeapBlock <char> allocatedData;
  27107. float* preallocatedChannelSpace [32];
  27108. void allocateData();
  27109. void allocateChannels (float** dataToReferTo, int offset);
  27110. JUCE_LEAK_DETECTOR (AudioSampleBuffer);
  27111. };
  27112. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27113. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  27114. /**
  27115. Used by AudioSource::getNextAudioBlock().
  27116. */
  27117. struct JUCE_API AudioSourceChannelInfo
  27118. {
  27119. /** The destination buffer to fill with audio data.
  27120. When the AudioSource::getNextAudioBlock() method is called, the active section
  27121. of this buffer should be filled with whatever output the source produces.
  27122. Only the samples specified by the startSample and numSamples members of this structure
  27123. should be affected by the call.
  27124. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  27125. method can be treated as the input if the source is performing some kind of filter operation,
  27126. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  27127. a handy way of doing this.
  27128. The number of channels in the buffer could be anything, so the AudioSource
  27129. must cope with this in whatever way is appropriate for its function.
  27130. */
  27131. AudioSampleBuffer* buffer;
  27132. /** The first sample in the buffer from which the callback is expected
  27133. to write data. */
  27134. int startSample;
  27135. /** The number of samples in the buffer which the callback is expected to
  27136. fill with data. */
  27137. int numSamples;
  27138. /** Convenient method to clear the buffer if the source is not producing any data. */
  27139. void clearActiveBufferRegion() const
  27140. {
  27141. if (buffer != 0)
  27142. buffer->clear (startSample, numSamples);
  27143. }
  27144. };
  27145. /**
  27146. Base class for objects that can produce a continuous stream of audio.
  27147. An AudioSource has two states: 'prepared' and 'unprepared'.
  27148. When a source needs to be played, it is first put into a 'prepared' state by a call to
  27149. prepareToPlay(), and then repeated calls will be made to its getNextAudioBlock() method to
  27150. process the audio data.
  27151. Once playback has finished, the releaseResources() method is called to put the stream
  27152. back into an 'unprepared' state.
  27153. @see AudioFormatReaderSource, ResamplingAudioSource
  27154. */
  27155. class JUCE_API AudioSource
  27156. {
  27157. protected:
  27158. /** Creates an AudioSource. */
  27159. AudioSource() throw() {}
  27160. public:
  27161. /** Destructor. */
  27162. virtual ~AudioSource() {}
  27163. /** Tells the source to prepare for playing.
  27164. An AudioSource has two states: prepared and unprepared.
  27165. The prepareToPlay() method is guaranteed to be called at least once on an 'unpreprared'
  27166. source to put it into a 'prepared' state before any calls will be made to getNextAudioBlock().
  27167. This callback allows the source to initialise any resources it might need when playing.
  27168. Once playback has finished, the releaseResources() method is called to put the stream
  27169. back into an 'unprepared' state.
  27170. Note that this method could be called more than once in succession without
  27171. a matching call to releaseResources(), so make sure your code is robust and
  27172. can handle that kind of situation.
  27173. @param samplesPerBlockExpected the number of samples that the source
  27174. will be expected to supply each time its
  27175. getNextAudioBlock() method is called. This
  27176. number may vary slightly, because it will be dependent
  27177. on audio hardware callbacks, and these aren't
  27178. guaranteed to always use a constant block size, so
  27179. the source should be able to cope with small variations.
  27180. @param sampleRate the sample rate that the output will be used at - this
  27181. is needed by sources such as tone generators.
  27182. @see releaseResources, getNextAudioBlock
  27183. */
  27184. virtual void prepareToPlay (int samplesPerBlockExpected,
  27185. double sampleRate) = 0;
  27186. /** Allows the source to release anything it no longer needs after playback has stopped.
  27187. This will be called when the source is no longer going to have its getNextAudioBlock()
  27188. method called, so it should release any spare memory, etc. that it might have
  27189. allocated during the prepareToPlay() call.
  27190. Note that there's no guarantee that prepareToPlay() will actually have been called before
  27191. releaseResources(), and it may be called more than once in succession, so make sure your
  27192. code is robust and doesn't make any assumptions about when it will be called.
  27193. @see prepareToPlay, getNextAudioBlock
  27194. */
  27195. virtual void releaseResources() = 0;
  27196. /** Called repeatedly to fetch subsequent blocks of audio data.
  27197. After calling the prepareToPlay() method, this callback will be made each
  27198. time the audio playback hardware (or whatever other destination the audio
  27199. data is going to) needs another block of data.
  27200. It will generally be called on a high-priority system thread, or possibly even
  27201. an interrupt, so be careful not to do too much work here, as that will cause
  27202. audio glitches!
  27203. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  27204. */
  27205. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  27206. };
  27207. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  27208. /*** End of inlined file: juce_AudioSource.h ***/
  27209. class AudioThumbnail;
  27210. /**
  27211. Writes samples to an audio file stream.
  27212. A subclass that writes a specific type of audio format will be created by
  27213. an AudioFormat object.
  27214. After creating one of these with the AudioFormat::createWriterFor() method
  27215. you can call its write() method to store the samples, and then delete it.
  27216. @see AudioFormat, AudioFormatReader
  27217. */
  27218. class JUCE_API AudioFormatWriter
  27219. {
  27220. protected:
  27221. /** Creates an AudioFormatWriter object.
  27222. @param destStream the stream to write to - this will be deleted
  27223. by this object when it is no longer needed
  27224. @param formatName the description that will be returned by the getFormatName()
  27225. method
  27226. @param sampleRate the sample rate to use - the base class just stores
  27227. this value, it doesn't do anything with it
  27228. @param numberOfChannels the number of channels to write - the base class just stores
  27229. this value, it doesn't do anything with it
  27230. @param bitsPerSample the bit depth of the stream - the base class just stores
  27231. this value, it doesn't do anything with it
  27232. */
  27233. AudioFormatWriter (OutputStream* destStream,
  27234. const String& formatName,
  27235. double sampleRate,
  27236. unsigned int numberOfChannels,
  27237. unsigned int bitsPerSample);
  27238. public:
  27239. /** Destructor. */
  27240. virtual ~AudioFormatWriter();
  27241. /** Returns a description of what type of format this is.
  27242. E.g. "AIFF file"
  27243. */
  27244. const String getFormatName() const throw() { return formatName; }
  27245. /** Writes a set of samples to the audio stream.
  27246. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  27247. can use AudioSampleBuffer::writeToAudioWriter().
  27248. @param samplesToWrite an array of arrays containing the sample data for
  27249. each channel to write. This is a zero-terminated
  27250. array of arrays, and can contain a different number
  27251. of channels than the actual stream uses, and the
  27252. writer should do its best to cope with this.
  27253. If the format is fixed-point, each channel will be formatted
  27254. as an array of signed integers using the full 32-bit
  27255. range -0x80000000 to 0x7fffffff, regardless of the source's
  27256. bit-depth. If it is a floating-point format, you should treat
  27257. the arrays as arrays of floats, and just cast it to an (int**)
  27258. to pass it into the method.
  27259. @param numSamples the number of samples to write
  27260. */
  27261. virtual bool write (const int** samplesToWrite,
  27262. int numSamples) = 0;
  27263. /** Reads a section of samples from an AudioFormatReader, and writes these to
  27264. the output.
  27265. This will take care of any floating-point conversion that's required to convert
  27266. between the two formats. It won't deal with sample-rate conversion, though.
  27267. If numSamplesToRead < 0, it will write the entire length of the reader.
  27268. @returns false if it can't read or write properly during the operation
  27269. */
  27270. bool writeFromAudioReader (AudioFormatReader& reader,
  27271. int64 startSample,
  27272. int64 numSamplesToRead);
  27273. /** Reads some samples from an AudioSource, and writes these to the output.
  27274. The source must already have been initialised with the AudioSource::prepareToPlay() method
  27275. @param source the source to read from
  27276. @param numSamplesToRead total number of samples to read and write
  27277. @param samplesPerBlock the maximum number of samples to fetch from the source
  27278. @returns false if it can't read or write properly during the operation
  27279. */
  27280. bool writeFromAudioSource (AudioSource& source,
  27281. int numSamplesToRead,
  27282. int samplesPerBlock = 2048);
  27283. /** Writes some samples from an AudioSampleBuffer.
  27284. */
  27285. bool writeFromAudioSampleBuffer (const AudioSampleBuffer& source,
  27286. int startSample, int numSamples);
  27287. /** Returns the sample rate being used. */
  27288. double getSampleRate() const throw() { return sampleRate; }
  27289. /** Returns the number of channels being written. */
  27290. int getNumChannels() const throw() { return numChannels; }
  27291. /** Returns the bit-depth of the data being written. */
  27292. int getBitsPerSample() const throw() { return bitsPerSample; }
  27293. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  27294. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  27295. /**
  27296. Provides a FIFO for an AudioFormatWriter, allowing you to push incoming
  27297. data into a buffer which will be flushed to disk by a background thread.
  27298. */
  27299. class ThreadedWriter
  27300. {
  27301. public:
  27302. /** Creates a ThreadedWriter for a given writer and a thread.
  27303. The writer object which is passed in here will be owned and deleted by
  27304. the ThreadedWriter when it is no longer needed.
  27305. To stop the writer and flush the buffer to disk, simply delete this object.
  27306. */
  27307. ThreadedWriter (AudioFormatWriter* writer,
  27308. TimeSliceThread& backgroundThread,
  27309. int numSamplesToBuffer);
  27310. /** Destructor. */
  27311. ~ThreadedWriter();
  27312. /** Pushes some incoming audio data into the FIFO.
  27313. If there's enough free space in the buffer, this will add the data to it,
  27314. If the FIFO is too full to accept this many samples, the method will return
  27315. false - then you could either wait until the background thread has had time to
  27316. consume some of the buffered data and try again, or you can give up
  27317. and lost this block.
  27318. The data must be an array containing the same number of channels as the
  27319. AudioFormatWriter object is using. None of these channels can be null.
  27320. */
  27321. bool write (const float** data, int numSamples);
  27322. /** Allows you to specify a thumbnail that this writer should update with the
  27323. incoming data.
  27324. The thumbnail will be cleared and will the writer will begin adding data to
  27325. it as it arrives. Pass a null pointer to stop the writer updating any thumbnails.
  27326. */
  27327. void setThumbnailToUpdate (AudioThumbnail* thumbnailToUpdate);
  27328. /** @internal */
  27329. class Buffer; // (only public for VC6 compatibility)
  27330. private:
  27331. friend class ScopedPointer<Buffer>;
  27332. ScopedPointer<Buffer> buffer;
  27333. };
  27334. protected:
  27335. /** The sample rate of the stream. */
  27336. double sampleRate;
  27337. /** The number of channels being written to the stream. */
  27338. unsigned int numChannels;
  27339. /** The bit depth of the file. */
  27340. unsigned int bitsPerSample;
  27341. /** True if it's a floating-point format, false if it's fixed-point. */
  27342. bool usesFloatingPointData;
  27343. /** The output stream for Use by subclasses. */
  27344. OutputStream* output;
  27345. /** Used by AudioFormatWriter subclasses to copy data to different formats. */
  27346. template <class DestSampleType, class SourceSampleType, class DestEndianness>
  27347. struct WriteHelper
  27348. {
  27349. typedef AudioData::Pointer <DestSampleType, DestEndianness, AudioData::Interleaved, AudioData::NonConst> DestType;
  27350. typedef AudioData::Pointer <SourceSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  27351. static void write (void* destData, int numDestChannels, const int** source,
  27352. int numSamples, const int sourceOffset = 0) throw()
  27353. {
  27354. for (int i = 0; i < numDestChannels; ++i)
  27355. {
  27356. const DestType dest (addBytesToPointer (destData, i * DestType::getBytesPerSample()), numDestChannels);
  27357. if (*source != 0)
  27358. {
  27359. dest.convertSamples (SourceType (*source + sourceOffset), numSamples);
  27360. ++source;
  27361. }
  27362. else
  27363. {
  27364. dest.clearSamples (numSamples);
  27365. }
  27366. }
  27367. }
  27368. };
  27369. private:
  27370. String formatName;
  27371. friend class ThreadedWriter;
  27372. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatWriter);
  27373. };
  27374. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27375. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  27376. /**
  27377. Subclasses of AudioFormat are used to read and write different audio
  27378. file formats.
  27379. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  27380. */
  27381. class JUCE_API AudioFormat
  27382. {
  27383. public:
  27384. /** Destructor. */
  27385. virtual ~AudioFormat();
  27386. /** Returns the name of this format.
  27387. e.g. "WAV file" or "AIFF file"
  27388. */
  27389. const String& getFormatName() const;
  27390. /** Returns all the file extensions that might apply to a file of this format.
  27391. The first item will be the one that's preferred when creating a new file.
  27392. So for a wav file this might just return ".wav"; for an AIFF file it might
  27393. return two items, ".aif" and ".aiff"
  27394. */
  27395. const StringArray& getFileExtensions() const;
  27396. /** Returns true if this the given file can be read by this format.
  27397. Subclasses shouldn't do too much work here, just check the extension or
  27398. file type. The base class implementation just checks the file's extension
  27399. against one of the ones that was registered in the constructor.
  27400. */
  27401. virtual bool canHandleFile (const File& fileToTest);
  27402. /** Returns a set of sample rates that the format can read and write. */
  27403. virtual const Array <int> getPossibleSampleRates() = 0;
  27404. /** Returns a set of bit depths that the format can read and write. */
  27405. virtual const Array <int> getPossibleBitDepths() = 0;
  27406. /** Returns true if the format can do 2-channel audio. */
  27407. virtual bool canDoStereo() = 0;
  27408. /** Returns true if the format can do 1-channel audio. */
  27409. virtual bool canDoMono() = 0;
  27410. /** Returns true if the format uses compressed data. */
  27411. virtual bool isCompressed();
  27412. /** Returns a list of different qualities that can be used when writing.
  27413. Non-compressed formats will just return an empty array, but for something
  27414. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  27415. When calling createWriterFor(), an index from this array is passed in to
  27416. tell the format which option is required.
  27417. */
  27418. virtual const StringArray getQualityOptions();
  27419. /** Tries to create an object that can read from a stream containing audio
  27420. data in this format.
  27421. The reader object that is returned can be used to read from the stream, and
  27422. should then be deleted by the caller.
  27423. @param sourceStream the stream to read from - the AudioFormatReader object
  27424. that is returned will delete this stream when it no longer
  27425. needs it.
  27426. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  27427. should delete the stream object that was passed-in. (If a valid
  27428. reader is returned, it will always be in charge of deleting the
  27429. stream, so this parameter is ignored)
  27430. @see AudioFormatReader
  27431. */
  27432. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27433. bool deleteStreamIfOpeningFails) = 0;
  27434. /** Tries to create an object that can write to a stream with this audio format.
  27435. The writer object that is returned can be used to write to the stream, and
  27436. should then be deleted by the caller.
  27437. If the stream can't be created for some reason (e.g. the parameters passed in
  27438. here aren't suitable), this will return 0.
  27439. @param streamToWriteTo the stream that the data will go to - this will be
  27440. deleted by the AudioFormatWriter object when it's no longer
  27441. needed. If no AudioFormatWriter can be created by this method,
  27442. the stream will NOT be deleted, so that the caller can re-use it
  27443. to try to open a different format, etc
  27444. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  27445. returned by getPossibleSampleRates()
  27446. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  27447. the choice will depend on the results of canDoMono() and
  27448. canDoStereo()
  27449. @param bitsPerSample the bits per sample to use - this must be one of the values
  27450. returned by getPossibleBitDepths()
  27451. @param metadataValues a set of metadata values that the writer should try to write
  27452. to the stream. Exactly what these are depends on the format,
  27453. and the subclass doesn't actually have to do anything with
  27454. them if it doesn't want to. Have a look at the specific format
  27455. implementation classes to see possible values that can be
  27456. used
  27457. @param qualityOptionIndex the index of one of compression qualities returned by the
  27458. getQualityOptions() method. If there aren't any quality options
  27459. for this format, just pass 0 in this parameter, as it'll be
  27460. ignored
  27461. @see AudioFormatWriter
  27462. */
  27463. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27464. double sampleRateToUse,
  27465. unsigned int numberOfChannels,
  27466. int bitsPerSample,
  27467. const StringPairArray& metadataValues,
  27468. int qualityOptionIndex) = 0;
  27469. protected:
  27470. /** Creates an AudioFormat object.
  27471. @param formatName this sets the value that will be returned by getFormatName()
  27472. @param fileExtensions a zero-terminated list of file extensions - this is what will
  27473. be returned by getFileExtension()
  27474. */
  27475. AudioFormat (const String& formatName,
  27476. const StringArray& fileExtensions);
  27477. private:
  27478. String formatName;
  27479. StringArray fileExtensions;
  27480. };
  27481. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  27482. /*** End of inlined file: juce_AudioFormat.h ***/
  27483. /**
  27484. Reads and Writes AIFF format audio files.
  27485. @see AudioFormat
  27486. */
  27487. class JUCE_API AiffAudioFormat : public AudioFormat
  27488. {
  27489. public:
  27490. /** Creates an format object. */
  27491. AiffAudioFormat();
  27492. /** Destructor. */
  27493. ~AiffAudioFormat();
  27494. const Array <int> getPossibleSampleRates();
  27495. const Array <int> getPossibleBitDepths();
  27496. bool canDoStereo();
  27497. bool canDoMono();
  27498. #if JUCE_MAC
  27499. bool canHandleFile (const File& fileToTest);
  27500. #endif
  27501. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27502. bool deleteStreamIfOpeningFails);
  27503. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27504. double sampleRateToUse,
  27505. unsigned int numberOfChannels,
  27506. int bitsPerSample,
  27507. const StringPairArray& metadataValues,
  27508. int qualityOptionIndex);
  27509. private:
  27510. JUCE_LEAK_DETECTOR (AiffAudioFormat);
  27511. };
  27512. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27513. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  27514. #endif
  27515. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27516. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  27517. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27518. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27519. #if JUCE_USE_CDBURNER || DOXYGEN
  27520. /**
  27521. */
  27522. class AudioCDBurner : public ChangeBroadcaster
  27523. {
  27524. public:
  27525. /** Returns a list of available optical drives.
  27526. Use openDevice() to open one of the items from this list.
  27527. */
  27528. static const StringArray findAvailableDevices();
  27529. /** Tries to open one of the optical drives.
  27530. The deviceIndex is an index into the array returned by findAvailableDevices().
  27531. */
  27532. static AudioCDBurner* openDevice (const int deviceIndex);
  27533. /** Destructor. */
  27534. ~AudioCDBurner();
  27535. enum DiskState
  27536. {
  27537. unknown, /**< An error condition, if the device isn't responding. */
  27538. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  27539. may seem to be permanently open. */
  27540. noDisc, /**< The drive has no disk in it. */
  27541. writableDiskPresent, /**< The drive contains a writeable disk. */
  27542. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  27543. };
  27544. /** Returns the current status of the device.
  27545. To get informed when the drive's status changes, attach a ChangeListener to
  27546. the AudioCDBurner.
  27547. */
  27548. DiskState getDiskState() const;
  27549. /** Returns true if there's a writable disk in the drive. */
  27550. bool isDiskPresent() const;
  27551. /** Sends an eject signal to the drive.
  27552. The eject will happen asynchronously, so you can use getDiskState() and
  27553. waitUntilStateChange() to monitor its progress.
  27554. */
  27555. bool openTray();
  27556. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  27557. @returns the device's new state
  27558. */
  27559. DiskState waitUntilStateChange (int timeOutMilliseconds);
  27560. /** Returns the set of possible write speeds that the device can handle.
  27561. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  27562. Note that if there's no media present in the drive, this value may be unavailable!
  27563. @see setWriteSpeed, getWriteSpeed
  27564. */
  27565. const Array<int> getAvailableWriteSpeeds() const;
  27566. /** Tries to enable or disable buffer underrun safety on devices that support it.
  27567. @returns true if it's now enabled. If the device doesn't support it, this
  27568. will always return false.
  27569. */
  27570. bool setBufferUnderrunProtection (bool shouldBeEnabled);
  27571. /** Returns the number of free blocks on the disk.
  27572. There are 75 blocks per second, at 44100Hz.
  27573. */
  27574. int getNumAvailableAudioBlocks() const;
  27575. /** Adds a track to be written.
  27576. The source passed-in here will be kept by this object, and it will
  27577. be used and deleted at some point in the future, either during the
  27578. burn() method or when this AudioCDBurner object is deleted. Your caller
  27579. method shouldn't keep a reference to it or use it again after passing
  27580. it in here.
  27581. */
  27582. bool addAudioTrack (AudioSource* source, int numSamples);
  27583. /** Receives progress callbacks during a cd-burn operation.
  27584. @see AudioCDBurner::burn()
  27585. */
  27586. class BurnProgressListener
  27587. {
  27588. public:
  27589. BurnProgressListener() throw() {}
  27590. virtual ~BurnProgressListener() {}
  27591. /** Called at intervals to report on the progress of the AudioCDBurner.
  27592. To cancel the burn, return true from this method.
  27593. */
  27594. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  27595. };
  27596. /** Runs the burn process.
  27597. This method will block until the operation is complete.
  27598. @param listener the object to receive callbacks about progress
  27599. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  27600. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  27601. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  27602. 0 or less to mean the fastest speed.
  27603. */
  27604. const String burn (BurnProgressListener* listener,
  27605. bool ejectDiscAfterwards,
  27606. bool performFakeBurnForTesting,
  27607. int writeSpeed);
  27608. /** If a burn operation is currently in progress, this tells it to stop
  27609. as soon as possible.
  27610. It's also possible to stop the burn process by returning true from
  27611. BurnProgressListener::audioCDBurnProgress()
  27612. */
  27613. void abortBurn();
  27614. private:
  27615. AudioCDBurner (const int deviceIndex);
  27616. class Pimpl;
  27617. friend class ScopedPointer<Pimpl>;
  27618. ScopedPointer<Pimpl> pimpl;
  27619. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDBurner);
  27620. };
  27621. #endif
  27622. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27623. /*** End of inlined file: juce_AudioCDBurner.h ***/
  27624. #endif
  27625. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27626. /*** Start of inlined file: juce_AudioCDReader.h ***/
  27627. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27628. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  27629. #if JUCE_USE_CDREADER || DOXYGEN
  27630. #if JUCE_MAC
  27631. #endif
  27632. /**
  27633. A type of AudioFormatReader that reads from an audio CD.
  27634. One of these can be used to read a CD as if it's one big audio stream. Use the
  27635. getPositionOfTrackStart() method to find where the individual tracks are
  27636. within the stream.
  27637. @see AudioFormatReader
  27638. */
  27639. class JUCE_API AudioCDReader : public AudioFormatReader
  27640. {
  27641. public:
  27642. /** Returns a list of names of Audio CDs currently available for reading.
  27643. If there's a CD drive but no CD in it, this might return an empty list, or
  27644. possibly a device that can be opened but which has no tracks, depending
  27645. on the platform.
  27646. @see createReaderForCD
  27647. */
  27648. static const StringArray getAvailableCDNames();
  27649. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  27650. @param index the index of one of the available CDs - use getAvailableCDNames()
  27651. to find out how many there are.
  27652. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  27653. caller will be responsible for deleting the object returned.
  27654. */
  27655. static AudioCDReader* createReaderForCD (const int index);
  27656. /** Destructor. */
  27657. ~AudioCDReader();
  27658. /** Implementation of the AudioFormatReader method. */
  27659. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  27660. int64 startSampleInFile, int numSamples);
  27661. /** Checks whether the CD has been removed from the drive.
  27662. */
  27663. bool isCDStillPresent() const;
  27664. /** Returns the total number of tracks (audio + data).
  27665. */
  27666. int getNumTracks() const;
  27667. /** Finds the sample offset of the start of a track.
  27668. @param trackNum the track number, where trackNum = 0 is the first track
  27669. and trackNum = getNumTracks() means the end of the CD.
  27670. */
  27671. int getPositionOfTrackStart (int trackNum) const;
  27672. /** Returns true if a given track is an audio track.
  27673. @param trackNum the track number, where 0 is the first track.
  27674. */
  27675. bool isTrackAudio (int trackNum) const;
  27676. /** Returns an array of sample offsets for the start of each track, followed by
  27677. the sample position of the end of the CD.
  27678. */
  27679. const Array<int>& getTrackOffsets() const;
  27680. /** Refreshes the object's table of contents.
  27681. If the disc has been ejected and a different one put in since this
  27682. object was created, this will cause it to update its idea of how many tracks
  27683. there are, etc.
  27684. */
  27685. void refreshTrackLengths();
  27686. /** Enables scanning for indexes within tracks.
  27687. @see getLastIndex
  27688. */
  27689. void enableIndexScanning (bool enabled);
  27690. /** Returns the index number found during the last read() call.
  27691. Index scanning is turned off by default - turn it on with enableIndexScanning().
  27692. Then when the read() method is called, if it comes across an index within that
  27693. block, the index number is stored and returned by this method.
  27694. Some devices might not support indexes, of course.
  27695. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  27696. @see enableIndexScanning
  27697. */
  27698. int getLastIndex() const;
  27699. /** Scans a track to find the position of any indexes within it.
  27700. @param trackNumber the track to look in, where 0 is the first track on the disc
  27701. @returns an array of sample positions of any index points found (not including
  27702. the index that marks the start of the track)
  27703. */
  27704. const Array <int> findIndexesInTrack (const int trackNumber);
  27705. /** Returns the CDDB id number for the CD.
  27706. It's not a great way of identifying a disc, but it's traditional.
  27707. */
  27708. int getCDDBId();
  27709. /** Tries to eject the disk.
  27710. Of course this might not be possible, if some other process is using it.
  27711. */
  27712. void ejectDisk();
  27713. enum
  27714. {
  27715. framesPerSecond = 75,
  27716. samplesPerFrame = 44100 / framesPerSecond
  27717. };
  27718. private:
  27719. Array<int> trackStartSamples;
  27720. #if JUCE_MAC
  27721. File volumeDir;
  27722. Array<File> tracks;
  27723. int currentReaderTrack;
  27724. ScopedPointer <AudioFormatReader> reader;
  27725. AudioCDReader (const File& volume);
  27726. #elif JUCE_WINDOWS
  27727. bool audioTracks [100];
  27728. void* handle;
  27729. bool indexingEnabled;
  27730. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  27731. MemoryBlock buffer;
  27732. AudioCDReader (void* handle);
  27733. int getIndexAt (int samplePos);
  27734. #elif JUCE_LINUX
  27735. AudioCDReader();
  27736. #endif
  27737. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDReader);
  27738. };
  27739. #endif
  27740. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  27741. /*** End of inlined file: juce_AudioCDReader.h ***/
  27742. #endif
  27743. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27744. #endif
  27745. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27746. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  27747. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27748. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27749. /**
  27750. A class for keeping a list of available audio formats, and for deciding which
  27751. one to use to open a given file.
  27752. You can either use this class as a singleton object, or create instances of it
  27753. yourself. Once created, use its registerFormat() method to tell it which
  27754. formats it should use.
  27755. @see AudioFormat
  27756. */
  27757. class JUCE_API AudioFormatManager
  27758. {
  27759. public:
  27760. /** Creates an empty format manager.
  27761. Before it'll be any use, you'll need to call registerFormat() with all the
  27762. formats you want it to be able to recognise.
  27763. */
  27764. AudioFormatManager();
  27765. /** Destructor. */
  27766. ~AudioFormatManager();
  27767. /** Adds a format to the manager's list of available file types.
  27768. The object passed-in will be deleted by this object, so don't keep a pointer
  27769. to it!
  27770. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  27771. return this one when called.
  27772. */
  27773. void registerFormat (AudioFormat* newFormat,
  27774. bool makeThisTheDefaultFormat);
  27775. /** Handy method to make it easy to register the formats that come with Juce.
  27776. Currently, this will add WAV and AIFF to the list.
  27777. */
  27778. void registerBasicFormats();
  27779. /** Clears the list of known formats. */
  27780. void clearFormats();
  27781. /** Returns the number of currently registered file formats. */
  27782. int getNumKnownFormats() const;
  27783. /** Returns one of the registered file formats. */
  27784. AudioFormat* getKnownFormat (int index) const;
  27785. /** Looks for which of the known formats is listed as being for a given file
  27786. extension.
  27787. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  27788. */
  27789. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  27790. /** Returns the format which has been set as the default one.
  27791. You can set a format as being the default when it is registered. It's useful
  27792. when you want to write to a file, because the best format may change between
  27793. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  27794. If none has been set as the default, this method will just return the first
  27795. one in the list.
  27796. */
  27797. AudioFormat* getDefaultFormat() const;
  27798. /** Returns a set of wildcards for file-matching that contains the extensions for
  27799. all known formats.
  27800. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  27801. */
  27802. const String getWildcardForAllFormats() const;
  27803. /** Searches through the known formats to try to create a suitable reader for
  27804. this file.
  27805. If none of the registered formats can open the file, it'll return 0. If it
  27806. returns a reader, it's the caller's responsibility to delete the reader.
  27807. */
  27808. AudioFormatReader* createReaderFor (const File& audioFile);
  27809. /** Searches through the known formats to try to create a suitable reader for
  27810. this stream.
  27811. The stream object that is passed-in will be deleted by this method or by the
  27812. reader that is returned, so the caller should not keep any references to it.
  27813. The stream that is passed-in must be capable of being repositioned so
  27814. that all the formats can have a go at opening it.
  27815. If none of the registered formats can open the stream, it'll return 0. If it
  27816. returns a reader, it's the caller's responsibility to delete the reader.
  27817. */
  27818. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  27819. private:
  27820. OwnedArray<AudioFormat> knownFormats;
  27821. int defaultFormatIndex;
  27822. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatManager);
  27823. };
  27824. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27825. /*** End of inlined file: juce_AudioFormatManager.h ***/
  27826. #endif
  27827. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27828. #endif
  27829. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27830. #endif
  27831. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27832. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  27833. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27834. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27835. /**
  27836. This class is used to wrap an AudioFormatReader and only read from a
  27837. subsection of the file.
  27838. So if you have a reader which can read a 1000 sample file, you could wrap it
  27839. in one of these to only access, e.g. samples 100 to 200, and any samples
  27840. outside that will come back as 0. Accessing sample 0 from this reader will
  27841. actually read the first sample from the other's subsection, which might
  27842. be at a non-zero position.
  27843. @see AudioFormatReader
  27844. */
  27845. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  27846. {
  27847. public:
  27848. /** Creates a AudioSubsectionReader for a given data source.
  27849. @param sourceReader the source reader from which we'll be taking data
  27850. @param subsectionStartSample the sample within the source reader which will be
  27851. mapped onto sample 0 for this reader.
  27852. @param subsectionLength the number of samples from the source that will
  27853. make up the subsection. If this reader is asked for
  27854. any samples beyond this region, it will return zero.
  27855. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  27856. this object is deleted.
  27857. */
  27858. AudioSubsectionReader (AudioFormatReader* sourceReader,
  27859. int64 subsectionStartSample,
  27860. int64 subsectionLength,
  27861. bool deleteSourceWhenDeleted);
  27862. /** Destructor. */
  27863. ~AudioSubsectionReader();
  27864. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  27865. int64 startSampleInFile, int numSamples);
  27866. void readMaxLevels (int64 startSample,
  27867. int64 numSamples,
  27868. float& lowestLeft,
  27869. float& highestLeft,
  27870. float& lowestRight,
  27871. float& highestRight);
  27872. private:
  27873. AudioFormatReader* const source;
  27874. int64 startSample, length;
  27875. const bool deleteSourceWhenDeleted;
  27876. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSubsectionReader);
  27877. };
  27878. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27879. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  27880. #endif
  27881. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27882. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  27883. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27884. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27885. class AudioThumbnailCache;
  27886. /**
  27887. Makes it easy to quickly draw scaled views of the waveform shape of an
  27888. audio file.
  27889. To use this class, just create an AudioThumbNail class for the file you want
  27890. to draw, call setSource to tell it which file or resource to use, then call
  27891. drawChannel() to draw it.
  27892. The class will asynchronously scan the wavefile to create its scaled-down view,
  27893. so you should make your UI repaint itself as this data comes in. To do this, the
  27894. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  27895. listeners should repaint themselves.
  27896. The thumbnail stores an internal low-res version of the wave data, and this can
  27897. be loaded and saved to avoid having to scan the file again.
  27898. @see AudioThumbnailCache
  27899. */
  27900. class JUCE_API AudioThumbnail : public ChangeBroadcaster
  27901. {
  27902. public:
  27903. /** Creates an audio thumbnail.
  27904. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  27905. of the audio data, this is the scale at which it should be done. (This
  27906. number is the number of original samples that will be averaged for each
  27907. low-res sample)
  27908. @param formatManagerToUse the audio format manager that is used to open the file
  27909. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  27910. thread and storage that is used to by the thumbnail, and the cache
  27911. object can be shared between multiple thumbnails
  27912. */
  27913. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  27914. AudioFormatManager& formatManagerToUse,
  27915. AudioThumbnailCache& cacheToUse);
  27916. /** Destructor. */
  27917. ~AudioThumbnail();
  27918. /** Clears and resets the thumbnail. */
  27919. void clear();
  27920. /** Specifies the file or stream that contains the audio file.
  27921. For a file, just call
  27922. @code
  27923. setSource (new FileInputSource (file))
  27924. @endcode
  27925. You can pass a zero in here to clear the thumbnail.
  27926. The source that is passed in will be deleted by this object when it is no longer needed.
  27927. @returns true if the source could be opened as a valid audio file, false if this failed for
  27928. some reason.
  27929. */
  27930. bool setSource (InputSource* newSource);
  27931. /** Gives the thumbnail an AudioFormatReader to use directly.
  27932. This will start parsing the audio in a background thread (unless the hash code
  27933. can be looked-up successfully in the thumbnail cache). Note that the reader
  27934. object will be held by the thumbnail and deleted later when no longer needed.
  27935. The thumbnail will actually keep hold of this reader until you clear the thumbnail
  27936. or change the input source, so the file will be held open for all this time. If
  27937. you don't want the thumbnail to keep a file handle open continuously, you
  27938. should use the setSource() method instead, which will only open the file when
  27939. it needs to.
  27940. */
  27941. void setReader (AudioFormatReader* newReader, int64 hashCode);
  27942. /** Resets the thumbnail, ready for adding data with the specified format.
  27943. If you're going to generate a thumbnail yourself, call this before using addBlock()
  27944. to add the data.
  27945. */
  27946. void reset (int numChannels, double sampleRate, int64 totalSamplesInSource = 0);
  27947. /** Adds a block of level data to the thumbnail.
  27948. Call reset() before using this, to tell the thumbnail about the data format.
  27949. */
  27950. void addBlock (int64 sampleNumberInSource, const AudioSampleBuffer& newData,
  27951. int startOffsetInBuffer, int numSamples);
  27952. /** Reloads the low res thumbnail data from an input stream.
  27953. This is not an audio file stream! It takes a stream of thumbnail data that would
  27954. previously have been created by the saveTo() method.
  27955. @see saveTo
  27956. */
  27957. void loadFrom (InputStream& input);
  27958. /** Saves the low res thumbnail data to an output stream.
  27959. The data that is written can later be reloaded using loadFrom().
  27960. @see loadFrom
  27961. */
  27962. void saveTo (OutputStream& output) const;
  27963. /** Returns the number of channels in the file. */
  27964. int getNumChannels() const throw();
  27965. /** Returns the length of the audio file, in seconds. */
  27966. double getTotalLength() const throw();
  27967. /** Draws the waveform for a channel.
  27968. The waveform will be drawn within the specified rectangle, where startTime
  27969. and endTime specify the times within the audio file that should be positioned
  27970. at the left and right edges of the rectangle.
  27971. The waveform will be scaled vertically so that a full-volume sample will fill
  27972. the rectangle vertically, but you can also specify an extra vertical scale factor
  27973. with the verticalZoomFactor parameter.
  27974. */
  27975. void drawChannel (Graphics& g,
  27976. const Rectangle<int>& area,
  27977. double startTimeSeconds,
  27978. double endTimeSeconds,
  27979. int channelNum,
  27980. float verticalZoomFactor);
  27981. /** Draws the waveforms for all channels in the thumbnail.
  27982. This will call drawChannel() to render each of the thumbnail's channels, stacked
  27983. above each other within the specified area.
  27984. @see drawChannel
  27985. */
  27986. void drawChannels (Graphics& g,
  27987. const Rectangle<int>& area,
  27988. double startTimeSeconds,
  27989. double endTimeSeconds,
  27990. float verticalZoomFactor);
  27991. /** Returns true if the low res preview is fully generated. */
  27992. bool isFullyLoaded() const throw();
  27993. /** Returns the number of samples that have been set in the thumbnail. */
  27994. int64 getNumSamplesFinished() const throw();
  27995. /** Returns the highest level in the thumbnail.
  27996. Note that because the thumb only stores low-resolution data, this isn't
  27997. an accurate representation of the highest value, it's only a rough approximation.
  27998. */
  27999. float getApproximatePeak() const;
  28000. /** Returns the hash code that was set by setSource() or setReader(). */
  28001. int64 getHashCode() const;
  28002. #ifndef DOXYGEN
  28003. // (this is only public to avoid a VC6 bug)
  28004. class LevelDataSource;
  28005. #endif
  28006. private:
  28007. AudioFormatManager& formatManagerToUse;
  28008. AudioThumbnailCache& cache;
  28009. struct MinMaxValue;
  28010. class ThumbData;
  28011. class CachedWindow;
  28012. friend class LevelDataSource;
  28013. friend class ScopedPointer<LevelDataSource>;
  28014. friend class ThumbData;
  28015. friend class OwnedArray<ThumbData>;
  28016. friend class CachedWindow;
  28017. friend class ScopedPointer<CachedWindow>;
  28018. ScopedPointer<LevelDataSource> source;
  28019. ScopedPointer<CachedWindow> window;
  28020. OwnedArray<ThumbData> channels;
  28021. int32 samplesPerThumbSample;
  28022. int64 totalSamples, numSamplesFinished;
  28023. int32 numChannels;
  28024. double sampleRate;
  28025. CriticalSection lock;
  28026. bool setDataSource (LevelDataSource* newSource);
  28027. void setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues);
  28028. void createChannels (int length);
  28029. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnail);
  28030. };
  28031. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28032. /*** End of inlined file: juce_AudioThumbnail.h ***/
  28033. #endif
  28034. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28035. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  28036. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28037. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28038. struct ThumbnailCacheEntry;
  28039. /**
  28040. An instance of this class is used to manage multiple AudioThumbnail objects.
  28041. The cache runs a single background thread that is shared by all the thumbnails
  28042. that need it, and it maintains a set of low-res previews in memory, to avoid
  28043. having to re-scan audio files too often.
  28044. @see AudioThumbnail
  28045. */
  28046. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  28047. {
  28048. public:
  28049. /** Creates a cache object.
  28050. The maxNumThumbsToStore parameter lets you specify how many previews should
  28051. be kept in memory at once.
  28052. */
  28053. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  28054. /** Destructor. */
  28055. ~AudioThumbnailCache();
  28056. /** Clears out any stored thumbnails.
  28057. */
  28058. void clear();
  28059. /** Reloads the specified thumb if this cache contains the appropriate stored
  28060. data.
  28061. This is called automatically by the AudioThumbnail class, so you shouldn't
  28062. normally need to call it directly.
  28063. */
  28064. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  28065. /** Stores the cachable data from the specified thumb in this cache.
  28066. This is called automatically by the AudioThumbnail class, so you shouldn't
  28067. normally need to call it directly.
  28068. */
  28069. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  28070. private:
  28071. OwnedArray <ThumbnailCacheEntry> thumbs;
  28072. int maxNumThumbsToStore;
  28073. ThumbnailCacheEntry* findThumbFor (int64 hash) const;
  28074. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnailCache);
  28075. };
  28076. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28077. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  28078. #endif
  28079. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28080. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  28081. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28082. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28083. #if JUCE_USE_FLAC || defined (DOXYGEN)
  28084. /**
  28085. Reads and writes the lossless-compression FLAC audio format.
  28086. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  28087. and make sure your include search path and library search path are set up to find
  28088. the FLAC header files and static libraries.
  28089. @see AudioFormat
  28090. */
  28091. class JUCE_API FlacAudioFormat : public AudioFormat
  28092. {
  28093. public:
  28094. FlacAudioFormat();
  28095. ~FlacAudioFormat();
  28096. const Array <int> getPossibleSampleRates();
  28097. const Array <int> getPossibleBitDepths();
  28098. bool canDoStereo();
  28099. bool canDoMono();
  28100. bool isCompressed();
  28101. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28102. bool deleteStreamIfOpeningFails);
  28103. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28104. double sampleRateToUse,
  28105. unsigned int numberOfChannels,
  28106. int bitsPerSample,
  28107. const StringPairArray& metadataValues,
  28108. int qualityOptionIndex);
  28109. private:
  28110. JUCE_LEAK_DETECTOR (FlacAudioFormat);
  28111. };
  28112. #endif
  28113. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28114. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  28115. #endif
  28116. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28117. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  28118. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28119. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28120. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  28121. /**
  28122. Reads and writes the Ogg-Vorbis audio format.
  28123. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  28124. and make sure your include search path and library search path are set up to find
  28125. the Vorbis and Ogg header files and static libraries.
  28126. @see AudioFormat,
  28127. */
  28128. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  28129. {
  28130. public:
  28131. OggVorbisAudioFormat();
  28132. ~OggVorbisAudioFormat();
  28133. const Array <int> getPossibleSampleRates();
  28134. const Array <int> getPossibleBitDepths();
  28135. bool canDoStereo();
  28136. bool canDoMono();
  28137. bool isCompressed();
  28138. const StringArray getQualityOptions();
  28139. /** Tries to estimate the quality level of an ogg file based on its size.
  28140. If it can't read the file for some reason, this will just return 1 (medium quality),
  28141. otherwise it will return the approximate quality setting that would have been used
  28142. to create the file.
  28143. @see getQualityOptions
  28144. */
  28145. int estimateOggFileQuality (const File& source);
  28146. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28147. bool deleteStreamIfOpeningFails);
  28148. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28149. double sampleRateToUse,
  28150. unsigned int numberOfChannels,
  28151. int bitsPerSample,
  28152. const StringPairArray& metadataValues,
  28153. int qualityOptionIndex);
  28154. private:
  28155. JUCE_LEAK_DETECTOR (OggVorbisAudioFormat);
  28156. };
  28157. #endif
  28158. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28159. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  28160. #endif
  28161. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28162. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  28163. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28164. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28165. #if JUCE_QUICKTIME
  28166. /**
  28167. Uses QuickTime to read the audio track a movie or media file.
  28168. As well as QuickTime movies, this should also manage to open other audio
  28169. files that quicktime can understand, like mp3, m4a, etc.
  28170. @see AudioFormat
  28171. */
  28172. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  28173. {
  28174. public:
  28175. /** Creates a format object. */
  28176. QuickTimeAudioFormat();
  28177. /** Destructor. */
  28178. ~QuickTimeAudioFormat();
  28179. const Array <int> getPossibleSampleRates();
  28180. const Array <int> getPossibleBitDepths();
  28181. bool canDoStereo();
  28182. bool canDoMono();
  28183. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28184. bool deleteStreamIfOpeningFails);
  28185. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28186. double sampleRateToUse,
  28187. unsigned int numberOfChannels,
  28188. int bitsPerSample,
  28189. const StringPairArray& metadataValues,
  28190. int qualityOptionIndex);
  28191. private:
  28192. JUCE_LEAK_DETECTOR (QuickTimeAudioFormat);
  28193. };
  28194. #endif
  28195. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28196. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  28197. #endif
  28198. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28199. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  28200. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28201. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28202. /**
  28203. Reads and Writes WAV format audio files.
  28204. @see AudioFormat
  28205. */
  28206. class JUCE_API WavAudioFormat : public AudioFormat
  28207. {
  28208. public:
  28209. /** Creates a format object. */
  28210. WavAudioFormat();
  28211. /** Destructor. */
  28212. ~WavAudioFormat();
  28213. /** Metadata property name used by wav readers and writers for adding
  28214. a BWAV chunk to the file.
  28215. @see AudioFormatReader::metadataValues, createWriterFor
  28216. */
  28217. static const char* const bwavDescription;
  28218. /** Metadata property name used by wav readers and writers for adding
  28219. a BWAV chunk to the file.
  28220. @see AudioFormatReader::metadataValues, createWriterFor
  28221. */
  28222. static const char* const bwavOriginator;
  28223. /** Metadata property name used by wav readers and writers for adding
  28224. a BWAV chunk to the file.
  28225. @see AudioFormatReader::metadataValues, createWriterFor
  28226. */
  28227. static const char* const bwavOriginatorRef;
  28228. /** Metadata property name used by wav readers and writers for adding
  28229. a BWAV chunk to the file.
  28230. Date format is: yyyy-mm-dd
  28231. @see AudioFormatReader::metadataValues, createWriterFor
  28232. */
  28233. static const char* const bwavOriginationDate;
  28234. /** Metadata property name used by wav readers and writers for adding
  28235. a BWAV chunk to the file.
  28236. Time format is: hh-mm-ss
  28237. @see AudioFormatReader::metadataValues, createWriterFor
  28238. */
  28239. static const char* const bwavOriginationTime;
  28240. /** Metadata property name used by wav readers and writers for adding
  28241. a BWAV chunk to the file.
  28242. This is the number of samples from the start of an edit that the
  28243. file is supposed to begin at. Seems like an obvious mistake to
  28244. only allow a file to occur in an edit once, but that's the way
  28245. it is..
  28246. @see AudioFormatReader::metadataValues, createWriterFor
  28247. */
  28248. static const char* const bwavTimeReference;
  28249. /** Metadata property name used by wav readers and writers for adding
  28250. a BWAV chunk to the file.
  28251. This is a
  28252. @see AudioFormatReader::metadataValues, createWriterFor
  28253. */
  28254. static const char* const bwavCodingHistory;
  28255. /** Utility function to fill out the appropriate metadata for a BWAV file.
  28256. This just makes it easier than using the property names directly, and it
  28257. fills out the time and date in the right format.
  28258. */
  28259. static const StringPairArray createBWAVMetadata (const String& description,
  28260. const String& originator,
  28261. const String& originatorRef,
  28262. const Time& dateAndTime,
  28263. const int64 timeReferenceSamples,
  28264. const String& codingHistory);
  28265. const Array <int> getPossibleSampleRates();
  28266. const Array <int> getPossibleBitDepths();
  28267. bool canDoStereo();
  28268. bool canDoMono();
  28269. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28270. bool deleteStreamIfOpeningFails);
  28271. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28272. double sampleRateToUse,
  28273. unsigned int numberOfChannels,
  28274. int bitsPerSample,
  28275. const StringPairArray& metadataValues,
  28276. int qualityOptionIndex);
  28277. /** Utility function to replace the metadata in a wav file with a new set of values.
  28278. If possible, this cheats by overwriting just the metadata region of the file, rather
  28279. than by copying the whole file again.
  28280. */
  28281. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  28282. private:
  28283. JUCE_LEAK_DETECTOR (WavAudioFormat);
  28284. };
  28285. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28286. /*** End of inlined file: juce_WavAudioFormat.h ***/
  28287. #endif
  28288. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28289. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  28290. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28291. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28292. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  28293. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28294. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28295. /**
  28296. A type of AudioSource which can be repositioned.
  28297. The basic AudioSource just streams continuously with no idea of a current
  28298. time or length, so the PositionableAudioSource is used for a finite stream
  28299. that has a current read position.
  28300. @see AudioSource, AudioTransportSource
  28301. */
  28302. class JUCE_API PositionableAudioSource : public AudioSource
  28303. {
  28304. protected:
  28305. /** Creates the PositionableAudioSource. */
  28306. PositionableAudioSource() throw() {}
  28307. public:
  28308. /** Destructor */
  28309. ~PositionableAudioSource() {}
  28310. /** Tells the stream to move to a new position.
  28311. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  28312. should return samples from this position.
  28313. Note that this may be called on a different thread to getNextAudioBlock(),
  28314. so the subclass should make sure it's synchronised.
  28315. */
  28316. virtual void setNextReadPosition (int64 newPosition) = 0;
  28317. /** Returns the position from which the next block will be returned.
  28318. @see setNextReadPosition
  28319. */
  28320. virtual int64 getNextReadPosition() const = 0;
  28321. /** Returns the total length of the stream (in samples). */
  28322. virtual int64 getTotalLength() const = 0;
  28323. /** Returns true if this source is actually playing in a loop. */
  28324. virtual bool isLooping() const = 0;
  28325. /** Tells the source whether you'd like it to play in a loop. */
  28326. virtual void setLooping (bool shouldLoop) { (void) shouldLoop; }
  28327. };
  28328. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28329. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  28330. /**
  28331. A type of AudioSource that will read from an AudioFormatReader.
  28332. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  28333. */
  28334. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  28335. {
  28336. public:
  28337. /** Creates an AudioFormatReaderSource for a given reader.
  28338. @param sourceReader the reader to use as the data source
  28339. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  28340. when this object is deleted; if false it will be
  28341. left up to the caller to manage its lifetime
  28342. */
  28343. AudioFormatReaderSource (AudioFormatReader* sourceReader,
  28344. bool deleteReaderWhenThisIsDeleted);
  28345. /** Destructor. */
  28346. ~AudioFormatReaderSource();
  28347. /** Toggles loop-mode.
  28348. If set to true, it will continuously loop the input source. If false,
  28349. it will just emit silence after the source has finished.
  28350. @see isLooping
  28351. */
  28352. void setLooping (bool shouldLoop);
  28353. /** Returns whether loop-mode is turned on or not. */
  28354. bool isLooping() const { return looping; }
  28355. /** Returns the reader that's being used. */
  28356. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  28357. /** Implementation of the AudioSource method. */
  28358. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28359. /** Implementation of the AudioSource method. */
  28360. void releaseResources();
  28361. /** Implementation of the AudioSource method. */
  28362. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28363. /** Implements the PositionableAudioSource method. */
  28364. void setNextReadPosition (int64 newPosition);
  28365. /** Implements the PositionableAudioSource method. */
  28366. int64 getNextReadPosition() const;
  28367. /** Implements the PositionableAudioSource method. */
  28368. int64 getTotalLength() const;
  28369. private:
  28370. AudioFormatReader* reader;
  28371. bool deleteReader;
  28372. int64 volatile nextPlayPos;
  28373. bool volatile looping;
  28374. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  28375. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReaderSource);
  28376. };
  28377. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28378. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  28379. #endif
  28380. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  28381. #endif
  28382. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  28383. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  28384. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  28385. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  28386. /*** Start of inlined file: juce_AudioIODevice.h ***/
  28387. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  28388. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  28389. class AudioIODevice;
  28390. /**
  28391. One of these is passed to an AudioIODevice object to stream the audio data
  28392. in and out.
  28393. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  28394. method on its own high-priority audio thread, when it needs to send or receive
  28395. the next block of data.
  28396. @see AudioIODevice, AudioDeviceManager
  28397. */
  28398. class JUCE_API AudioIODeviceCallback
  28399. {
  28400. public:
  28401. /** Destructor. */
  28402. virtual ~AudioIODeviceCallback() {}
  28403. /** Processes a block of incoming and outgoing audio data.
  28404. The subclass's implementation should use the incoming audio for whatever
  28405. purposes it needs to, and must fill all the output channels with the next
  28406. block of output data before returning.
  28407. The channel data is arranged with the same array indices as the channel name
  28408. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  28409. that aren't specified in AudioIODevice::open() will have a null pointer for their
  28410. associated channel, so remember to check for this.
  28411. @param inputChannelData a set of arrays containing the audio data for each
  28412. incoming channel - this data is valid until the function
  28413. returns. There will be one channel of data for each input
  28414. channel that was enabled when the audio device was opened
  28415. (see AudioIODevice::open())
  28416. @param numInputChannels the number of pointers to channel data in the
  28417. inputChannelData array.
  28418. @param outputChannelData a set of arrays which need to be filled with the data
  28419. that should be sent to each outgoing channel of the device.
  28420. There will be one channel of data for each output channel
  28421. that was enabled when the audio device was opened (see
  28422. AudioIODevice::open())
  28423. The initial contents of the array is undefined, so the
  28424. callback function must fill all the channels with zeros if
  28425. its output is silence. Failing to do this could cause quite
  28426. an unpleasant noise!
  28427. @param numOutputChannels the number of pointers to channel data in the
  28428. outputChannelData array.
  28429. @param numSamples the number of samples in each channel of the input and
  28430. output arrays. The number of samples will depend on the
  28431. audio device's buffer size and will usually remain constant,
  28432. although this isn't guaranteed, so make sure your code can
  28433. cope with reasonable changes in the buffer size from one
  28434. callback to the next.
  28435. */
  28436. virtual void audioDeviceIOCallback (const float** inputChannelData,
  28437. int numInputChannels,
  28438. float** outputChannelData,
  28439. int numOutputChannels,
  28440. int numSamples) = 0;
  28441. /** Called to indicate that the device is about to start calling back.
  28442. This will be called just before the audio callbacks begin, either when this
  28443. callback has just been added to an audio device, or after the device has been
  28444. restarted because of a sample-rate or block-size change.
  28445. You can use this opportunity to find out the sample rate and block size
  28446. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  28447. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  28448. @param device the audio IO device that will be used to drive the callback.
  28449. Note that if you're going to store this this pointer, it is
  28450. only valid until the next time that audioDeviceStopped is called.
  28451. */
  28452. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  28453. /** Called to indicate that the device has stopped.
  28454. */
  28455. virtual void audioDeviceStopped() = 0;
  28456. };
  28457. /**
  28458. Base class for an audio device with synchronised input and output channels.
  28459. Subclasses of this are used to implement different protocols such as DirectSound,
  28460. ASIO, CoreAudio, etc.
  28461. To create one of these, you'll need to use the AudioIODeviceType class - see the
  28462. documentation for that class for more info.
  28463. For an easier way of managing audio devices and their settings, have a look at the
  28464. AudioDeviceManager class.
  28465. @see AudioIODeviceType, AudioDeviceManager
  28466. */
  28467. class JUCE_API AudioIODevice
  28468. {
  28469. public:
  28470. /** Destructor. */
  28471. virtual ~AudioIODevice();
  28472. /** Returns the device's name, (as set in the constructor). */
  28473. const String& getName() const throw() { return name; }
  28474. /** Returns the type of the device.
  28475. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  28476. */
  28477. const String& getTypeName() const throw() { return typeName; }
  28478. /** Returns the names of all the available output channels on this device.
  28479. To find out which of these are currently in use, call getActiveOutputChannels().
  28480. */
  28481. virtual const StringArray getOutputChannelNames() = 0;
  28482. /** Returns the names of all the available input channels on this device.
  28483. To find out which of these are currently in use, call getActiveInputChannels().
  28484. */
  28485. virtual const StringArray getInputChannelNames() = 0;
  28486. /** Returns the number of sample-rates this device supports.
  28487. To find out which rates are available on this device, use this method to
  28488. find out how many there are, and getSampleRate() to get the rates.
  28489. @see getSampleRate
  28490. */
  28491. virtual int getNumSampleRates() = 0;
  28492. /** Returns one of the sample-rates this device supports.
  28493. To find out which rates are available on this device, use getNumSampleRates() to
  28494. find out how many there are, and getSampleRate() to get the individual rates.
  28495. The sample rate is set by the open() method.
  28496. (Note that for DirectSound some rates might not work, depending on combinations
  28497. of i/o channels that are being opened).
  28498. @see getNumSampleRates
  28499. */
  28500. virtual double getSampleRate (int index) = 0;
  28501. /** Returns the number of sizes of buffer that are available.
  28502. @see getBufferSizeSamples, getDefaultBufferSize
  28503. */
  28504. virtual int getNumBufferSizesAvailable() = 0;
  28505. /** Returns one of the possible buffer-sizes.
  28506. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  28507. @returns a number of samples
  28508. @see getNumBufferSizesAvailable, getDefaultBufferSize
  28509. */
  28510. virtual int getBufferSizeSamples (int index) = 0;
  28511. /** Returns the default buffer-size to use.
  28512. @returns a number of samples
  28513. @see getNumBufferSizesAvailable, getBufferSizeSamples
  28514. */
  28515. virtual int getDefaultBufferSize() = 0;
  28516. /** Tries to open the device ready to play.
  28517. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  28518. input channel should be enabled
  28519. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  28520. output channel should be enabled
  28521. @param sampleRate the sample rate to try to use - to find out which rates are
  28522. available, see getNumSampleRates() and getSampleRate()
  28523. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  28524. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  28525. @returns an error description if there's a problem, or an empty string if it succeeds in
  28526. opening the device
  28527. @see close
  28528. */
  28529. virtual const String open (const BigInteger& inputChannels,
  28530. const BigInteger& outputChannels,
  28531. double sampleRate,
  28532. int bufferSizeSamples) = 0;
  28533. /** Closes and releases the device if it's open. */
  28534. virtual void close() = 0;
  28535. /** Returns true if the device is still open.
  28536. A device might spontaneously close itself if something goes wrong, so this checks if
  28537. it's still open.
  28538. */
  28539. virtual bool isOpen() = 0;
  28540. /** Starts the device actually playing.
  28541. This must be called after the device has been opened.
  28542. @param callback the callback to use for streaming the data.
  28543. @see AudioIODeviceCallback, open
  28544. */
  28545. virtual void start (AudioIODeviceCallback* callback) = 0;
  28546. /** Stops the device playing.
  28547. Once a device has been started, this will stop it. Any pending calls to the
  28548. callback class will be flushed before this method returns.
  28549. */
  28550. virtual void stop() = 0;
  28551. /** Returns true if the device is still calling back.
  28552. The device might mysteriously stop, so this checks whether it's
  28553. still playing.
  28554. */
  28555. virtual bool isPlaying() = 0;
  28556. /** Returns the last error that happened if anything went wrong. */
  28557. virtual const String getLastError() = 0;
  28558. /** Returns the buffer size that the device is currently using.
  28559. If the device isn't actually open, this value doesn't really mean much.
  28560. */
  28561. virtual int getCurrentBufferSizeSamples() = 0;
  28562. /** Returns the sample rate that the device is currently using.
  28563. If the device isn't actually open, this value doesn't really mean much.
  28564. */
  28565. virtual double getCurrentSampleRate() = 0;
  28566. /** Returns the device's current physical bit-depth.
  28567. If the device isn't actually open, this value doesn't really mean much.
  28568. */
  28569. virtual int getCurrentBitDepth() = 0;
  28570. /** Returns a mask showing which of the available output channels are currently
  28571. enabled.
  28572. @see getOutputChannelNames
  28573. */
  28574. virtual const BigInteger getActiveOutputChannels() const = 0;
  28575. /** Returns a mask showing which of the available input channels are currently
  28576. enabled.
  28577. @see getInputChannelNames
  28578. */
  28579. virtual const BigInteger getActiveInputChannels() const = 0;
  28580. /** Returns the device's output latency.
  28581. This is the delay in samples between a callback getting a block of data, and
  28582. that data actually getting played.
  28583. */
  28584. virtual int getOutputLatencyInSamples() = 0;
  28585. /** Returns the device's input latency.
  28586. This is the delay in samples between some audio actually arriving at the soundcard,
  28587. and the callback getting passed this block of data.
  28588. */
  28589. virtual int getInputLatencyInSamples() = 0;
  28590. /** True if this device can show a pop-up control panel for editing its settings.
  28591. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  28592. to display it.
  28593. */
  28594. virtual bool hasControlPanel() const;
  28595. /** Shows a device-specific control panel if there is one.
  28596. This should only be called for devices which return true from hasControlPanel().
  28597. */
  28598. virtual bool showControlPanel();
  28599. protected:
  28600. /** Creates a device, setting its name and type member variables. */
  28601. AudioIODevice (const String& deviceName,
  28602. const String& typeName);
  28603. /** @internal */
  28604. String name, typeName;
  28605. };
  28606. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  28607. /*** End of inlined file: juce_AudioIODevice.h ***/
  28608. /**
  28609. Wrapper class to continuously stream audio from an audio source to an
  28610. AudioIODevice.
  28611. This object acts as an AudioIODeviceCallback, so can be attached to an
  28612. output device, and will stream audio from an AudioSource.
  28613. */
  28614. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  28615. {
  28616. public:
  28617. /** Creates an empty AudioSourcePlayer. */
  28618. AudioSourcePlayer();
  28619. /** Destructor.
  28620. Make sure this object isn't still being used by an AudioIODevice before
  28621. deleting it!
  28622. */
  28623. virtual ~AudioSourcePlayer();
  28624. /** Changes the current audio source to play from.
  28625. If the source passed in is already being used, this method will do nothing.
  28626. If the source is not null, its prepareToPlay() method will be called
  28627. before it starts being used for playback.
  28628. If there's another source currently playing, its releaseResources() method
  28629. will be called after it has been swapped for the new one.
  28630. @param newSource the new source to use - this will NOT be deleted
  28631. by this object when no longer needed, so it's the
  28632. caller's responsibility to manage it.
  28633. */
  28634. void setSource (AudioSource* newSource);
  28635. /** Returns the source that's playing.
  28636. May return 0 if there's no source.
  28637. */
  28638. AudioSource* getCurrentSource() const throw() { return source; }
  28639. /** Sets a gain to apply to the audio data.
  28640. @see getGain
  28641. */
  28642. void setGain (float newGain) throw();
  28643. /** Returns the current gain.
  28644. @see setGain
  28645. */
  28646. float getGain() const throw() { return gain; }
  28647. /** Implementation of the AudioIODeviceCallback method. */
  28648. void audioDeviceIOCallback (const float** inputChannelData,
  28649. int totalNumInputChannels,
  28650. float** outputChannelData,
  28651. int totalNumOutputChannels,
  28652. int numSamples);
  28653. /** Implementation of the AudioIODeviceCallback method. */
  28654. void audioDeviceAboutToStart (AudioIODevice* device);
  28655. /** Implementation of the AudioIODeviceCallback method. */
  28656. void audioDeviceStopped();
  28657. private:
  28658. CriticalSection readLock;
  28659. AudioSource* source;
  28660. double sampleRate;
  28661. int bufferSize;
  28662. float* channels [128];
  28663. float* outputChans [128];
  28664. const float* inputChans [128];
  28665. AudioSampleBuffer tempBuffer;
  28666. float lastGain, gain;
  28667. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSourcePlayer);
  28668. };
  28669. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  28670. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  28671. #endif
  28672. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  28673. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  28674. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  28675. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  28676. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  28677. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  28678. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  28679. /**
  28680. An AudioSource which takes another source as input, and buffers it using a thread.
  28681. Create this as a wrapper around another thread, and it will read-ahead with
  28682. a background thread to smooth out playback. You can either create one of these
  28683. directly, or use it indirectly using an AudioTransportSource.
  28684. @see PositionableAudioSource, AudioTransportSource
  28685. */
  28686. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  28687. {
  28688. public:
  28689. /** Creates a BufferingAudioSource.
  28690. @param source the input source to read from
  28691. @param deleteSourceWhenDeleted if true, then the input source object will
  28692. be deleted when this object is deleted
  28693. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  28694. */
  28695. BufferingAudioSource (PositionableAudioSource* source,
  28696. bool deleteSourceWhenDeleted,
  28697. int numberOfSamplesToBuffer);
  28698. /** Destructor.
  28699. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  28700. flag was set in the constructor.
  28701. */
  28702. ~BufferingAudioSource();
  28703. /** Implementation of the AudioSource method. */
  28704. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28705. /** Implementation of the AudioSource method. */
  28706. void releaseResources();
  28707. /** Implementation of the AudioSource method. */
  28708. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28709. /** Implements the PositionableAudioSource method. */
  28710. void setNextReadPosition (int64 newPosition);
  28711. /** Implements the PositionableAudioSource method. */
  28712. int64 getNextReadPosition() const;
  28713. /** Implements the PositionableAudioSource method. */
  28714. int64 getTotalLength() const { return source->getTotalLength(); }
  28715. /** Implements the PositionableAudioSource method. */
  28716. bool isLooping() const { return source->isLooping(); }
  28717. private:
  28718. PositionableAudioSource* source;
  28719. bool deleteSourceWhenDeleted;
  28720. int numberOfSamplesToBuffer;
  28721. AudioSampleBuffer buffer;
  28722. CriticalSection bufferStartPosLock;
  28723. int64 volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  28724. bool wasSourceLooping;
  28725. double volatile sampleRate;
  28726. friend class SharedBufferingAudioSourceThread;
  28727. bool readNextBufferChunk();
  28728. void readBufferSection (int64 start, int length, int bufferOffset);
  28729. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferingAudioSource);
  28730. };
  28731. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  28732. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  28733. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  28734. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  28735. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  28736. /**
  28737. A type of AudioSource that takes an input source and changes its sample rate.
  28738. @see AudioSource
  28739. */
  28740. class JUCE_API ResamplingAudioSource : public AudioSource
  28741. {
  28742. public:
  28743. /** Creates a ResamplingAudioSource for a given input source.
  28744. @param inputSource the input source to read from
  28745. @param deleteInputWhenDeleted if true, the input source will be deleted when
  28746. this object is deleted
  28747. @param numChannels the number of channels to process
  28748. */
  28749. ResamplingAudioSource (AudioSource* inputSource,
  28750. bool deleteInputWhenDeleted,
  28751. int numChannels = 2);
  28752. /** Destructor. */
  28753. ~ResamplingAudioSource();
  28754. /** Changes the resampling ratio.
  28755. (This value can be changed at any time, even while the source is running).
  28756. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  28757. values will speed it up; lower values will slow it
  28758. down. The ratio must be greater than 0
  28759. */
  28760. void setResamplingRatio (double samplesInPerOutputSample);
  28761. /** Returns the current resampling ratio.
  28762. This is the value that was set by setResamplingRatio().
  28763. */
  28764. double getResamplingRatio() const throw() { return ratio; }
  28765. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28766. void releaseResources();
  28767. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28768. private:
  28769. AudioSource* const input;
  28770. const bool deleteInputWhenDeleted;
  28771. double ratio, lastRatio;
  28772. AudioSampleBuffer buffer;
  28773. int bufferPos, sampsInBuffer;
  28774. double subSampleOffset;
  28775. double coefficients[6];
  28776. CriticalSection ratioLock;
  28777. const int numChannels;
  28778. HeapBlock<float*> destBuffers, srcBuffers;
  28779. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  28780. void createLowPass (double proportionalRate);
  28781. struct FilterState
  28782. {
  28783. double x1, x2, y1, y2;
  28784. };
  28785. HeapBlock<FilterState> filterStates;
  28786. void resetFilters();
  28787. void applyFilter (float* samples, int num, FilterState& fs);
  28788. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResamplingAudioSource);
  28789. };
  28790. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  28791. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  28792. /**
  28793. An AudioSource that takes a PositionableAudioSource and allows it to be
  28794. played, stopped, started, etc.
  28795. This can also be told use a buffer and background thread to read ahead, and
  28796. if can correct for different sample-rates.
  28797. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  28798. to control playback of an audio file.
  28799. @see AudioSource, AudioSourcePlayer
  28800. */
  28801. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  28802. public ChangeBroadcaster
  28803. {
  28804. public:
  28805. /** Creates an AudioTransportSource.
  28806. After creating one of these, use the setSource() method to select an input source.
  28807. */
  28808. AudioTransportSource();
  28809. /** Destructor. */
  28810. ~AudioTransportSource();
  28811. /** Sets the reader that is being used as the input source.
  28812. This will stop playback, reset the position to 0 and change to the new reader.
  28813. The source passed in will not be deleted by this object, so must be managed by
  28814. the caller.
  28815. @param newSource the new input source to use. This may be zero
  28816. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  28817. is zero, no reading ahead will be done; if it's
  28818. greater than zero, a BufferingAudioSource will be used
  28819. to do the reading-ahead
  28820. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  28821. rate of the source, and playback will be sample-rate
  28822. adjusted to maintain playback at the correct pitch. If
  28823. this is 0, no sample-rate adjustment will be performed
  28824. @param maxNumChannels the maximum number of channels that may need to be played
  28825. */
  28826. void setSource (PositionableAudioSource* newSource,
  28827. int readAheadBufferSize = 0,
  28828. double sourceSampleRateToCorrectFor = 0.0,
  28829. int maxNumChannels = 2);
  28830. /** Changes the current playback position in the source stream.
  28831. The next time the getNextAudioBlock() method is called, this
  28832. is the time from which it'll read data.
  28833. @see getPosition
  28834. */
  28835. void setPosition (double newPosition);
  28836. /** Returns the position that the next data block will be read from
  28837. This is a time in seconds.
  28838. */
  28839. double getCurrentPosition() const;
  28840. /** Returns the stream's length in seconds. */
  28841. double getLengthInSeconds() const;
  28842. /** Returns true if the player has stopped because its input stream ran out of data.
  28843. */
  28844. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  28845. /** Starts playing (if a source has been selected).
  28846. If it starts playing, this will send a message to any ChangeListeners
  28847. that are registered with this object.
  28848. */
  28849. void start();
  28850. /** Stops playing.
  28851. If it's actually playing, this will send a message to any ChangeListeners
  28852. that are registered with this object.
  28853. */
  28854. void stop();
  28855. /** Returns true if it's currently playing. */
  28856. bool isPlaying() const throw() { return playing; }
  28857. /** Changes the gain to apply to the output.
  28858. @param newGain a factor by which to multiply the outgoing samples,
  28859. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  28860. */
  28861. void setGain (float newGain) throw();
  28862. /** Returns the current gain setting.
  28863. @see setGain
  28864. */
  28865. float getGain() const throw() { return gain; }
  28866. /** Implementation of the AudioSource method. */
  28867. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28868. /** Implementation of the AudioSource method. */
  28869. void releaseResources();
  28870. /** Implementation of the AudioSource method. */
  28871. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28872. /** Implements the PositionableAudioSource method. */
  28873. void setNextReadPosition (int64 newPosition);
  28874. /** Implements the PositionableAudioSource method. */
  28875. int64 getNextReadPosition() const;
  28876. /** Implements the PositionableAudioSource method. */
  28877. int64 getTotalLength() const;
  28878. /** Implements the PositionableAudioSource method. */
  28879. bool isLooping() const;
  28880. private:
  28881. PositionableAudioSource* source;
  28882. ResamplingAudioSource* resamplerSource;
  28883. BufferingAudioSource* bufferingSource;
  28884. PositionableAudioSource* positionableSource;
  28885. AudioSource* masterSource;
  28886. CriticalSection callbackLock;
  28887. float volatile gain, lastGain;
  28888. bool volatile playing, stopped;
  28889. double sampleRate, sourceSampleRate;
  28890. int blockSize, readAheadBufferSize;
  28891. bool isPrepared, inputStreamEOF;
  28892. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioTransportSource);
  28893. };
  28894. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  28895. /*** End of inlined file: juce_AudioTransportSource.h ***/
  28896. #endif
  28897. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  28898. #endif
  28899. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  28900. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  28901. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  28902. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  28903. /**
  28904. An AudioSource that takes the audio from another source, and re-maps its
  28905. input and output channels to a different arrangement.
  28906. You can use this to increase or decrease the number of channels that an
  28907. audio source uses, or to re-order those channels.
  28908. Call the reset() method before using it to set up a default mapping, and then
  28909. the setInputChannelMapping() and setOutputChannelMapping() methods to
  28910. create an appropriate mapping, otherwise no channels will be connected and
  28911. it'll produce silence.
  28912. @see AudioSource
  28913. */
  28914. class ChannelRemappingAudioSource : public AudioSource
  28915. {
  28916. public:
  28917. /** Creates a remapping source that will pass on audio from the given input.
  28918. @param source the input source to use. Make sure that this doesn't
  28919. get deleted before the ChannelRemappingAudioSource object
  28920. @param deleteSourceWhenDeleted if true, the input source will be deleted
  28921. when this object is deleted, if false, the caller is
  28922. responsible for its deletion
  28923. */
  28924. ChannelRemappingAudioSource (AudioSource* source,
  28925. bool deleteSourceWhenDeleted);
  28926. /** Destructor. */
  28927. ~ChannelRemappingAudioSource();
  28928. /** Specifies a number of channels that this audio source must produce from its
  28929. getNextAudioBlock() callback.
  28930. */
  28931. void setNumberOfChannelsToProduce (int requiredNumberOfChannels);
  28932. /** Clears any mapped channels.
  28933. After this, no channels are mapped, so this object will produce silence. Create
  28934. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  28935. */
  28936. void clearAllMappings();
  28937. /** Creates an input channel mapping.
  28938. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  28939. data will be sent to destChannelIndex of our input source.
  28940. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  28941. source specified when this object was created).
  28942. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  28943. during our getNextAudioBlock() callback
  28944. */
  28945. void setInputChannelMapping (int destChannelIndex,
  28946. int sourceChannelIndex);
  28947. /** Creates an output channel mapping.
  28948. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  28949. our input audio source will be copied to channel destChannelIndex of the final buffer.
  28950. @param sourceChannelIndex the index of an output channel coming from our input audio source
  28951. (i.e. the source specified when this object was created).
  28952. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  28953. during our getNextAudioBlock() callback
  28954. */
  28955. void setOutputChannelMapping (int sourceChannelIndex,
  28956. int destChannelIndex);
  28957. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  28958. our input audio source.
  28959. */
  28960. int getRemappedInputChannel (int inputChannelIndex) const;
  28961. /** Returns the output channel to which channel outputChannelIndex of our input audio
  28962. source will be sent to.
  28963. */
  28964. int getRemappedOutputChannel (int outputChannelIndex) const;
  28965. /** Returns an XML object to encapsulate the state of the mappings.
  28966. @see restoreFromXml
  28967. */
  28968. XmlElement* createXml() const;
  28969. /** Restores the mappings from an XML object created by createXML().
  28970. @see createXml
  28971. */
  28972. void restoreFromXml (const XmlElement& e);
  28973. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28974. void releaseResources();
  28975. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28976. private:
  28977. int requiredNumberOfChannels;
  28978. Array <int> remappedInputs, remappedOutputs;
  28979. AudioSource* const source;
  28980. const bool deleteSourceWhenDeleted;
  28981. AudioSampleBuffer buffer;
  28982. AudioSourceChannelInfo remappedInfo;
  28983. CriticalSection lock;
  28984. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelRemappingAudioSource);
  28985. };
  28986. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  28987. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  28988. #endif
  28989. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  28990. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  28991. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  28992. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  28993. /*** Start of inlined file: juce_IIRFilter.h ***/
  28994. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  28995. #define __JUCE_IIRFILTER_JUCEHEADER__
  28996. /**
  28997. An IIR filter that can perform low, high, or band-pass filtering on an
  28998. audio signal.
  28999. @see IIRFilterAudioSource
  29000. */
  29001. class JUCE_API IIRFilter
  29002. {
  29003. public:
  29004. /** Creates a filter.
  29005. Initially the filter is inactive, so will have no effect on samples that
  29006. you process with it. Use the appropriate method to turn it into the type
  29007. of filter needed.
  29008. */
  29009. IIRFilter();
  29010. /** Creates a copy of another filter. */
  29011. IIRFilter (const IIRFilter& other);
  29012. /** Destructor. */
  29013. ~IIRFilter();
  29014. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  29015. Note that this clears the processing state, but the type of filter and
  29016. its coefficients aren't changed. To put a filter into an inactive state, use
  29017. the makeInactive() method.
  29018. */
  29019. void reset() throw();
  29020. /** Performs the filter operation on the given set of samples.
  29021. */
  29022. void processSamples (float* samples,
  29023. int numSamples) throw();
  29024. /** Processes a single sample, without any locking or checking.
  29025. Use this if you need fast processing of a single value, but be aware that
  29026. this isn't thread-safe in the way that processSamples() is.
  29027. */
  29028. float processSingleSampleRaw (float sample) throw();
  29029. /** Sets the filter up to act as a low-pass filter.
  29030. */
  29031. void makeLowPass (double sampleRate,
  29032. double frequency) throw();
  29033. /** Sets the filter up to act as a high-pass filter.
  29034. */
  29035. void makeHighPass (double sampleRate,
  29036. double frequency) throw();
  29037. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  29038. The gain is a scale factor that the low frequencies are multiplied by, so values
  29039. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  29040. attenuate them.
  29041. */
  29042. void makeLowShelf (double sampleRate,
  29043. double cutOffFrequency,
  29044. double Q,
  29045. float gainFactor) throw();
  29046. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  29047. The gain is a scale factor that the high frequencies are multiplied by, so values
  29048. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  29049. attenuate them.
  29050. */
  29051. void makeHighShelf (double sampleRate,
  29052. double cutOffFrequency,
  29053. double Q,
  29054. float gainFactor) throw();
  29055. /** Sets the filter up to act as a band pass filter centred around a
  29056. frequency, with a variable Q and gain.
  29057. The gain is a scale factor that the centre frequencies are multiplied by, so
  29058. values greater than 1.0 will boost the centre frequencies, values less than
  29059. 1.0 will attenuate them.
  29060. */
  29061. void makeBandPass (double sampleRate,
  29062. double centreFrequency,
  29063. double Q,
  29064. float gainFactor) throw();
  29065. /** Clears the filter's coefficients so that it becomes inactive.
  29066. */
  29067. void makeInactive() throw();
  29068. /** Makes this filter duplicate the set-up of another one.
  29069. */
  29070. void copyCoefficientsFrom (const IIRFilter& other) throw();
  29071. protected:
  29072. CriticalSection processLock;
  29073. void setCoefficients (double c1, double c2, double c3,
  29074. double c4, double c5, double c6) throw();
  29075. bool active;
  29076. float coefficients[6];
  29077. float x1, x2, y1, y2;
  29078. // (use the copyCoefficientsFrom() method instead of this operator)
  29079. IIRFilter& operator= (const IIRFilter&);
  29080. JUCE_LEAK_DETECTOR (IIRFilter);
  29081. };
  29082. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  29083. /*** End of inlined file: juce_IIRFilter.h ***/
  29084. /**
  29085. An AudioSource that performs an IIR filter on another source.
  29086. */
  29087. class JUCE_API IIRFilterAudioSource : public AudioSource
  29088. {
  29089. public:
  29090. /** Creates a IIRFilterAudioSource for a given input source.
  29091. @param inputSource the input source to read from
  29092. @param deleteInputWhenDeleted if true, the input source will be deleted when
  29093. this object is deleted
  29094. */
  29095. IIRFilterAudioSource (AudioSource* inputSource,
  29096. bool deleteInputWhenDeleted);
  29097. /** Destructor. */
  29098. ~IIRFilterAudioSource();
  29099. /** Changes the filter to use the same parameters as the one being passed in.
  29100. */
  29101. void setFilterParameters (const IIRFilter& newSettings);
  29102. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29103. void releaseResources();
  29104. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29105. private:
  29106. AudioSource* const input;
  29107. const bool deleteInputWhenDeleted;
  29108. OwnedArray <IIRFilter> iirFilters;
  29109. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IIRFilterAudioSource);
  29110. };
  29111. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29112. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  29113. #endif
  29114. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29115. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  29116. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29117. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29118. /**
  29119. An AudioSource that mixes together the output of a set of other AudioSources.
  29120. Input sources can be added and removed while the mixer is running as long as their
  29121. prepareToPlay() and releaseResources() methods are called before and after adding
  29122. them to the mixer.
  29123. */
  29124. class JUCE_API MixerAudioSource : public AudioSource
  29125. {
  29126. public:
  29127. /** Creates a MixerAudioSource.
  29128. */
  29129. MixerAudioSource();
  29130. /** Destructor. */
  29131. ~MixerAudioSource();
  29132. /** Adds an input source to the mixer.
  29133. If the mixer is running you'll need to make sure that the input source
  29134. is ready to play by calling its prepareToPlay() method before adding it.
  29135. If the mixer is stopped, then its input sources will be automatically
  29136. prepared when the mixer's prepareToPlay() method is called.
  29137. @param newInput the source to add to the mixer
  29138. @param deleteWhenRemoved if true, then this source will be deleted when
  29139. the mixer is deleted or when removeAllInputs() is
  29140. called (unless the source is previously removed
  29141. with the removeInputSource method)
  29142. */
  29143. void addInputSource (AudioSource* newInput, bool deleteWhenRemoved);
  29144. /** Removes an input source.
  29145. If the mixer is running, this will remove the source but not call its
  29146. releaseResources() method, so the caller might want to do this manually.
  29147. @param input the source to remove
  29148. @param deleteSource whether to delete this source after it's been removed
  29149. */
  29150. void removeInputSource (AudioSource* input, bool deleteSource);
  29151. /** Removes all the input sources.
  29152. If the mixer is running, this will remove the sources but not call their
  29153. releaseResources() method, so the caller might want to do this manually.
  29154. Any sources which were added with the deleteWhenRemoved flag set will be
  29155. deleted by this method.
  29156. */
  29157. void removeAllInputs();
  29158. /** Implementation of the AudioSource method.
  29159. This will call prepareToPlay() on all its input sources.
  29160. */
  29161. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29162. /** Implementation of the AudioSource method.
  29163. This will call releaseResources() on all its input sources.
  29164. */
  29165. void releaseResources();
  29166. /** Implementation of the AudioSource method. */
  29167. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29168. private:
  29169. Array <AudioSource*> inputs;
  29170. BigInteger inputsToDelete;
  29171. CriticalSection lock;
  29172. AudioSampleBuffer tempBuffer;
  29173. double currentSampleRate;
  29174. int bufferSizeExpected;
  29175. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MixerAudioSource);
  29176. };
  29177. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29178. /*** End of inlined file: juce_MixerAudioSource.h ***/
  29179. #endif
  29180. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29181. #endif
  29182. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29183. #endif
  29184. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29185. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  29186. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29187. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29188. /**
  29189. A simple AudioSource that generates a sine wave.
  29190. */
  29191. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  29192. {
  29193. public:
  29194. /** Creates a ToneGeneratorAudioSource. */
  29195. ToneGeneratorAudioSource();
  29196. /** Destructor. */
  29197. ~ToneGeneratorAudioSource();
  29198. /** Sets the signal's amplitude. */
  29199. void setAmplitude (float newAmplitude);
  29200. /** Sets the signal's frequency. */
  29201. void setFrequency (double newFrequencyHz);
  29202. /** Implementation of the AudioSource method. */
  29203. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29204. /** Implementation of the AudioSource method. */
  29205. void releaseResources();
  29206. /** Implementation of the AudioSource method. */
  29207. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29208. private:
  29209. double frequency, sampleRate;
  29210. double currentPhase, phasePerSample;
  29211. float amplitude;
  29212. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToneGeneratorAudioSource);
  29213. };
  29214. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29215. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  29216. #endif
  29217. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  29218. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  29219. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  29220. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  29221. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  29222. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  29223. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  29224. class AudioDeviceManager;
  29225. class Component;
  29226. /**
  29227. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  29228. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  29229. method. Each of the objects returned can then be used to list the available
  29230. devices of that type. E.g.
  29231. @code
  29232. OwnedArray <AudioIODeviceType> types;
  29233. myAudioDeviceManager.createAudioDeviceTypes (types);
  29234. for (int i = 0; i < types.size(); ++i)
  29235. {
  29236. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  29237. types[i]->scanForDevices(); // This must be called before getting the list of devices
  29238. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  29239. for (int j = 0; j < deviceNames.size(); ++j)
  29240. {
  29241. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  29242. ...
  29243. }
  29244. }
  29245. @endcode
  29246. For an easier way of managing audio devices and their settings, have a look at the
  29247. AudioDeviceManager class.
  29248. @see AudioIODevice, AudioDeviceManager
  29249. */
  29250. class JUCE_API AudioIODeviceType
  29251. {
  29252. public:
  29253. /** Returns the name of this type of driver that this object manages.
  29254. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  29255. */
  29256. const String& getTypeName() const throw() { return typeName; }
  29257. /** Refreshes the object's cached list of known devices.
  29258. This must be called at least once before calling getDeviceNames() or any of
  29259. the other device creation methods.
  29260. */
  29261. virtual void scanForDevices() = 0;
  29262. /** Returns the list of available devices of this type.
  29263. The scanForDevices() method must have been called to create this list.
  29264. @param wantInputNames only really used by DirectSound where devices are split up
  29265. into inputs and outputs, this indicates whether to use
  29266. the input or output name to refer to a pair of devices.
  29267. */
  29268. virtual const StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  29269. /** Returns the name of the default device.
  29270. This will be one of the names from the getDeviceNames() list.
  29271. @param forInput if true, this means that a default input device should be
  29272. returned; if false, it should return the default output
  29273. */
  29274. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  29275. /** Returns the index of a given device in the list of device names.
  29276. If asInput is true, it shows the index in the inputs list, otherwise it
  29277. looks for it in the outputs list.
  29278. */
  29279. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  29280. /** Returns true if two different devices can be used for the input and output.
  29281. */
  29282. virtual bool hasSeparateInputsAndOutputs() const = 0;
  29283. /** Creates one of the devices of this type.
  29284. The deviceName must be one of the strings returned by getDeviceNames(), and
  29285. scanForDevices() must have been called before this method is used.
  29286. */
  29287. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  29288. const String& inputDeviceName) = 0;
  29289. struct DeviceSetupDetails
  29290. {
  29291. AudioDeviceManager* manager;
  29292. int minNumInputChannels, maxNumInputChannels;
  29293. int minNumOutputChannels, maxNumOutputChannels;
  29294. bool useStereoPairs;
  29295. };
  29296. /** Destructor. */
  29297. virtual ~AudioIODeviceType();
  29298. /** Creates a CoreAudio device type if it's available on this platform, or returns null. */
  29299. static AudioIODeviceType* createAudioIODeviceType_CoreAudio();
  29300. /** Creates an iOS device type if it's available on this platform, or returns null. */
  29301. static AudioIODeviceType* createAudioIODeviceType_iOSAudio();
  29302. /** Creates a WASAPI device type if it's available on this platform, or returns null. */
  29303. static AudioIODeviceType* createAudioIODeviceType_WASAPI();
  29304. /** Creates a DirectSound device type if it's available on this platform, or returns null. */
  29305. static AudioIODeviceType* createAudioIODeviceType_DirectSound();
  29306. /** Creates an ASIO device type if it's available on this platform, or returns null. */
  29307. static AudioIODeviceType* createAudioIODeviceType_ASIO();
  29308. /** Creates an ALSA device type if it's available on this platform, or returns null. */
  29309. static AudioIODeviceType* createAudioIODeviceType_ALSA();
  29310. /** Creates a JACK device type if it's available on this platform, or returns null. */
  29311. static AudioIODeviceType* createAudioIODeviceType_JACK();
  29312. protected:
  29313. explicit AudioIODeviceType (const String& typeName);
  29314. private:
  29315. String typeName;
  29316. JUCE_DECLARE_NON_COPYABLE (AudioIODeviceType);
  29317. };
  29318. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  29319. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  29320. /*** Start of inlined file: juce_MidiInput.h ***/
  29321. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  29322. #define __JUCE_MIDIINPUT_JUCEHEADER__
  29323. /*** Start of inlined file: juce_MidiMessage.h ***/
  29324. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  29325. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  29326. /**
  29327. Encapsulates a MIDI message.
  29328. @see MidiMessageSequence, MidiOutput, MidiInput
  29329. */
  29330. class JUCE_API MidiMessage
  29331. {
  29332. public:
  29333. /** Creates a 3-byte short midi message.
  29334. @param byte1 message byte 1
  29335. @param byte2 message byte 2
  29336. @param byte3 message byte 3
  29337. @param timeStamp the time to give the midi message - this value doesn't
  29338. use any particular units, so will be application-specific
  29339. */
  29340. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) throw();
  29341. /** Creates a 2-byte short midi message.
  29342. @param byte1 message byte 1
  29343. @param byte2 message byte 2
  29344. @param timeStamp the time to give the midi message - this value doesn't
  29345. use any particular units, so will be application-specific
  29346. */
  29347. MidiMessage (int byte1, int byte2, double timeStamp = 0) throw();
  29348. /** Creates a 1-byte short midi message.
  29349. @param byte1 message byte 1
  29350. @param timeStamp the time to give the midi message - this value doesn't
  29351. use any particular units, so will be application-specific
  29352. */
  29353. MidiMessage (int byte1, double timeStamp = 0) throw();
  29354. /** Creates a midi message from a block of data. */
  29355. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  29356. /** Reads the next midi message from some data.
  29357. This will read as many bytes from a data stream as it needs to make a
  29358. complete message, and will return the number of bytes it used. This lets
  29359. you read a sequence of midi messages from a file or stream.
  29360. @param data the data to read from
  29361. @param maxBytesToUse the maximum number of bytes it's allowed to read
  29362. @param numBytesUsed returns the number of bytes that were actually needed
  29363. @param lastStatusByte in a sequence of midi messages, the initial byte
  29364. can be dropped from a message if it's the same as the
  29365. first byte of the previous message, so this lets you
  29366. supply the byte to use if the first byte of the message
  29367. has in fact been dropped.
  29368. @param timeStamp the time to give the midi message - this value doesn't
  29369. use any particular units, so will be application-specific
  29370. */
  29371. MidiMessage (const void* data, int maxBytesToUse,
  29372. int& numBytesUsed, uint8 lastStatusByte,
  29373. double timeStamp = 0);
  29374. /** Creates an active-sense message.
  29375. Since the MidiMessage has to contain a valid message, this default constructor
  29376. just initialises it with an empty sysex message.
  29377. */
  29378. MidiMessage() throw();
  29379. /** Creates a copy of another midi message. */
  29380. MidiMessage (const MidiMessage& other);
  29381. /** Creates a copy of another midi message, with a different timestamp. */
  29382. MidiMessage (const MidiMessage& other, double newTimeStamp);
  29383. /** Destructor. */
  29384. ~MidiMessage();
  29385. /** Copies this message from another one. */
  29386. MidiMessage& operator= (const MidiMessage& other);
  29387. /** Returns a pointer to the raw midi data.
  29388. @see getRawDataSize
  29389. */
  29390. uint8* getRawData() const throw() { return data; }
  29391. /** Returns the number of bytes of data in the message.
  29392. @see getRawData
  29393. */
  29394. int getRawDataSize() const throw() { return size; }
  29395. /** Returns the timestamp associated with this message.
  29396. The exact meaning of this time and its units will vary, as messages are used in
  29397. a variety of different contexts.
  29398. If you're getting the message from a midi file, this could be a time in seconds, or
  29399. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  29400. If the message is being used in a MidiBuffer, it might indicate the number of
  29401. audio samples from the start of the buffer.
  29402. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  29403. for details of the way that it initialises this value.
  29404. @see setTimeStamp, addToTimeStamp
  29405. */
  29406. double getTimeStamp() const throw() { return timeStamp; }
  29407. /** Changes the message's associated timestamp.
  29408. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  29409. @see addToTimeStamp, getTimeStamp
  29410. */
  29411. void setTimeStamp (double newTimestamp) throw() { timeStamp = newTimestamp; }
  29412. /** Adds a value to the message's timestamp.
  29413. The units for the timestamp will be application-specific.
  29414. */
  29415. void addToTimeStamp (double delta) throw() { timeStamp += delta; }
  29416. /** Returns the midi channel associated with the message.
  29417. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  29418. if it's a sysex)
  29419. @see isForChannel, setChannel
  29420. */
  29421. int getChannel() const throw();
  29422. /** Returns true if the message applies to the given midi channel.
  29423. @param channelNumber the channel number to look for, in the range 1 to 16
  29424. @see getChannel, setChannel
  29425. */
  29426. bool isForChannel (int channelNumber) const throw();
  29427. /** Changes the message's midi channel.
  29428. This won't do anything for non-channel messages like sysexes.
  29429. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  29430. */
  29431. void setChannel (int newChannelNumber) throw();
  29432. /** Returns true if this is a system-exclusive message.
  29433. */
  29434. bool isSysEx() const throw();
  29435. /** Returns a pointer to the sysex data inside the message.
  29436. If this event isn't a sysex event, it'll return 0.
  29437. @see getSysExDataSize
  29438. */
  29439. const uint8* getSysExData() const throw();
  29440. /** Returns the size of the sysex data.
  29441. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  29442. @see getSysExData
  29443. */
  29444. int getSysExDataSize() const throw();
  29445. /** Returns true if this message is a 'key-down' event.
  29446. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  29447. velocity 0, it will still be considered to be a note-on and the
  29448. method will return true. If returnTrueForVelocity0 is false, then
  29449. if this is a note-on event with velocity 0, it'll be regarded as
  29450. a note-off, and the method will return false
  29451. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  29452. */
  29453. bool isNoteOn (bool returnTrueForVelocity0 = false) const throw();
  29454. /** Creates a key-down message (using a floating-point velocity).
  29455. @param channel the midi channel, in the range 1 to 16
  29456. @param noteNumber the key number, 0 to 127
  29457. @param velocity in the range 0 to 1.0
  29458. @see isNoteOn
  29459. */
  29460. static const MidiMessage noteOn (int channel, int noteNumber, float velocity) throw();
  29461. /** Creates a key-down message (using an integer velocity).
  29462. @param channel the midi channel, in the range 1 to 16
  29463. @param noteNumber the key number, 0 to 127
  29464. @param velocity in the range 0 to 127
  29465. @see isNoteOn
  29466. */
  29467. static const MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) throw();
  29468. /** Returns true if this message is a 'key-up' event.
  29469. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  29470. for a note-on event with a velocity of 0.
  29471. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  29472. */
  29473. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const throw();
  29474. /** Creates a key-up message.
  29475. @param channel the midi channel, in the range 1 to 16
  29476. @param noteNumber the key number, 0 to 127
  29477. @see isNoteOff
  29478. */
  29479. static const MidiMessage noteOff (int channel, int noteNumber, uint8 velocity = 0) throw();
  29480. /** Returns true if this message is a 'key-down' or 'key-up' event.
  29481. @see isNoteOn, isNoteOff
  29482. */
  29483. bool isNoteOnOrOff() const throw();
  29484. /** Returns the midi note number for note-on and note-off messages.
  29485. If the message isn't a note-on or off, the value returned will be
  29486. meaningless.
  29487. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  29488. */
  29489. int getNoteNumber() const throw();
  29490. /** Changes the midi note number of a note-on or note-off message.
  29491. If the message isn't a note on or off, this will do nothing.
  29492. */
  29493. void setNoteNumber (int newNoteNumber) throw();
  29494. /** Returns the velocity of a note-on or note-off message.
  29495. The value returned will be in the range 0 to 127.
  29496. If the message isn't a note-on or off event, it will return 0.
  29497. @see getFloatVelocity
  29498. */
  29499. uint8 getVelocity() const throw();
  29500. /** Returns the velocity of a note-on or note-off message.
  29501. The value returned will be in the range 0 to 1.0
  29502. If the message isn't a note-on or off event, it will return 0.
  29503. @see getVelocity, setVelocity
  29504. */
  29505. float getFloatVelocity() const throw();
  29506. /** Changes the velocity of a note-on or note-off message.
  29507. If the message isn't a note on or off, this will do nothing.
  29508. @param newVelocity the new velocity, in the range 0 to 1.0
  29509. @see getFloatVelocity, multiplyVelocity
  29510. */
  29511. void setVelocity (float newVelocity) throw();
  29512. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  29513. If the message isn't a note on or off, this will do nothing.
  29514. @param scaleFactor the value by which to multiply the velocity
  29515. @see setVelocity
  29516. */
  29517. void multiplyVelocity (float scaleFactor) throw();
  29518. /** Returns true if the message is a program (patch) change message.
  29519. @see getProgramChangeNumber, getGMInstrumentName
  29520. */
  29521. bool isProgramChange() const throw();
  29522. /** Returns the new program number of a program change message.
  29523. If the message isn't a program change, the value returned will be
  29524. nonsense.
  29525. @see isProgramChange, getGMInstrumentName
  29526. */
  29527. int getProgramChangeNumber() const throw();
  29528. /** Creates a program-change message.
  29529. @param channel the midi channel, in the range 1 to 16
  29530. @param programNumber the midi program number, 0 to 127
  29531. @see isProgramChange, getGMInstrumentName
  29532. */
  29533. static const MidiMessage programChange (int channel, int programNumber) throw();
  29534. /** Returns true if the message is a pitch-wheel move.
  29535. @see getPitchWheelValue, pitchWheel
  29536. */
  29537. bool isPitchWheel() const throw();
  29538. /** Returns the pitch wheel position from a pitch-wheel move message.
  29539. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  29540. If called for messages which aren't pitch wheel events, the number returned will be
  29541. nonsense.
  29542. @see isPitchWheel
  29543. */
  29544. int getPitchWheelValue() const throw();
  29545. /** Creates a pitch-wheel move message.
  29546. @param channel the midi channel, in the range 1 to 16
  29547. @param position the wheel position, in the range 0 to 16383
  29548. @see isPitchWheel
  29549. */
  29550. static const MidiMessage pitchWheel (int channel, int position) throw();
  29551. /** Returns true if the message is an aftertouch event.
  29552. For aftertouch events, use the getNoteNumber() method to find out the key
  29553. that it applies to, and getAftertouchValue() to find out the amount. Use
  29554. getChannel() to find out the channel.
  29555. @see getAftertouchValue, getNoteNumber
  29556. */
  29557. bool isAftertouch() const throw();
  29558. /** Returns the amount of aftertouch from an aftertouch messages.
  29559. The value returned is in the range 0 to 127, and will be nonsense for messages
  29560. other than aftertouch messages.
  29561. @see isAftertouch
  29562. */
  29563. int getAfterTouchValue() const throw();
  29564. /** Creates an aftertouch message.
  29565. @param channel the midi channel, in the range 1 to 16
  29566. @param noteNumber the key number, 0 to 127
  29567. @param aftertouchAmount the amount of aftertouch, 0 to 127
  29568. @see isAftertouch
  29569. */
  29570. static const MidiMessage aftertouchChange (int channel,
  29571. int noteNumber,
  29572. int aftertouchAmount) throw();
  29573. /** Returns true if the message is a channel-pressure change event.
  29574. This is like aftertouch, but common to the whole channel rather than a specific
  29575. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  29576. to find out the channel.
  29577. @see channelPressureChange
  29578. */
  29579. bool isChannelPressure() const throw();
  29580. /** Returns the pressure from a channel pressure change message.
  29581. @returns the pressure, in the range 0 to 127
  29582. @see isChannelPressure, channelPressureChange
  29583. */
  29584. int getChannelPressureValue() const throw();
  29585. /** Creates a channel-pressure change event.
  29586. @param channel the midi channel: 1 to 16
  29587. @param pressure the pressure, 0 to 127
  29588. @see isChannelPressure
  29589. */
  29590. static const MidiMessage channelPressureChange (int channel, int pressure) throw();
  29591. /** Returns true if this is a midi controller message.
  29592. @see getControllerNumber, getControllerValue, controllerEvent
  29593. */
  29594. bool isController() const throw();
  29595. /** Returns the controller number of a controller message.
  29596. The name of the controller can be looked up using the getControllerName() method.
  29597. Note that the value returned is invalid for messages that aren't controller changes.
  29598. @see isController, getControllerName, getControllerValue
  29599. */
  29600. int getControllerNumber() const throw();
  29601. /** Returns the controller value from a controller message.
  29602. A value 0 to 127 is returned to indicate the new controller position.
  29603. Note that the value returned is invalid for messages that aren't controller changes.
  29604. @see isController, getControllerNumber
  29605. */
  29606. int getControllerValue() const throw();
  29607. /** Creates a controller message.
  29608. @param channel the midi channel, in the range 1 to 16
  29609. @param controllerType the type of controller
  29610. @param value the controller value
  29611. @see isController
  29612. */
  29613. static const MidiMessage controllerEvent (int channel,
  29614. int controllerType,
  29615. int value) throw();
  29616. /** Checks whether this message is an all-notes-off message.
  29617. @see allNotesOff
  29618. */
  29619. bool isAllNotesOff() const throw();
  29620. /** Checks whether this message is an all-sound-off message.
  29621. @see allSoundOff
  29622. */
  29623. bool isAllSoundOff() const throw();
  29624. /** Creates an all-notes-off message.
  29625. @param channel the midi channel, in the range 1 to 16
  29626. @see isAllNotesOff
  29627. */
  29628. static const MidiMessage allNotesOff (int channel) throw();
  29629. /** Creates an all-sound-off message.
  29630. @param channel the midi channel, in the range 1 to 16
  29631. @see isAllSoundOff
  29632. */
  29633. static const MidiMessage allSoundOff (int channel) throw();
  29634. /** Creates an all-controllers-off message.
  29635. @param channel the midi channel, in the range 1 to 16
  29636. */
  29637. static const MidiMessage allControllersOff (int channel) throw();
  29638. /** Returns true if this event is a meta-event.
  29639. Meta-events are things like tempo changes, track names, etc.
  29640. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  29641. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  29642. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  29643. */
  29644. bool isMetaEvent() const throw();
  29645. /** Returns a meta-event's type number.
  29646. If the message isn't a meta-event, this will return -1.
  29647. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  29648. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  29649. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  29650. */
  29651. int getMetaEventType() const throw();
  29652. /** Returns a pointer to the data in a meta-event.
  29653. @see isMetaEvent, getMetaEventLength
  29654. */
  29655. const uint8* getMetaEventData() const throw();
  29656. /** Returns the length of the data for a meta-event.
  29657. @see isMetaEvent, getMetaEventData
  29658. */
  29659. int getMetaEventLength() const throw();
  29660. /** Returns true if this is a 'track' meta-event. */
  29661. bool isTrackMetaEvent() const throw();
  29662. /** Returns true if this is an 'end-of-track' meta-event. */
  29663. bool isEndOfTrackMetaEvent() const throw();
  29664. /** Creates an end-of-track meta-event.
  29665. @see isEndOfTrackMetaEvent
  29666. */
  29667. static const MidiMessage endOfTrack() throw();
  29668. /** Returns true if this is an 'track name' meta-event.
  29669. You can use the getTextFromTextMetaEvent() method to get the track's name.
  29670. */
  29671. bool isTrackNameEvent() const throw();
  29672. /** Returns true if this is a 'text' meta-event.
  29673. @see getTextFromTextMetaEvent
  29674. */
  29675. bool isTextMetaEvent() const throw();
  29676. /** Returns the text from a text meta-event.
  29677. @see isTextMetaEvent
  29678. */
  29679. const String getTextFromTextMetaEvent() const;
  29680. /** Returns true if this is a 'tempo' meta-event.
  29681. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  29682. */
  29683. bool isTempoMetaEvent() const throw();
  29684. /** Returns the tick length from a tempo meta-event.
  29685. @param timeFormat the 16-bit time format value from the midi file's header.
  29686. @returns the tick length (in seconds).
  29687. @see isTempoMetaEvent
  29688. */
  29689. double getTempoMetaEventTickLength (short timeFormat) const throw();
  29690. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  29691. @see isTempoMetaEvent, getTempoMetaEventTickLength
  29692. */
  29693. double getTempoSecondsPerQuarterNote() const throw();
  29694. /** Creates a tempo meta-event.
  29695. @see isTempoMetaEvent
  29696. */
  29697. static const MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) throw();
  29698. /** Returns true if this is a 'time-signature' meta-event.
  29699. @see getTimeSignatureInfo
  29700. */
  29701. bool isTimeSignatureMetaEvent() const throw();
  29702. /** Returns the time-signature values from a time-signature meta-event.
  29703. @see isTimeSignatureMetaEvent
  29704. */
  29705. void getTimeSignatureInfo (int& numerator, int& denominator) const throw();
  29706. /** Creates a time-signature meta-event.
  29707. @see isTimeSignatureMetaEvent
  29708. */
  29709. static const MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  29710. /** Returns true if this is a 'key-signature' meta-event.
  29711. @see getKeySignatureNumberOfSharpsOrFlats
  29712. */
  29713. bool isKeySignatureMetaEvent() const throw();
  29714. /** Returns the key from a key-signature meta-event.
  29715. @see isKeySignatureMetaEvent
  29716. */
  29717. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  29718. /** Returns true if this is a 'channel' meta-event.
  29719. A channel meta-event specifies the midi channel that should be used
  29720. for subsequent meta-events.
  29721. @see getMidiChannelMetaEventChannel
  29722. */
  29723. bool isMidiChannelMetaEvent() const throw();
  29724. /** Returns the channel number from a channel meta-event.
  29725. @returns the channel, in the range 1 to 16.
  29726. @see isMidiChannelMetaEvent
  29727. */
  29728. int getMidiChannelMetaEventChannel() const throw();
  29729. /** Creates a midi channel meta-event.
  29730. @param channel the midi channel, in the range 1 to 16
  29731. @see isMidiChannelMetaEvent
  29732. */
  29733. static const MidiMessage midiChannelMetaEvent (int channel) throw();
  29734. /** Returns true if this is an active-sense message. */
  29735. bool isActiveSense() const throw();
  29736. /** Returns true if this is a midi start event.
  29737. @see midiStart
  29738. */
  29739. bool isMidiStart() const throw();
  29740. /** Creates a midi start event. */
  29741. static const MidiMessage midiStart() throw();
  29742. /** Returns true if this is a midi continue event.
  29743. @see midiContinue
  29744. */
  29745. bool isMidiContinue() const throw();
  29746. /** Creates a midi continue event. */
  29747. static const MidiMessage midiContinue() throw();
  29748. /** Returns true if this is a midi stop event.
  29749. @see midiStop
  29750. */
  29751. bool isMidiStop() const throw();
  29752. /** Creates a midi stop event. */
  29753. static const MidiMessage midiStop() throw();
  29754. /** Returns true if this is a midi clock event.
  29755. @see midiClock, songPositionPointer
  29756. */
  29757. bool isMidiClock() const throw();
  29758. /** Creates a midi clock event. */
  29759. static const MidiMessage midiClock() throw();
  29760. /** Returns true if this is a song-position-pointer message.
  29761. @see getSongPositionPointerMidiBeat, songPositionPointer
  29762. */
  29763. bool isSongPositionPointer() const throw();
  29764. /** Returns the midi beat-number of a song-position-pointer message.
  29765. @see isSongPositionPointer, songPositionPointer
  29766. */
  29767. int getSongPositionPointerMidiBeat() const throw();
  29768. /** Creates a song-position-pointer message.
  29769. The position is a number of midi beats from the start of the song, where 1 midi
  29770. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  29771. are 4 midi beats in a quarter-note.
  29772. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  29773. */
  29774. static const MidiMessage songPositionPointer (int positionInMidiBeats) throw();
  29775. /** Returns true if this is a quarter-frame midi timecode message.
  29776. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  29777. */
  29778. bool isQuarterFrame() const throw();
  29779. /** Returns the sequence number of a quarter-frame midi timecode message.
  29780. This will be a value between 0 and 7.
  29781. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  29782. */
  29783. int getQuarterFrameSequenceNumber() const throw();
  29784. /** Returns the value from a quarter-frame message.
  29785. This will be the lower nybble of the message's data-byte, a value
  29786. between 0 and 15
  29787. */
  29788. int getQuarterFrameValue() const throw();
  29789. /** Creates a quarter-frame MTC message.
  29790. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  29791. @param value a value 0 to 15 for the lower nybble of the message's data byte
  29792. */
  29793. static const MidiMessage quarterFrame (int sequenceNumber, int value) throw();
  29794. /** SMPTE timecode types.
  29795. Used by the getFullFrameParameters() and fullFrame() methods.
  29796. */
  29797. enum SmpteTimecodeType
  29798. {
  29799. fps24 = 0,
  29800. fps25 = 1,
  29801. fps30drop = 2,
  29802. fps30 = 3
  29803. };
  29804. /** Returns true if this is a full-frame midi timecode message.
  29805. */
  29806. bool isFullFrame() const throw();
  29807. /** Extracts the timecode information from a full-frame midi timecode message.
  29808. You should only call this on messages where you've used isFullFrame() to
  29809. check that they're the right kind.
  29810. */
  29811. void getFullFrameParameters (int& hours,
  29812. int& minutes,
  29813. int& seconds,
  29814. int& frames,
  29815. SmpteTimecodeType& timecodeType) const throw();
  29816. /** Creates a full-frame MTC message.
  29817. */
  29818. static const MidiMessage fullFrame (int hours,
  29819. int minutes,
  29820. int seconds,
  29821. int frames,
  29822. SmpteTimecodeType timecodeType);
  29823. /** Types of MMC command.
  29824. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  29825. */
  29826. enum MidiMachineControlCommand
  29827. {
  29828. mmc_stop = 1,
  29829. mmc_play = 2,
  29830. mmc_deferredplay = 3,
  29831. mmc_fastforward = 4,
  29832. mmc_rewind = 5,
  29833. mmc_recordStart = 6,
  29834. mmc_recordStop = 7,
  29835. mmc_pause = 9
  29836. };
  29837. /** Checks whether this is an MMC message.
  29838. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  29839. */
  29840. bool isMidiMachineControlMessage() const throw();
  29841. /** For an MMC message, this returns its type.
  29842. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  29843. calling this method.
  29844. */
  29845. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  29846. /** Creates an MMC message.
  29847. */
  29848. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  29849. /** Checks whether this is an MMC "goto" message.
  29850. If it is, the parameters passed-in are set to the time that the message contains.
  29851. @see midiMachineControlGoto
  29852. */
  29853. bool isMidiMachineControlGoto (int& hours,
  29854. int& minutes,
  29855. int& seconds,
  29856. int& frames) const throw();
  29857. /** Creates an MMC "goto" message.
  29858. This messages tells the device to go to a specific frame.
  29859. @see isMidiMachineControlGoto
  29860. */
  29861. static const MidiMessage midiMachineControlGoto (int hours,
  29862. int minutes,
  29863. int seconds,
  29864. int frames);
  29865. /** Creates a master-volume change message.
  29866. @param volume the volume, 0 to 1.0
  29867. */
  29868. static const MidiMessage masterVolume (float volume);
  29869. /** Creates a system-exclusive message.
  29870. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  29871. */
  29872. static const MidiMessage createSysExMessage (const uint8* sysexData,
  29873. int dataSize);
  29874. /** Reads a midi variable-length integer.
  29875. @param data the data to read the number from
  29876. @param numBytesUsed on return, this will be set to the number of bytes that were read
  29877. */
  29878. static int readVariableLengthVal (const uint8* data,
  29879. int& numBytesUsed) throw();
  29880. /** Based on the first byte of a short midi message, this uses a lookup table
  29881. to return the message length (either 1, 2, or 3 bytes).
  29882. The value passed in must be 0x80 or higher.
  29883. */
  29884. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  29885. /** Returns the name of a midi note number.
  29886. E.g "C", "D#", etc.
  29887. @param noteNumber the midi note number, 0 to 127
  29888. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  29889. they'll be flattened, e.g. "Db"
  29890. @param includeOctaveNumber if true, the octave number will be appended to the string,
  29891. e.g. "C#4"
  29892. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  29893. number that will be used for middle C's octave
  29894. @see getMidiNoteInHertz
  29895. */
  29896. static const String getMidiNoteName (int noteNumber,
  29897. bool useSharps,
  29898. bool includeOctaveNumber,
  29899. int octaveNumForMiddleC);
  29900. /** Returns the frequency of a midi note number.
  29901. The frequencyOfA parameter is an optional frequency for 'A', normally 440-444Hz for concert pitch.
  29902. @see getMidiNoteName
  29903. */
  29904. static const double getMidiNoteInHertz (int noteNumber, const double frequencyOfA = 440.0) throw();
  29905. /** Returns the standard name of a GM instrument.
  29906. @param midiInstrumentNumber the program number 0 to 127
  29907. @see getProgramChangeNumber
  29908. */
  29909. static const String getGMInstrumentName (int midiInstrumentNumber);
  29910. /** Returns the name of a bank of GM instruments.
  29911. @param midiBankNumber the bank, 0 to 15
  29912. */
  29913. static const String getGMInstrumentBankName (int midiBankNumber);
  29914. /** Returns the standard name of a channel 10 percussion sound.
  29915. @param midiNoteNumber the key number, 35 to 81
  29916. */
  29917. static const String getRhythmInstrumentName (int midiNoteNumber);
  29918. /** Returns the name of a controller type number.
  29919. @see getControllerNumber
  29920. */
  29921. static const String getControllerName (int controllerNumber);
  29922. private:
  29923. double timeStamp;
  29924. uint8* data;
  29925. int size;
  29926. #ifndef DOXYGEN
  29927. union
  29928. {
  29929. uint8 asBytes[4];
  29930. uint32 asInt32;
  29931. } preallocatedData;
  29932. #endif
  29933. };
  29934. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  29935. /*** End of inlined file: juce_MidiMessage.h ***/
  29936. class MidiInput;
  29937. /**
  29938. Receives incoming messages from a physical MIDI input device.
  29939. This class is overridden to handle incoming midi messages. See the MidiInput
  29940. class for more details.
  29941. @see MidiInput
  29942. */
  29943. class JUCE_API MidiInputCallback
  29944. {
  29945. public:
  29946. /** Destructor. */
  29947. virtual ~MidiInputCallback() {}
  29948. /** Receives an incoming message.
  29949. A MidiInput object will call this method when a midi event arrives. It'll be
  29950. called on a high-priority system thread, so avoid doing anything time-consuming
  29951. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  29952. for queueing incoming messages for use later.
  29953. @param source the MidiInput object that generated the message
  29954. @param message the incoming message. The message's timestamp is set to a value
  29955. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  29956. time when the message arrived.
  29957. */
  29958. virtual void handleIncomingMidiMessage (MidiInput* source,
  29959. const MidiMessage& message) = 0;
  29960. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  29961. If a long sysex message is broken up into multiple packets, this callback is made
  29962. for each packet that arrives until the message is finished, at which point
  29963. the normal handleIncomingMidiMessage() callback will be made with the entire
  29964. message.
  29965. The message passed in will contain the start of a sysex, but won't be finished
  29966. with the terminating 0xf7 byte.
  29967. */
  29968. virtual void handlePartialSysexMessage (MidiInput* source,
  29969. const uint8* messageData,
  29970. const int numBytesSoFar,
  29971. const double timestamp)
  29972. {
  29973. // (this bit is just to avoid compiler warnings about unused variables)
  29974. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  29975. }
  29976. };
  29977. /**
  29978. Represents a midi input device.
  29979. To create one of these, use the static getDevices() method to find out what inputs are
  29980. available, and then use the openDevice() method to try to open one.
  29981. @see MidiOutput
  29982. */
  29983. class JUCE_API MidiInput
  29984. {
  29985. public:
  29986. /** Returns a list of the available midi input devices.
  29987. You can open one of the devices by passing its index into the
  29988. openDevice() method.
  29989. @see getDefaultDeviceIndex, openDevice
  29990. */
  29991. static const StringArray getDevices();
  29992. /** Returns the index of the default midi input device to use.
  29993. This refers to the index in the list returned by getDevices().
  29994. */
  29995. static int getDefaultDeviceIndex();
  29996. /** Tries to open one of the midi input devices.
  29997. This will return a MidiInput object if it manages to open it. You can then
  29998. call start() and stop() on this device, and delete it when no longer needed.
  29999. If the device can't be opened, this will return a null pointer.
  30000. @param deviceIndex the index of a device from the list returned by getDevices()
  30001. @param callback the object that will receive the midi messages from this device.
  30002. @see MidiInputCallback, getDevices
  30003. */
  30004. static MidiInput* openDevice (int deviceIndex,
  30005. MidiInputCallback* callback);
  30006. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  30007. /** This will try to create a new midi input device (Not available on Windows).
  30008. This will attempt to create a new midi input device with the specified name,
  30009. for other apps to connect to.
  30010. Returns 0 if a device can't be created.
  30011. @param deviceName the name to use for the new device
  30012. @param callback the object that will receive the midi messages from this device.
  30013. */
  30014. static MidiInput* createNewDevice (const String& deviceName,
  30015. MidiInputCallback* callback);
  30016. #endif
  30017. /** Destructor. */
  30018. virtual ~MidiInput();
  30019. /** Returns the name of this device.
  30020. */
  30021. virtual const String getName() const throw() { return name; }
  30022. /** Allows you to set a custom name for the device, in case you don't like the name
  30023. it was given when created.
  30024. */
  30025. virtual void setName (const String& newName) throw() { name = newName; }
  30026. /** Starts the device running.
  30027. After calling this, the device will start sending midi messages to the
  30028. MidiInputCallback object that was specified when the openDevice() method
  30029. was called.
  30030. @see stop
  30031. */
  30032. virtual void start();
  30033. /** Stops the device running.
  30034. @see start
  30035. */
  30036. virtual void stop();
  30037. protected:
  30038. String name;
  30039. void* internal;
  30040. explicit MidiInput (const String& name);
  30041. private:
  30042. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInput);
  30043. };
  30044. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  30045. /*** End of inlined file: juce_MidiInput.h ***/
  30046. /*** Start of inlined file: juce_MidiOutput.h ***/
  30047. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  30048. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  30049. /*** Start of inlined file: juce_MidiBuffer.h ***/
  30050. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  30051. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  30052. /**
  30053. Holds a sequence of time-stamped midi events.
  30054. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  30055. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  30056. @see MidiMessage
  30057. */
  30058. class JUCE_API MidiBuffer
  30059. {
  30060. public:
  30061. /** Creates an empty MidiBuffer. */
  30062. MidiBuffer() throw();
  30063. /** Creates a MidiBuffer containing a single midi message. */
  30064. explicit MidiBuffer (const MidiMessage& message) throw();
  30065. /** Creates a copy of another MidiBuffer. */
  30066. MidiBuffer (const MidiBuffer& other) throw();
  30067. /** Makes a copy of another MidiBuffer. */
  30068. MidiBuffer& operator= (const MidiBuffer& other) throw();
  30069. /** Destructor */
  30070. ~MidiBuffer();
  30071. /** Removes all events from the buffer. */
  30072. void clear() throw();
  30073. /** Removes all events between two times from the buffer.
  30074. All events for which (start <= event position < start + numSamples) will
  30075. be removed.
  30076. */
  30077. void clear (int start, int numSamples);
  30078. /** Returns true if the buffer is empty.
  30079. To actually retrieve the events, use a MidiBuffer::Iterator object
  30080. */
  30081. bool isEmpty() const throw();
  30082. /** Counts the number of events in the buffer.
  30083. This is actually quite a slow operation, as it has to iterate through all
  30084. the events, so you might prefer to call isEmpty() if that's all you need
  30085. to know.
  30086. */
  30087. int getNumEvents() const throw();
  30088. /** Adds an event to the buffer.
  30089. The sample number will be used to determine the position of the event in
  30090. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  30091. ignored.
  30092. If an event is added whose sample position is the same as one or more events
  30093. already in the buffer, the new event will be placed after the existing ones.
  30094. To retrieve events, use a MidiBuffer::Iterator object
  30095. */
  30096. void addEvent (const MidiMessage& midiMessage, int sampleNumber);
  30097. /** Adds an event to the buffer from raw midi data.
  30098. The sample number will be used to determine the position of the event in
  30099. the buffer, which is always kept sorted.
  30100. If an event is added whose sample position is the same as one or more events
  30101. already in the buffer, the new event will be placed after the existing ones.
  30102. The event data will be inspected to calculate the number of bytes in length that
  30103. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  30104. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  30105. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  30106. add an event at all.
  30107. To retrieve events, use a MidiBuffer::Iterator object
  30108. */
  30109. void addEvent (const void* rawMidiData,
  30110. int maxBytesOfMidiData,
  30111. int sampleNumber);
  30112. /** Adds some events from another buffer to this one.
  30113. @param otherBuffer the buffer containing the events you want to add
  30114. @param startSample the lowest sample number in the source buffer for which
  30115. events should be added. Any source events whose timestamp is
  30116. less than this will be ignored
  30117. @param numSamples the valid range of samples from the source buffer for which
  30118. events should be added - i.e. events in the source buffer whose
  30119. timestamp is greater than or equal to (startSample + numSamples)
  30120. will be ignored. If this value is less than 0, all events after
  30121. startSample will be taken.
  30122. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  30123. that are added to this buffer
  30124. */
  30125. void addEvents (const MidiBuffer& otherBuffer,
  30126. int startSample,
  30127. int numSamples,
  30128. int sampleDeltaToAdd);
  30129. /** Returns the sample number of the first event in the buffer.
  30130. If the buffer's empty, this will just return 0.
  30131. */
  30132. int getFirstEventTime() const throw();
  30133. /** Returns the sample number of the last event in the buffer.
  30134. If the buffer's empty, this will just return 0.
  30135. */
  30136. int getLastEventTime() const throw();
  30137. /** Exchanges the contents of this buffer with another one.
  30138. This is a quick operation, because no memory allocating or copying is done, it
  30139. just swaps the internal state of the two buffers.
  30140. */
  30141. void swapWith (MidiBuffer& other) throw();
  30142. /** Preallocates some memory for the buffer to use.
  30143. This helps to avoid needing to reallocate space when the buffer has messages
  30144. added to it.
  30145. */
  30146. void ensureSize (size_t minimumNumBytes);
  30147. /**
  30148. Used to iterate through the events in a MidiBuffer.
  30149. Note that altering the buffer while an iterator is using it isn't a
  30150. safe operation.
  30151. @see MidiBuffer
  30152. */
  30153. class JUCE_API Iterator
  30154. {
  30155. public:
  30156. /** Creates an Iterator for this MidiBuffer. */
  30157. Iterator (const MidiBuffer& buffer) throw();
  30158. /** Destructor. */
  30159. ~Iterator() throw();
  30160. /** Repositions the iterator so that the next event retrieved will be the first
  30161. one whose sample position is at greater than or equal to the given position.
  30162. */
  30163. void setNextSamplePosition (int samplePosition) throw();
  30164. /** Retrieves a copy of the next event from the buffer.
  30165. @param result on return, this will be the message (the MidiMessage's timestamp
  30166. is not set)
  30167. @param samplePosition on return, this will be the position of the event
  30168. @returns true if an event was found, or false if the iterator has reached
  30169. the end of the buffer
  30170. */
  30171. bool getNextEvent (MidiMessage& result,
  30172. int& samplePosition) throw();
  30173. /** Retrieves the next event from the buffer.
  30174. @param midiData on return, this pointer will be set to a block of data containing
  30175. the midi message. Note that to make it fast, this is a pointer
  30176. directly into the MidiBuffer's internal data, so is only valid
  30177. temporarily until the MidiBuffer is altered.
  30178. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  30179. midi message
  30180. @param samplePosition on return, this will be the position of the event
  30181. @returns true if an event was found, or false if the iterator has reached
  30182. the end of the buffer
  30183. */
  30184. bool getNextEvent (const uint8* &midiData,
  30185. int& numBytesOfMidiData,
  30186. int& samplePosition) throw();
  30187. private:
  30188. const MidiBuffer& buffer;
  30189. const uint8* data;
  30190. JUCE_DECLARE_NON_COPYABLE (Iterator);
  30191. };
  30192. private:
  30193. friend class MidiBuffer::Iterator;
  30194. MemoryBlock data;
  30195. int bytesUsed;
  30196. uint8* getData() const throw();
  30197. uint8* findEventAfter (uint8* d, int samplePosition) const throw();
  30198. static int getEventTime (const void* d) throw();
  30199. static uint16 getEventDataSize (const void* d) throw();
  30200. static uint16 getEventTotalSize (const void* d) throw();
  30201. JUCE_LEAK_DETECTOR (MidiBuffer);
  30202. };
  30203. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  30204. /*** End of inlined file: juce_MidiBuffer.h ***/
  30205. /**
  30206. Controls a physical MIDI output device.
  30207. To create one of these, use the static getDevices() method to get a list of the
  30208. available output devices, then use the openDevice() method to try to open one.
  30209. @see MidiInput
  30210. */
  30211. class JUCE_API MidiOutput : private Thread
  30212. {
  30213. public:
  30214. /** Returns a list of the available midi output devices.
  30215. You can open one of the devices by passing its index into the
  30216. openDevice() method.
  30217. @see getDefaultDeviceIndex, openDevice
  30218. */
  30219. static const StringArray getDevices();
  30220. /** Returns the index of the default midi output device to use.
  30221. This refers to the index in the list returned by getDevices().
  30222. */
  30223. static int getDefaultDeviceIndex();
  30224. /** Tries to open one of the midi output devices.
  30225. This will return a MidiOutput object if it manages to open it. You can then
  30226. send messages to this device, and delete it when no longer needed.
  30227. If the device can't be opened, this will return a null pointer.
  30228. @param deviceIndex the index of a device from the list returned by getDevices()
  30229. @see getDevices
  30230. */
  30231. static MidiOutput* openDevice (int deviceIndex);
  30232. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  30233. /** This will try to create a new midi output device (Not available on Windows).
  30234. This will attempt to create a new midi output device that other apps can connect
  30235. to and use as their midi input.
  30236. Returns 0 if a device can't be created.
  30237. @param deviceName the name to use for the new device
  30238. */
  30239. static MidiOutput* createNewDevice (const String& deviceName);
  30240. #endif
  30241. /** Destructor. */
  30242. virtual ~MidiOutput();
  30243. /** Makes this device output a midi message.
  30244. @see MidiMessage
  30245. */
  30246. virtual void sendMessageNow (const MidiMessage& message);
  30247. /** Sends a midi reset to the device. */
  30248. virtual void reset();
  30249. /** Returns the current volume setting for this device. */
  30250. virtual bool getVolume (float& leftVol,
  30251. float& rightVol);
  30252. /** Changes the overall volume for this device. */
  30253. virtual void setVolume (float leftVol,
  30254. float rightVol);
  30255. /** This lets you supply a block of messages that will be sent out at some point
  30256. in the future.
  30257. The MidiOutput class has an internal thread that can send out timestamped
  30258. messages - this appends a set of messages to its internal buffer, ready for
  30259. sending.
  30260. This will only work if you've already started the thread with startBackgroundThread().
  30261. A time is supplied, at which the block of messages should be sent. This time uses
  30262. the same time base as Time::getMillisecondCounter(), and must be in the future.
  30263. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  30264. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  30265. samplesPerSecondForBuffer value is needed to convert this sample position to a
  30266. real time.
  30267. */
  30268. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  30269. double millisecondCounterToStartAt,
  30270. double samplesPerSecondForBuffer);
  30271. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  30272. */
  30273. virtual void clearAllPendingMessages();
  30274. /** Starts up a background thread so that the device can send blocks of data.
  30275. Call this to get the device ready, before using sendBlockOfMessages().
  30276. */
  30277. virtual void startBackgroundThread();
  30278. /** Stops the background thread, and clears any pending midi events.
  30279. @see startBackgroundThread
  30280. */
  30281. virtual void stopBackgroundThread();
  30282. protected:
  30283. void* internal;
  30284. struct PendingMessage
  30285. {
  30286. PendingMessage (const void* data, int len, double timeStamp);
  30287. MidiMessage message;
  30288. PendingMessage* next;
  30289. };
  30290. CriticalSection lock;
  30291. PendingMessage* firstMessage;
  30292. MidiOutput();
  30293. void run();
  30294. private:
  30295. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutput);
  30296. };
  30297. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  30298. /*** End of inlined file: juce_MidiOutput.h ***/
  30299. /*** Start of inlined file: juce_ComboBox.h ***/
  30300. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  30301. #define __JUCE_COMBOBOX_JUCEHEADER__
  30302. /*** Start of inlined file: juce_Label.h ***/
  30303. #ifndef __JUCE_LABEL_JUCEHEADER__
  30304. #define __JUCE_LABEL_JUCEHEADER__
  30305. /*** Start of inlined file: juce_TextEditor.h ***/
  30306. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  30307. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  30308. /*** Start of inlined file: juce_Viewport.h ***/
  30309. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  30310. #define __JUCE_VIEWPORT_JUCEHEADER__
  30311. /*** Start of inlined file: juce_ScrollBar.h ***/
  30312. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  30313. #define __JUCE_SCROLLBAR_JUCEHEADER__
  30314. /*** Start of inlined file: juce_Button.h ***/
  30315. #ifndef __JUCE_BUTTON_JUCEHEADER__
  30316. #define __JUCE_BUTTON_JUCEHEADER__
  30317. /*** Start of inlined file: juce_TooltipWindow.h ***/
  30318. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  30319. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  30320. /*** Start of inlined file: juce_TooltipClient.h ***/
  30321. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  30322. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  30323. /**
  30324. Components that want to use pop-up tooltips should implement this interface.
  30325. A TooltipWindow will wait for the mouse to hover over a component that
  30326. implements the TooltipClient interface, and when it finds one, it will display
  30327. the tooltip returned by its getTooltip() method.
  30328. @see TooltipWindow, SettableTooltipClient
  30329. */
  30330. class JUCE_API TooltipClient
  30331. {
  30332. public:
  30333. /** Destructor. */
  30334. virtual ~TooltipClient() {}
  30335. /** Returns the string that this object wants to show as its tooltip. */
  30336. virtual const String getTooltip() = 0;
  30337. };
  30338. /**
  30339. An implementation of TooltipClient that stores the tooltip string and a method
  30340. for changing it.
  30341. This makes it easy to add a tooltip to a custom component, by simply adding this
  30342. as a base class and calling setTooltip().
  30343. Many of the Juce widgets already use this as a base class to implement their
  30344. tooltips.
  30345. @see TooltipClient, TooltipWindow
  30346. */
  30347. class JUCE_API SettableTooltipClient : public TooltipClient
  30348. {
  30349. public:
  30350. /** Destructor. */
  30351. virtual ~SettableTooltipClient() {}
  30352. /** Assigns a new tooltip to this object. */
  30353. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  30354. /** Returns the tooltip assigned to this object. */
  30355. virtual const String getTooltip() { return tooltipString; }
  30356. protected:
  30357. SettableTooltipClient() {}
  30358. private:
  30359. String tooltipString;
  30360. };
  30361. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  30362. /*** End of inlined file: juce_TooltipClient.h ***/
  30363. /**
  30364. A window that displays a pop-up tooltip when the mouse hovers over another component.
  30365. To enable tooltips in your app, just create a single instance of a TooltipWindow
  30366. object.
  30367. The TooltipWindow object will then stay invisible, waiting until the mouse
  30368. hovers for the specified length of time - it will then see if it's currently
  30369. over a component which implements the TooltipClient interface, and if so,
  30370. it will make itself visible to show the tooltip in the appropriate place.
  30371. @see TooltipClient, SettableTooltipClient
  30372. */
  30373. class JUCE_API TooltipWindow : public Component,
  30374. private Timer
  30375. {
  30376. public:
  30377. /** Creates a tooltip window.
  30378. Make sure your app only creates one instance of this class, otherwise you'll
  30379. get multiple overlaid tooltips appearing. The window will initially be invisible
  30380. and will make itself visible when it needs to display a tip.
  30381. To change the style of tooltips, see the LookAndFeel class for its tooltip
  30382. methods.
  30383. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  30384. otherwise the tooltip will be added to the given parent
  30385. component.
  30386. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  30387. before a tooltip will be shown
  30388. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  30389. */
  30390. explicit TooltipWindow (Component* parentComponent = 0,
  30391. int millisecondsBeforeTipAppears = 700);
  30392. /** Destructor. */
  30393. ~TooltipWindow();
  30394. /** Changes the time before the tip appears.
  30395. This lets you change the value that was set in the constructor.
  30396. */
  30397. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) throw();
  30398. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  30399. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30400. methods.
  30401. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30402. */
  30403. enum ColourIds
  30404. {
  30405. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  30406. textColourId = 0x1001c00, /**< The colour to use for the text. */
  30407. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  30408. };
  30409. private:
  30410. int millisecondsBeforeTipAppears;
  30411. Point<int> lastMousePos;
  30412. int mouseClicks;
  30413. unsigned int lastCompChangeTime, lastHideTime;
  30414. Component* lastComponentUnderMouse;
  30415. bool changedCompsSinceShown;
  30416. String tipShowing, lastTipUnderMouse;
  30417. void paint (Graphics& g);
  30418. void mouseEnter (const MouseEvent& e);
  30419. void timerCallback();
  30420. static const String getTipFor (Component* c);
  30421. void showFor (const String& tip);
  30422. void hide();
  30423. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TooltipWindow);
  30424. };
  30425. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  30426. /*** End of inlined file: juce_TooltipWindow.h ***/
  30427. #if JUCE_VC6
  30428. #define Listener ButtonListener
  30429. #endif
  30430. /**
  30431. A base class for buttons.
  30432. This contains all the logic for button behaviours such as enabling/disabling,
  30433. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  30434. and radio groups, etc.
  30435. @see TextButton, DrawableButton, ToggleButton
  30436. */
  30437. class JUCE_API Button : public Component,
  30438. public SettableTooltipClient,
  30439. public ApplicationCommandManagerListener,
  30440. public ValueListener,
  30441. private KeyListener
  30442. {
  30443. protected:
  30444. /** Creates a button.
  30445. @param buttonName the text to put in the button (the component's name is also
  30446. initially set to this string, but these can be changed later
  30447. using the setName() and setButtonText() methods)
  30448. */
  30449. explicit Button (const String& buttonName);
  30450. public:
  30451. /** Destructor. */
  30452. virtual ~Button();
  30453. /** Changes the button's text.
  30454. @see getButtonText
  30455. */
  30456. void setButtonText (const String& newText);
  30457. /** Returns the text displayed in the button.
  30458. @see setButtonText
  30459. */
  30460. const String getButtonText() const { return text; }
  30461. /** Returns true if the button is currently being held down by the mouse.
  30462. @see isOver
  30463. */
  30464. bool isDown() const throw();
  30465. /** Returns true if the mouse is currently over the button.
  30466. This will be also be true if the mouse is being held down.
  30467. @see isDown
  30468. */
  30469. bool isOver() const throw();
  30470. /** A button has an on/off state associated with it, and this changes that.
  30471. By default buttons are 'off' and for simple buttons that you click to perform
  30472. an action you won't change this. Toggle buttons, however will want to
  30473. change their state when turned on or off.
  30474. @param shouldBeOn whether to set the button's toggle state to be on or
  30475. off. If it's a member of a button group, this will
  30476. always try to turn it on, and to turn off any other
  30477. buttons in the group
  30478. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  30479. the button will be repainted but no notification will
  30480. be sent
  30481. @see getToggleState, setRadioGroupId
  30482. */
  30483. void setToggleState (bool shouldBeOn,
  30484. bool sendChangeNotification);
  30485. /** Returns true if the button in 'on'.
  30486. By default buttons are 'off' and for simple buttons that you click to perform
  30487. an action you won't change this. Toggle buttons, however will want to
  30488. change their state when turned on or off.
  30489. @see setToggleState
  30490. */
  30491. bool getToggleState() const throw() { return isOn.getValue(); }
  30492. /** Returns the Value object that represents the botton's toggle state.
  30493. You can use this Value object to connect the button's state to external values or setters,
  30494. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  30495. your own Value object.
  30496. @see getToggleState, Value
  30497. */
  30498. Value& getToggleStateValue() { return isOn; }
  30499. /** This tells the button to automatically flip the toggle state when
  30500. the button is clicked.
  30501. If set to true, then before the clicked() callback occurs, the toggle-state
  30502. of the button is flipped.
  30503. */
  30504. void setClickingTogglesState (bool shouldToggle) throw();
  30505. /** Returns true if this button is set to be an automatic toggle-button.
  30506. This returns the last value that was passed to setClickingTogglesState().
  30507. */
  30508. bool getClickingTogglesState() const throw();
  30509. /** Enables the button to act as a member of a mutually-exclusive group
  30510. of 'radio buttons'.
  30511. If the group ID is set to a non-zero number, then this button will
  30512. act as part of a group of buttons with the same ID, only one of
  30513. which can be 'on' at the same time. Note that when it's part of
  30514. a group, clicking a toggle-button that's 'on' won't turn it off.
  30515. To find other buttons with the same ID, this button will search through
  30516. its sibling components for ToggleButtons, so all the buttons for a
  30517. particular group must be placed inside the same parent component.
  30518. Set the group ID back to zero if you want it to act as a normal toggle
  30519. button again.
  30520. @see getRadioGroupId
  30521. */
  30522. void setRadioGroupId (int newGroupId);
  30523. /** Returns the ID of the group to which this button belongs.
  30524. (See setRadioGroupId() for an explanation of this).
  30525. */
  30526. int getRadioGroupId() const throw() { return radioGroupId; }
  30527. /**
  30528. Used to receive callbacks when a button is clicked.
  30529. @see Button::addListener, Button::removeListener
  30530. */
  30531. class JUCE_API Listener
  30532. {
  30533. public:
  30534. /** Destructor. */
  30535. virtual ~Listener() {}
  30536. /** Called when the button is clicked. */
  30537. virtual void buttonClicked (Button* button) = 0;
  30538. /** Called when the button's state changes. */
  30539. virtual void buttonStateChanged (Button*) {}
  30540. };
  30541. /** Registers a listener to receive events when this button's state changes.
  30542. If the listener is already registered, this will not register it again.
  30543. @see removeListener
  30544. */
  30545. void addListener (Listener* newListener);
  30546. /** Removes a previously-registered button listener
  30547. @see addListener
  30548. */
  30549. void removeListener (Listener* listener);
  30550. /** Causes the button to act as if it's been clicked.
  30551. This will asynchronously make the button draw itself going down and up, and
  30552. will then call back the clicked() method as if mouse was clicked on it.
  30553. @see clicked
  30554. */
  30555. virtual void triggerClick();
  30556. /** Sets a command ID for this button to automatically invoke when it's clicked.
  30557. When the button is pressed, it will use the given manager to trigger the
  30558. command ID.
  30559. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  30560. before this button is. To disable the command triggering, call this method and
  30561. pass 0 for the parameters.
  30562. If generateTooltip is true, then the button's tooltip will be automatically
  30563. generated based on the name of this command and its current shortcut key.
  30564. @see addShortcut, getCommandID
  30565. */
  30566. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  30567. int commandID,
  30568. bool generateTooltip);
  30569. /** Returns the command ID that was set by setCommandToTrigger().
  30570. */
  30571. int getCommandID() const throw() { return commandID; }
  30572. /** Assigns a shortcut key to trigger the button.
  30573. The button registers itself with its top-level parent component for keypresses.
  30574. Note that a different way of linking buttons to keypresses is by using the
  30575. setCommandToTrigger() method to invoke a command.
  30576. @see clearShortcuts
  30577. */
  30578. void addShortcut (const KeyPress& key);
  30579. /** Removes all key shortcuts that had been set for this button.
  30580. @see addShortcut
  30581. */
  30582. void clearShortcuts();
  30583. /** Returns true if the given keypress is a shortcut for this button.
  30584. @see addShortcut
  30585. */
  30586. bool isRegisteredForShortcut (const KeyPress& key) const;
  30587. /** Sets an auto-repeat speed for the button when it is held down.
  30588. (Auto-repeat is disabled by default).
  30589. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  30590. triggering the next click. If this is zero, auto-repeat
  30591. is disabled
  30592. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  30593. triggered
  30594. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  30595. get faster, the longer the button is held down, up to the
  30596. minimum interval specified here
  30597. */
  30598. void setRepeatSpeed (int initialDelayInMillisecs,
  30599. int repeatDelayInMillisecs,
  30600. int minimumDelayInMillisecs = -1) throw();
  30601. /** Sets whether the button click should happen when the mouse is pressed or released.
  30602. By default the button is only considered to have been clicked when the mouse is
  30603. released, but setting this to true will make it call the clicked() method as soon
  30604. as the button is pressed.
  30605. This is useful if the button is being used to show a pop-up menu, as it allows
  30606. the click to be used as a drag onto the menu.
  30607. */
  30608. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) throw();
  30609. /** Returns the number of milliseconds since the last time the button
  30610. went into the 'down' state.
  30611. */
  30612. uint32 getMillisecondsSinceButtonDown() const throw();
  30613. /** Sets the tooltip for this button.
  30614. @see TooltipClient, TooltipWindow
  30615. */
  30616. void setTooltip (const String& newTooltip);
  30617. // (implementation of the TooltipClient method)
  30618. const String getTooltip();
  30619. /** A combination of these flags are used by setConnectedEdges().
  30620. */
  30621. enum ConnectedEdgeFlags
  30622. {
  30623. ConnectedOnLeft = 1,
  30624. ConnectedOnRight = 2,
  30625. ConnectedOnTop = 4,
  30626. ConnectedOnBottom = 8
  30627. };
  30628. /** Hints about which edges of the button might be connected to adjoining buttons.
  30629. The value passed in is a bitwise combination of any of the values in the
  30630. ConnectedEdgeFlags enum.
  30631. E.g. if you are placing two buttons adjacent to each other, you could use this to
  30632. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  30633. without rounded corners on the edges that connect. It's only a hint, so the
  30634. LookAndFeel can choose to ignore it if it's not relevent for this type of
  30635. button.
  30636. */
  30637. void setConnectedEdges (int connectedEdgeFlags);
  30638. /** Returns the set of flags passed into setConnectedEdges(). */
  30639. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  30640. /** Indicates whether the button adjoins another one on its left edge.
  30641. @see setConnectedEdges
  30642. */
  30643. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  30644. /** Indicates whether the button adjoins another one on its right edge.
  30645. @see setConnectedEdges
  30646. */
  30647. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  30648. /** Indicates whether the button adjoins another one on its top edge.
  30649. @see setConnectedEdges
  30650. */
  30651. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  30652. /** Indicates whether the button adjoins another one on its bottom edge.
  30653. @see setConnectedEdges
  30654. */
  30655. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  30656. /** Used by setState(). */
  30657. enum ButtonState
  30658. {
  30659. buttonNormal,
  30660. buttonOver,
  30661. buttonDown
  30662. };
  30663. /** Can be used to force the button into a particular state.
  30664. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  30665. from happening.
  30666. The state that you set here will only last until it is automatically changed when the mouse
  30667. enters or exits the button, or the mouse-button is pressed or released.
  30668. */
  30669. void setState (const ButtonState newState);
  30670. // These are deprecated - please use addListener() and removeListener() instead!
  30671. JUCE_DEPRECATED (void addButtonListener (Listener*));
  30672. JUCE_DEPRECATED (void removeButtonListener (Listener*));
  30673. protected:
  30674. /** This method is called when the button has been clicked.
  30675. Subclasses can override this to perform whatever they actions they need
  30676. to do.
  30677. Alternatively, a ButtonListener can be added to the button, and these listeners
  30678. will be called when the click occurs.
  30679. @see triggerClick
  30680. */
  30681. virtual void clicked();
  30682. /** This method is called when the button has been clicked.
  30683. By default it just calls clicked(), but you might want to override it to handle
  30684. things like clicking when a modifier key is pressed, etc.
  30685. @see ModifierKeys
  30686. */
  30687. virtual void clicked (const ModifierKeys& modifiers);
  30688. /** Subclasses should override this to actually paint the button's contents.
  30689. It's better to use this than the paint method, because it gives you information
  30690. about the over/down state of the button.
  30691. @param g the graphics context to use
  30692. @param isMouseOverButton true if the button is either in the 'over' or
  30693. 'down' state
  30694. @param isButtonDown true if the button should be drawn in the 'down' position
  30695. */
  30696. virtual void paintButton (Graphics& g,
  30697. bool isMouseOverButton,
  30698. bool isButtonDown) = 0;
  30699. /** Called when the button's up/down/over state changes.
  30700. Subclasses can override this if they need to do something special when the button
  30701. goes up or down.
  30702. @see isDown, isOver
  30703. */
  30704. virtual void buttonStateChanged();
  30705. /** @internal */
  30706. virtual void internalClickCallback (const ModifierKeys& modifiers);
  30707. /** @internal */
  30708. void handleCommandMessage (int commandId);
  30709. /** @internal */
  30710. void mouseEnter (const MouseEvent& e);
  30711. /** @internal */
  30712. void mouseExit (const MouseEvent& e);
  30713. /** @internal */
  30714. void mouseDown (const MouseEvent& e);
  30715. /** @internal */
  30716. void mouseDrag (const MouseEvent& e);
  30717. /** @internal */
  30718. void mouseUp (const MouseEvent& e);
  30719. /** @internal */
  30720. bool keyPressed (const KeyPress& key);
  30721. /** @internal */
  30722. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  30723. /** @internal */
  30724. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  30725. /** @internal */
  30726. void paint (Graphics& g);
  30727. /** @internal */
  30728. void parentHierarchyChanged();
  30729. /** @internal */
  30730. void visibilityChanged();
  30731. /** @internal */
  30732. void focusGained (FocusChangeType cause);
  30733. /** @internal */
  30734. void focusLost (FocusChangeType cause);
  30735. /** @internal */
  30736. void enablementChanged();
  30737. /** @internal */
  30738. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  30739. /** @internal */
  30740. void applicationCommandListChanged();
  30741. /** @internal */
  30742. void valueChanged (Value& value);
  30743. private:
  30744. Array <KeyPress> shortcuts;
  30745. WeakReference<Component> keySource;
  30746. String text;
  30747. ListenerList <Listener> buttonListeners;
  30748. class RepeatTimer;
  30749. friend class RepeatTimer;
  30750. friend class ScopedPointer <RepeatTimer>;
  30751. ScopedPointer <RepeatTimer> repeatTimer;
  30752. uint32 buttonPressTime, lastRepeatTime;
  30753. ApplicationCommandManager* commandManagerToUse;
  30754. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  30755. int radioGroupId, commandID, connectedEdgeFlags;
  30756. ButtonState buttonState;
  30757. Value isOn;
  30758. bool lastToggleState : 1;
  30759. bool clickTogglesState : 1;
  30760. bool needsToRelease : 1;
  30761. bool needsRepainting : 1;
  30762. bool isKeyDown : 1;
  30763. bool triggerOnMouseDown : 1;
  30764. bool generateTooltip : 1;
  30765. void repeatTimerCallback();
  30766. RepeatTimer& getRepeatTimer();
  30767. ButtonState updateState();
  30768. ButtonState updateState (bool isOver, bool isDown);
  30769. bool isShortcutPressed() const;
  30770. void turnOffOtherButtonsInGroup (bool sendChangeNotification);
  30771. void flashButtonState();
  30772. void sendClickMessage (const ModifierKeys& modifiers);
  30773. void sendStateMessage();
  30774. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Button);
  30775. };
  30776. #ifndef DOXYGEN
  30777. /** This typedef is just for compatibility with old code and VC6 - newer code should use Button::Listener instead. */
  30778. typedef Button::Listener ButtonListener;
  30779. #endif
  30780. #if JUCE_VC6
  30781. #undef Listener
  30782. #endif
  30783. #endif // __JUCE_BUTTON_JUCEHEADER__
  30784. /*** End of inlined file: juce_Button.h ***/
  30785. /**
  30786. A scrollbar component.
  30787. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  30788. sets the range of values it can represent. Then you can use setCurrentRange() to
  30789. change the position and size of the scrollbar's 'thumb'.
  30790. Registering a ScrollBar::Listener with the scrollbar will allow you to find out when
  30791. the user moves it, and you can use the getCurrentRangeStart() to find out where
  30792. they moved it to.
  30793. The scrollbar will adjust its own visibility according to whether its thumb size
  30794. allows it to actually be scrolled.
  30795. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  30796. instead of handling a scrollbar directly.
  30797. @see ScrollBar::Listener
  30798. */
  30799. class JUCE_API ScrollBar : public Component,
  30800. public AsyncUpdater,
  30801. private Timer
  30802. {
  30803. public:
  30804. /** Creates a Scrollbar.
  30805. @param isVertical whether it should be a vertical or horizontal bar
  30806. @param buttonsAreVisible whether to show the up/down or left/right buttons
  30807. */
  30808. ScrollBar (bool isVertical,
  30809. bool buttonsAreVisible = true);
  30810. /** Destructor. */
  30811. ~ScrollBar();
  30812. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  30813. bool isVertical() const throw() { return vertical; }
  30814. /** Changes the scrollbar's direction.
  30815. You'll also need to resize the bar appropriately - this just changes its internal
  30816. layout.
  30817. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  30818. */
  30819. void setOrientation (bool shouldBeVertical);
  30820. /** Shows or hides the scrollbar's buttons. */
  30821. void setButtonVisibility (bool buttonsAreVisible);
  30822. /** Tells the scrollbar whether to make itself invisible when not needed.
  30823. The default behaviour is for a scrollbar to become invisible when the thumb
  30824. fills the whole of its range (i.e. when it can't be moved). Setting this
  30825. value to false forces the bar to always be visible.
  30826. @see autoHides()
  30827. */
  30828. void setAutoHide (bool shouldHideWhenFullRange);
  30829. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  30830. as its maximum range.
  30831. @see setAutoHide
  30832. */
  30833. bool autoHides() const throw();
  30834. /** Sets the minimum and maximum values that the bar will move between.
  30835. The bar's thumb will always be constrained so that the entire thumb lies
  30836. within this range.
  30837. @see setCurrentRange
  30838. */
  30839. void setRangeLimits (const Range<double>& newRangeLimit);
  30840. /** Sets the minimum and maximum values that the bar will move between.
  30841. The bar's thumb will always be constrained so that the entire thumb lies
  30842. within this range.
  30843. @see setCurrentRange
  30844. */
  30845. void setRangeLimits (double minimum, double maximum);
  30846. /** Returns the current limits on the thumb position.
  30847. @see setRangeLimits
  30848. */
  30849. const Range<double> getRangeLimit() const throw() { return totalRange; }
  30850. /** Returns the lower value that the thumb can be set to.
  30851. This is the value set by setRangeLimits().
  30852. */
  30853. double getMinimumRangeLimit() const throw() { return totalRange.getStart(); }
  30854. /** Returns the upper value that the thumb can be set to.
  30855. This is the value set by setRangeLimits().
  30856. */
  30857. double getMaximumRangeLimit() const throw() { return totalRange.getEnd(); }
  30858. /** Changes the position of the scrollbar's 'thumb'.
  30859. If this method call actually changes the scrollbar's position, it will trigger an
  30860. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  30861. are registered.
  30862. @see getCurrentRange. setCurrentRangeStart
  30863. */
  30864. void setCurrentRange (const Range<double>& newRange);
  30865. /** Changes the position of the scrollbar's 'thumb'.
  30866. This sets both the position and size of the thumb - to just set the position without
  30867. changing the size, you can use setCurrentRangeStart().
  30868. If this method call actually changes the scrollbar's position, it will trigger an
  30869. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  30870. are registered.
  30871. @param newStart the top (or left) of the thumb, in the range
  30872. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  30873. value is beyond these limits, it will be clipped.
  30874. @param newSize the size of the thumb, such that
  30875. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  30876. size is beyond these limits, it will be clipped.
  30877. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  30878. */
  30879. void setCurrentRange (double newStart, double newSize);
  30880. /** Moves the bar's thumb position.
  30881. This will move the thumb position without changing the thumb size. Note
  30882. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  30883. If this method call actually changes the scrollbar's position, it will trigger an
  30884. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  30885. are registered.
  30886. @see setCurrentRange
  30887. */
  30888. void setCurrentRangeStart (double newStart);
  30889. /** Returns the current thumb range.
  30890. @see getCurrentRange, setCurrentRange
  30891. */
  30892. const Range<double> getCurrentRange() const throw() { return visibleRange; }
  30893. /** Returns the position of the top of the thumb.
  30894. @see getCurrentRange, setCurrentRangeStart
  30895. */
  30896. double getCurrentRangeStart() const throw() { return visibleRange.getStart(); }
  30897. /** Returns the current size of the thumb.
  30898. @see getCurrentRange, setCurrentRange
  30899. */
  30900. double getCurrentRangeSize() const throw() { return visibleRange.getLength(); }
  30901. /** Sets the amount by which the up and down buttons will move the bar.
  30902. The value here is in terms of the total range, and is added or subtracted
  30903. from the thumb position when the user clicks an up/down (or left/right) button.
  30904. */
  30905. void setSingleStepSize (double newSingleStepSize);
  30906. /** Moves the scrollbar by a number of single-steps.
  30907. This will move the bar by a multiple of its single-step interval (as
  30908. specified using the setSingleStepSize() method).
  30909. A positive value here will move the bar down or to the right, a negative
  30910. value moves it up or to the left.
  30911. */
  30912. void moveScrollbarInSteps (int howManySteps);
  30913. /** Moves the scroll bar up or down in pages.
  30914. This will move the bar by a multiple of its current thumb size, effectively
  30915. doing a page-up or down.
  30916. A positive value here will move the bar down or to the right, a negative
  30917. value moves it up or to the left.
  30918. */
  30919. void moveScrollbarInPages (int howManyPages);
  30920. /** Scrolls to the top (or left).
  30921. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  30922. */
  30923. void scrollToTop();
  30924. /** Scrolls to the bottom (or right).
  30925. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  30926. */
  30927. void scrollToBottom();
  30928. /** Changes the delay before the up and down buttons autorepeat when they are held
  30929. down.
  30930. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  30931. @see Button::setRepeatSpeed
  30932. */
  30933. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  30934. int repeatDelayInMillisecs,
  30935. int minimumDelayInMillisecs = -1);
  30936. /** A set of colour IDs to use to change the colour of various aspects of the component.
  30937. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30938. methods.
  30939. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30940. */
  30941. enum ColourIds
  30942. {
  30943. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  30944. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  30945. 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. */
  30946. };
  30947. /**
  30948. A class for receiving events from a ScrollBar.
  30949. You can register a ScrollBar::Listener with a ScrollBar using the ScrollBar::addListener()
  30950. method, and it will be called when the bar's position changes.
  30951. @see ScrollBar::addListener, ScrollBar::removeListener
  30952. */
  30953. class JUCE_API Listener
  30954. {
  30955. public:
  30956. /** Destructor. */
  30957. virtual ~Listener() {}
  30958. /** Called when a ScrollBar is moved.
  30959. @param scrollBarThatHasMoved the bar that has moved
  30960. @param newRangeStart the new range start of this bar
  30961. */
  30962. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  30963. double newRangeStart) = 0;
  30964. };
  30965. /** Registers a listener that will be called when the scrollbar is moved. */
  30966. void addListener (Listener* listener);
  30967. /** Deregisters a previously-registered listener. */
  30968. void removeListener (Listener* listener);
  30969. /** @internal */
  30970. bool keyPressed (const KeyPress& key);
  30971. /** @internal */
  30972. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  30973. /** @internal */
  30974. void lookAndFeelChanged();
  30975. /** @internal */
  30976. void handleAsyncUpdate();
  30977. /** @internal */
  30978. void mouseDown (const MouseEvent& e);
  30979. /** @internal */
  30980. void mouseDrag (const MouseEvent& e);
  30981. /** @internal */
  30982. void mouseUp (const MouseEvent& e);
  30983. /** @internal */
  30984. void paint (Graphics& g);
  30985. /** @internal */
  30986. void resized();
  30987. private:
  30988. Range <double> totalRange, visibleRange;
  30989. double singleStepSize, dragStartRange;
  30990. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  30991. int dragStartMousePos, lastMousePos;
  30992. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  30993. bool vertical, isDraggingThumb, autohides;
  30994. class ScrollbarButton;
  30995. friend class ScopedPointer<ScrollbarButton>;
  30996. ScopedPointer<ScrollbarButton> upButton, downButton;
  30997. ListenerList <Listener> listeners;
  30998. void updateThumbPosition();
  30999. void timerCallback();
  31000. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollBar);
  31001. };
  31002. /** This typedef is just for compatibility with old code - newer code should use the ScrollBar::Listener class directly. */
  31003. typedef ScrollBar::Listener ScrollBarListener;
  31004. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  31005. /*** End of inlined file: juce_ScrollBar.h ***/
  31006. /**
  31007. A Viewport is used to contain a larger child component, and allows the child
  31008. to be automatically scrolled around.
  31009. To use a Viewport, just create one and set the component that goes inside it
  31010. using the setViewedComponent() method. When the child component changes size,
  31011. the Viewport will adjust its scrollbars accordingly.
  31012. A subclass of the viewport can be created which will receive calls to its
  31013. visibleAreaChanged() method when the subcomponent changes position or size.
  31014. */
  31015. class JUCE_API Viewport : public Component,
  31016. private ComponentListener,
  31017. private ScrollBar::Listener
  31018. {
  31019. public:
  31020. /** Creates a Viewport.
  31021. The viewport is initially empty - use the setViewedComponent() method to
  31022. add a child component for it to manage.
  31023. */
  31024. explicit Viewport (const String& componentName = String::empty);
  31025. /** Destructor. */
  31026. ~Viewport();
  31027. /** Sets the component that this viewport will contain and scroll around.
  31028. This will add the given component to this Viewport and position it at (0, 0).
  31029. (Don't add or remove any child components directly using the normal
  31030. Component::addChildComponent() methods).
  31031. @param newViewedComponent the component to add to this viewport, or null to remove
  31032. the current component.
  31033. @param deleteComponentWhenNoLongerNeeded if true, the component will be deleted
  31034. automatically when the viewport is deleted or when a different
  31035. component is added. If false, the caller must manage the lifetime
  31036. of the component
  31037. @see getViewedComponent
  31038. */
  31039. void setViewedComponent (Component* newViewedComponent,
  31040. bool deleteComponentWhenNoLongerNeeded = true);
  31041. /** Returns the component that's currently being used inside the Viewport.
  31042. @see setViewedComponent
  31043. */
  31044. Component* getViewedComponent() const throw() { return contentComp; }
  31045. /** Changes the position of the viewed component.
  31046. The inner component will be moved so that the pixel at the top left of
  31047. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  31048. within the inner component.
  31049. This will update the scrollbars and might cause a call to visibleAreaChanged().
  31050. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  31051. */
  31052. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  31053. /** Changes the position of the viewed component.
  31054. The inner component will be moved so that the pixel at the top left of
  31055. the viewport will be the pixel at the specified coordinates within the
  31056. inner component.
  31057. This will update the scrollbars and might cause a call to visibleAreaChanged().
  31058. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  31059. */
  31060. void setViewPosition (const Point<int>& newPosition);
  31061. /** Changes the view position as a proportion of the distance it can move.
  31062. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  31063. visible area in the top-left, and (1, 1) would put it as far down and
  31064. to the right as it's possible to go whilst keeping the child component
  31065. on-screen.
  31066. */
  31067. void setViewPositionProportionately (double proportionX, double proportionY);
  31068. /** If the specified position is at the edges of the viewport, this method scrolls
  31069. the viewport to bring that position nearer to the centre.
  31070. Call this if you're dragging an object inside a viewport and want to make it scroll
  31071. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  31072. useful when auto-scrolling.
  31073. @param mouseX the x position, relative to the Viewport's top-left
  31074. @param mouseY the y position, relative to the Viewport's top-left
  31075. @param distanceFromEdge specifies how close to an edge the position needs to be
  31076. before the viewport should scroll in that direction
  31077. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  31078. to scroll by.
  31079. @returns true if the viewport was scrolled
  31080. */
  31081. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  31082. /** Returns the position within the child component of the top-left of its visible area.
  31083. */
  31084. const Point<int> getViewPosition() const throw() { return lastVisibleArea.getPosition(); }
  31085. /** Returns the position within the child component of the top-left of its visible area.
  31086. @see getViewWidth, setViewPosition
  31087. */
  31088. int getViewPositionX() const throw() { return lastVisibleArea.getX(); }
  31089. /** Returns the position within the child component of the top-left of its visible area.
  31090. @see getViewHeight, setViewPosition
  31091. */
  31092. int getViewPositionY() const throw() { return lastVisibleArea.getY(); }
  31093. /** Returns the width of the visible area of the child component.
  31094. This may be less than the width of this Viewport if there's a vertical scrollbar
  31095. or if the child component is itself smaller.
  31096. */
  31097. int getViewWidth() const throw() { return lastVisibleArea.getWidth(); }
  31098. /** Returns the height of the visible area of the child component.
  31099. This may be less than the height of this Viewport if there's a horizontal scrollbar
  31100. or if the child component is itself smaller.
  31101. */
  31102. int getViewHeight() const throw() { return lastVisibleArea.getHeight(); }
  31103. /** Returns the width available within this component for the contents.
  31104. This will be the width of the viewport component minus the width of a
  31105. vertical scrollbar (if visible).
  31106. */
  31107. int getMaximumVisibleWidth() const;
  31108. /** Returns the height available within this component for the contents.
  31109. This will be the height of the viewport component minus the space taken up
  31110. by a horizontal scrollbar (if visible).
  31111. */
  31112. int getMaximumVisibleHeight() const;
  31113. /** Callback method that is called when the visible area changes.
  31114. This will be called when the visible area is moved either be scrolling or
  31115. by calls to setViewPosition(), etc.
  31116. */
  31117. virtual void visibleAreaChanged (const Rectangle<int>& newVisibleArea);
  31118. /** Turns scrollbars on or off.
  31119. If set to false, the scrollbars won't ever appear. When true (the default)
  31120. they will appear only when needed.
  31121. */
  31122. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  31123. bool showHorizontalScrollbarIfNeeded);
  31124. /** True if the vertical scrollbar is enabled.
  31125. @see setScrollBarsShown
  31126. */
  31127. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  31128. /** True if the horizontal scrollbar is enabled.
  31129. @see setScrollBarsShown
  31130. */
  31131. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  31132. /** Changes the width of the scrollbars.
  31133. If this isn't specified, the default width from the LookAndFeel class will be used.
  31134. @see LookAndFeel::getDefaultScrollbarWidth
  31135. */
  31136. void setScrollBarThickness (int thickness);
  31137. /** Returns the thickness of the scrollbars.
  31138. @see setScrollBarThickness
  31139. */
  31140. int getScrollBarThickness() const;
  31141. /** Changes the distance that a single-step click on a scrollbar button
  31142. will move the viewport.
  31143. */
  31144. void setSingleStepSizes (int stepX, int stepY);
  31145. /** Shows or hides the buttons on any scrollbars that are used.
  31146. @see ScrollBar::setButtonVisibility
  31147. */
  31148. void setScrollBarButtonVisibility (bool buttonsVisible);
  31149. /** Returns a pointer to the scrollbar component being used.
  31150. Handy if you need to customise the bar somehow.
  31151. */
  31152. ScrollBar* getVerticalScrollBar() throw() { return &verticalScrollBar; }
  31153. /** Returns a pointer to the scrollbar component being used.
  31154. Handy if you need to customise the bar somehow.
  31155. */
  31156. ScrollBar* getHorizontalScrollBar() throw() { return &horizontalScrollBar; }
  31157. /** @internal */
  31158. void resized();
  31159. /** @internal */
  31160. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  31161. /** @internal */
  31162. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31163. /** @internal */
  31164. bool keyPressed (const KeyPress& key);
  31165. /** @internal */
  31166. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  31167. /** @internal */
  31168. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31169. private:
  31170. WeakReference<Component> contentComp;
  31171. Rectangle<int> lastVisibleArea;
  31172. int scrollBarThickness;
  31173. int singleStepX, singleStepY;
  31174. bool showHScrollbar, showVScrollbar, deleteContent;
  31175. Component contentHolder;
  31176. ScrollBar verticalScrollBar;
  31177. ScrollBar horizontalScrollBar;
  31178. void updateVisibleArea();
  31179. void deleteContentComp();
  31180. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  31181. // If you get an error here, it's because this method's parameters have changed! See the new definition above..
  31182. virtual int visibleAreaChanged (int, int, int, int) { return 0; }
  31183. #endif
  31184. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Viewport);
  31185. };
  31186. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  31187. /*** End of inlined file: juce_Viewport.h ***/
  31188. /*** Start of inlined file: juce_PopupMenu.h ***/
  31189. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  31190. #define __JUCE_POPUPMENU_JUCEHEADER__
  31191. /** Creates and displays a popup-menu.
  31192. To show a popup-menu, you create one of these, add some items to it, then
  31193. call its show() method, which returns the id of the item the user selects.
  31194. E.g. @code
  31195. void MyWidget::mouseDown (const MouseEvent& e)
  31196. {
  31197. PopupMenu m;
  31198. m.addItem (1, "item 1");
  31199. m.addItem (2, "item 2");
  31200. const int result = m.show();
  31201. if (result == 0)
  31202. {
  31203. // user dismissed the menu without picking anything
  31204. }
  31205. else if (result == 1)
  31206. {
  31207. // user picked item 1
  31208. }
  31209. else if (result == 2)
  31210. {
  31211. // user picked item 2
  31212. }
  31213. }
  31214. @endcode
  31215. Submenus are easy too: @code
  31216. void MyWidget::mouseDown (const MouseEvent& e)
  31217. {
  31218. PopupMenu subMenu;
  31219. subMenu.addItem (1, "item 1");
  31220. subMenu.addItem (2, "item 2");
  31221. PopupMenu mainMenu;
  31222. mainMenu.addItem (3, "item 3");
  31223. mainMenu.addSubMenu ("other choices", subMenu);
  31224. const int result = m.show();
  31225. ...etc
  31226. }
  31227. @endcode
  31228. */
  31229. class JUCE_API PopupMenu
  31230. {
  31231. public:
  31232. /** Creates an empty popup menu. */
  31233. PopupMenu();
  31234. /** Creates a copy of another menu. */
  31235. PopupMenu (const PopupMenu& other);
  31236. /** Destructor. */
  31237. ~PopupMenu();
  31238. /** Copies this menu from another one. */
  31239. PopupMenu& operator= (const PopupMenu& other);
  31240. /** Resets the menu, removing all its items. */
  31241. void clear();
  31242. /** Appends a new text item for this menu to show.
  31243. @param itemResultId the number that will be returned from the show() method
  31244. if the user picks this item. The value should never be
  31245. zero, because that's used to indicate that the user didn't
  31246. select anything.
  31247. @param itemText the text to show.
  31248. @param isActive if false, the item will be shown 'greyed-out' and can't be
  31249. picked
  31250. @param isTicked if true, the item will be shown with a tick next to it
  31251. @param iconToUse if this is non-zero, it should be an image that will be
  31252. displayed to the left of the item. This method will take its
  31253. own copy of the image passed-in, so there's no need to keep
  31254. it hanging around.
  31255. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  31256. */
  31257. void addItem (int itemResultId,
  31258. const String& itemText,
  31259. bool isActive = true,
  31260. bool isTicked = false,
  31261. const Image& iconToUse = Image::null);
  31262. /** Adds an item that represents one of the commands in a command manager object.
  31263. @param commandManager the manager to use to trigger the command and get information
  31264. about it
  31265. @param commandID the ID of the command
  31266. @param displayName if this is non-empty, then this string will be used instead of
  31267. the command's registered name
  31268. */
  31269. void addCommandItem (ApplicationCommandManager* commandManager,
  31270. int commandID,
  31271. const String& displayName = String::empty);
  31272. /** Appends a text item with a special colour.
  31273. This is the same as addItem(), but specifies a colour to use for the
  31274. text, which will override the default colours that are used by the
  31275. current look-and-feel. See addItem() for a description of the parameters.
  31276. */
  31277. void addColouredItem (int itemResultId,
  31278. const String& itemText,
  31279. const Colour& itemTextColour,
  31280. bool isActive = true,
  31281. bool isTicked = false,
  31282. const Image& iconToUse = Image::null);
  31283. /** Appends a custom menu item that can't be used to trigger a result.
  31284. This will add a user-defined component to use as a menu item. Unlike the
  31285. addCustomItem() method that takes a PopupMenu::CustomComponent, this version
  31286. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  31287. delete the component when it's finished, so it's the caller's responsibility
  31288. to manage the component that is passed-in.
  31289. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  31290. detection of a mouse-click on your component, and use that to trigger the
  31291. menu ID specified in itemResultId. If this is false, the menu item can't
  31292. be triggered, so itemResultId is not used.
  31293. @see CustomComponent
  31294. */
  31295. void addCustomItem (int itemResultId,
  31296. Component* customComponent,
  31297. int idealWidth, int idealHeight,
  31298. bool triggerMenuItemAutomaticallyWhenClicked);
  31299. /** Appends a sub-menu.
  31300. If the menu that's passed in is empty, it will appear as an inactive item.
  31301. */
  31302. void addSubMenu (const String& subMenuName,
  31303. const PopupMenu& subMenu,
  31304. bool isActive = true,
  31305. const Image& iconToUse = Image::null,
  31306. bool isTicked = false);
  31307. /** Appends a separator to the menu, to help break it up into sections.
  31308. The menu class is smart enough not to display separators at the top or bottom
  31309. of the menu, and it will replace mutliple adjacent separators with a single
  31310. one, so your code can be quite free and easy about adding these, and it'll
  31311. always look ok.
  31312. */
  31313. void addSeparator();
  31314. /** Adds a non-clickable text item to the menu.
  31315. This is a bold-font items which can be used as a header to separate the items
  31316. into named groups.
  31317. */
  31318. void addSectionHeader (const String& title);
  31319. /** Returns the number of items that the menu currently contains.
  31320. (This doesn't count separators).
  31321. */
  31322. int getNumItems() const throw();
  31323. /** Returns true if the menu contains a command item that triggers the given command. */
  31324. bool containsCommandItem (int commandID) const;
  31325. /** Returns true if the menu contains any items that can be used. */
  31326. bool containsAnyActiveItems() const throw();
  31327. /** Class used to create a set of options to pass to the show() method.
  31328. You can chain together a series of calls to this class's methods to create
  31329. a set of whatever options you want to specify.
  31330. E.g. @code
  31331. PopupMenu menu;
  31332. ...
  31333. menu.showMenu (PopupMenu::Options().withMaximumWidth (100),
  31334. .withMaximumNumColumns (3)
  31335. .withTargetComponent (myComp));
  31336. @endcode
  31337. */
  31338. class JUCE_API Options
  31339. {
  31340. public:
  31341. Options();
  31342. const Options withTargetComponent (Component* targetComponent) const;
  31343. const Options withTargetScreenArea (const Rectangle<int>& targetArea) const;
  31344. const Options withMinimumWidth (int minWidth) const;
  31345. const Options withMaximumNumColumns (int maxNumColumns) const;
  31346. const Options withStandardItemHeight (int standardHeight) const;
  31347. const Options withItemThatMustBeVisible (int idOfItemToBeVisible) const;
  31348. private:
  31349. friend class PopupMenu;
  31350. Rectangle<int> targetArea;
  31351. Component* targetComponent;
  31352. int visibleItemID, minWidth, maxColumns, standardHeight;
  31353. };
  31354. #if JUCE_MODAL_LOOPS_PERMITTED
  31355. /** Displays the menu and waits for the user to pick something.
  31356. This will display the menu modally, and return the ID of the item that the
  31357. user picks. If they click somewhere off the menu to get rid of it without
  31358. choosing anything, this will return 0.
  31359. The current location of the mouse will be used as the position to show the
  31360. menu - to explicitly set the menu's position, use showAt() instead. Depending
  31361. on where this point is on the screen, the menu will appear above, below or
  31362. to the side of the point.
  31363. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  31364. then when the menu first appears, it will make sure
  31365. that this item is visible. So if the menu has too many
  31366. items to fit on the screen, it will be scrolled to a
  31367. position where this item is visible.
  31368. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  31369. than this if some items are too long to fit.
  31370. @param maximumNumColumns if there are too many items to fit on-screen in a single
  31371. vertical column, the menu may be laid out as a series of
  31372. columns - this is the maximum number allowed. To use the
  31373. default value for this (probably about 7), you can pass
  31374. in zero.
  31375. @param standardItemHeight if this is non-zero, it will be used as the standard
  31376. height for menu items (apart from custom items)
  31377. @param callback if this is non-zero, the menu will be launched asynchronously,
  31378. returning immediately, and the callback will receive a
  31379. call when the menu is either dismissed or has an item
  31380. selected. This object will be owned and deleted by the
  31381. system, so make sure that it works safely and that any
  31382. pointers that it uses are safely within scope.
  31383. @see showAt
  31384. */
  31385. int show (int itemIdThatMustBeVisible = 0,
  31386. int minimumWidth = 0,
  31387. int maximumNumColumns = 0,
  31388. int standardItemHeight = 0,
  31389. ModalComponentManager::Callback* callback = 0);
  31390. /** Displays the menu at a specific location.
  31391. This is the same as show(), but uses a specific location (in global screen
  31392. co-ordinates) rather than the current mouse position.
  31393. The screenAreaToAttachTo parameter indicates a screen area to which the menu
  31394. will be adjacent. Depending on where this is, the menu will decide which edge to
  31395. attach itself to, in order to fit itself fully on-screen. If you just want to
  31396. trigger a menu at a specific point, you can pass in a rectangle of size (0, 0)
  31397. with the position that you want.
  31398. @see show()
  31399. */
  31400. int showAt (const Rectangle<int>& screenAreaToAttachTo,
  31401. int itemIdThatMustBeVisible = 0,
  31402. int minimumWidth = 0,
  31403. int maximumNumColumns = 0,
  31404. int standardItemHeight = 0,
  31405. ModalComponentManager::Callback* callback = 0);
  31406. /** Displays the menu as if it's attached to a component such as a button.
  31407. This is similar to showAt(), but will position it next to the given component, e.g.
  31408. so that the menu's edge is aligned with that of the component. This is intended for
  31409. things like buttons that trigger a pop-up menu.
  31410. */
  31411. int showAt (Component* componentToAttachTo,
  31412. int itemIdThatMustBeVisible = 0,
  31413. int minimumWidth = 0,
  31414. int maximumNumColumns = 0,
  31415. int standardItemHeight = 0,
  31416. ModalComponentManager::Callback* callback = 0);
  31417. /** Displays and runs the menu modally, with a set of options.
  31418. */
  31419. int showMenu (const Options& options);
  31420. #endif
  31421. /** Runs the menu asynchronously, with a user-provided callback that will receive the result. */
  31422. void showMenuAsync (const Options& options,
  31423. ModalComponentManager::Callback* callback);
  31424. /** Closes any menus that are currently open.
  31425. This might be useful if you have a situation where your window is being closed
  31426. by some means other than a user action, and you'd like to make sure that menus
  31427. aren't left hanging around.
  31428. */
  31429. static bool JUCE_CALLTYPE dismissAllActiveMenus();
  31430. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  31431. This can be called before show() if you need a customised menu. Be careful
  31432. not to delete the LookAndFeel object before the menu has been deleted.
  31433. */
  31434. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  31435. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  31436. These constants can be used either via the LookAndFeel::setColour()
  31437. method for the look and feel that is set for this menu with setLookAndFeel()
  31438. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  31439. */
  31440. enum ColourIds
  31441. {
  31442. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  31443. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  31444. colour is specified when the item is added). */
  31445. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  31446. addSectionHeader() method). */
  31447. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  31448. highlighted menu item. */
  31449. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  31450. highlighted item. */
  31451. };
  31452. /**
  31453. Allows you to iterate through the items in a pop-up menu, and examine
  31454. their properties.
  31455. To use this, just create one and repeatedly call its next() method. When this
  31456. returns true, all the member variables of the iterator are filled-out with
  31457. information describing the menu item. When it returns false, the end of the
  31458. list has been reached.
  31459. */
  31460. class JUCE_API MenuItemIterator
  31461. {
  31462. public:
  31463. /** Creates an iterator that will scan through the items in the specified
  31464. menu.
  31465. Be careful not to add any items to a menu while it is being iterated,
  31466. or things could get out of step.
  31467. */
  31468. MenuItemIterator (const PopupMenu& menu);
  31469. /** Destructor. */
  31470. ~MenuItemIterator();
  31471. /** Returns true if there is another item, and sets up all this object's
  31472. member variables to reflect that item's properties.
  31473. */
  31474. bool next();
  31475. String itemName;
  31476. const PopupMenu* subMenu;
  31477. int itemId;
  31478. bool isSeparator;
  31479. bool isTicked;
  31480. bool isEnabled;
  31481. bool isCustomComponent;
  31482. bool isSectionHeader;
  31483. const Colour* customColour;
  31484. Image customImage;
  31485. ApplicationCommandManager* commandManager;
  31486. private:
  31487. const PopupMenu& menu;
  31488. int index;
  31489. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuItemIterator);
  31490. };
  31491. /** A user-defined copmonent that can be used as an item in a popup menu.
  31492. @see PopupMenu::addCustomItem
  31493. */
  31494. class JUCE_API CustomComponent : public Component,
  31495. public ReferenceCountedObject
  31496. {
  31497. public:
  31498. /** Creates a custom item.
  31499. If isTriggeredAutomatically is true, then the menu will automatically detect
  31500. a mouse-click on this component and use that to invoke the menu item. If it's
  31501. false, then it's up to your class to manually trigger the item when it wants to.
  31502. */
  31503. CustomComponent (bool isTriggeredAutomatically = true);
  31504. /** Destructor. */
  31505. ~CustomComponent();
  31506. /** Returns a rectangle with the size that this component would like to have.
  31507. Note that the size which this method returns isn't necessarily the one that
  31508. the menu will give it, as the items will be stretched to have a uniform width.
  31509. */
  31510. virtual void getIdealSize (int& idealWidth, int& idealHeight) = 0;
  31511. /** Dismisses the menu, indicating that this item has been chosen.
  31512. This will cause the menu to exit from its modal state, returning
  31513. this item's id as the result.
  31514. */
  31515. void triggerMenuItem();
  31516. /** Returns true if this item should be highlighted because the mouse is over it.
  31517. You can call this method in your paint() method to find out whether
  31518. to draw a highlight.
  31519. */
  31520. bool isItemHighlighted() const throw() { return isHighlighted; }
  31521. /** @internal. */
  31522. bool isTriggeredAutomatically() const throw() { return triggeredAutomatically; }
  31523. /** @internal. */
  31524. void setHighlighted (bool shouldBeHighlighted);
  31525. private:
  31526. bool isHighlighted, triggeredAutomatically;
  31527. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponent);
  31528. };
  31529. /** Appends a custom menu item.
  31530. This will add a user-defined component to use as a menu item. The component
  31531. passed in will be deleted by this menu when it's no longer needed.
  31532. @see CustomComponent
  31533. */
  31534. void addCustomItem (int itemResultId, CustomComponent* customComponent);
  31535. private:
  31536. class Item;
  31537. class ItemComponent;
  31538. class Window;
  31539. friend class MenuItemIterator;
  31540. friend class ItemComponent;
  31541. friend class Window;
  31542. friend class CustomComponent;
  31543. friend class MenuBarComponent;
  31544. friend class OwnedArray <Item>;
  31545. friend class OwnedArray <ItemComponent>;
  31546. friend class ScopedPointer <Window>;
  31547. OwnedArray <Item> items;
  31548. LookAndFeel* lookAndFeel;
  31549. bool separatorPending;
  31550. void addSeparatorIfPending();
  31551. Component* createWindow (const Options&, ApplicationCommandManager**) const;
  31552. int showWithOptionalCallback (const Options&, ModalComponentManager::Callback*, bool);
  31553. JUCE_LEAK_DETECTOR (PopupMenu);
  31554. };
  31555. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  31556. /*** End of inlined file: juce_PopupMenu.h ***/
  31557. /*** Start of inlined file: juce_TextInputTarget.h ***/
  31558. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  31559. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  31560. /** An abstract base class that is implemented by components that wish to be used
  31561. as text editors.
  31562. This class allows different types of text editor component to provide a uniform
  31563. interface, which can be used by things like OS-specific input methods, on-screen
  31564. keyboards, etc.
  31565. */
  31566. class JUCE_API TextInputTarget
  31567. {
  31568. public:
  31569. /** */
  31570. TextInputTarget() {}
  31571. /** Destructor. */
  31572. virtual ~TextInputTarget() {}
  31573. /** Returns true if this input target is currently accepting input.
  31574. For example, a text editor might return false if it's in read-only mode.
  31575. */
  31576. virtual bool isTextInputActive() const = 0;
  31577. /** Returns the extents of the selected text region, or an empty range if
  31578. nothing is selected,
  31579. */
  31580. virtual const Range<int> getHighlightedRegion() const = 0;
  31581. /** Sets the currently-selected text region.
  31582. */
  31583. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  31584. /** Returns a specified sub-section of the text.
  31585. */
  31586. virtual const String getTextInRange (const Range<int>& range) const = 0;
  31587. /** Inserts some text, overwriting the selected text region, if there is one. */
  31588. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  31589. };
  31590. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  31591. /*** End of inlined file: juce_TextInputTarget.h ***/
  31592. /**
  31593. A component containing text that can be edited.
  31594. A TextEditor can either be in single- or multi-line mode, and supports mixed
  31595. fonts and colours.
  31596. @see TextEditor::Listener, Label
  31597. */
  31598. class JUCE_API TextEditor : public Component,
  31599. public TextInputTarget,
  31600. public SettableTooltipClient
  31601. {
  31602. public:
  31603. /** Creates a new, empty text editor.
  31604. @param componentName the name to pass to the component for it to use as its name
  31605. @param passwordCharacter if this is not zero, this character will be used as a replacement
  31606. for all characters that are drawn on screen - e.g. to create
  31607. a password-style textbox containing circular blobs instead of text,
  31608. you could set this value to 0x25cf, which is the unicode character
  31609. for a black splodge (not all fonts include this, though), or 0x2022,
  31610. which is a bullet (probably the best choice for linux).
  31611. */
  31612. explicit TextEditor (const String& componentName = String::empty,
  31613. juce_wchar passwordCharacter = 0);
  31614. /** Destructor. */
  31615. virtual ~TextEditor();
  31616. /** Puts the editor into either multi- or single-line mode.
  31617. By default, the editor will be in single-line mode, so use this if you need a multi-line
  31618. editor.
  31619. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  31620. on if you want a multi-line editor with line-breaks.
  31621. @see isMultiLine, setReturnKeyStartsNewLine
  31622. */
  31623. void setMultiLine (bool shouldBeMultiLine,
  31624. bool shouldWordWrap = true);
  31625. /** Returns true if the editor is in multi-line mode.
  31626. */
  31627. bool isMultiLine() const;
  31628. /** Changes the behaviour of the return key.
  31629. If set to true, the return key will insert a new-line into the text; if false
  31630. it will trigger a call to the TextEditor::Listener::textEditorReturnKeyPressed()
  31631. method. By default this is set to false, and when true it will only insert
  31632. new-lines when in multi-line mode (see setMultiLine()).
  31633. */
  31634. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  31635. /** Returns the value set by setReturnKeyStartsNewLine().
  31636. See setReturnKeyStartsNewLine() for more info.
  31637. */
  31638. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  31639. /** Indicates whether the tab key should be accepted and used to input a tab character,
  31640. or whether it gets ignored.
  31641. By default the tab key is ignored, so that it can be used to switch keyboard focus
  31642. between components.
  31643. */
  31644. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  31645. /** Returns true if the tab key is being used for input.
  31646. @see setTabKeyUsedAsCharacter
  31647. */
  31648. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  31649. /** Changes the editor to read-only mode.
  31650. By default, the text editor is not read-only. If you're making it read-only, you
  31651. might also want to call setCaretVisible (false) to get rid of the caret.
  31652. The text can still be highlighted and copied when in read-only mode.
  31653. @see isReadOnly, setCaretVisible
  31654. */
  31655. void setReadOnly (bool shouldBeReadOnly);
  31656. /** Returns true if the editor is in read-only mode.
  31657. */
  31658. bool isReadOnly() const;
  31659. /** Makes the caret visible or invisible.
  31660. By default the caret is visible.
  31661. @see setCaretColour, setCaretPosition
  31662. */
  31663. void setCaretVisible (bool shouldBeVisible);
  31664. /** Returns true if the caret is enabled.
  31665. @see setCaretVisible
  31666. */
  31667. bool isCaretVisible() const { return caretVisible; }
  31668. /** Enables/disables a vertical scrollbar.
  31669. (This only applies when in multi-line mode). When the text gets too long to fit
  31670. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  31671. this is enabled, the scrollbar will be hidden unless it's needed.
  31672. By default the scrollbar is enabled.
  31673. */
  31674. void setScrollbarsShown (bool shouldBeEnabled);
  31675. /** Returns true if scrollbars are enabled.
  31676. @see setScrollbarsShown
  31677. */
  31678. bool areScrollbarsShown() const { return scrollbarVisible; }
  31679. /** Changes the password character used to disguise the text.
  31680. @param passwordCharacter if this is not zero, this character will be used as a replacement
  31681. for all characters that are drawn on screen - e.g. to create
  31682. a password-style textbox containing circular blobs instead of text,
  31683. you could set this value to 0x25cf, which is the unicode character
  31684. for a black splodge (not all fonts include this, though), or 0x2022,
  31685. which is a bullet (probably the best choice for linux).
  31686. */
  31687. void setPasswordCharacter (juce_wchar passwordCharacter);
  31688. /** Returns the current password character.
  31689. @see setPasswordCharacter
  31690. */
  31691. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  31692. /** Allows a right-click menu to appear for the editor.
  31693. (This defaults to being enabled).
  31694. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  31695. of options such as cut/copy/paste, undo/redo, etc.
  31696. */
  31697. void setPopupMenuEnabled (bool menuEnabled);
  31698. /** Returns true if the right-click menu is enabled.
  31699. @see setPopupMenuEnabled
  31700. */
  31701. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  31702. /** Returns true if a popup-menu is currently being displayed.
  31703. */
  31704. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  31705. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  31706. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31707. methods.
  31708. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31709. */
  31710. enum ColourIds
  31711. {
  31712. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  31713. transparent if necessary. */
  31714. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  31715. that because the editor can contain multiple colours, calling this
  31716. method won't change the colour of existing text - to do that, call
  31717. applyFontToAllText() after calling this method.*/
  31718. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  31719. the text - this can be transparent if you don't want to show any
  31720. highlighting.*/
  31721. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  31722. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  31723. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  31724. the edge of the component. */
  31725. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  31726. the edge of the component when it has focus. */
  31727. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  31728. around the edge of the editor. */
  31729. };
  31730. /** Sets the font to use for newly added text.
  31731. This will change the font that will be used next time any text is added or entered
  31732. into the editor. It won't change the font of any existing text - to do that, use
  31733. applyFontToAllText() instead.
  31734. @see applyFontToAllText
  31735. */
  31736. void setFont (const Font& newFont);
  31737. /** Applies a font to all the text in the editor.
  31738. This will also set the current font to use for any new text that's added.
  31739. @see setFont
  31740. */
  31741. void applyFontToAllText (const Font& newFont);
  31742. /** Returns the font that's currently being used for new text.
  31743. @see setFont
  31744. */
  31745. const Font getFont() const;
  31746. /** If set to true, focusing on the editor will highlight all its text.
  31747. (Set to false by default).
  31748. This is useful for boxes where you expect the user to re-enter all the
  31749. text when they focus on the component, rather than editing what's already there.
  31750. */
  31751. void setSelectAllWhenFocused (bool b);
  31752. /** Sets limits on the characters that can be entered.
  31753. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  31754. limit is set
  31755. @param allowedCharacters if this is non-empty, then only characters that occur in
  31756. this string are allowed to be entered into the editor.
  31757. */
  31758. void setInputRestrictions (int maxTextLength,
  31759. const String& allowedCharacters = String::empty);
  31760. /** When the text editor is empty, it can be set to display a message.
  31761. This is handy for things like telling the user what to type in the box - the
  31762. string is only displayed, it's not taken to actually be the contents of
  31763. the editor.
  31764. */
  31765. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  31766. /** Changes the size of the scrollbars that are used.
  31767. Handy if you need smaller scrollbars for a small text box.
  31768. */
  31769. void setScrollBarThickness (int newThicknessPixels);
  31770. /** Shows or hides the buttons on any scrollbars that are used.
  31771. @see ScrollBar::setButtonVisibility
  31772. */
  31773. void setScrollBarButtonVisibility (bool buttonsVisible);
  31774. /**
  31775. Receives callbacks from a TextEditor component when it changes.
  31776. @see TextEditor::addListener
  31777. */
  31778. class JUCE_API Listener
  31779. {
  31780. public:
  31781. /** Destructor. */
  31782. virtual ~Listener() {}
  31783. /** Called when the user changes the text in some way. */
  31784. virtual void textEditorTextChanged (TextEditor& editor);
  31785. /** Called when the user presses the return key. */
  31786. virtual void textEditorReturnKeyPressed (TextEditor& editor);
  31787. /** Called when the user presses the escape key. */
  31788. virtual void textEditorEscapeKeyPressed (TextEditor& editor);
  31789. /** Called when the text editor loses focus. */
  31790. virtual void textEditorFocusLost (TextEditor& editor);
  31791. };
  31792. /** Registers a listener to be told when things happen to the text.
  31793. @see removeListener
  31794. */
  31795. void addListener (Listener* newListener);
  31796. /** Deregisters a listener.
  31797. @see addListener
  31798. */
  31799. void removeListener (Listener* listenerToRemove);
  31800. /** Returns the entire contents of the editor. */
  31801. const String getText() const;
  31802. /** Returns a section of the contents of the editor. */
  31803. const String getTextInRange (const Range<int>& textRange) const;
  31804. /** Returns true if there are no characters in the editor.
  31805. This is more efficient than calling getText().isEmpty().
  31806. */
  31807. bool isEmpty() const;
  31808. /** Sets the entire content of the editor.
  31809. This will clear the editor and insert the given text (using the current text colour
  31810. and font). You can set the current text colour using
  31811. @code setColour (TextEditor::textColourId, ...);
  31812. @endcode
  31813. @param newText the text to add
  31814. @param sendTextChangeMessage if true, this will cause a change message to
  31815. be sent to all the listeners.
  31816. @see insertText
  31817. */
  31818. void setText (const String& newText,
  31819. bool sendTextChangeMessage = true);
  31820. /** Returns a Value object that can be used to get or set the text.
  31821. Bear in mind that this operate quite slowly if your text box contains large
  31822. amounts of text, as it needs to dynamically build the string that's involved. It's
  31823. best used for small text boxes.
  31824. */
  31825. Value& getTextValue();
  31826. /** Inserts some text at the current cursor position.
  31827. If a section of the text is highlighted, it will be replaced by
  31828. this string, otherwise it will be inserted.
  31829. To delete a section of text, you can use setHighlightedRegion() to
  31830. highlight it, and call insertTextAtCursor (String::empty).
  31831. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  31832. */
  31833. void insertTextAtCaret (const String& textToInsert);
  31834. /** Deletes all the text from the editor. */
  31835. void clear();
  31836. /** Deletes the currently selected region, and puts it on the clipboard.
  31837. @see copy, paste, SystemClipboard
  31838. */
  31839. void cut();
  31840. /** Copies any currently selected region to the clipboard.
  31841. @see cut, paste, SystemClipboard
  31842. */
  31843. void copy();
  31844. /** Pastes the contents of the clipboard into the editor at the cursor position.
  31845. @see cut, copy, SystemClipboard
  31846. */
  31847. void paste();
  31848. /** Moves the caret to be in front of a given character.
  31849. @see getCaretPosition
  31850. */
  31851. void setCaretPosition (int newIndex);
  31852. /** Returns the current index of the caret.
  31853. @see setCaretPosition
  31854. */
  31855. int getCaretPosition() const;
  31856. /** Attempts to scroll the text editor so that the caret ends up at
  31857. a specified position.
  31858. This won't affect the caret's position within the text, it tries to scroll
  31859. the entire editor vertically and horizontally so that the caret is sitting
  31860. at the given position (relative to the top-left of this component).
  31861. Depending on the amount of text available, it might not be possible to
  31862. scroll far enough for the caret to reach this exact position, but it
  31863. will go as far as it can in that direction.
  31864. */
  31865. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  31866. /** Get the graphical position of the caret.
  31867. The rectangle returned is relative to the component's top-left corner.
  31868. @see scrollEditorToPositionCaret
  31869. */
  31870. const Rectangle<int> getCaretRectangle();
  31871. /** Selects a section of the text. */
  31872. void setHighlightedRegion (const Range<int>& newSelection);
  31873. /** Returns the range of characters that are selected.
  31874. If nothing is selected, this will return an empty range.
  31875. @see setHighlightedRegion
  31876. */
  31877. const Range<int> getHighlightedRegion() const { return selection; }
  31878. /** Returns the section of text that is currently selected. */
  31879. const String getHighlightedText() const;
  31880. /** Finds the index of the character at a given position.
  31881. The co-ordinates are relative to the component's top-left.
  31882. */
  31883. int getTextIndexAt (int x, int y);
  31884. /** Counts the number of characters in the text.
  31885. This is quicker than getting the text as a string if you just need to know
  31886. the length.
  31887. */
  31888. int getTotalNumChars() const;
  31889. /** Returns the total width of the text, as it is currently laid-out.
  31890. This may be larger than the size of the TextEditor, and can change when
  31891. the TextEditor is resized or the text changes.
  31892. */
  31893. int getTextWidth() const;
  31894. /** Returns the maximum height of the text, as it is currently laid-out.
  31895. This may be larger than the size of the TextEditor, and can change when
  31896. the TextEditor is resized or the text changes.
  31897. */
  31898. int getTextHeight() const;
  31899. /** Changes the size of the gap at the top and left-edge of the editor.
  31900. By default there's a gap of 4 pixels.
  31901. */
  31902. void setIndents (int newLeftIndent, int newTopIndent);
  31903. /** Changes the size of border left around the edge of the component.
  31904. @see getBorder
  31905. */
  31906. void setBorder (const BorderSize<int>& border);
  31907. /** Returns the size of border around the edge of the component.
  31908. @see setBorder
  31909. */
  31910. const BorderSize<int> getBorder() const;
  31911. /** Used to disable the auto-scrolling which keeps the cursor visible.
  31912. If true (the default), the editor will scroll when the cursor moves offscreen. If
  31913. set to false, it won't.
  31914. */
  31915. void setScrollToShowCursor (bool shouldScrollToShowCursor);
  31916. /** @internal */
  31917. void paint (Graphics& g);
  31918. /** @internal */
  31919. void paintOverChildren (Graphics& g);
  31920. /** @internal */
  31921. void mouseDown (const MouseEvent& e);
  31922. /** @internal */
  31923. void mouseUp (const MouseEvent& e);
  31924. /** @internal */
  31925. void mouseDrag (const MouseEvent& e);
  31926. /** @internal */
  31927. void mouseDoubleClick (const MouseEvent& e);
  31928. /** @internal */
  31929. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31930. /** @internal */
  31931. bool keyPressed (const KeyPress& key);
  31932. /** @internal */
  31933. bool keyStateChanged (bool isKeyDown);
  31934. /** @internal */
  31935. void focusGained (FocusChangeType cause);
  31936. /** @internal */
  31937. void focusLost (FocusChangeType cause);
  31938. /** @internal */
  31939. void resized();
  31940. /** @internal */
  31941. void enablementChanged();
  31942. /** @internal */
  31943. void colourChanged();
  31944. /** @internal */
  31945. bool isTextInputActive() const;
  31946. /** This adds the items to the popup menu.
  31947. By default it adds the cut/copy/paste items, but you can override this if
  31948. you need to replace these with your own items.
  31949. If you want to add your own items to the existing ones, you can override this,
  31950. call the base class's addPopupMenuItems() method, then append your own items.
  31951. When the menu has been shown, performPopupMenuAction() will be called to
  31952. perform the item that the user has chosen.
  31953. The default menu items will be added using item IDs in the range
  31954. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  31955. menu IDs.
  31956. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  31957. a pointer to the info about it, or may be null if the menu is being triggered
  31958. by some other means.
  31959. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  31960. */
  31961. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  31962. const MouseEvent* mouseClickEvent);
  31963. /** This is called to perform one of the items that was shown on the popup menu.
  31964. If you've overridden addPopupMenuItems(), you should also override this
  31965. to perform the actions that you've added.
  31966. If you've overridden addPopupMenuItems() but have still left the default items
  31967. on the menu, remember to call the superclass's performPopupMenuAction()
  31968. so that it can perform the default actions if that's what the user clicked on.
  31969. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  31970. */
  31971. virtual void performPopupMenuAction (int menuItemID);
  31972. protected:
  31973. /** Scrolls the minimum distance needed to get the caret into view. */
  31974. void scrollToMakeSureCursorIsVisible();
  31975. /** @internal */
  31976. void moveCaret (int newCaretPos);
  31977. /** @internal */
  31978. void moveCursorTo (int newPosition, bool isSelecting);
  31979. /** Used internally to dispatch a text-change message. */
  31980. void textChanged();
  31981. /** Begins a new transaction in the UndoManager.
  31982. */
  31983. void newTransaction();
  31984. /** Used internally to trigger an undo or redo. */
  31985. void doUndoRedo (bool isRedo);
  31986. /** Can be overridden to intercept return key presses directly */
  31987. virtual void returnPressed();
  31988. /** Can be overridden to intercept escape key presses directly */
  31989. virtual void escapePressed();
  31990. /** @internal */
  31991. void handleCommandMessage (int commandId);
  31992. private:
  31993. class Iterator;
  31994. class UniformTextSection;
  31995. class TextHolderComponent;
  31996. class InsertAction;
  31997. class RemoveAction;
  31998. friend class InsertAction;
  31999. friend class RemoveAction;
  32000. ScopedPointer <Viewport> viewport;
  32001. TextHolderComponent* textHolder;
  32002. BorderSize<int> borderSize;
  32003. bool readOnly : 1;
  32004. bool multiline : 1;
  32005. bool wordWrap : 1;
  32006. bool returnKeyStartsNewLine : 1;
  32007. bool caretVisible : 1;
  32008. bool popupMenuEnabled : 1;
  32009. bool selectAllTextWhenFocused : 1;
  32010. bool scrollbarVisible : 1;
  32011. bool wasFocused : 1;
  32012. bool caretFlashState : 1;
  32013. bool keepCursorOnScreen : 1;
  32014. bool tabKeyUsed : 1;
  32015. bool menuActive : 1;
  32016. bool valueTextNeedsUpdating : 1;
  32017. UndoManager undoManager;
  32018. float cursorX, cursorY, cursorHeight;
  32019. int maxTextLength;
  32020. Range<int> selection;
  32021. int leftIndent, topIndent;
  32022. unsigned int lastTransactionTime;
  32023. Font currentFont;
  32024. mutable int totalNumChars;
  32025. int caretPosition;
  32026. Array <UniformTextSection*> sections;
  32027. String textToShowWhenEmpty;
  32028. Colour colourForTextWhenEmpty;
  32029. juce_wchar passwordCharacter;
  32030. Value textValue;
  32031. enum
  32032. {
  32033. notDragging,
  32034. draggingSelectionStart,
  32035. draggingSelectionEnd
  32036. } dragType;
  32037. String allowedCharacters;
  32038. ListenerList <Listener> listeners;
  32039. void coalesceSimilarSections();
  32040. void splitSection (int sectionIndex, int charToSplitAt);
  32041. void clearInternal (UndoManager* um);
  32042. void insert (const String& text, int insertIndex, const Font& font,
  32043. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  32044. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  32045. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  32046. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  32047. void updateCaretPosition();
  32048. void textWasChangedByValue();
  32049. int indexAtPosition (float x, float y);
  32050. int findWordBreakAfter (int position) const;
  32051. int findWordBreakBefore (int position) const;
  32052. friend class TextHolderComponent;
  32053. friend class TextEditorViewport;
  32054. void drawContent (Graphics& g);
  32055. void updateTextHolderSize();
  32056. float getWordWrapWidth() const;
  32057. void timerCallbackInt();
  32058. void repaintCaret();
  32059. void repaintText (const Range<int>& range);
  32060. UndoManager* getUndoManager() throw();
  32061. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditor);
  32062. };
  32063. /** This typedef is just for compatibility with old code - newer code should use the TextEditor::Listener class directly. */
  32064. typedef TextEditor::Listener TextEditorListener;
  32065. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  32066. /*** End of inlined file: juce_TextEditor.h ***/
  32067. #if JUCE_VC6
  32068. #define Listener ButtonListener
  32069. #endif
  32070. /**
  32071. A component that displays a text string, and can optionally become a text
  32072. editor when clicked.
  32073. */
  32074. class JUCE_API Label : public Component,
  32075. public SettableTooltipClient,
  32076. protected TextEditorListener,
  32077. private ComponentListener,
  32078. private ValueListener
  32079. {
  32080. public:
  32081. /** Creates a Label.
  32082. @param componentName the name to give the component
  32083. @param labelText the text to show in the label
  32084. */
  32085. Label (const String& componentName = String::empty,
  32086. const String& labelText = String::empty);
  32087. /** Destructor. */
  32088. ~Label();
  32089. /** Changes the label text.
  32090. If broadcastChangeMessage is true and the new text is different to the current
  32091. text, then the class will broadcast a change message to any Label::Listener objects
  32092. that are registered.
  32093. */
  32094. void setText (const String& newText, bool broadcastChangeMessage);
  32095. /** Returns the label's current text.
  32096. @param returnActiveEditorContents if this is true and the label is currently
  32097. being edited, then this method will return the
  32098. text as it's being shown in the editor. If false,
  32099. then the value returned here won't be updated until
  32100. the user has finished typing and pressed the return
  32101. key.
  32102. */
  32103. const String getText (bool returnActiveEditorContents = false) const;
  32104. /** Returns the text content as a Value object.
  32105. You can call Value::referTo() on this object to make the label read and control
  32106. a Value object that you supply.
  32107. */
  32108. Value& getTextValue() { return textValue; }
  32109. /** Changes the font to use to draw the text.
  32110. @see getFont
  32111. */
  32112. void setFont (const Font& newFont);
  32113. /** Returns the font currently being used.
  32114. @see setFont
  32115. */
  32116. const Font& getFont() const throw();
  32117. /** A set of colour IDs to use to change the colour of various aspects of the label.
  32118. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32119. methods.
  32120. Note that you can also use the constants from TextEditor::ColourIds to change the
  32121. colour of the text editor that is opened when a label is editable.
  32122. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32123. */
  32124. enum ColourIds
  32125. {
  32126. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  32127. textColourId = 0x1000281, /**< The colour for the text. */
  32128. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  32129. Leave this transparent to not have an outline. */
  32130. };
  32131. /** Sets the style of justification to be used for positioning the text.
  32132. (The default is Justification::centredLeft)
  32133. */
  32134. void setJustificationType (const Justification& justification);
  32135. /** Returns the type of justification, as set in setJustificationType(). */
  32136. const Justification getJustificationType() const throw() { return justification; }
  32137. /** Changes the gap that is left between the edge of the component and the text.
  32138. By default there's a small gap left at the sides of the component to allow for
  32139. the drawing of the border, but you can change this if necessary.
  32140. */
  32141. void setBorderSize (int horizontalBorder, int verticalBorder);
  32142. /** Returns the size of the horizontal gap being left around the text.
  32143. */
  32144. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  32145. /** Returns the size of the vertical gap being left around the text.
  32146. */
  32147. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  32148. /** Makes this label "stick to" another component.
  32149. This will cause the label to follow another component around, staying
  32150. either to its left or above it.
  32151. @param owner the component to follow
  32152. @param onLeft if true, the label will stay on the left of its component; if
  32153. false, it will stay above it.
  32154. */
  32155. void attachToComponent (Component* owner, bool onLeft);
  32156. /** If this label has been attached to another component using attachToComponent, this
  32157. returns the other component.
  32158. Returns 0 if the label is not attached.
  32159. */
  32160. Component* getAttachedComponent() const;
  32161. /** If the label is attached to the left of another component, this returns true.
  32162. Returns false if the label is above the other component. This is only relevent if
  32163. attachToComponent() has been called.
  32164. */
  32165. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  32166. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  32167. using ellipsis.
  32168. @see Graphics::drawFittedText
  32169. */
  32170. void setMinimumHorizontalScale (float newScale);
  32171. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  32172. /**
  32173. A class for receiving events from a Label.
  32174. You can register a Label::Listener with a Label using the Label::addListener()
  32175. method, and it will be called when the text of the label changes, either because
  32176. of a call to Label::setText() or by the user editing the text (if the label is
  32177. editable).
  32178. @see Label::addListener, Label::removeListener
  32179. */
  32180. class JUCE_API Listener
  32181. {
  32182. public:
  32183. /** Destructor. */
  32184. virtual ~Listener() {}
  32185. /** Called when a Label's text has changed.
  32186. */
  32187. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  32188. };
  32189. /** Registers a listener that will be called when the label's text changes. */
  32190. void addListener (Listener* listener);
  32191. /** Deregisters a previously-registered listener. */
  32192. void removeListener (Listener* listener);
  32193. /** Makes the label turn into a TextEditor when clicked.
  32194. By default this is turned off.
  32195. If turned on, then single- or double-clicking will turn the label into
  32196. an editor. If the user then changes the text, then the ChangeBroadcaster
  32197. base class will be used to send change messages to any listeners that
  32198. have registered.
  32199. If the user changes the text, the textWasEdited() method will be called
  32200. afterwards, and subclasses can override this if they need to do anything
  32201. special.
  32202. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  32203. @param editOnDoubleClick if true, a double-click is needed to start editing
  32204. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  32205. edited will discard any changes; if false, then this will
  32206. commit the changes.
  32207. @see showEditor, setEditorColours, TextEditor
  32208. */
  32209. void setEditable (bool editOnSingleClick,
  32210. bool editOnDoubleClick = false,
  32211. bool lossOfFocusDiscardsChanges = false);
  32212. /** Returns true if this option was set using setEditable(). */
  32213. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  32214. /** Returns true if this option was set using setEditable(). */
  32215. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  32216. /** Returns true if this option has been set in a call to setEditable(). */
  32217. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  32218. /** Returns true if the user can edit this label's text. */
  32219. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  32220. /** Makes the editor appear as if the label had been clicked by the user.
  32221. @see textWasEdited, setEditable
  32222. */
  32223. void showEditor();
  32224. /** Hides the editor if it was being shown.
  32225. @param discardCurrentEditorContents if true, the label's text will be
  32226. reset to whatever it was before the editor
  32227. was shown; if false, the current contents of the
  32228. editor will be used to set the label's text
  32229. before it is hidden.
  32230. */
  32231. void hideEditor (bool discardCurrentEditorContents);
  32232. /** Returns true if the editor is currently focused and active. */
  32233. bool isBeingEdited() const throw();
  32234. protected:
  32235. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  32236. Subclasses can override this if they need to customise this component in some way.
  32237. */
  32238. virtual TextEditor* createEditorComponent();
  32239. /** Called after the user changes the text. */
  32240. virtual void textWasEdited();
  32241. /** Called when the text has been altered. */
  32242. virtual void textWasChanged();
  32243. /** Called when the text editor has just appeared, due to a user click or other focus change. */
  32244. virtual void editorShown (TextEditor* editorComponent);
  32245. /** Called when the text editor is going to be deleted, after editing has finished. */
  32246. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  32247. /** @internal */
  32248. void paint (Graphics& g);
  32249. /** @internal */
  32250. void resized();
  32251. /** @internal */
  32252. void mouseUp (const MouseEvent& e);
  32253. /** @internal */
  32254. void mouseDoubleClick (const MouseEvent& e);
  32255. /** @internal */
  32256. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  32257. /** @internal */
  32258. void componentParentHierarchyChanged (Component& component);
  32259. /** @internal */
  32260. void componentVisibilityChanged (Component& component);
  32261. /** @internal */
  32262. void inputAttemptWhenModal();
  32263. /** @internal */
  32264. void focusGained (FocusChangeType);
  32265. /** @internal */
  32266. void enablementChanged();
  32267. /** @internal */
  32268. KeyboardFocusTraverser* createFocusTraverser();
  32269. /** @internal */
  32270. void textEditorTextChanged (TextEditor& editor);
  32271. /** @internal */
  32272. void textEditorReturnKeyPressed (TextEditor& editor);
  32273. /** @internal */
  32274. void textEditorEscapeKeyPressed (TextEditor& editor);
  32275. /** @internal */
  32276. void textEditorFocusLost (TextEditor& editor);
  32277. /** @internal */
  32278. void colourChanged();
  32279. /** @internal */
  32280. void valueChanged (Value&);
  32281. private:
  32282. Value textValue;
  32283. String lastTextValue;
  32284. Font font;
  32285. Justification justification;
  32286. ScopedPointer<TextEditor> editor;
  32287. ListenerList<Listener> listeners;
  32288. WeakReference<Component> ownerComponent;
  32289. int horizontalBorderSize, verticalBorderSize;
  32290. float minimumHorizontalScale;
  32291. bool editSingleClick : 1;
  32292. bool editDoubleClick : 1;
  32293. bool lossOfFocusDiscardsChanges : 1;
  32294. bool leftOfOwnerComp : 1;
  32295. bool updateFromTextEditorContents (TextEditor&);
  32296. void callChangeListeners();
  32297. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Label);
  32298. };
  32299. /** This typedef is just for compatibility with old code - newer code should use the Label::Listener class directly. */
  32300. typedef Label::Listener LabelListener;
  32301. #if JUCE_VC6
  32302. #undef Listener
  32303. #endif
  32304. #endif // __JUCE_LABEL_JUCEHEADER__
  32305. /*** End of inlined file: juce_Label.h ***/
  32306. #if JUCE_VC6
  32307. #define Listener SliderListener
  32308. #endif
  32309. /**
  32310. A component that lets the user choose from a drop-down list of choices.
  32311. The combo-box has a list of text strings, each with an associated id number,
  32312. that will be shown in the drop-down list when the user clicks on the component.
  32313. The currently selected choice is displayed in the combo-box, and this can
  32314. either be read-only text, or editable.
  32315. To find out when the user selects a different item or edits the text, you
  32316. can register a ComboBox::Listener to receive callbacks.
  32317. @see ComboBox::Listener
  32318. */
  32319. class JUCE_API ComboBox : public Component,
  32320. public SettableTooltipClient,
  32321. public LabelListener, // (can't use Label::Listener due to idiotic VC2005 bug)
  32322. public ValueListener,
  32323. private AsyncUpdater
  32324. {
  32325. public:
  32326. /** Creates a combo-box.
  32327. On construction, the text field will be empty, so you should call the
  32328. setSelectedId() or setText() method to choose the initial value before
  32329. displaying it.
  32330. @param componentName the name to set for the component (see Component::setName())
  32331. */
  32332. explicit ComboBox (const String& componentName = String::empty);
  32333. /** Destructor. */
  32334. ~ComboBox();
  32335. /** Sets whether the test in the combo-box is editable.
  32336. The default state for a new ComboBox is non-editable, and can only be changed
  32337. by choosing from the drop-down list.
  32338. */
  32339. void setEditableText (bool isEditable);
  32340. /** Returns true if the text is directly editable.
  32341. @see setEditableText
  32342. */
  32343. bool isTextEditable() const throw();
  32344. /** Sets the style of justification to be used for positioning the text.
  32345. The default is Justification::centredLeft. The text is displayed using a
  32346. Label component inside the ComboBox.
  32347. */
  32348. void setJustificationType (const Justification& justification);
  32349. /** Returns the current justification for the text box.
  32350. @see setJustificationType
  32351. */
  32352. const Justification getJustificationType() const throw();
  32353. /** Adds an item to be shown in the drop-down list.
  32354. @param newItemText the text of the item to show in the list
  32355. @param newItemId an associated ID number that can be set or retrieved - see
  32356. getSelectedId() and setSelectedId(). Note that this value can not
  32357. be 0!
  32358. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  32359. */
  32360. void addItem (const String& newItemText, int newItemId);
  32361. /** Adds a separator line to the drop-down list.
  32362. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  32363. */
  32364. void addSeparator();
  32365. /** Adds a heading to the drop-down list, so that you can group the items into
  32366. different sections.
  32367. The headings are indented slightly differently to set them apart from the
  32368. items on the list, and obviously can't be selected. You might want to add
  32369. separators between your sections too.
  32370. @see addItem, addSeparator
  32371. */
  32372. void addSectionHeading (const String& headingName);
  32373. /** This allows items in the drop-down list to be selectively disabled.
  32374. When you add an item, it's enabled by default, but you can call this
  32375. method to change its status.
  32376. If you disable an item which is already selected, this won't change the
  32377. current selection - it just stops the user choosing that item from the list.
  32378. */
  32379. void setItemEnabled (int itemId, bool shouldBeEnabled);
  32380. /** Returns true if the given item is enabled. */
  32381. bool isItemEnabled (int itemId) const throw();
  32382. /** Changes the text for an existing item.
  32383. */
  32384. void changeItemText (int itemId, const String& newText);
  32385. /** Removes all the items from the drop-down list.
  32386. If this call causes the content to be cleared, then a change-message
  32387. will be broadcast unless dontSendChangeMessage is true.
  32388. @see addItem, removeItem, getNumItems
  32389. */
  32390. void clear (bool dontSendChangeMessage = false);
  32391. /** Returns the number of items that have been added to the list.
  32392. Note that this doesn't include headers or separators.
  32393. */
  32394. int getNumItems() const throw();
  32395. /** Returns the text for one of the items in the list.
  32396. Note that this doesn't include headers or separators.
  32397. @param index the item's index from 0 to (getNumItems() - 1)
  32398. */
  32399. const String getItemText (int index) const;
  32400. /** Returns the ID for one of the items in the list.
  32401. Note that this doesn't include headers or separators.
  32402. @param index the item's index from 0 to (getNumItems() - 1)
  32403. */
  32404. int getItemId (int index) const throw();
  32405. /** Returns the index in the list of a particular item ID.
  32406. If no such ID is found, this will return -1.
  32407. */
  32408. int indexOfItemId (int itemId) const throw();
  32409. /** Returns the ID of the item that's currently shown in the box.
  32410. If no item is selected, or if the text is editable and the user
  32411. has entered something which isn't one of the items in the list, then
  32412. this will return 0.
  32413. @see setSelectedId, getSelectedItemIndex, getText
  32414. */
  32415. int getSelectedId() const throw();
  32416. /** Returns a Value object that can be used to get or set the selected item's ID.
  32417. You can call Value::referTo() on this object to make the combo box control
  32418. another Value object.
  32419. */
  32420. Value& getSelectedIdAsValue() { return currentId; }
  32421. /** Sets one of the items to be the current selection.
  32422. This will set the ComboBox's text to that of the item that matches
  32423. this ID.
  32424. @param newItemId the new item to select
  32425. @param dontSendChangeMessage if set to true, this method won't trigger a
  32426. change notification
  32427. @see getSelectedId, setSelectedItemIndex, setText
  32428. */
  32429. void setSelectedId (int newItemId, bool dontSendChangeMessage = false);
  32430. /** Returns the index of the item that's currently shown in the box.
  32431. If no item is selected, or if the text is editable and the user
  32432. has entered something which isn't one of the items in the list, then
  32433. this will return -1.
  32434. @see setSelectedItemIndex, getSelectedId, getText
  32435. */
  32436. int getSelectedItemIndex() const;
  32437. /** Sets one of the items to be the current selection.
  32438. This will set the ComboBox's text to that of the item at the given
  32439. index in the list.
  32440. @param newItemIndex the new item to select
  32441. @param dontSendChangeMessage if set to true, this method won't trigger a
  32442. change notification
  32443. @see getSelectedItemIndex, setSelectedId, setText
  32444. */
  32445. void setSelectedItemIndex (int newItemIndex, bool dontSendChangeMessage = false);
  32446. /** Returns the text that is currently shown in the combo-box's text field.
  32447. If the ComboBox has editable text, then this text may have been edited
  32448. by the user; otherwise it will be one of the items from the list, or
  32449. possibly an empty string if nothing was selected.
  32450. @see setText, getSelectedId, getSelectedItemIndex
  32451. */
  32452. const String getText() const;
  32453. /** Sets the contents of the combo-box's text field.
  32454. The text passed-in will be set as the current text regardless of whether
  32455. it is one of the items in the list. If the current text isn't one of the
  32456. items, then getSelectedId() will return -1, otherwise it wil return
  32457. the approriate ID.
  32458. @param newText the text to select
  32459. @param dontSendChangeMessage if set to true, this method won't trigger a
  32460. change notification
  32461. @see getText
  32462. */
  32463. void setText (const String& newText, bool dontSendChangeMessage = false);
  32464. /** Programmatically opens the text editor to allow the user to edit the current item.
  32465. This is the same effect as when the box is clicked-on.
  32466. @see Label::showEditor();
  32467. */
  32468. void showEditor();
  32469. /** Pops up the combo box's list. */
  32470. void showPopup();
  32471. /**
  32472. A class for receiving events from a ComboBox.
  32473. You can register a ComboBox::Listener with a ComboBox using the ComboBox::addListener()
  32474. method, and it will be called when the selected item in the box changes.
  32475. @see ComboBox::addListener, ComboBox::removeListener
  32476. */
  32477. class JUCE_API Listener
  32478. {
  32479. public:
  32480. /** Destructor. */
  32481. virtual ~Listener() {}
  32482. /** Called when a ComboBox has its selected item changed. */
  32483. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  32484. };
  32485. /** Registers a listener that will be called when the box's content changes. */
  32486. void addListener (Listener* listener);
  32487. /** Deregisters a previously-registered listener. */
  32488. void removeListener (Listener* listener);
  32489. /** Sets a message to display when there is no item currently selected.
  32490. @see getTextWhenNothingSelected
  32491. */
  32492. void setTextWhenNothingSelected (const String& newMessage);
  32493. /** Returns the text that is shown when no item is selected.
  32494. @see setTextWhenNothingSelected
  32495. */
  32496. const String getTextWhenNothingSelected() const;
  32497. /** Sets the message to show when there are no items in the list, and the user clicks
  32498. on the drop-down box.
  32499. By default it just says "no choices", but this lets you change it to something more
  32500. meaningful.
  32501. */
  32502. void setTextWhenNoChoicesAvailable (const String& newMessage);
  32503. /** Returns the text shown when no items have been added to the list.
  32504. @see setTextWhenNoChoicesAvailable
  32505. */
  32506. const String getTextWhenNoChoicesAvailable() const;
  32507. /** Gives the ComboBox a tooltip. */
  32508. void setTooltip (const String& newTooltip);
  32509. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  32510. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32511. methods.
  32512. To change the colours of the menu that pops up
  32513. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32514. */
  32515. enum ColourIds
  32516. {
  32517. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  32518. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  32519. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  32520. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  32521. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  32522. };
  32523. /** @internal */
  32524. void labelTextChanged (Label*);
  32525. /** @internal */
  32526. void enablementChanged();
  32527. /** @internal */
  32528. void colourChanged();
  32529. /** @internal */
  32530. void focusGained (Component::FocusChangeType cause);
  32531. /** @internal */
  32532. void focusLost (Component::FocusChangeType cause);
  32533. /** @internal */
  32534. void handleAsyncUpdate();
  32535. /** @internal */
  32536. const String getTooltip() { return label->getTooltip(); }
  32537. /** @internal */
  32538. void mouseDown (const MouseEvent&);
  32539. /** @internal */
  32540. void mouseDrag (const MouseEvent&);
  32541. /** @internal */
  32542. void mouseUp (const MouseEvent&);
  32543. /** @internal */
  32544. void lookAndFeelChanged();
  32545. /** @internal */
  32546. void paint (Graphics&);
  32547. /** @internal */
  32548. void resized();
  32549. /** @internal */
  32550. bool keyStateChanged (bool isKeyDown);
  32551. /** @internal */
  32552. bool keyPressed (const KeyPress&);
  32553. /** @internal */
  32554. void valueChanged (Value&);
  32555. private:
  32556. struct ItemInfo
  32557. {
  32558. ItemInfo (const String& name, int itemId, bool isEnabled, bool isHeading);
  32559. bool isSeparator() const throw();
  32560. bool isRealItem() const throw();
  32561. String name;
  32562. int itemId;
  32563. bool isEnabled : 1, isHeading : 1;
  32564. };
  32565. OwnedArray <ItemInfo> items;
  32566. Value currentId;
  32567. int lastCurrentId;
  32568. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  32569. ListenerList <Listener> listeners;
  32570. ScopedPointer<Label> label;
  32571. String textWhenNothingSelected, noChoicesMessage;
  32572. ItemInfo* getItemForId (int itemId) const throw();
  32573. ItemInfo* getItemForIndex (int index) const throw();
  32574. bool selectIfEnabled (int index);
  32575. static void popupMenuFinishedCallback (int, ComboBox*);
  32576. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBox);
  32577. };
  32578. /** This typedef is just for compatibility with old code - newer code should use the ComboBox::Listener class directly. */
  32579. typedef ComboBox::Listener ComboBoxListener;
  32580. #if JUCE_VC6
  32581. #undef Listener
  32582. #endif
  32583. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  32584. /*** End of inlined file: juce_ComboBox.h ***/
  32585. /**
  32586. Manages the state of some audio and midi i/o devices.
  32587. This class keeps tracks of a currently-selected audio device, through
  32588. with which it continuously streams data from an audio callback, as well as
  32589. one or more midi inputs.
  32590. The idea is that your application will create one global instance of this object,
  32591. and let it take care of creating and deleting specific types of audio devices
  32592. internally. So when the device is changed, your callbacks will just keep running
  32593. without having to worry about this.
  32594. The manager can save and reload all of its device settings as XML, which
  32595. makes it very easy for you to save and reload the audio setup of your
  32596. application.
  32597. And to make it easy to let the user change its settings, there's a component
  32598. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  32599. device selection/sample-rate/latency controls.
  32600. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  32601. call addAudioCallback() to register your audio callback with it, and use that to process
  32602. your audio data.
  32603. The manager also acts as a handy hub for incoming midi messages, allowing a
  32604. listener to register for messages from either a specific midi device, or from whatever
  32605. the current default midi input device is. The listener then doesn't have to worry about
  32606. re-registering with different midi devices if they are changed or deleted.
  32607. And yet another neat trick is that amount of CPU time being used is measured and
  32608. available with the getCpuUsage() method.
  32609. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  32610. listeners whenever one of its settings is changed.
  32611. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  32612. */
  32613. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  32614. {
  32615. public:
  32616. /** Creates a default AudioDeviceManager.
  32617. Initially no audio device will be selected. You should call the initialise() method
  32618. and register an audio callback with setAudioCallback() before it'll be able to
  32619. actually make any noise.
  32620. */
  32621. AudioDeviceManager();
  32622. /** Destructor. */
  32623. ~AudioDeviceManager();
  32624. /**
  32625. This structure holds a set of properties describing the current audio setup.
  32626. An AudioDeviceManager uses this class to save/load its current settings, and to
  32627. specify your preferred options when opening a device.
  32628. @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
  32629. */
  32630. struct JUCE_API AudioDeviceSetup
  32631. {
  32632. /** Creates an AudioDeviceSetup object.
  32633. The default constructor sets all the member variables to indicate default values.
  32634. You can then fill-in any values you want to before passing the object to
  32635. AudioDeviceManager::initialise().
  32636. */
  32637. AudioDeviceSetup();
  32638. bool operator== (const AudioDeviceSetup& other) const;
  32639. /** The name of the audio device used for output.
  32640. The name has to be one of the ones listed by the AudioDeviceManager's currently
  32641. selected device type.
  32642. This may be the same as the input device.
  32643. An empty string indicates the default device.
  32644. */
  32645. String outputDeviceName;
  32646. /** The name of the audio device used for input.
  32647. This may be the same as the output device.
  32648. An empty string indicates the default device.
  32649. */
  32650. String inputDeviceName;
  32651. /** The current sample rate.
  32652. This rate is used for both the input and output devices.
  32653. A value of 0 indicates the default rate.
  32654. */
  32655. double sampleRate;
  32656. /** The buffer size, in samples.
  32657. This buffer size is used for both the input and output devices.
  32658. A value of 0 indicates the default buffer size.
  32659. */
  32660. int bufferSize;
  32661. /** The set of active input channels.
  32662. The bits that are set in this array indicate the channels of the
  32663. input device that are active.
  32664. If useDefaultInputChannels is true, this value is ignored.
  32665. */
  32666. BigInteger inputChannels;
  32667. /** If this is true, it indicates that the inputChannels array
  32668. should be ignored, and instead, the device's default channels
  32669. should be used.
  32670. */
  32671. bool useDefaultInputChannels;
  32672. /** The set of active output channels.
  32673. The bits that are set in this array indicate the channels of the
  32674. input device that are active.
  32675. If useDefaultOutputChannels is true, this value is ignored.
  32676. */
  32677. BigInteger outputChannels;
  32678. /** If this is true, it indicates that the outputChannels array
  32679. should be ignored, and instead, the device's default channels
  32680. should be used.
  32681. */
  32682. bool useDefaultOutputChannels;
  32683. };
  32684. /** Opens a set of audio devices ready for use.
  32685. This will attempt to open either a default audio device, or one that was
  32686. previously saved as XML.
  32687. @param numInputChannelsNeeded a minimum number of input channels needed
  32688. by your app.
  32689. @param numOutputChannelsNeeded a minimum number of output channels to open
  32690. @param savedState either a previously-saved state that was produced
  32691. by createStateXml(), or 0 if you want the manager
  32692. to choose the best device to open.
  32693. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  32694. fails to open, then a default device will be used
  32695. instead. If false, then on failure, no device is
  32696. opened.
  32697. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  32698. name, then that will be used as the default device
  32699. (assuming that there wasn't one specified in the XML).
  32700. The string can actually be a simple wildcard, containing "*"
  32701. and "?" characters
  32702. @param preferredSetupOptions if this is non-null, the structure will be used as the
  32703. set of preferred settings when opening the device. If you
  32704. use this parameter, the preferredDefaultDeviceName
  32705. field will be ignored
  32706. @returns an error message if anything went wrong, or an empty string if it worked ok.
  32707. */
  32708. const String initialise (int numInputChannelsNeeded,
  32709. int numOutputChannelsNeeded,
  32710. const XmlElement* savedState,
  32711. bool selectDefaultDeviceOnFailure,
  32712. const String& preferredDefaultDeviceName = String::empty,
  32713. const AudioDeviceSetup* preferredSetupOptions = 0);
  32714. /** Returns some XML representing the current state of the manager.
  32715. This stores the current device, its samplerate, block size, etc, and
  32716. can be restored later with initialise().
  32717. */
  32718. XmlElement* createStateXml() const;
  32719. /** Returns the current device properties that are in use.
  32720. @see setAudioDeviceSetup
  32721. */
  32722. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  32723. /** Changes the current device or its settings.
  32724. If you want to change a device property, like the current sample rate or
  32725. block size, you can call getAudioDeviceSetup() to retrieve the current
  32726. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  32727. and pass it back into this method to apply the new settings.
  32728. @param newSetup the settings that you'd like to use
  32729. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  32730. settings will be taken as having been explicitly chosen by the
  32731. user, and the next time createStateXml() is called, these settings
  32732. will be returned. If it's false, then the device is treated as a
  32733. temporary or default device, and a call to createStateXml() will
  32734. return either the last settings that were made with treatAsChosenDevice
  32735. as true, or the last XML settings that were passed into initialise().
  32736. @returns an error message if anything went wrong, or an empty string if it worked ok.
  32737. @see getAudioDeviceSetup
  32738. */
  32739. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  32740. bool treatAsChosenDevice);
  32741. /** Returns the currently-active audio device. */
  32742. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  32743. /** Returns the type of audio device currently in use.
  32744. @see setCurrentAudioDeviceType
  32745. */
  32746. const String getCurrentAudioDeviceType() const { return currentDeviceType; }
  32747. /** Returns the currently active audio device type object.
  32748. Don't keep a copy of this pointer - it's owned by the device manager and could
  32749. change at any time.
  32750. */
  32751. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  32752. /** Changes the class of audio device being used.
  32753. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  32754. this because there's only one type: CoreAudio.
  32755. For a list of types, see getAvailableDeviceTypes().
  32756. */
  32757. void setCurrentAudioDeviceType (const String& type,
  32758. bool treatAsChosenDevice);
  32759. /** Closes the currently-open device.
  32760. You can call restartLastAudioDevice() later to reopen it in the same state
  32761. that it was just in.
  32762. */
  32763. void closeAudioDevice();
  32764. /** Tries to reload the last audio device that was running.
  32765. Note that this only reloads the last device that was running before
  32766. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  32767. and can only be called after a device has been opened with SetAudioDevice().
  32768. If a device is already open, this call will do nothing.
  32769. */
  32770. void restartLastAudioDevice();
  32771. /** Registers an audio callback to be used.
  32772. The manager will redirect callbacks from whatever audio device is currently
  32773. in use to all registered callback objects. If more than one callback is
  32774. active, they will all be given the same input data, and their outputs will
  32775. be summed.
  32776. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  32777. object before returning.
  32778. To remove a callback, use removeAudioCallback().
  32779. */
  32780. void addAudioCallback (AudioIODeviceCallback* newCallback);
  32781. /** Deregisters a previously added callback.
  32782. If necessary, this method will invoke audioDeviceStopped() on the callback
  32783. object before returning.
  32784. @see addAudioCallback
  32785. */
  32786. void removeAudioCallback (AudioIODeviceCallback* callback);
  32787. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  32788. Returns a value between 0 and 1.0
  32789. */
  32790. double getCpuUsage() const;
  32791. /** Enables or disables a midi input device.
  32792. The list of devices can be obtained with the MidiInput::getDevices() method.
  32793. Any incoming messages from enabled input devices will be forwarded on to all the
  32794. listeners that have been registered with the addMidiInputCallback() method. They
  32795. can either register for messages from a particular device, or from just the
  32796. "default" midi input.
  32797. Routing the midi input via an AudioDeviceManager means that when a listener
  32798. registers for the default midi input, this default device can be changed by the
  32799. manager without the listeners having to know about it or re-register.
  32800. It also means that a listener can stay registered for a midi input that is disabled
  32801. or not present, so that when the input is re-enabled, the listener will start
  32802. receiving messages again.
  32803. @see addMidiInputCallback, isMidiInputEnabled
  32804. */
  32805. void setMidiInputEnabled (const String& midiInputDeviceName, bool enabled);
  32806. /** Returns true if a given midi input device is being used.
  32807. @see setMidiInputEnabled
  32808. */
  32809. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  32810. /** Registers a listener for callbacks when midi events arrive from a midi input.
  32811. The device name can be empty to indicate that it wants events from whatever the
  32812. current "default" device is. Or it can be the name of one of the midi input devices
  32813. (see MidiInput::getDevices() for the names).
  32814. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  32815. events forwarded on to listeners.
  32816. */
  32817. void addMidiInputCallback (const String& midiInputDeviceName,
  32818. MidiInputCallback* callback);
  32819. /** Removes a listener that was previously registered with addMidiInputCallback().
  32820. */
  32821. void removeMidiInputCallback (const String& midiInputDeviceName,
  32822. MidiInputCallback* callback);
  32823. /** Sets a midi output device to use as the default.
  32824. The list of devices can be obtained with the MidiOutput::getDevices() method.
  32825. The specified device will be opened automatically and can be retrieved with the
  32826. getDefaultMidiOutput() method.
  32827. Pass in an empty string to deselect all devices. For the default device, you
  32828. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  32829. @see getDefaultMidiOutput, getDefaultMidiOutputName
  32830. */
  32831. void setDefaultMidiOutput (const String& deviceName);
  32832. /** Returns the name of the default midi output.
  32833. @see setDefaultMidiOutput, getDefaultMidiOutput
  32834. */
  32835. const String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  32836. /** Returns the current default midi output device.
  32837. If no device has been selected, or the device can't be opened, this will
  32838. return 0.
  32839. @see getDefaultMidiOutputName
  32840. */
  32841. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  32842. /** Returns a list of the types of device supported.
  32843. */
  32844. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  32845. /** Creates a list of available types.
  32846. This will add a set of new AudioIODeviceType objects to the specified list, to
  32847. represent each available types of device.
  32848. You can override this if your app needs to do something specific, like avoid
  32849. using DirectSound devices, etc.
  32850. */
  32851. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  32852. /** Plays a beep through the current audio device.
  32853. This is here to allow the audio setup UI panels to easily include a "test"
  32854. button so that the user can check where the audio is coming from.
  32855. */
  32856. void playTestSound();
  32857. /** Turns on level-measuring.
  32858. When enabled, the device manager will measure the peak input level
  32859. across all channels, and you can get this level by calling getCurrentInputLevel().
  32860. This is mainly intended for audio setup UI panels to use to create a mic
  32861. level display, so that the user can check that they've selected the right
  32862. device.
  32863. A simple filter is used to make the level decay smoothly, but this is
  32864. only intended for giving rough feedback, and not for any kind of accurate
  32865. measurement.
  32866. */
  32867. void enableInputLevelMeasurement (bool enableMeasurement);
  32868. /** Returns the current input level.
  32869. To use this, you must first enable it by calling enableInputLevelMeasurement().
  32870. See enableInputLevelMeasurement() for more info.
  32871. */
  32872. double getCurrentInputLevel() const;
  32873. /** Returns the a lock that can be used to synchronise access to the audio callback.
  32874. Obviously while this is locked, you're blocking the audio thread from running, so
  32875. it must only be used for very brief periods when absolutely necessary.
  32876. */
  32877. CriticalSection& getAudioCallbackLock() throw() { return audioCallbackLock; }
  32878. /** Returns the a lock that can be used to synchronise access to the midi callback.
  32879. Obviously while this is locked, you're blocking the midi system from running, so
  32880. it must only be used for very brief periods when absolutely necessary.
  32881. */
  32882. CriticalSection& getMidiCallbackLock() throw() { return midiCallbackLock; }
  32883. private:
  32884. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  32885. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  32886. AudioDeviceSetup currentSetup;
  32887. ScopedPointer <AudioIODevice> currentAudioDevice;
  32888. SortedSet <AudioIODeviceCallback*> callbacks;
  32889. int numInputChansNeeded, numOutputChansNeeded;
  32890. String currentDeviceType;
  32891. BigInteger inputChannels, outputChannels;
  32892. ScopedPointer <XmlElement> lastExplicitSettings;
  32893. mutable bool listNeedsScanning;
  32894. bool useInputNames;
  32895. int inputLevelMeasurementEnabledCount;
  32896. double inputLevel;
  32897. ScopedPointer <AudioSampleBuffer> testSound;
  32898. int testSoundPosition;
  32899. AudioSampleBuffer tempBuffer;
  32900. StringArray midiInsFromXml;
  32901. OwnedArray <MidiInput> enabledMidiInputs;
  32902. Array <MidiInputCallback*> midiCallbacks;
  32903. StringArray midiCallbackDevices;
  32904. String defaultMidiOutputName;
  32905. ScopedPointer <MidiOutput> defaultMidiOutput;
  32906. CriticalSection audioCallbackLock, midiCallbackLock;
  32907. double cpuUsageMs, timeToCpuScale;
  32908. class CallbackHandler : public AudioIODeviceCallback,
  32909. public MidiInputCallback
  32910. {
  32911. public:
  32912. void audioDeviceIOCallback (const float**, int, float**, int, int);
  32913. void audioDeviceAboutToStart (AudioIODevice*);
  32914. void audioDeviceStopped();
  32915. void handleIncomingMidiMessage (MidiInput*, const MidiMessage&);
  32916. AudioDeviceManager* owner;
  32917. };
  32918. CallbackHandler callbackHandler;
  32919. friend class CallbackHandler;
  32920. void audioDeviceIOCallbackInt (const float** inputChannelData, int totalNumInputChannels,
  32921. float** outputChannelData, int totalNumOutputChannels, int numSamples);
  32922. void audioDeviceAboutToStartInt (AudioIODevice*);
  32923. void audioDeviceStoppedInt();
  32924. void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
  32925. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  32926. const BigInteger& ins, const BigInteger& outs);
  32927. void stopDevice();
  32928. void updateXml();
  32929. void createDeviceTypesIfNeeded();
  32930. void scanDevicesIfNeeded();
  32931. void deleteCurrentDevice();
  32932. double chooseBestSampleRate (double preferred) const;
  32933. int chooseBestBufferSize (int preferred) const;
  32934. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  32935. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  32936. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager);
  32937. };
  32938. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  32939. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  32940. #endif
  32941. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  32942. #endif
  32943. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  32944. #endif
  32945. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  32946. #endif
  32947. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  32948. #endif
  32949. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  32950. /*** Start of inlined file: juce_Decibels.h ***/
  32951. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  32952. #define __JUCE_DECIBELS_JUCEHEADER__
  32953. /**
  32954. This class contains some helpful static methods for dealing with decibel values.
  32955. */
  32956. class Decibels
  32957. {
  32958. public:
  32959. /** Converts a dBFS value to its equivalent gain level.
  32960. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values. Any
  32961. decibel value lower than minusInfinityDb will return a gain of 0.
  32962. */
  32963. template <typename Type>
  32964. static Type decibelsToGain (const Type decibels,
  32965. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  32966. {
  32967. return decibels > minusInfinityDb ? powf ((Type) 10.0, decibels * (Type) 0.05)
  32968. : Type();
  32969. }
  32970. /** Converts a gain level into a dBFS value.
  32971. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values.
  32972. If the gain is 0 (or negative), then the method will return the value
  32973. provided as minusInfinityDb.
  32974. */
  32975. template <typename Type>
  32976. static Type gainToDecibels (const Type gain,
  32977. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  32978. {
  32979. return gain > Type() ? jmax (minusInfinityDb, (Type) std::log10 (gain) * (Type) 20.0)
  32980. : minusInfinityDb;
  32981. }
  32982. /** Converts a decibel reading to a string, with the 'dB' suffix.
  32983. If the decibel value is lower than minusInfinityDb, the return value will
  32984. be "-INF dB".
  32985. */
  32986. template <typename Type>
  32987. static const String toString (const Type decibels,
  32988. const int decimalPlaces = 2,
  32989. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  32990. {
  32991. String s;
  32992. if (decibels <= minusInfinityDb)
  32993. {
  32994. s = "-INF dB";
  32995. }
  32996. else
  32997. {
  32998. if (decibels >= Type())
  32999. s << '+';
  33000. s << String (decibels, decimalPlaces) << " dB";
  33001. }
  33002. return s;
  33003. }
  33004. private:
  33005. enum
  33006. {
  33007. defaultMinusInfinitydB = -100
  33008. };
  33009. Decibels(); // This class can't be instantiated, it's just a holder for static methods..
  33010. JUCE_DECLARE_NON_COPYABLE (Decibels);
  33011. };
  33012. #endif // __JUCE_DECIBELS_JUCEHEADER__
  33013. /*** End of inlined file: juce_Decibels.h ***/
  33014. #endif
  33015. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  33016. #endif
  33017. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  33018. #endif
  33019. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  33020. /*** Start of inlined file: juce_MidiFile.h ***/
  33021. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  33022. #define __JUCE_MIDIFILE_JUCEHEADER__
  33023. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  33024. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  33025. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  33026. /**
  33027. A sequence of timestamped midi messages.
  33028. This allows the sequence to be manipulated, and also to be read from and
  33029. written to a standard midi file.
  33030. @see MidiMessage, MidiFile
  33031. */
  33032. class JUCE_API MidiMessageSequence
  33033. {
  33034. public:
  33035. /** Creates an empty midi sequence object. */
  33036. MidiMessageSequence();
  33037. /** Creates a copy of another sequence. */
  33038. MidiMessageSequence (const MidiMessageSequence& other);
  33039. /** Replaces this sequence with another one. */
  33040. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  33041. /** Destructor. */
  33042. ~MidiMessageSequence();
  33043. /** Structure used to hold midi events in the sequence.
  33044. These structures act as 'handles' on the events as they are moved about in
  33045. the list, and make it quick to find the matching note-offs for note-on events.
  33046. @see MidiMessageSequence::getEventPointer
  33047. */
  33048. class MidiEventHolder
  33049. {
  33050. public:
  33051. /** Destructor. */
  33052. ~MidiEventHolder();
  33053. /** The message itself, whose timestamp is used to specify the event's time.
  33054. */
  33055. MidiMessage message;
  33056. /** The matching note-off event (if this is a note-on event).
  33057. If this isn't a note-on, this pointer will be null.
  33058. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  33059. note-offs up-to-date after events have been moved around in the sequence
  33060. or deleted.
  33061. */
  33062. MidiEventHolder* noteOffObject;
  33063. private:
  33064. friend class MidiMessageSequence;
  33065. MidiEventHolder (const MidiMessage& message);
  33066. JUCE_LEAK_DETECTOR (MidiEventHolder);
  33067. };
  33068. /** Clears the sequence. */
  33069. void clear();
  33070. /** Returns the number of events in the sequence. */
  33071. int getNumEvents() const;
  33072. /** Returns a pointer to one of the events. */
  33073. MidiEventHolder* getEventPointer (int index) const;
  33074. /** Returns the time of the note-up that matches the note-on at this index.
  33075. If the event at this index isn't a note-on, it'll just return 0.
  33076. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  33077. */
  33078. double getTimeOfMatchingKeyUp (int index) const;
  33079. /** Returns the index of the note-up that matches the note-on at this index.
  33080. If the event at this index isn't a note-on, it'll just return -1.
  33081. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  33082. */
  33083. int getIndexOfMatchingKeyUp (int index) const;
  33084. /** Returns the index of an event. */
  33085. int getIndexOf (MidiEventHolder* event) const;
  33086. /** Returns the index of the first event on or after the given timestamp.
  33087. If the time is beyond the end of the sequence, this will return the
  33088. number of events.
  33089. */
  33090. int getNextIndexAtTime (double timeStamp) const;
  33091. /** Returns the timestamp of the first event in the sequence.
  33092. @see getEndTime
  33093. */
  33094. double getStartTime() const;
  33095. /** Returns the timestamp of the last event in the sequence.
  33096. @see getStartTime
  33097. */
  33098. double getEndTime() const;
  33099. /** Returns the timestamp of the event at a given index.
  33100. If the index is out-of-range, this will return 0.0
  33101. */
  33102. double getEventTime (int index) const;
  33103. /** Inserts a midi message into the sequence.
  33104. The index at which the new message gets inserted will depend on its timestamp,
  33105. because the sequence is kept sorted.
  33106. Remember to call updateMatchedPairs() after adding note-on events.
  33107. @param newMessage the new message to add (an internal copy will be made)
  33108. @param timeAdjustment an optional value to add to the timestamp of the message
  33109. that will be inserted
  33110. @see updateMatchedPairs
  33111. */
  33112. void addEvent (const MidiMessage& newMessage,
  33113. double timeAdjustment = 0);
  33114. /** Deletes one of the events in the sequence.
  33115. Remember to call updateMatchedPairs() after removing events.
  33116. @param index the index of the event to delete
  33117. @param deleteMatchingNoteUp whether to also remove the matching note-off
  33118. if the event you're removing is a note-on
  33119. */
  33120. void deleteEvent (int index, bool deleteMatchingNoteUp);
  33121. /** Merges another sequence into this one.
  33122. Remember to call updateMatchedPairs() after using this method.
  33123. @param other the sequence to add from
  33124. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  33125. as they are read from the other sequence
  33126. @param firstAllowableDestTime events will not be added if their time is earlier
  33127. than this time. (This is after their time has been adjusted
  33128. by the timeAdjustmentDelta)
  33129. @param endOfAllowableDestTimes events will not be added if their time is equal to
  33130. or greater than this time. (This is after their time has
  33131. been adjusted by the timeAdjustmentDelta)
  33132. */
  33133. void addSequence (const MidiMessageSequence& other,
  33134. double timeAdjustmentDelta,
  33135. double firstAllowableDestTime,
  33136. double endOfAllowableDestTimes);
  33137. /** Makes sure all the note-on and note-off pairs are up-to-date.
  33138. Call this after moving messages about or deleting/adding messages, and it
  33139. will scan the list and make sure all the note-offs in the MidiEventHolder
  33140. structures are pointing at the correct ones.
  33141. */
  33142. void updateMatchedPairs();
  33143. /** Copies all the messages for a particular midi channel to another sequence.
  33144. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  33145. @param destSequence the sequence that the chosen events should be copied to
  33146. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  33147. channel) will also be copied across.
  33148. @see extractSysExMessages
  33149. */
  33150. void extractMidiChannelMessages (int channelNumberToExtract,
  33151. MidiMessageSequence& destSequence,
  33152. bool alsoIncludeMetaEvents) const;
  33153. /** Copies all midi sys-ex messages to another sequence.
  33154. @param destSequence this is the sequence to which any sys-exes in this sequence
  33155. will be added
  33156. @see extractMidiChannelMessages
  33157. */
  33158. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  33159. /** Removes any messages in this sequence that have a specific midi channel.
  33160. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  33161. */
  33162. void deleteMidiChannelMessages (int channelNumberToRemove);
  33163. /** Removes any sys-ex messages from this sequence.
  33164. */
  33165. void deleteSysExMessages();
  33166. /** Adds an offset to the timestamps of all events in the sequence.
  33167. @param deltaTime the amount to add to each timestamp.
  33168. */
  33169. void addTimeToMessages (double deltaTime);
  33170. /** Scans through the sequence to determine the state of any midi controllers at
  33171. a given time.
  33172. This will create a sequence of midi controller changes that can be
  33173. used to set all midi controllers to the state they would be in at the
  33174. specified time within this sequence.
  33175. As well as controllers, it will also recreate the midi program number
  33176. and pitch bend position.
  33177. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  33178. for other channels will be ignored.
  33179. @param time the time at which you want to find out the state - there are
  33180. no explicit units for this time measurement, it's the same units
  33181. as used for the timestamps of the messages
  33182. @param resultMessages an array to which midi controller-change messages will be added. This
  33183. will be the minimum number of controller changes to recreate the
  33184. state at the required time.
  33185. */
  33186. void createControllerUpdatesForTime (int channelNumber, double time,
  33187. OwnedArray<MidiMessage>& resultMessages);
  33188. /** Swaps this sequence with another one. */
  33189. void swapWith (MidiMessageSequence& other) throw();
  33190. /** @internal */
  33191. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  33192. const MidiMessageSequence::MidiEventHolder* second) throw();
  33193. private:
  33194. friend class MidiFile;
  33195. OwnedArray <MidiEventHolder> list;
  33196. void sort();
  33197. JUCE_LEAK_DETECTOR (MidiMessageSequence);
  33198. };
  33199. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  33200. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  33201. /**
  33202. Reads/writes standard midi format files.
  33203. To read a midi file, create a MidiFile object and call its readFrom() method. You
  33204. can then get the individual midi tracks from it using the getTrack() method.
  33205. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  33206. to it using the addTrack() method, and then call its writeTo() method to stream
  33207. it out.
  33208. @see MidiMessageSequence
  33209. */
  33210. class JUCE_API MidiFile
  33211. {
  33212. public:
  33213. /** Creates an empty MidiFile object.
  33214. */
  33215. MidiFile();
  33216. /** Destructor. */
  33217. ~MidiFile();
  33218. /** Returns the number of tracks in the file.
  33219. @see getTrack, addTrack
  33220. */
  33221. int getNumTracks() const throw();
  33222. /** Returns a pointer to one of the tracks in the file.
  33223. @returns a pointer to the track, or 0 if the index is out-of-range
  33224. @see getNumTracks, addTrack
  33225. */
  33226. const MidiMessageSequence* getTrack (int index) const throw();
  33227. /** Adds a midi track to the file.
  33228. This will make its own internal copy of the sequence that is passed-in.
  33229. @see getNumTracks, getTrack
  33230. */
  33231. void addTrack (const MidiMessageSequence& trackSequence);
  33232. /** Removes all midi tracks from the file.
  33233. @see getNumTracks
  33234. */
  33235. void clear();
  33236. /** Returns the raw time format code that will be written to a stream.
  33237. After reading a midi file, this method will return the time-format that
  33238. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  33239. or setSmpteTimeFormat() methods.
  33240. If the value returned is positive, it indicates the number of midi ticks
  33241. per quarter-note - see setTicksPerQuarterNote().
  33242. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  33243. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  33244. */
  33245. short getTimeFormat() const throw();
  33246. /** Sets the time format to use when this file is written to a stream.
  33247. If this is called, the file will be written as bars/beats using the
  33248. specified resolution, rather than SMPTE absolute times, as would be
  33249. used if setSmpteTimeFormat() had been called instead.
  33250. @param ticksPerQuarterNote e.g. 96, 960
  33251. @see setSmpteTimeFormat
  33252. */
  33253. void setTicksPerQuarterNote (int ticksPerQuarterNote) throw();
  33254. /** Sets the time format to use when this file is written to a stream.
  33255. If this is called, the file will be written using absolute times, rather
  33256. than bars/beats as would be the case if setTicksPerBeat() had been called
  33257. instead.
  33258. @param framesPerSecond must be 24, 25, 29 or 30
  33259. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  33260. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  33261. timing, setSmpteTimeFormat (25, 40)
  33262. @see setTicksPerBeat
  33263. */
  33264. void setSmpteTimeFormat (int framesPerSecond,
  33265. int subframeResolution) throw();
  33266. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  33267. Useful for finding the positions of all the tempo changes in a file.
  33268. @param tempoChangeEvents a list to which all the events will be added
  33269. */
  33270. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  33271. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  33272. Useful for finding the positions of all the tempo changes in a file.
  33273. @param timeSigEvents a list to which all the events will be added
  33274. */
  33275. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  33276. /** Returns the latest timestamp in any of the tracks.
  33277. (Useful for finding the length of the file).
  33278. */
  33279. double getLastTimestamp() const;
  33280. /** Reads a midi file format stream.
  33281. After calling this, you can get the tracks that were read from the file by using the
  33282. getNumTracks() and getTrack() methods.
  33283. The timestamps of the midi events in the tracks will represent their positions in
  33284. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  33285. method.
  33286. @returns true if the stream was read successfully
  33287. */
  33288. bool readFrom (InputStream& sourceStream);
  33289. /** Writes the midi tracks as a standard midi file.
  33290. @returns true if the operation succeeded.
  33291. */
  33292. bool writeTo (OutputStream& destStream);
  33293. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  33294. This will use the midi time format and tempo/time signature info in the
  33295. tracks to convert all the timestamps to absolute values in seconds.
  33296. */
  33297. void convertTimestampTicksToSeconds();
  33298. private:
  33299. OwnedArray <MidiMessageSequence> tracks;
  33300. short timeFormat;
  33301. void readNextTrack (const uint8* data, int size);
  33302. void writeTrack (OutputStream& mainOut, int trackNum);
  33303. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiFile);
  33304. };
  33305. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  33306. /*** End of inlined file: juce_MidiFile.h ***/
  33307. #endif
  33308. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  33309. #endif
  33310. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33311. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  33312. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33313. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33314. class MidiKeyboardState;
  33315. /**
  33316. Receives events from a MidiKeyboardState object.
  33317. @see MidiKeyboardState
  33318. */
  33319. class JUCE_API MidiKeyboardStateListener
  33320. {
  33321. public:
  33322. MidiKeyboardStateListener() throw() {}
  33323. virtual ~MidiKeyboardStateListener() {}
  33324. /** Called when one of the MidiKeyboardState's keys is pressed.
  33325. This will be called synchronously when the state is either processing a
  33326. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  33327. when a note is being played with its MidiKeyboardState::noteOn() method.
  33328. Note that this callback could happen from an audio callback thread, so be
  33329. careful not to block, and avoid any UI activity in the callback.
  33330. */
  33331. virtual void handleNoteOn (MidiKeyboardState* source,
  33332. int midiChannel, int midiNoteNumber, float velocity) = 0;
  33333. /** Called when one of the MidiKeyboardState's keys is released.
  33334. This will be called synchronously when the state is either processing a
  33335. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  33336. when a note is being played with its MidiKeyboardState::noteOff() method.
  33337. Note that this callback could happen from an audio callback thread, so be
  33338. careful not to block, and avoid any UI activity in the callback.
  33339. */
  33340. virtual void handleNoteOff (MidiKeyboardState* source,
  33341. int midiChannel, int midiNoteNumber) = 0;
  33342. };
  33343. /**
  33344. Represents a piano keyboard, keeping track of which keys are currently pressed.
  33345. This object can parse a stream of midi events, using them to update its idea
  33346. of which keys are pressed for each individiual midi channel.
  33347. When keys go up or down, it can broadcast these events to listener objects.
  33348. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  33349. methods, and midi messages for these events will be merged into the
  33350. midi stream that gets processed by processNextMidiBuffer().
  33351. */
  33352. class JUCE_API MidiKeyboardState
  33353. {
  33354. public:
  33355. MidiKeyboardState();
  33356. ~MidiKeyboardState();
  33357. /** Resets the state of the object.
  33358. All internal data for all the channels is reset, but no events are sent as a
  33359. result.
  33360. If you want to release any keys that are currently down, and to send out note-up
  33361. midi messages for this, use the allNotesOff() method instead.
  33362. */
  33363. void reset();
  33364. /** Returns true if the given midi key is currently held down for the given midi channel.
  33365. The channel number must be between 1 and 16. If you want to see if any notes are
  33366. on for a range of channels, use the isNoteOnForChannels() method.
  33367. */
  33368. bool isNoteOn (int midiChannel, int midiNoteNumber) const throw();
  33369. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  33370. The channel mask has a bit set for each midi channel you want to test for - bit
  33371. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  33372. If a note is on for at least one of the specified channels, this returns true.
  33373. */
  33374. bool isNoteOnForChannels (int midiChannelMask, int midiNoteNumber) const throw();
  33375. /** Turns a specified note on.
  33376. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  33377. next call to processNextMidiBuffer().
  33378. It will also trigger a synchronous callback to the listeners to tell them that the key has
  33379. gone down.
  33380. */
  33381. void noteOn (int midiChannel, int midiNoteNumber, float velocity);
  33382. /** Turns a specified note off.
  33383. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  33384. next call to processNextMidiBuffer().
  33385. It will also trigger a synchronous callback to the listeners to tell them that the key has
  33386. gone up.
  33387. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  33388. */
  33389. void noteOff (int midiChannel, int midiNoteNumber);
  33390. /** This will turn off any currently-down notes for the given midi channel.
  33391. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  33392. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  33393. and events being added to the midi stream.
  33394. */
  33395. void allNotesOff (int midiChannel);
  33396. /** Looks at a key-up/down event and uses it to update the state of this object.
  33397. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  33398. instead.
  33399. */
  33400. void processNextMidiEvent (const MidiMessage& message);
  33401. /** Scans a midi stream for up/down events and adds its own events to it.
  33402. This will look for any up/down events and use them to update the internal state,
  33403. synchronously making suitable callbacks to the listeners.
  33404. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  33405. and noteOff() calls will be added into the buffer.
  33406. Only the section of the buffer whose timestamps are between startSample and
  33407. (startSample + numSamples) will be affected, and any events added will be placed
  33408. between these times.
  33409. If you're going to use this method, you'll need to keep calling it regularly for
  33410. it to work satisfactorily.
  33411. To process a single midi event at a time, use the processNextMidiEvent() method
  33412. instead.
  33413. */
  33414. void processNextMidiBuffer (MidiBuffer& buffer,
  33415. int startSample,
  33416. int numSamples,
  33417. bool injectIndirectEvents);
  33418. /** Registers a listener for callbacks when keys go up or down.
  33419. @see removeListener
  33420. */
  33421. void addListener (MidiKeyboardStateListener* listener);
  33422. /** Deregisters a listener.
  33423. @see addListener
  33424. */
  33425. void removeListener (MidiKeyboardStateListener* listener);
  33426. private:
  33427. CriticalSection lock;
  33428. uint16 noteStates [128];
  33429. MidiBuffer eventsToAdd;
  33430. Array <MidiKeyboardStateListener*> listeners;
  33431. void noteOnInternal (int midiChannel, int midiNoteNumber, float velocity);
  33432. void noteOffInternal (int midiChannel, int midiNoteNumber);
  33433. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardState);
  33434. };
  33435. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33436. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  33437. #endif
  33438. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  33439. #endif
  33440. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  33441. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  33442. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  33443. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  33444. /**
  33445. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  33446. processing by a block-based audio callback.
  33447. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  33448. so it can easily use a midi input or keyboard component as its source.
  33449. @see MidiMessage, MidiInput
  33450. */
  33451. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  33452. public MidiInputCallback
  33453. {
  33454. public:
  33455. /** Creates a MidiMessageCollector. */
  33456. MidiMessageCollector();
  33457. /** Destructor. */
  33458. ~MidiMessageCollector();
  33459. /** Clears any messages from the queue.
  33460. You need to call this method before starting to use the collector, so that
  33461. it knows the correct sample rate to use.
  33462. */
  33463. void reset (double sampleRate);
  33464. /** Takes an incoming real-time message and adds it to the queue.
  33465. The message's timestamp is taken, and it will be ready for retrieval as part
  33466. of the block returned by the next call to removeNextBlockOfMessages().
  33467. This method is fully thread-safe when overlapping calls are made with
  33468. removeNextBlockOfMessages().
  33469. */
  33470. void addMessageToQueue (const MidiMessage& message);
  33471. /** Removes all the pending messages from the queue as a buffer.
  33472. This will also correct the messages' timestamps to make sure they're in
  33473. the range 0 to numSamples - 1.
  33474. This call should be made regularly by something like an audio processing
  33475. callback, because the time that it happens is used in calculating the
  33476. midi event positions.
  33477. This method is fully thread-safe when overlapping calls are made with
  33478. addMessageToQueue().
  33479. */
  33480. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  33481. /** @internal */
  33482. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  33483. /** @internal */
  33484. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  33485. /** @internal */
  33486. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  33487. private:
  33488. double lastCallbackTime;
  33489. CriticalSection midiCallbackLock;
  33490. MidiBuffer incomingMessages;
  33491. double sampleRate;
  33492. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiMessageCollector);
  33493. };
  33494. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  33495. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  33496. #endif
  33497. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  33498. #endif
  33499. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  33500. #endif
  33501. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  33502. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  33503. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  33504. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  33505. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  33506. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  33507. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  33508. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  33509. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  33510. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  33511. /*** Start of inlined file: juce_AudioProcessor.h ***/
  33512. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  33513. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  33514. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  33515. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  33516. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  33517. class AudioProcessor;
  33518. /**
  33519. Base class for the component that acts as the GUI for an AudioProcessor.
  33520. Derive your editor component from this class, and create an instance of it
  33521. by overriding the AudioProcessor::createEditor() method.
  33522. @see AudioProcessor, GenericAudioProcessorEditor
  33523. */
  33524. class JUCE_API AudioProcessorEditor : public Component
  33525. {
  33526. protected:
  33527. /** Creates an editor for the specified processor.
  33528. */
  33529. AudioProcessorEditor (AudioProcessor* owner);
  33530. public:
  33531. /** Destructor. */
  33532. ~AudioProcessorEditor();
  33533. /** Returns a pointer to the processor that this editor represents. */
  33534. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  33535. private:
  33536. AudioProcessor* const owner;
  33537. JUCE_DECLARE_NON_COPYABLE (AudioProcessorEditor);
  33538. };
  33539. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  33540. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  33541. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  33542. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  33543. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  33544. class AudioProcessor;
  33545. /**
  33546. Base class for listeners that want to know about changes to an AudioProcessor.
  33547. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  33548. @see AudioProcessor
  33549. */
  33550. class JUCE_API AudioProcessorListener
  33551. {
  33552. public:
  33553. /** Destructor. */
  33554. virtual ~AudioProcessorListener() {}
  33555. /** Receives a callback when a parameter is changed.
  33556. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  33557. many audio processors will change their parameter during their audio callback.
  33558. This means that not only has your handler code got to be completely thread-safe,
  33559. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  33560. this event on your message thread, use this callback to trigger an AsyncUpdater
  33561. or ChangeBroadcaster which you can respond to on the message thread.
  33562. */
  33563. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  33564. int parameterIndex,
  33565. float newValue) = 0;
  33566. /** Called to indicate that something else in the plugin has changed, like its
  33567. program, number of parameters, etc.
  33568. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  33569. call it during their audio callback. This means that not only has your handler code
  33570. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  33571. blocking. If you need to handle this event on your message thread, use this callback
  33572. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  33573. message thread.
  33574. */
  33575. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  33576. /** Indicates that a parameter change gesture has started.
  33577. E.g. if the user is dragging a slider, this would be called when they first
  33578. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  33579. called when they release it.
  33580. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  33581. call it during their audio callback. This means that not only has your handler code
  33582. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  33583. blocking. If you need to handle this event on your message thread, use this callback
  33584. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  33585. message thread.
  33586. @see audioProcessorParameterChangeGestureEnd
  33587. */
  33588. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  33589. int parameterIndex);
  33590. /** Indicates that a parameter change gesture has finished.
  33591. E.g. if the user is dragging a slider, this would be called when they release
  33592. the mouse button.
  33593. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  33594. call it during their audio callback. This means that not only has your handler code
  33595. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  33596. blocking. If you need to handle this event on your message thread, use this callback
  33597. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  33598. message thread.
  33599. @see audioProcessorParameterChangeGestureBegin
  33600. */
  33601. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  33602. int parameterIndex);
  33603. };
  33604. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  33605. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  33606. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  33607. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  33608. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  33609. /**
  33610. A subclass of AudioPlayHead can supply information about the position and
  33611. status of a moving play head during audio playback.
  33612. One of these can be supplied to an AudioProcessor object so that it can find
  33613. out about the position of the audio that it is rendering.
  33614. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  33615. */
  33616. class JUCE_API AudioPlayHead
  33617. {
  33618. protected:
  33619. AudioPlayHead() {}
  33620. public:
  33621. virtual ~AudioPlayHead() {}
  33622. /** Frame rate types. */
  33623. enum FrameRateType
  33624. {
  33625. fps24 = 0,
  33626. fps25 = 1,
  33627. fps2997 = 2,
  33628. fps30 = 3,
  33629. fps2997drop = 4,
  33630. fps30drop = 5,
  33631. fpsUnknown = 99
  33632. };
  33633. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  33634. */
  33635. struct CurrentPositionInfo
  33636. {
  33637. /** The tempo in BPM */
  33638. double bpm;
  33639. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  33640. int timeSigNumerator;
  33641. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  33642. int timeSigDenominator;
  33643. /** The current play position, in seconds from the start of the edit. */
  33644. double timeInSeconds;
  33645. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  33646. double editOriginTime;
  33647. /** The current play position in pulses-per-quarter-note.
  33648. This is the number of quarter notes since the edit start.
  33649. */
  33650. double ppqPosition;
  33651. /** The position of the start of the last bar, in pulses-per-quarter-note.
  33652. This is the number of quarter notes from the start of the edit to the
  33653. start of the current bar.
  33654. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  33655. it's not available, the value will be 0.
  33656. */
  33657. double ppqPositionOfLastBarStart;
  33658. /** The video frame rate, if applicable. */
  33659. FrameRateType frameRate;
  33660. /** True if the transport is currently playing. */
  33661. bool isPlaying;
  33662. /** True if the transport is currently recording.
  33663. (When isRecording is true, then isPlaying will also be true).
  33664. */
  33665. bool isRecording;
  33666. bool operator== (const CurrentPositionInfo& other) const throw();
  33667. bool operator!= (const CurrentPositionInfo& other) const throw();
  33668. void resetToDefault();
  33669. };
  33670. /** Fills-in the given structure with details about the transport's
  33671. position at the start of the current processing block.
  33672. */
  33673. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  33674. };
  33675. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  33676. /*** End of inlined file: juce_AudioPlayHead.h ***/
  33677. /**
  33678. Base class for audio processing filters or plugins.
  33679. This is intended to act as a base class of audio filter that is general enough to
  33680. be wrapped as a VST, AU, RTAS, etc, or used internally.
  33681. It is also used by the plugin hosting code as the wrapper around an instance
  33682. of a loaded plugin.
  33683. Derive your filter class from this base class, and if you're building a plugin,
  33684. you should implement a global function called createPluginFilter() which creates
  33685. and returns a new instance of your subclass.
  33686. */
  33687. class JUCE_API AudioProcessor
  33688. {
  33689. protected:
  33690. /** Constructor.
  33691. You can also do your initialisation tasks in the initialiseFilterInfo()
  33692. call, which will be made after this object has been created.
  33693. */
  33694. AudioProcessor();
  33695. public:
  33696. /** Destructor. */
  33697. virtual ~AudioProcessor();
  33698. /** Returns the name of this processor.
  33699. */
  33700. virtual const String getName() const = 0;
  33701. /** Called before playback starts, to let the filter prepare itself.
  33702. The sample rate is the target sample rate, and will remain constant until
  33703. playback stops.
  33704. The estimatedSamplesPerBlock value is a HINT about the typical number of
  33705. samples that will be processed for each callback, but isn't any kind
  33706. of guarantee. The actual block sizes that the host uses may be different
  33707. each time the callback happens, and may be more or less than this value.
  33708. */
  33709. virtual void prepareToPlay (double sampleRate,
  33710. int estimatedSamplesPerBlock) = 0;
  33711. /** Called after playback has stopped, to let the filter free up any resources it
  33712. no longer needs.
  33713. */
  33714. virtual void releaseResources() = 0;
  33715. /** Renders the next block.
  33716. When this method is called, the buffer contains a number of channels which is
  33717. at least as great as the maximum number of input and output channels that
  33718. this filter is using. It will be filled with the filter's input data and
  33719. should be replaced with the filter's output.
  33720. So for example if your filter has 2 input channels and 4 output channels, then
  33721. the buffer will contain 4 channels, the first two being filled with the
  33722. input data. Your filter should read these, do its processing, and replace
  33723. the contents of all 4 channels with its output.
  33724. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  33725. all filled with data, and your filter should overwrite the first 2 of these
  33726. with its output. But be VERY careful not to write anything to the last 3
  33727. channels, as these might be mapped to memory that the host assumes is read-only!
  33728. Note that if you have more outputs than inputs, then only those channels that
  33729. correspond to an input channel are guaranteed to contain sensible data - e.g.
  33730. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  33731. but the last two channels may contain garbage, so you should be careful not to
  33732. let this pass through without being overwritten or cleared.
  33733. Also note that the buffer may have more channels than are strictly necessary,
  33734. but your should only read/write from the ones that your filter is supposed to
  33735. be using.
  33736. The number of samples in these buffers is NOT guaranteed to be the same for every
  33737. callback, and may be more or less than the estimated value given to prepareToPlay().
  33738. Your code must be able to cope with variable-sized blocks, or you're going to get
  33739. clicks and crashes!
  33740. If the filter is receiving a midi input, then the midiMessages array will be filled
  33741. with the midi messages for this block. Each message's timestamp will indicate the
  33742. message's time, as a number of samples from the start of the block.
  33743. Any messages left in the midi buffer when this method has finished are assumed to
  33744. be the filter's midi output. This means that your filter should be careful to
  33745. clear any incoming messages from the array if it doesn't want them to be passed-on.
  33746. Be very careful about what you do in this callback - it's going to be called by
  33747. the audio thread, so any kind of interaction with the UI is absolutely
  33748. out of the question. If you change a parameter in here and need to tell your UI to
  33749. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  33750. the UI components register as listeners, and then call sendChangeMessage() inside the
  33751. processBlock() method to send out an asynchronous message. You could also use
  33752. the AsyncUpdater class in a similar way.
  33753. */
  33754. virtual void processBlock (AudioSampleBuffer& buffer,
  33755. MidiBuffer& midiMessages) = 0;
  33756. /** Returns the current AudioPlayHead object that should be used to find
  33757. out the state and position of the playhead.
  33758. You can call this from your processBlock() method, and use the AudioPlayHead
  33759. object to get the details about the time of the start of the block currently
  33760. being processed.
  33761. If the host hasn't supplied a playhead object, this will return 0.
  33762. */
  33763. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  33764. /** Returns the current sample rate.
  33765. This can be called from your processBlock() method - it's not guaranteed
  33766. to be valid at any other time, and may return 0 if it's unknown.
  33767. */
  33768. double getSampleRate() const throw() { return sampleRate; }
  33769. /** Returns the current typical block size that is being used.
  33770. This can be called from your processBlock() method - it's not guaranteed
  33771. to be valid at any other time.
  33772. Remember it's not the ONLY block size that may be used when calling
  33773. processBlock, it's just the normal one. The actual block sizes used may be
  33774. larger or smaller than this, and will vary between successive calls.
  33775. */
  33776. int getBlockSize() const throw() { return blockSize; }
  33777. /** Returns the number of input channels that the host will be sending the filter.
  33778. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  33779. number of channels that your filter would prefer to have, and this method lets
  33780. you know how many the host is actually using.
  33781. Note that this method is only valid during or after the prepareToPlay()
  33782. method call. Until that point, the number of channels will be unknown.
  33783. */
  33784. int getNumInputChannels() const throw() { return numInputChannels; }
  33785. /** Returns the number of output channels that the host will be sending the filter.
  33786. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  33787. number of channels that your filter would prefer to have, and this method lets
  33788. you know how many the host is actually using.
  33789. Note that this method is only valid during or after the prepareToPlay()
  33790. method call. Until that point, the number of channels will be unknown.
  33791. */
  33792. int getNumOutputChannels() const throw() { return numOutputChannels; }
  33793. /** Returns the name of one of the input channels, as returned by the host.
  33794. The host might not supply very useful names for channels, and this might be
  33795. something like "1", "2", "left", "right", etc.
  33796. */
  33797. virtual const String getInputChannelName (int channelIndex) const = 0;
  33798. /** Returns the name of one of the output channels, as returned by the host.
  33799. The host might not supply very useful names for channels, and this might be
  33800. something like "1", "2", "left", "right", etc.
  33801. */
  33802. virtual const String getOutputChannelName (int channelIndex) const = 0;
  33803. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  33804. virtual bool isInputChannelStereoPair (int index) const = 0;
  33805. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  33806. virtual bool isOutputChannelStereoPair (int index) const = 0;
  33807. /** This returns the number of samples delay that the filter imposes on the audio
  33808. passing through it.
  33809. The host will call this to find the latency - the filter itself should set this value
  33810. by calling setLatencySamples() as soon as it can during its initialisation.
  33811. */
  33812. int getLatencySamples() const throw() { return latencySamples; }
  33813. /** The filter should call this to set the number of samples delay that it introduces.
  33814. The filter should call this as soon as it can during initialisation, and can call it
  33815. later if the value changes.
  33816. */
  33817. void setLatencySamples (int newLatency);
  33818. /** Returns true if the processor wants midi messages. */
  33819. virtual bool acceptsMidi() const = 0;
  33820. /** Returns true if the processor produces midi messages. */
  33821. virtual bool producesMidi() const = 0;
  33822. /** This returns a critical section that will automatically be locked while the host
  33823. is calling the processBlock() method.
  33824. Use it from your UI or other threads to lock access to variables that are used
  33825. by the process callback, but obviously be careful not to keep it locked for
  33826. too long, because that could cause stuttering playback. If you need to do something
  33827. that'll take a long time and need the processing to stop while it happens, use the
  33828. suspendProcessing() method instead.
  33829. @see suspendProcessing
  33830. */
  33831. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  33832. /** Enables and disables the processing callback.
  33833. If you need to do something time-consuming on a thread and would like to make sure
  33834. the audio processing callback doesn't happen until you've finished, use this
  33835. to disable the callback and re-enable it again afterwards.
  33836. E.g.
  33837. @code
  33838. void loadNewPatch()
  33839. {
  33840. suspendProcessing (true);
  33841. ..do something that takes ages..
  33842. suspendProcessing (false);
  33843. }
  33844. @endcode
  33845. If the host tries to make an audio callback while processing is suspended, the
  33846. filter will return an empty buffer, but won't block the audio thread like it would
  33847. do if you use the getCallbackLock() critical section to synchronise access.
  33848. If you're going to use this, your processBlock() method must call isSuspended() and
  33849. check whether it's suspended or not. If it is, then it should skip doing any real
  33850. processing, either emitting silence or passing the input through unchanged.
  33851. @see getCallbackLock
  33852. */
  33853. void suspendProcessing (bool shouldBeSuspended);
  33854. /** Returns true if processing is currently suspended.
  33855. @see suspendProcessing
  33856. */
  33857. bool isSuspended() const throw() { return suspended; }
  33858. /** A plugin can override this to be told when it should reset any playing voices.
  33859. The default implementation does nothing, but a host may call this to tell the
  33860. plugin that it should stop any tails or sounds that have been left running.
  33861. */
  33862. virtual void reset();
  33863. /** Returns true if the processor is being run in an offline mode for rendering.
  33864. If the processor is being run live on realtime signals, this returns false.
  33865. If the mode is unknown, this will assume it's realtime and return false.
  33866. This value may be unreliable until the prepareToPlay() method has been called,
  33867. and could change each time prepareToPlay() is called.
  33868. @see setNonRealtime()
  33869. */
  33870. bool isNonRealtime() const throw() { return nonRealtime; }
  33871. /** Called by the host to tell this processor whether it's being used in a non-realime
  33872. capacity for offline rendering or bouncing.
  33873. Whatever value is passed-in will be
  33874. */
  33875. void setNonRealtime (bool isNonRealtime) throw();
  33876. /** Creates the filter's UI.
  33877. This can return 0 if you want a UI-less filter, in which case the host may create
  33878. a generic UI that lets the user twiddle the parameters directly.
  33879. If you do want to pass back a component, the component should be created and set to
  33880. the correct size before returning it. If you implement this method, you must
  33881. also implement the hasEditor() method and make it return true.
  33882. Remember not to do anything silly like allowing your filter to keep a pointer to
  33883. the component that gets created - it could be deleted later without any warning, which
  33884. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  33885. The correct way to handle the connection between an editor component and its
  33886. filter is to use something like a ChangeBroadcaster so that the editor can
  33887. register itself as a listener, and be told when a change occurs. This lets them
  33888. safely unregister themselves when they are deleted.
  33889. Here are a few things to bear in mind when writing an editor:
  33890. - Initially there won't be an editor, until the user opens one, or they might
  33891. not open one at all. Your filter mustn't rely on it being there.
  33892. - An editor object may be deleted and a replacement one created again at any time.
  33893. - It's safe to assume that an editor will be deleted before its filter.
  33894. @see hasEditor
  33895. */
  33896. virtual AudioProcessorEditor* createEditor() = 0;
  33897. /** Your filter must override this and return true if it can create an editor component.
  33898. @see createEditor
  33899. */
  33900. virtual bool hasEditor() const = 0;
  33901. /** Returns the active editor, if there is one.
  33902. Bear in mind this can return 0, even if an editor has previously been
  33903. opened.
  33904. */
  33905. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  33906. /** Returns the active editor, or if there isn't one, it will create one.
  33907. This may call createEditor() internally to create the component.
  33908. */
  33909. AudioProcessorEditor* createEditorIfNeeded();
  33910. /** This must return the correct value immediately after the object has been
  33911. created, and mustn't change the number of parameters later.
  33912. */
  33913. virtual int getNumParameters() = 0;
  33914. /** Returns the name of a particular parameter. */
  33915. virtual const String getParameterName (int parameterIndex) = 0;
  33916. /** Called by the host to find out the value of one of the filter's parameters.
  33917. The host will expect the value returned to be between 0 and 1.0.
  33918. This could be called quite frequently, so try to make your code efficient.
  33919. It's also likely to be called by non-UI threads, so the code in here should
  33920. be thread-aware.
  33921. */
  33922. virtual float getParameter (int parameterIndex) = 0;
  33923. /** Returns the value of a parameter as a text string. */
  33924. virtual const String getParameterText (int parameterIndex) = 0;
  33925. /** The host will call this method to change the value of one of the filter's parameters.
  33926. The host may call this at any time, including during the audio processing
  33927. callback, so the filter has to process this very fast and avoid blocking.
  33928. If you want to set the value of a parameter internally, e.g. from your
  33929. editor component, then don't call this directly - instead, use the
  33930. setParameterNotifyingHost() method, which will also send a message to
  33931. the host telling it about the change. If the message isn't sent, the host
  33932. won't be able to automate your parameters properly.
  33933. The value passed will be between 0 and 1.0.
  33934. */
  33935. virtual void setParameter (int parameterIndex,
  33936. float newValue) = 0;
  33937. /** Your filter can call this when it needs to change one of its parameters.
  33938. This could happen when the editor or some other internal operation changes
  33939. a parameter. This method will call the setParameter() method to change the
  33940. value, and will then send a message to the host telling it about the change.
  33941. Note that to make sure the host correctly handles automation, you should call
  33942. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  33943. tell the host when the user has started and stopped changing the parameter.
  33944. */
  33945. void setParameterNotifyingHost (int parameterIndex,
  33946. float newValue);
  33947. /** Returns true if the host can automate this parameter.
  33948. By default, this returns true for all parameters.
  33949. */
  33950. virtual bool isParameterAutomatable (int parameterIndex) const;
  33951. /** Should return true if this parameter is a "meta" parameter.
  33952. A meta-parameter is a parameter that changes other params. It is used
  33953. by some hosts (e.g. AudioUnit hosts).
  33954. By default this returns false.
  33955. */
  33956. virtual bool isMetaParameter (int parameterIndex) const;
  33957. /** Sends a signal to the host to tell it that the user is about to start changing this
  33958. parameter.
  33959. This allows the host to know when a parameter is actively being held by the user, and
  33960. it may use this information to help it record automation.
  33961. If you call this, it must be matched by a later call to endParameterChangeGesture().
  33962. */
  33963. void beginParameterChangeGesture (int parameterIndex);
  33964. /** Tells the host that the user has finished changing this parameter.
  33965. This allows the host to know when a parameter is actively being held by the user, and
  33966. it may use this information to help it record automation.
  33967. A call to this method must follow a call to beginParameterChangeGesture().
  33968. */
  33969. void endParameterChangeGesture (int parameterIndex);
  33970. /** The filter can call this when something (apart from a parameter value) has changed.
  33971. It sends a hint to the host that something like the program, number of parameters,
  33972. etc, has changed, and that it should update itself.
  33973. */
  33974. void updateHostDisplay();
  33975. /** Returns the number of preset programs the filter supports.
  33976. The value returned must be valid as soon as this object is created, and
  33977. must not change over its lifetime.
  33978. This value shouldn't be less than 1.
  33979. */
  33980. virtual int getNumPrograms() = 0;
  33981. /** Returns the number of the currently active program.
  33982. */
  33983. virtual int getCurrentProgram() = 0;
  33984. /** Called by the host to change the current program.
  33985. */
  33986. virtual void setCurrentProgram (int index) = 0;
  33987. /** Must return the name of a given program. */
  33988. virtual const String getProgramName (int index) = 0;
  33989. /** Called by the host to rename a program.
  33990. */
  33991. virtual void changeProgramName (int index, const String& newName) = 0;
  33992. /** The host will call this method when it wants to save the filter's internal state.
  33993. This must copy any info about the filter's state into the block of memory provided,
  33994. so that the host can store this and later restore it using setStateInformation().
  33995. Note that there's also a getCurrentProgramStateInformation() method, which only
  33996. stores the current program, not the state of the entire filter.
  33997. See also the helper function copyXmlToBinary() for storing settings as XML.
  33998. @see getCurrentProgramStateInformation
  33999. */
  34000. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  34001. /** The host will call this method if it wants to save the state of just the filter's
  34002. current program.
  34003. Unlike getStateInformation, this should only return the current program's state.
  34004. Not all hosts support this, and if you don't implement it, the base class
  34005. method just calls getStateInformation() instead. If you do implement it, be
  34006. sure to also implement getCurrentProgramStateInformation.
  34007. @see getStateInformation, setCurrentProgramStateInformation
  34008. */
  34009. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  34010. /** This must restore the filter's state from a block of data previously created
  34011. using getStateInformation().
  34012. Note that there's also a setCurrentProgramStateInformation() method, which tries
  34013. to restore just the current program, not the state of the entire filter.
  34014. See also the helper function getXmlFromBinary() for loading settings as XML.
  34015. @see setCurrentProgramStateInformation
  34016. */
  34017. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  34018. /** The host will call this method if it wants to restore the state of just the filter's
  34019. current program.
  34020. Not all hosts support this, and if you don't implement it, the base class
  34021. method just calls setStateInformation() instead. If you do implement it, be
  34022. sure to also implement getCurrentProgramStateInformation.
  34023. @see setStateInformation, getCurrentProgramStateInformation
  34024. */
  34025. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  34026. /** Adds a listener that will be called when an aspect of this processor changes. */
  34027. void addListener (AudioProcessorListener* newListener);
  34028. /** Removes a previously added listener. */
  34029. void removeListener (AudioProcessorListener* listenerToRemove);
  34030. /** Tells the processor to use this playhead object.
  34031. The processor will not take ownership of the object, so the caller must delete it when
  34032. it is no longer being used.
  34033. */
  34034. void setPlayHead (AudioPlayHead* newPlayHead) throw();
  34035. /** Not for public use - this is called before deleting an editor component. */
  34036. void editorBeingDeleted (AudioProcessorEditor* editor) throw();
  34037. /** Not for public use - this is called to initialise the processor before playing. */
  34038. void setPlayConfigDetails (int numIns, int numOuts,
  34039. double sampleRate,
  34040. int blockSize) throw();
  34041. protected:
  34042. /** Helper function that just converts an xml element into a binary blob.
  34043. Use this in your filter's getStateInformation() method if you want to
  34044. store its state as xml.
  34045. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  34046. from a binary blob.
  34047. */
  34048. static void copyXmlToBinary (const XmlElement& xml,
  34049. JUCE_NAMESPACE::MemoryBlock& destData);
  34050. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  34051. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  34052. an XmlElement object that the caller must delete when no longer needed.
  34053. */
  34054. static XmlElement* getXmlFromBinary (const void* data, int sizeInBytes);
  34055. /** @internal */
  34056. AudioPlayHead* playHead;
  34057. /** @internal */
  34058. void sendParamChangeMessageToListeners (int parameterIndex, float newValue);
  34059. private:
  34060. Array <AudioProcessorListener*> listeners;
  34061. Component::SafePointer<AudioProcessorEditor> activeEditor;
  34062. double sampleRate;
  34063. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  34064. bool suspended, nonRealtime;
  34065. CriticalSection callbackLock, listenerLock;
  34066. #if JUCE_DEBUG
  34067. BigInteger changingParams;
  34068. #endif
  34069. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessor);
  34070. };
  34071. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  34072. /*** End of inlined file: juce_AudioProcessor.h ***/
  34073. /*** Start of inlined file: juce_PluginDescription.h ***/
  34074. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34075. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34076. /**
  34077. A small class to represent some facts about a particular type of plugin.
  34078. This class is for storing and managing the details about a plugin without
  34079. actually having to load an instance of it.
  34080. A KnownPluginList contains a list of PluginDescription objects.
  34081. @see KnownPluginList
  34082. */
  34083. class JUCE_API PluginDescription
  34084. {
  34085. public:
  34086. PluginDescription();
  34087. PluginDescription (const PluginDescription& other);
  34088. PluginDescription& operator= (const PluginDescription& other);
  34089. ~PluginDescription();
  34090. /** The name of the plugin. */
  34091. String name;
  34092. /** A more descriptive name for the plugin.
  34093. This may be the same as the 'name' field, but some plugins may provide an
  34094. alternative name.
  34095. */
  34096. String descriptiveName;
  34097. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  34098. */
  34099. String pluginFormatName;
  34100. /** A category, such as "Dynamics", "Reverbs", etc.
  34101. */
  34102. String category;
  34103. /** The manufacturer. */
  34104. String manufacturerName;
  34105. /** The version. This string doesn't have any particular format. */
  34106. String version;
  34107. /** Either the file containing the plugin module, or some other unique way
  34108. of identifying it.
  34109. E.g. for an AU, this would be an ID string that the component manager
  34110. could use to retrieve the plugin. For a VST, it's the file path.
  34111. */
  34112. String fileOrIdentifier;
  34113. /** The last time the plugin file was changed.
  34114. This is handy when scanning for new or changed plugins.
  34115. */
  34116. Time lastFileModTime;
  34117. /** A unique ID for the plugin.
  34118. Note that this might not be unique between formats, e.g. a VST and some
  34119. other format might actually have the same id.
  34120. @see createIdentifierString
  34121. */
  34122. int uid;
  34123. /** True if the plugin identifies itself as a synthesiser. */
  34124. bool isInstrument;
  34125. /** The number of inputs. */
  34126. int numInputChannels;
  34127. /** The number of outputs. */
  34128. int numOutputChannels;
  34129. /** Returns true if the two descriptions refer the the same plugin.
  34130. This isn't quite as simple as them just having the same file (because of
  34131. shell plugins).
  34132. */
  34133. bool isDuplicateOf (const PluginDescription& other) const;
  34134. /** Returns a string that can be saved and used to uniquely identify the
  34135. plugin again.
  34136. This contains less info than the XML encoding, and is independent of the
  34137. plugin's file location, so can be used to store a plugin ID for use
  34138. across different machines.
  34139. */
  34140. const String createIdentifierString() const;
  34141. /** Creates an XML object containing these details.
  34142. @see loadFromXml
  34143. */
  34144. XmlElement* createXml() const;
  34145. /** Reloads the info in this structure from an XML record that was previously
  34146. saved with createXML().
  34147. Returns true if the XML was a valid plugin description.
  34148. */
  34149. bool loadFromXml (const XmlElement& xml);
  34150. private:
  34151. JUCE_LEAK_DETECTOR (PluginDescription);
  34152. };
  34153. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34154. /*** End of inlined file: juce_PluginDescription.h ***/
  34155. /**
  34156. Base class for an active instance of a plugin.
  34157. This derives from the AudioProcessor class, and adds some extra functionality
  34158. that helps when wrapping dynamically loaded plugins.
  34159. @see AudioProcessor, AudioPluginFormat
  34160. */
  34161. class JUCE_API AudioPluginInstance : public AudioProcessor
  34162. {
  34163. public:
  34164. /** Destructor.
  34165. Make sure that you delete any UI components that belong to this plugin before
  34166. deleting the plugin.
  34167. */
  34168. virtual ~AudioPluginInstance();
  34169. /** Fills-in the appropriate parts of this plugin description object.
  34170. */
  34171. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  34172. /** Returns a pointer to some kind of platform-specific data about the plugin.
  34173. E.g. For a VST, this value can be cast to an AEffect*. For an AudioUnit, it can be
  34174. cast to an AudioUnit handle.
  34175. */
  34176. virtual void* getPlatformSpecificData();
  34177. protected:
  34178. AudioPluginInstance();
  34179. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginInstance);
  34180. };
  34181. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  34182. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  34183. class PluginDescription;
  34184. /**
  34185. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  34186. Use the static getNumFormats() and getFormat() calls to find the types
  34187. of format that are available.
  34188. */
  34189. class JUCE_API AudioPluginFormat
  34190. {
  34191. public:
  34192. /** Destructor. */
  34193. virtual ~AudioPluginFormat();
  34194. /** Returns the format name.
  34195. E.g. "VST", "AudioUnit", etc.
  34196. */
  34197. virtual const String getName() const = 0;
  34198. /** This tries to create descriptions for all the plugin types available in
  34199. a binary module file.
  34200. The file will be some kind of DLL or bundle.
  34201. Normally there will only be one type returned, but some plugins
  34202. (e.g. VST shells) can use a single DLL to create a set of different plugin
  34203. subtypes, so in that case, each subtype is returned as a separate object.
  34204. */
  34205. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  34206. const String& fileOrIdentifier) = 0;
  34207. /** Tries to recreate a type from a previously generated PluginDescription.
  34208. @see PluginDescription::createInstance
  34209. */
  34210. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  34211. /** Should do a quick check to see if this file or directory might be a plugin of
  34212. this format.
  34213. This is for searching for potential files, so it shouldn't actually try to
  34214. load the plugin or do anything time-consuming.
  34215. */
  34216. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  34217. /** Returns a readable version of the name of the plugin that this identifier refers to.
  34218. */
  34219. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  34220. /** Checks whether this plugin could possibly be loaded.
  34221. It doesn't actually need to load it, just to check whether the file or component
  34222. still exists.
  34223. */
  34224. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  34225. /** Searches a suggested set of directories for any plugins in this format.
  34226. The path might be ignored, e.g. by AUs, which are found by the OS rather
  34227. than manually.
  34228. */
  34229. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  34230. bool recursive) = 0;
  34231. /** Returns the typical places to look for this kind of plugin.
  34232. Note that if this returns no paths, it means that the format can't be scanned-for
  34233. (i.e. it's an internal format that doesn't live in files)
  34234. */
  34235. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  34236. protected:
  34237. AudioPluginFormat() throw();
  34238. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormat);
  34239. };
  34240. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  34241. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  34242. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  34243. /**
  34244. Implements a plugin format manager for AudioUnits.
  34245. */
  34246. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  34247. {
  34248. public:
  34249. AudioUnitPluginFormat();
  34250. ~AudioUnitPluginFormat();
  34251. const String getName() const { return "AudioUnit"; }
  34252. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34253. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34254. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34255. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  34256. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  34257. bool doesPluginStillExist (const PluginDescription& desc);
  34258. const FileSearchPath getDefaultLocationsToSearch();
  34259. private:
  34260. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginFormat);
  34261. };
  34262. #endif
  34263. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  34264. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  34265. #endif
  34266. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34267. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  34268. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34269. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34270. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  34271. // Sorry, this file is just a placeholder at the moment!...
  34272. /**
  34273. Implements a plugin format manager for DirectX plugins.
  34274. */
  34275. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  34276. {
  34277. public:
  34278. DirectXPluginFormat();
  34279. ~DirectXPluginFormat();
  34280. const String getName() const { return "DirectX"; }
  34281. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34282. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34283. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34284. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  34285. const FileSearchPath getDefaultLocationsToSearch();
  34286. private:
  34287. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectXPluginFormat);
  34288. };
  34289. #endif
  34290. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34291. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  34292. #endif
  34293. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34294. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  34295. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34296. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34297. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  34298. // Sorry, this file is just a placeholder at the moment!...
  34299. /**
  34300. Implements a plugin format manager for DirectX plugins.
  34301. */
  34302. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  34303. {
  34304. public:
  34305. LADSPAPluginFormat();
  34306. ~LADSPAPluginFormat();
  34307. const String getName() const { return "LADSPA"; }
  34308. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34309. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34310. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34311. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  34312. const FileSearchPath getDefaultLocationsToSearch();
  34313. private:
  34314. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LADSPAPluginFormat);
  34315. };
  34316. #endif
  34317. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34318. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  34319. #endif
  34320. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34321. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  34322. #ifdef __aeffect__
  34323. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34324. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34325. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  34326. events to the list.
  34327. This is used by both the VST hosting code and the plugin wrapper.
  34328. */
  34329. class VSTMidiEventList
  34330. {
  34331. public:
  34332. VSTMidiEventList()
  34333. : numEventsUsed (0), numEventsAllocated (0)
  34334. {
  34335. }
  34336. ~VSTMidiEventList()
  34337. {
  34338. freeEvents();
  34339. }
  34340. void clear()
  34341. {
  34342. numEventsUsed = 0;
  34343. if (events != 0)
  34344. events->numEvents = 0;
  34345. }
  34346. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  34347. {
  34348. ensureSize (numEventsUsed + 1);
  34349. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  34350. events->numEvents = ++numEventsUsed;
  34351. if (numBytes <= 4)
  34352. {
  34353. if (e->type == kVstSysExType)
  34354. {
  34355. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  34356. e->type = kVstMidiType;
  34357. e->byteSize = sizeof (VstMidiEvent);
  34358. e->noteLength = 0;
  34359. e->noteOffset = 0;
  34360. e->detune = 0;
  34361. e->noteOffVelocity = 0;
  34362. }
  34363. e->deltaFrames = frameOffset;
  34364. memcpy (e->midiData, midiData, numBytes);
  34365. }
  34366. else
  34367. {
  34368. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  34369. if (se->type == kVstSysExType)
  34370. delete[] se->sysexDump;
  34371. se->sysexDump = new char [numBytes];
  34372. memcpy (se->sysexDump, midiData, numBytes);
  34373. se->type = kVstSysExType;
  34374. se->byteSize = sizeof (VstMidiSysexEvent);
  34375. se->deltaFrames = frameOffset;
  34376. se->flags = 0;
  34377. se->dumpBytes = numBytes;
  34378. se->resvd1 = 0;
  34379. se->resvd2 = 0;
  34380. }
  34381. }
  34382. // Handy method to pull the events out of an event buffer supplied by the host
  34383. // or plugin.
  34384. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  34385. {
  34386. for (int i = 0; i < events->numEvents; ++i)
  34387. {
  34388. const VstEvent* const e = events->events[i];
  34389. if (e != 0)
  34390. {
  34391. if (e->type == kVstMidiType)
  34392. {
  34393. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  34394. 4, e->deltaFrames);
  34395. }
  34396. else if (e->type == kVstSysExType)
  34397. {
  34398. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  34399. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  34400. e->deltaFrames);
  34401. }
  34402. }
  34403. }
  34404. }
  34405. void ensureSize (int numEventsNeeded)
  34406. {
  34407. if (numEventsNeeded > numEventsAllocated)
  34408. {
  34409. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  34410. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  34411. if (events == 0)
  34412. events.calloc (size, 1);
  34413. else
  34414. events.realloc (size, 1);
  34415. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  34416. {
  34417. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  34418. (int) sizeof (VstMidiSysexEvent)));
  34419. e->type = kVstMidiType;
  34420. e->byteSize = sizeof (VstMidiEvent);
  34421. events->events[i] = (VstEvent*) e;
  34422. }
  34423. numEventsAllocated = numEventsNeeded;
  34424. }
  34425. }
  34426. void freeEvents()
  34427. {
  34428. if (events != 0)
  34429. {
  34430. for (int i = numEventsAllocated; --i >= 0;)
  34431. {
  34432. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  34433. if (e->type == kVstSysExType)
  34434. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  34435. juce_free (e);
  34436. }
  34437. events.free();
  34438. numEventsUsed = 0;
  34439. numEventsAllocated = 0;
  34440. }
  34441. }
  34442. HeapBlock <VstEvents> events;
  34443. private:
  34444. int numEventsUsed, numEventsAllocated;
  34445. };
  34446. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34447. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34448. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  34449. #endif
  34450. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  34451. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  34452. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  34453. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  34454. #if JUCE_PLUGINHOST_VST
  34455. /**
  34456. Implements a plugin format manager for VSTs.
  34457. */
  34458. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  34459. {
  34460. public:
  34461. VSTPluginFormat();
  34462. ~VSTPluginFormat();
  34463. const String getName() const { return "VST"; }
  34464. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34465. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34466. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34467. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  34468. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  34469. bool doesPluginStillExist (const PluginDescription& desc);
  34470. const FileSearchPath getDefaultLocationsToSearch();
  34471. private:
  34472. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  34473. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginFormat);
  34474. };
  34475. #endif
  34476. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  34477. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  34478. #endif
  34479. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  34480. #endif
  34481. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  34482. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  34483. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  34484. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  34485. /**
  34486. This maintains a list of known AudioPluginFormats.
  34487. @see AudioPluginFormat
  34488. */
  34489. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  34490. {
  34491. public:
  34492. AudioPluginFormatManager();
  34493. /** Destructor. */
  34494. ~AudioPluginFormatManager();
  34495. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  34496. /** Adds any formats that it knows about, e.g. VST.
  34497. */
  34498. void addDefaultFormats();
  34499. /** Returns the number of types of format that are available.
  34500. Use getFormat() to get one of them.
  34501. */
  34502. int getNumFormats();
  34503. /** Returns one of the available formats.
  34504. @see getNumFormats
  34505. */
  34506. AudioPluginFormat* getFormat (int index);
  34507. /** Adds a format to the list.
  34508. The object passed in will be owned and deleted by the manager.
  34509. */
  34510. void addFormat (AudioPluginFormat* format);
  34511. /** Tries to load the type for this description, by trying all the formats
  34512. that this manager knows about.
  34513. The caller is responsible for deleting the object that is returned.
  34514. If it can't load the plugin, it returns 0 and leaves a message in the
  34515. errorMessage string.
  34516. */
  34517. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  34518. String& errorMessage) const;
  34519. /** Checks that the file or component for this plugin actually still exists.
  34520. (This won't try to load the plugin)
  34521. */
  34522. bool doesPluginStillExist (const PluginDescription& description) const;
  34523. private:
  34524. OwnedArray <AudioPluginFormat> formats;
  34525. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormatManager);
  34526. };
  34527. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  34528. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  34529. #endif
  34530. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  34531. #endif
  34532. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  34533. /*** Start of inlined file: juce_KnownPluginList.h ***/
  34534. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  34535. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  34536. /**
  34537. Manages a list of plugin types.
  34538. This can be easily edited, saved and loaded, and used to create instances of
  34539. the plugin types in it.
  34540. @see PluginListComponent
  34541. */
  34542. class JUCE_API KnownPluginList : public ChangeBroadcaster
  34543. {
  34544. public:
  34545. /** Creates an empty list.
  34546. */
  34547. KnownPluginList();
  34548. /** Destructor. */
  34549. ~KnownPluginList();
  34550. /** Clears the list. */
  34551. void clear();
  34552. /** Returns the number of types currently in the list.
  34553. @see getType
  34554. */
  34555. int getNumTypes() const throw() { return types.size(); }
  34556. /** Returns one of the types.
  34557. @see getNumTypes
  34558. */
  34559. PluginDescription* getType (int index) const throw() { return types [index]; }
  34560. /** Looks for a type in the list which comes from this file.
  34561. */
  34562. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const;
  34563. /** Looks for a type in the list which matches a plugin type ID.
  34564. The identifierString parameter must have been created by
  34565. PluginDescription::createIdentifierString().
  34566. */
  34567. PluginDescription* getTypeForIdentifierString (const String& identifierString) const;
  34568. /** Adds a type manually from its description. */
  34569. bool addType (const PluginDescription& type);
  34570. /** Removes a type. */
  34571. void removeType (int index);
  34572. /** Looks for all types that can be loaded from a given file, and adds them
  34573. to the list.
  34574. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  34575. re-tested if it's not already in the list, or if the file's modification
  34576. time has changed since the list was created. If dontRescanIfAlreadyInList is
  34577. false, the file will always be reloaded and tested.
  34578. Returns true if any new types were added, and all the types found in this
  34579. file (even if it was already known and hasn't been re-scanned) get returned
  34580. in the array.
  34581. */
  34582. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  34583. bool dontRescanIfAlreadyInList,
  34584. OwnedArray <PluginDescription>& typesFound,
  34585. AudioPluginFormat& formatToUse);
  34586. /** Returns true if the specified file is already known about and if it
  34587. hasn't been modified since our entry was created.
  34588. */
  34589. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const;
  34590. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  34591. If any types are found in the files, their descriptions are returned in the array.
  34592. */
  34593. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  34594. OwnedArray <PluginDescription>& typesFound);
  34595. /** Sort methods used to change the order of the plugins in the list.
  34596. */
  34597. enum SortMethod
  34598. {
  34599. defaultOrder = 0,
  34600. sortAlphabetically,
  34601. sortByCategory,
  34602. sortByManufacturer,
  34603. sortByFileSystemLocation
  34604. };
  34605. /** Adds all the plugin types to a popup menu so that the user can select one.
  34606. Depending on the sort method, it may add sub-menus for categories,
  34607. manufacturers, etc.
  34608. Use getIndexChosenByMenu() to find out the type that was chosen.
  34609. */
  34610. void addToMenu (PopupMenu& menu,
  34611. const SortMethod sortMethod) const;
  34612. /** Converts a menu item index that has been chosen into its index in this list.
  34613. Returns -1 if it's not an ID that was used.
  34614. @see addToMenu
  34615. */
  34616. int getIndexChosenByMenu (int menuResultCode) const;
  34617. /** Sorts the list. */
  34618. void sort (const SortMethod method);
  34619. /** Creates some XML that can be used to store the state of this list.
  34620. */
  34621. XmlElement* createXml() const;
  34622. /** Recreates the state of this list from its stored XML format.
  34623. */
  34624. void recreateFromXml (const XmlElement& xml);
  34625. private:
  34626. OwnedArray <PluginDescription> types;
  34627. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KnownPluginList);
  34628. };
  34629. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  34630. /*** End of inlined file: juce_KnownPluginList.h ***/
  34631. #endif
  34632. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34633. #endif
  34634. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  34635. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  34636. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  34637. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  34638. /**
  34639. Scans a directory for plugins, and adds them to a KnownPluginList.
  34640. To use one of these, create it and call scanNextFile() repeatedly, until
  34641. it returns false.
  34642. */
  34643. class JUCE_API PluginDirectoryScanner
  34644. {
  34645. public:
  34646. /**
  34647. Creates a scanner.
  34648. @param listToAddResultsTo this will get the new types added to it.
  34649. @param formatToLookFor this is the type of format that you want to look for
  34650. @param directoriesToSearch the path to search
  34651. @param searchRecursively true to search recursively
  34652. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  34653. be used as a file to store the names of any plugins
  34654. that crash during initialisation. If there are
  34655. any plugins listed in it, then these will always
  34656. be scanned after all other possible files have
  34657. been tried - in this way, even if there's a few
  34658. dodgy plugins in your path, then a couple of rescans
  34659. will still manage to find all the proper plugins.
  34660. It's probably best to choose a file in the user's
  34661. application data directory (alongside your app's
  34662. settings file) for this. The file format it uses
  34663. is just a list of filenames of the modules that
  34664. failed.
  34665. */
  34666. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  34667. AudioPluginFormat& formatToLookFor,
  34668. FileSearchPath directoriesToSearch,
  34669. bool searchRecursively,
  34670. const File& deadMansPedalFile);
  34671. /** Destructor. */
  34672. ~PluginDirectoryScanner();
  34673. /** Tries the next likely-looking file.
  34674. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  34675. re-tested if it's not already in the list, or if the file's modification
  34676. time has changed since the list was created. If dontRescanIfAlreadyInList is
  34677. false, the file will always be reloaded and tested.
  34678. Returns false when there are no more files to try.
  34679. */
  34680. bool scanNextFile (bool dontRescanIfAlreadyInList);
  34681. /** Skips over the next file without scanning it.
  34682. Returns false when there are no more files to try.
  34683. */
  34684. bool skipNextFile();
  34685. /** Returns the description of the plugin that will be scanned during the next
  34686. call to scanNextFile().
  34687. This is handy if you want to show the user which file is currently getting
  34688. scanned.
  34689. */
  34690. const String getNextPluginFileThatWillBeScanned() const;
  34691. /** Returns the estimated progress, between 0 and 1.
  34692. */
  34693. float getProgress() const { return progress; }
  34694. /** This returns a list of all the filenames of things that looked like being
  34695. a plugin file, but which failed to open for some reason.
  34696. */
  34697. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  34698. private:
  34699. KnownPluginList& list;
  34700. AudioPluginFormat& format;
  34701. StringArray filesOrIdentifiersToScan;
  34702. File deadMansPedalFile;
  34703. StringArray failedFiles;
  34704. int nextIndex;
  34705. float progress;
  34706. const StringArray getDeadMansPedalFile();
  34707. void setDeadMansPedalFile (const StringArray& newContents);
  34708. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginDirectoryScanner);
  34709. };
  34710. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  34711. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  34712. #endif
  34713. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  34714. /*** Start of inlined file: juce_PluginListComponent.h ***/
  34715. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  34716. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  34717. /*** Start of inlined file: juce_ListBox.h ***/
  34718. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  34719. #define __JUCE_LISTBOX_JUCEHEADER__
  34720. class ListViewport;
  34721. /**
  34722. A subclass of this is used to drive a ListBox.
  34723. @see ListBox
  34724. */
  34725. class JUCE_API ListBoxModel
  34726. {
  34727. public:
  34728. /** Destructor. */
  34729. virtual ~ListBoxModel() {}
  34730. /** This has to return the number of items in the list.
  34731. @see ListBox::getNumRows()
  34732. */
  34733. virtual int getNumRows() = 0;
  34734. /** This method must be implemented to draw a row of the list.
  34735. */
  34736. virtual void paintListBoxItem (int rowNumber,
  34737. Graphics& g,
  34738. int width, int height,
  34739. bool rowIsSelected) = 0;
  34740. /** This is used to create or update a custom component to go in a row of the list.
  34741. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  34742. and handle mouse clicks with listBoxItemClicked().
  34743. This method will be called whenever a custom component might need to be updated - e.g.
  34744. when the table is changed, or TableListBox::updateContent() is called.
  34745. If you don't need a custom component for the specified row, then return 0.
  34746. If you do want a custom component, and the existingComponentToUpdate is null, then
  34747. this method must create a suitable new component and return it.
  34748. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  34749. by this method. In this case, the method must either update it to make sure it's correctly representing
  34750. the given row (which may be different from the one that the component was created for), or it can
  34751. delete this component and return a new one.
  34752. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  34753. */
  34754. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  34755. Component* existingComponentToUpdate);
  34756. /** This can be overridden to react to the user clicking on a row.
  34757. @see listBoxItemDoubleClicked
  34758. */
  34759. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  34760. /** This can be overridden to react to the user double-clicking on a row.
  34761. @see listBoxItemClicked
  34762. */
  34763. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  34764. /** This can be overridden to react to the user double-clicking on a part of the list where
  34765. there are no rows.
  34766. @see listBoxItemClicked
  34767. */
  34768. virtual void backgroundClicked();
  34769. /** Override this to be informed when rows are selected or deselected.
  34770. This will be called whenever a row is selected or deselected. If a range of
  34771. rows is selected all at once, this will just be called once for that event.
  34772. @param lastRowSelected the last row that the user selected. If no
  34773. rows are currently selected, this may be -1.
  34774. */
  34775. virtual void selectedRowsChanged (int lastRowSelected);
  34776. /** Override this to be informed when the delete key is pressed.
  34777. If no rows are selected when they press the key, this won't be called.
  34778. @param lastRowSelected the last row that had been selected when they pressed the
  34779. key - if there are multiple selections, this might not be
  34780. very useful
  34781. */
  34782. virtual void deleteKeyPressed (int lastRowSelected);
  34783. /** Override this to be informed when the return key is pressed.
  34784. If no rows are selected when they press the key, this won't be called.
  34785. @param lastRowSelected the last row that had been selected when they pressed the
  34786. key - if there are multiple selections, this might not be
  34787. very useful
  34788. */
  34789. virtual void returnKeyPressed (int lastRowSelected);
  34790. /** Override this to be informed when the list is scrolled.
  34791. This might be caused by the user moving the scrollbar, or by programmatic changes
  34792. to the list position.
  34793. */
  34794. virtual void listWasScrolled();
  34795. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  34796. If this returns a non-empty name then when the user drags a row, the listbox will
  34797. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  34798. a drag-and-drop operation, using this string as the source description, with the listbox
  34799. itself as the source component.
  34800. @see DragAndDropContainer::startDragging
  34801. */
  34802. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  34803. /** You can override this to provide tool tips for specific rows.
  34804. @see TooltipClient
  34805. */
  34806. virtual const String getTooltipForRow (int row);
  34807. };
  34808. /**
  34809. A list of items that can be scrolled vertically.
  34810. To create a list, you'll need to create a subclass of ListBoxModel. This can
  34811. either paint each row of the list and respond to events via callbacks, or for
  34812. more specialised tasks, it can supply a custom component to fill each row.
  34813. @see ComboBox, TableListBox
  34814. */
  34815. class JUCE_API ListBox : public Component,
  34816. public SettableTooltipClient
  34817. {
  34818. public:
  34819. /** Creates a ListBox.
  34820. The model pointer passed-in can be null, in which case you can set it later
  34821. with setModel().
  34822. */
  34823. ListBox (const String& componentName = String::empty,
  34824. ListBoxModel* model = 0);
  34825. /** Destructor. */
  34826. ~ListBox();
  34827. /** Changes the current data model to display. */
  34828. void setModel (ListBoxModel* newModel);
  34829. /** Returns the current list model. */
  34830. ListBoxModel* getModel() const throw() { return model; }
  34831. /** Causes the list to refresh its content.
  34832. Call this when the number of rows in the list changes, or if you want it
  34833. to call refreshComponentForRow() on all the row components.
  34834. Be careful not to call it from a different thread, though, as it's not
  34835. thread-safe.
  34836. */
  34837. void updateContent();
  34838. /** Turns on multiple-selection of rows.
  34839. By default this is disabled.
  34840. When your row component gets clicked you'll need to call the
  34841. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  34842. clicked and to get it to do the appropriate selection based on whether
  34843. the ctrl/shift keys are held down.
  34844. */
  34845. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  34846. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  34847. This function is here primarily for the ComboBox class to use, but might be
  34848. useful for some other purpose too.
  34849. */
  34850. void setMouseMoveSelectsRows (bool shouldSelect);
  34851. /** Selects a row.
  34852. If the row is already selected, this won't do anything.
  34853. @param rowNumber the row to select
  34854. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  34855. the selected row is off-screen, it'll scroll to make
  34856. sure that row is on-screen
  34857. @param deselectOthersFirst if true and there are multiple selections, these will
  34858. first be deselected before this item is selected
  34859. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  34860. deselectAllRows, selectRangeOfRows
  34861. */
  34862. void selectRow (int rowNumber,
  34863. bool dontScrollToShowThisRow = false,
  34864. bool deselectOthersFirst = true);
  34865. /** Selects a set of rows.
  34866. This will add these rows to the current selection, so you might need to
  34867. clear the current selection first with deselectAllRows()
  34868. @param firstRow the first row to select (inclusive)
  34869. @param lastRow the last row to select (inclusive)
  34870. */
  34871. void selectRangeOfRows (int firstRow,
  34872. int lastRow);
  34873. /** Deselects a row.
  34874. If it's not currently selected, this will do nothing.
  34875. @see selectRow, deselectAllRows
  34876. */
  34877. void deselectRow (int rowNumber);
  34878. /** Deselects any currently selected rows.
  34879. @see deselectRow
  34880. */
  34881. void deselectAllRows();
  34882. /** Selects or deselects a row.
  34883. If the row's currently selected, this deselects it, and vice-versa.
  34884. */
  34885. void flipRowSelection (int rowNumber);
  34886. /** Returns a sparse set indicating the rows that are currently selected.
  34887. @see setSelectedRows
  34888. */
  34889. const SparseSet<int> getSelectedRows() const;
  34890. /** Sets the rows that should be selected, based on an explicit set of ranges.
  34891. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  34892. method will be called. If it's false, no notification will be sent to the model.
  34893. @see getSelectedRows
  34894. */
  34895. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  34896. bool sendNotificationEventToModel = true);
  34897. /** Checks whether a row is selected.
  34898. */
  34899. bool isRowSelected (int rowNumber) const;
  34900. /** Returns the number of rows that are currently selected.
  34901. @see getSelectedRow, isRowSelected, getLastRowSelected
  34902. */
  34903. int getNumSelectedRows() const;
  34904. /** Returns the row number of a selected row.
  34905. This will return the row number of the Nth selected row. The row numbers returned will
  34906. be sorted in order from low to high.
  34907. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  34908. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  34909. selected
  34910. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  34911. */
  34912. int getSelectedRow (int index = 0) const;
  34913. /** Returns the last row that the user selected.
  34914. This isn't the same as the highest row number that is currently selected - if the user
  34915. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  34916. If nothing is selected, it will return -1.
  34917. */
  34918. int getLastRowSelected() const;
  34919. /** Multiply-selects rows based on the modifier keys.
  34920. If no modifier keys are down, this will select the given row and
  34921. deselect any others.
  34922. If the ctrl (or command on the Mac) key is down, it'll flip the
  34923. state of the selected row.
  34924. If the shift key is down, it'll select up to the given row from the
  34925. last row selected.
  34926. @see selectRow
  34927. */
  34928. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  34929. const ModifierKeys& modifiers,
  34930. bool isMouseUpEvent);
  34931. /** Scrolls the list to a particular position.
  34932. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  34933. 1.0 scrolls to the bottom.
  34934. If the total number of rows all fit onto the screen at once, then this
  34935. method won't do anything.
  34936. @see getVerticalPosition
  34937. */
  34938. void setVerticalPosition (double newProportion);
  34939. /** Returns the current vertical position as a proportion of the total.
  34940. This can be used in conjunction with setVerticalPosition() to save and restore
  34941. the list's position. It returns a value in the range 0 to 1.
  34942. @see setVerticalPosition
  34943. */
  34944. double getVerticalPosition() const;
  34945. /** Scrolls if necessary to make sure that a particular row is visible.
  34946. */
  34947. void scrollToEnsureRowIsOnscreen (int row);
  34948. /** Returns a pointer to the scrollbar.
  34949. (Unlikely to be useful for most people).
  34950. */
  34951. ScrollBar* getVerticalScrollBar() const throw();
  34952. /** Returns a pointer to the scrollbar.
  34953. (Unlikely to be useful for most people).
  34954. */
  34955. ScrollBar* getHorizontalScrollBar() const throw();
  34956. /** Finds the row index that contains a given x,y position.
  34957. The position is relative to the ListBox's top-left.
  34958. If no row exists at this position, the method will return -1.
  34959. @see getComponentForRowNumber
  34960. */
  34961. int getRowContainingPosition (int x, int y) const throw();
  34962. /** Finds a row index that would be the most suitable place to insert a new
  34963. item for a given position.
  34964. This is useful when the user is e.g. dragging and dropping onto the listbox,
  34965. because it lets you easily choose the best position to insert the item that
  34966. they drop, based on where they drop it.
  34967. If the position is out of range, this will return -1. If the position is
  34968. beyond the end of the list, it will return getNumRows() to indicate the end
  34969. of the list.
  34970. @see getComponentForRowNumber
  34971. */
  34972. int getInsertionIndexForPosition (int x, int y) const throw();
  34973. /** Returns the position of one of the rows, relative to the top-left of
  34974. the listbox.
  34975. This may be off-screen, and the range of the row number that is passed-in is
  34976. not checked to see if it's a valid row.
  34977. */
  34978. const Rectangle<int> getRowPosition (int rowNumber,
  34979. bool relativeToComponentTopLeft) const throw();
  34980. /** Finds the row component for a given row in the list.
  34981. The component returned will have been created using createRowComponent().
  34982. If the component for this row is off-screen or if the row is out-of-range,
  34983. this will return 0.
  34984. @see getRowContainingPosition
  34985. */
  34986. Component* getComponentForRowNumber (int rowNumber) const throw();
  34987. /** Returns the row number that the given component represents.
  34988. If the component isn't one of the list's rows, this will return -1.
  34989. */
  34990. int getRowNumberOfComponent (Component* rowComponent) const throw();
  34991. /** Returns the width of a row (which may be less than the width of this component
  34992. if there's a scrollbar).
  34993. */
  34994. int getVisibleRowWidth() const throw();
  34995. /** Sets the height of each row in the list.
  34996. The default height is 22 pixels.
  34997. @see getRowHeight
  34998. */
  34999. void setRowHeight (int newHeight);
  35000. /** Returns the height of a row in the list.
  35001. @see setRowHeight
  35002. */
  35003. int getRowHeight() const throw() { return rowHeight; }
  35004. /** Returns the number of rows actually visible.
  35005. This is the number of whole rows which will fit on-screen, so the value might
  35006. be more than the actual number of rows in the list.
  35007. */
  35008. int getNumRowsOnScreen() const throw();
  35009. /** A set of colour IDs to use to change the colour of various aspects of the label.
  35010. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35011. methods.
  35012. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35013. */
  35014. enum ColourIds
  35015. {
  35016. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  35017. Make this transparent if you don't want the background to be filled. */
  35018. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  35019. Make this transparent to not have an outline. */
  35020. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  35021. };
  35022. /** Sets the thickness of a border that will be drawn around the box.
  35023. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  35024. @see outlineColourId
  35025. */
  35026. void setOutlineThickness (int outlineThickness);
  35027. /** Returns the thickness of outline that will be drawn around the listbox.
  35028. @see setOutlineColour
  35029. */
  35030. int getOutlineThickness() const throw() { return outlineThickness; }
  35031. /** Sets a component that the list should use as a header.
  35032. This will position the given component at the top of the list, maintaining the
  35033. height of the component passed-in, but rescaling it horizontally to match the
  35034. width of the items in the listbox.
  35035. The component will be deleted when setHeaderComponent() is called with a
  35036. different component, or when the listbox is deleted.
  35037. */
  35038. void setHeaderComponent (Component* newHeaderComponent);
  35039. /** Changes the width of the rows in the list.
  35040. This can be used to make the list's row components wider than the list itself - the
  35041. width of the rows will be either the width of the list or this value, whichever is
  35042. greater, and if the rows become wider than the list, a horizontal scrollbar will
  35043. appear.
  35044. The default value for this is 0, which means that the rows will always
  35045. be the same width as the list.
  35046. */
  35047. void setMinimumContentWidth (int newMinimumWidth);
  35048. /** Returns the space currently available for the row items, taking into account
  35049. borders, scrollbars, etc.
  35050. */
  35051. int getVisibleContentWidth() const throw();
  35052. /** Repaints one of the rows.
  35053. This is a lightweight alternative to calling updateContent, and just causes a
  35054. repaint of the row's area.
  35055. */
  35056. void repaintRow (int rowNumber) throw();
  35057. /** This fairly obscure method creates an image that just shows the currently
  35058. selected row components.
  35059. It's a handy method for doing drag-and-drop, as it can be passed to the
  35060. DragAndDropContainer for use as the drag image.
  35061. Note that it will make the row components temporarily invisible, so if you're
  35062. using custom components this could affect them if they're sensitive to that
  35063. sort of thing.
  35064. @see Component::createComponentSnapshot
  35065. */
  35066. virtual const Image createSnapshotOfSelectedRows (int& x, int& y);
  35067. /** Returns the viewport that this ListBox uses.
  35068. You may need to use this to change parameters such as whether scrollbars
  35069. are shown, etc.
  35070. */
  35071. Viewport* getViewport() const throw();
  35072. /** @internal */
  35073. bool keyPressed (const KeyPress& key);
  35074. /** @internal */
  35075. bool keyStateChanged (bool isKeyDown);
  35076. /** @internal */
  35077. void paint (Graphics& g);
  35078. /** @internal */
  35079. void paintOverChildren (Graphics& g);
  35080. /** @internal */
  35081. void resized();
  35082. /** @internal */
  35083. void visibilityChanged();
  35084. /** @internal */
  35085. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  35086. /** @internal */
  35087. void mouseMove (const MouseEvent&);
  35088. /** @internal */
  35089. void mouseExit (const MouseEvent&);
  35090. /** @internal */
  35091. void mouseUp (const MouseEvent&);
  35092. /** @internal */
  35093. void colourChanged();
  35094. /** @internal */
  35095. void startDragAndDrop (const MouseEvent& e, const String& dragDescription);
  35096. private:
  35097. friend class ListViewport;
  35098. friend class TableListBox;
  35099. ListBoxModel* model;
  35100. ScopedPointer<ListViewport> viewport;
  35101. ScopedPointer<Component> headerComponent;
  35102. int totalItems, rowHeight, minimumRowWidth;
  35103. int outlineThickness;
  35104. int lastRowSelected;
  35105. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  35106. SparseSet <int> selected;
  35107. void selectRowInternal (int rowNumber,
  35108. bool dontScrollToShowThisRow,
  35109. bool deselectOthersFirst,
  35110. bool isMouseClick);
  35111. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBox);
  35112. };
  35113. #endif // __JUCE_LISTBOX_JUCEHEADER__
  35114. /*** End of inlined file: juce_ListBox.h ***/
  35115. /*** Start of inlined file: juce_TextButton.h ***/
  35116. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  35117. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  35118. /**
  35119. A button that uses the standard lozenge-shaped background with a line of
  35120. text on it.
  35121. @see Button, DrawableButton
  35122. */
  35123. class JUCE_API TextButton : public Button
  35124. {
  35125. public:
  35126. /** Creates a TextButton.
  35127. @param buttonName the text to put in the button (the component's name is also
  35128. initially set to this string, but these can be changed later
  35129. using the setName() and setButtonText() methods)
  35130. @param toolTip an optional string to use as a toolip
  35131. @see Button
  35132. */
  35133. TextButton (const String& buttonName = String::empty,
  35134. const String& toolTip = String::empty);
  35135. /** Destructor. */
  35136. ~TextButton();
  35137. /** A set of colour IDs to use to change the colour of various aspects of the button.
  35138. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35139. methods.
  35140. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35141. */
  35142. enum ColourIds
  35143. {
  35144. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  35145. 'off'). The look-and-feel class might re-interpret this to add
  35146. effects, etc. */
  35147. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  35148. 'on'). The look-and-feel class might re-interpret this to add
  35149. effects, etc. */
  35150. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  35151. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  35152. };
  35153. /** Resizes the button to fit neatly around its current text.
  35154. If newHeight is >= 0, the button's height will be changed to this
  35155. value. If it's less than zero, its height will be unaffected.
  35156. */
  35157. void changeWidthToFitText (int newHeight = -1);
  35158. /** This can be overridden to use different fonts than the default one.
  35159. Note that you'll need to set the font's size appropriately, too.
  35160. */
  35161. virtual const Font getFont();
  35162. protected:
  35163. /** @internal */
  35164. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  35165. /** @internal */
  35166. void colourChanged();
  35167. private:
  35168. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextButton);
  35169. };
  35170. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  35171. /*** End of inlined file: juce_TextButton.h ***/
  35172. /**
  35173. A component displaying a list of plugins, with options to scan for them,
  35174. add, remove and sort them.
  35175. */
  35176. class JUCE_API PluginListComponent : public Component,
  35177. public ListBoxModel,
  35178. public ChangeListener,
  35179. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  35180. public Timer
  35181. {
  35182. public:
  35183. /**
  35184. Creates the list component.
  35185. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  35186. The properties file, if supplied, is used to store the user's last search paths.
  35187. */
  35188. PluginListComponent (KnownPluginList& listToRepresent,
  35189. const File& deadMansPedalFile,
  35190. PropertiesFile* propertiesToUse);
  35191. /** Destructor. */
  35192. ~PluginListComponent();
  35193. /** @internal */
  35194. void resized();
  35195. /** @internal */
  35196. bool isInterestedInFileDrag (const StringArray& files);
  35197. /** @internal */
  35198. void filesDropped (const StringArray& files, int, int);
  35199. /** @internal */
  35200. int getNumRows();
  35201. /** @internal */
  35202. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  35203. /** @internal */
  35204. void deleteKeyPressed (int lastRowSelected);
  35205. /** @internal */
  35206. void buttonClicked (Button* b);
  35207. /** @internal */
  35208. void changeListenerCallback (ChangeBroadcaster*);
  35209. /** @internal */
  35210. void timerCallback();
  35211. private:
  35212. KnownPluginList& list;
  35213. File deadMansPedalFile;
  35214. ListBox listBox;
  35215. TextButton optionsButton;
  35216. PropertiesFile* propertiesToUse;
  35217. int typeToScan;
  35218. void scanFor (AudioPluginFormat* format);
  35219. static void optionsMenuStaticCallback (int result, PluginListComponent*);
  35220. void optionsMenuCallback (int result);
  35221. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginListComponent);
  35222. };
  35223. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35224. /*** End of inlined file: juce_PluginListComponent.h ***/
  35225. #endif
  35226. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  35227. #endif
  35228. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  35229. #endif
  35230. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  35231. #endif
  35232. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35233. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  35234. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35235. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35236. /**
  35237. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  35238. Use one of these objects if you want to wire-up a set of AudioProcessors
  35239. and play back the result.
  35240. Processors can be added to the graph as "nodes" using addNode(), and once
  35241. added, you can connect any of their input or output channels to other
  35242. nodes using addConnection().
  35243. To play back a graph through an audio device, you might want to use an
  35244. AudioProcessorPlayer object.
  35245. */
  35246. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  35247. public AsyncUpdater
  35248. {
  35249. public:
  35250. /** Creates an empty graph.
  35251. */
  35252. AudioProcessorGraph();
  35253. /** Destructor.
  35254. Any processor objects that have been added to the graph will also be deleted.
  35255. */
  35256. ~AudioProcessorGraph();
  35257. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  35258. To create a node, call AudioProcessorGraph::addNode().
  35259. */
  35260. class JUCE_API Node : public ReferenceCountedObject
  35261. {
  35262. public:
  35263. /** The ID number assigned to this node.
  35264. This is assigned by the graph that owns it, and can't be changed.
  35265. */
  35266. const uint32 id;
  35267. /** The actual processor object that this node represents. */
  35268. AudioProcessor* getProcessor() const throw() { return processor; }
  35269. /** A set of user-definable properties that are associated with this node.
  35270. This can be used to attach values to the node for whatever purpose seems
  35271. useful. For example, you might store an x and y position if your application
  35272. is displaying the nodes on-screen.
  35273. */
  35274. NamedValueSet properties;
  35275. /** A convenient typedef for referring to a pointer to a node object.
  35276. */
  35277. typedef ReferenceCountedObjectPtr <Node> Ptr;
  35278. private:
  35279. friend class AudioProcessorGraph;
  35280. const ScopedPointer<AudioProcessor> processor;
  35281. bool isPrepared;
  35282. Node (uint32 id, AudioProcessor* processor);
  35283. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  35284. void unprepare();
  35285. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Node);
  35286. };
  35287. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  35288. To create a connection, use AudioProcessorGraph::addConnection().
  35289. */
  35290. struct JUCE_API Connection
  35291. {
  35292. public:
  35293. /** The ID number of the node which is the input source for this connection.
  35294. @see AudioProcessorGraph::getNodeForId
  35295. */
  35296. uint32 sourceNodeId;
  35297. /** The index of the output channel of the source node from which this
  35298. connection takes its data.
  35299. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  35300. it is referring to the source node's midi output. Otherwise, it is the zero-based
  35301. index of an audio output channel in the source node.
  35302. */
  35303. int sourceChannelIndex;
  35304. /** The ID number of the node which is the destination for this connection.
  35305. @see AudioProcessorGraph::getNodeForId
  35306. */
  35307. uint32 destNodeId;
  35308. /** The index of the input channel of the destination node to which this
  35309. connection delivers its data.
  35310. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  35311. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  35312. index of an audio input channel in the destination node.
  35313. */
  35314. int destChannelIndex;
  35315. private:
  35316. JUCE_LEAK_DETECTOR (Connection);
  35317. };
  35318. /** Deletes all nodes and connections from this graph.
  35319. Any processor objects in the graph will be deleted.
  35320. */
  35321. void clear();
  35322. /** Returns the number of nodes in the graph. */
  35323. int getNumNodes() const { return nodes.size(); }
  35324. /** Returns a pointer to one of the nodes in the graph.
  35325. This will return 0 if the index is out of range.
  35326. @see getNodeForId
  35327. */
  35328. Node* getNode (const int index) const { return nodes [index]; }
  35329. /** Searches the graph for a node with the given ID number and returns it.
  35330. If no such node was found, this returns 0.
  35331. @see getNode
  35332. */
  35333. Node* getNodeForId (const uint32 nodeId) const;
  35334. /** Adds a node to the graph.
  35335. This creates a new node in the graph, for the specified processor. Once you have
  35336. added a processor to the graph, the graph owns it and will delete it later when
  35337. it is no longer needed.
  35338. The optional nodeId parameter lets you specify an ID to use for the node, but
  35339. if the value is already in use, this new node will overwrite the old one.
  35340. If this succeeds, it returns a pointer to the newly-created node.
  35341. */
  35342. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  35343. /** Deletes a node within the graph which has the specified ID.
  35344. This will also delete any connections that are attached to this node.
  35345. */
  35346. bool removeNode (uint32 nodeId);
  35347. /** Returns the number of connections in the graph. */
  35348. int getNumConnections() const { return connections.size(); }
  35349. /** Returns a pointer to one of the connections in the graph. */
  35350. const Connection* getConnection (int index) const { return connections [index]; }
  35351. /** Searches for a connection between some specified channels.
  35352. If no such connection is found, this returns 0.
  35353. */
  35354. const Connection* getConnectionBetween (uint32 sourceNodeId,
  35355. int sourceChannelIndex,
  35356. uint32 destNodeId,
  35357. int destChannelIndex) const;
  35358. /** Returns true if there is a connection between any of the channels of
  35359. two specified nodes.
  35360. */
  35361. bool isConnected (uint32 possibleSourceNodeId,
  35362. uint32 possibleDestNodeId) const;
  35363. /** Returns true if it would be legal to connect the specified points.
  35364. */
  35365. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  35366. uint32 destNodeId, int destChannelIndex) const;
  35367. /** Attempts to connect two specified channels of two nodes.
  35368. If this isn't allowed (e.g. because you're trying to connect a midi channel
  35369. to an audio one or other such nonsense), then it'll return false.
  35370. */
  35371. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  35372. uint32 destNodeId, int destChannelIndex);
  35373. /** Deletes the connection with the specified index.
  35374. Returns true if a connection was actually deleted.
  35375. */
  35376. void removeConnection (int index);
  35377. /** Deletes any connection between two specified points.
  35378. Returns true if a connection was actually deleted.
  35379. */
  35380. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  35381. uint32 destNodeId, int destChannelIndex);
  35382. /** Removes all connections from the specified node.
  35383. */
  35384. bool disconnectNode (uint32 nodeId);
  35385. /** Performs a sanity checks of all the connections.
  35386. This might be useful if some of the processors are doing things like changing
  35387. their channel counts, which could render some connections obsolete.
  35388. */
  35389. bool removeIllegalConnections();
  35390. /** A special number that represents the midi channel of a node.
  35391. This is used as a channel index value if you want to refer to the midi input
  35392. or output instead of an audio channel.
  35393. */
  35394. static const int midiChannelIndex;
  35395. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  35396. in order to use the audio that comes into and out of the graph itself.
  35397. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  35398. node in the graph which delivers the audio that is coming into the parent
  35399. graph. This allows you to stream the data to other nodes and process the
  35400. incoming audio.
  35401. Likewise, one of these in "output" mode can be sent data which it will add to
  35402. the sum of data being sent to the graph's output.
  35403. @see AudioProcessorGraph
  35404. */
  35405. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  35406. {
  35407. public:
  35408. /** Specifies the mode in which this processor will operate.
  35409. */
  35410. enum IODeviceType
  35411. {
  35412. audioInputNode, /**< In this mode, the processor has output channels
  35413. representing all the audio input channels that are
  35414. coming into its parent audio graph. */
  35415. audioOutputNode, /**< In this mode, the processor has input channels
  35416. representing all the audio output channels that are
  35417. going out of its parent audio graph. */
  35418. midiInputNode, /**< In this mode, the processor has a midi output which
  35419. delivers the same midi data that is arriving at its
  35420. parent graph. */
  35421. midiOutputNode /**< In this mode, the processor has a midi input and
  35422. any data sent to it will be passed out of the parent
  35423. graph. */
  35424. };
  35425. /** Returns the mode of this processor. */
  35426. IODeviceType getType() const { return type; }
  35427. /** Returns the parent graph to which this processor belongs, or 0 if it
  35428. hasn't yet been added to one. */
  35429. AudioProcessorGraph* getParentGraph() const { return graph; }
  35430. /** True if this is an audio or midi input. */
  35431. bool isInput() const;
  35432. /** True if this is an audio or midi output. */
  35433. bool isOutput() const;
  35434. AudioGraphIOProcessor (const IODeviceType type);
  35435. ~AudioGraphIOProcessor();
  35436. const String getName() const;
  35437. void fillInPluginDescription (PluginDescription& d) const;
  35438. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  35439. void releaseResources();
  35440. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  35441. const String getInputChannelName (int channelIndex) const;
  35442. const String getOutputChannelName (int channelIndex) const;
  35443. bool isInputChannelStereoPair (int index) const;
  35444. bool isOutputChannelStereoPair (int index) const;
  35445. bool acceptsMidi() const;
  35446. bool producesMidi() const;
  35447. bool hasEditor() const;
  35448. AudioProcessorEditor* createEditor();
  35449. int getNumParameters();
  35450. const String getParameterName (int);
  35451. float getParameter (int);
  35452. const String getParameterText (int);
  35453. void setParameter (int, float);
  35454. int getNumPrograms();
  35455. int getCurrentProgram();
  35456. void setCurrentProgram (int);
  35457. const String getProgramName (int);
  35458. void changeProgramName (int, const String&);
  35459. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  35460. void setStateInformation (const void* data, int sizeInBytes);
  35461. /** @internal */
  35462. void setParentGraph (AudioProcessorGraph* graph);
  35463. private:
  35464. const IODeviceType type;
  35465. AudioProcessorGraph* graph;
  35466. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioGraphIOProcessor);
  35467. };
  35468. // AudioProcessor methods:
  35469. const String getName() const;
  35470. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  35471. void releaseResources();
  35472. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  35473. const String getInputChannelName (int channelIndex) const;
  35474. const String getOutputChannelName (int channelIndex) const;
  35475. bool isInputChannelStereoPair (int index) const;
  35476. bool isOutputChannelStereoPair (int index) const;
  35477. bool acceptsMidi() const;
  35478. bool producesMidi() const;
  35479. bool hasEditor() const { return false; }
  35480. AudioProcessorEditor* createEditor() { return 0; }
  35481. int getNumParameters() { return 0; }
  35482. const String getParameterName (int) { return String::empty; }
  35483. float getParameter (int) { return 0; }
  35484. const String getParameterText (int) { return String::empty; }
  35485. void setParameter (int, float) { }
  35486. int getNumPrograms() { return 0; }
  35487. int getCurrentProgram() { return 0; }
  35488. void setCurrentProgram (int) { }
  35489. const String getProgramName (int) { return String::empty; }
  35490. void changeProgramName (int, const String&) { }
  35491. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  35492. void setStateInformation (const void* data, int sizeInBytes);
  35493. /** @internal */
  35494. void handleAsyncUpdate();
  35495. private:
  35496. ReferenceCountedArray <Node> nodes;
  35497. OwnedArray <Connection> connections;
  35498. int lastNodeId;
  35499. AudioSampleBuffer renderingBuffers;
  35500. OwnedArray <MidiBuffer> midiBuffers;
  35501. CriticalSection renderLock;
  35502. Array<void*> renderingOps;
  35503. friend class AudioGraphIOProcessor;
  35504. AudioSampleBuffer* currentAudioInputBuffer;
  35505. AudioSampleBuffer currentAudioOutputBuffer;
  35506. MidiBuffer* currentMidiInputBuffer;
  35507. MidiBuffer currentMidiOutputBuffer;
  35508. void clearRenderingSequence();
  35509. void buildRenderingSequence();
  35510. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  35511. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorGraph);
  35512. };
  35513. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35514. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  35515. #endif
  35516. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  35517. #endif
  35518. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35519. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  35520. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35521. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35522. /**
  35523. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  35524. To use one of these, just make it the callback used by your AudioIODevice, and
  35525. give it a processor to use by calling setProcessor().
  35526. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  35527. input to send both streams through the processor.
  35528. @see AudioProcessor, AudioProcessorGraph
  35529. */
  35530. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  35531. public MidiInputCallback
  35532. {
  35533. public:
  35534. /**
  35535. */
  35536. AudioProcessorPlayer();
  35537. /** Destructor. */
  35538. virtual ~AudioProcessorPlayer();
  35539. /** Sets the processor that should be played.
  35540. The processor that is passed in will not be deleted or owned by this object.
  35541. To stop anything playing, pass in 0 to this method.
  35542. */
  35543. void setProcessor (AudioProcessor* processorToPlay);
  35544. /** Returns the current audio processor that is being played.
  35545. */
  35546. AudioProcessor* getCurrentProcessor() const { return processor; }
  35547. /** Returns a midi message collector that you can pass midi messages to if you
  35548. want them to be injected into the midi stream that is being sent to the
  35549. processor.
  35550. */
  35551. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  35552. /** @internal */
  35553. void audioDeviceIOCallback (const float** inputChannelData,
  35554. int totalNumInputChannels,
  35555. float** outputChannelData,
  35556. int totalNumOutputChannels,
  35557. int numSamples);
  35558. /** @internal */
  35559. void audioDeviceAboutToStart (AudioIODevice* device);
  35560. /** @internal */
  35561. void audioDeviceStopped();
  35562. /** @internal */
  35563. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  35564. private:
  35565. AudioProcessor* processor;
  35566. CriticalSection lock;
  35567. double sampleRate;
  35568. int blockSize;
  35569. bool isPrepared;
  35570. int numInputChans, numOutputChans;
  35571. float* channels [128];
  35572. AudioSampleBuffer tempBuffer;
  35573. MidiBuffer incomingMidi;
  35574. MidiMessageCollector messageCollector;
  35575. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorPlayer);
  35576. };
  35577. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35578. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  35579. #endif
  35580. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35581. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  35582. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35583. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35584. /*** Start of inlined file: juce_PropertyPanel.h ***/
  35585. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  35586. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  35587. /*** Start of inlined file: juce_PropertyComponent.h ***/
  35588. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35589. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35590. class EditableProperty;
  35591. /**
  35592. A base class for a component that goes in a PropertyPanel and displays one of
  35593. an item's properties.
  35594. Subclasses of this are used to display a property in various forms, e.g. a
  35595. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  35596. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  35597. A subclass must implement the refresh() method which will be called to tell the
  35598. component to update itself, and is also responsible for calling this it when the
  35599. item that it refers to is changed.
  35600. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  35601. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  35602. */
  35603. class JUCE_API PropertyComponent : public Component,
  35604. public SettableTooltipClient
  35605. {
  35606. public:
  35607. /** Creates a PropertyComponent.
  35608. @param propertyName the name is stored as this component's name, and is
  35609. used as the name displayed next to this component in
  35610. a property panel
  35611. @param preferredHeight the height that the component should be given - some
  35612. items may need to be larger than a normal row height.
  35613. This value can also be set if a subclass changes the
  35614. preferredHeight member variable.
  35615. */
  35616. PropertyComponent (const String& propertyName,
  35617. int preferredHeight = 25);
  35618. /** Destructor. */
  35619. ~PropertyComponent();
  35620. /** Returns this item's preferred height.
  35621. This value is specified either in the constructor or by a subclass changing the
  35622. preferredHeight member variable.
  35623. */
  35624. int getPreferredHeight() const throw() { return preferredHeight; }
  35625. void setPreferredHeight (int newHeight) throw() { preferredHeight = newHeight; }
  35626. /** Updates the property component if the item it refers to has changed.
  35627. A subclass must implement this method, and other objects may call it to
  35628. force it to refresh itself.
  35629. The subclass should be economical in the amount of work is done, so for
  35630. example it should check whether it really needs to do a repaint rather than
  35631. just doing one every time this method is called, as it may be called when
  35632. the value being displayed hasn't actually changed.
  35633. */
  35634. virtual void refresh() = 0;
  35635. /** The default paint method fills the background and draws a label for the
  35636. item's name.
  35637. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  35638. */
  35639. void paint (Graphics& g);
  35640. /** The default resize method positions any child component to the right of this
  35641. one, based on the look and feel's default label size.
  35642. */
  35643. void resized();
  35644. /** By default, this just repaints the component. */
  35645. void enablementChanged();
  35646. protected:
  35647. /** Used by the PropertyPanel to determine how high this component needs to be.
  35648. A subclass can update this value in its constructor but shouldn't alter it later
  35649. as changes won't necessarily be picked up.
  35650. */
  35651. int preferredHeight;
  35652. private:
  35653. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyComponent);
  35654. };
  35655. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35656. /*** End of inlined file: juce_PropertyComponent.h ***/
  35657. /**
  35658. A panel that holds a list of PropertyComponent objects.
  35659. This panel displays a list of PropertyComponents, and allows them to be organised
  35660. into collapsible sections.
  35661. To use, simply create one of these and add your properties to it with addProperties()
  35662. or addSection().
  35663. @see PropertyComponent
  35664. */
  35665. class JUCE_API PropertyPanel : public Component
  35666. {
  35667. public:
  35668. /** Creates an empty property panel. */
  35669. PropertyPanel();
  35670. /** Destructor. */
  35671. ~PropertyPanel();
  35672. /** Deletes all property components from the panel.
  35673. */
  35674. void clear();
  35675. /** Adds a set of properties to the panel.
  35676. The components in the list will be owned by this object and will be automatically
  35677. deleted later on when no longer needed.
  35678. These properties are added without them being inside a named section. If you
  35679. want them to be kept together in a collapsible section, use addSection() instead.
  35680. */
  35681. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  35682. /** Adds a set of properties to the panel.
  35683. These properties are added at the bottom of the list, under a section heading with
  35684. a plus/minus button that allows it to be opened and closed.
  35685. The components in the list will be owned by this object and will be automatically
  35686. deleted later on when no longer needed.
  35687. To add properies without them being in a section, use addProperties().
  35688. */
  35689. void addSection (const String& sectionTitle,
  35690. const Array <PropertyComponent*>& newPropertyComponents,
  35691. bool shouldSectionInitiallyBeOpen = true);
  35692. /** Calls the refresh() method of all PropertyComponents in the panel */
  35693. void refreshAll() const;
  35694. /** Returns a list of all the names of sections in the panel.
  35695. These are the sections that have been added with addSection().
  35696. */
  35697. const StringArray getSectionNames() const;
  35698. /** Returns true if the section at this index is currently open.
  35699. The index is from 0 up to the number of items returned by getSectionNames().
  35700. */
  35701. bool isSectionOpen (int sectionIndex) const;
  35702. /** Opens or closes one of the sections.
  35703. The index is from 0 up to the number of items returned by getSectionNames().
  35704. */
  35705. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  35706. /** Enables or disables one of the sections.
  35707. The index is from 0 up to the number of items returned by getSectionNames().
  35708. */
  35709. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  35710. /** Saves the current state of open/closed sections so it can be restored later.
  35711. The caller is responsible for deleting the object that is returned.
  35712. To restore this state, use restoreOpennessState().
  35713. @see restoreOpennessState
  35714. */
  35715. XmlElement* getOpennessState() const;
  35716. /** Restores a previously saved arrangement of open/closed sections.
  35717. This will try to restore a snapshot of the panel's state that was created by
  35718. the getOpennessState() method. If any of the sections named in the original
  35719. XML aren't present, they will be ignored.
  35720. @see getOpennessState
  35721. */
  35722. void restoreOpennessState (const XmlElement& newState);
  35723. /** Sets a message to be displayed when there are no properties in the panel.
  35724. The default message is "nothing selected".
  35725. */
  35726. void setMessageWhenEmpty (const String& newMessage);
  35727. /** Returns the message that is displayed when there are no properties.
  35728. @see setMessageWhenEmpty
  35729. */
  35730. const String& getMessageWhenEmpty() const;
  35731. /** @internal */
  35732. void paint (Graphics& g);
  35733. /** @internal */
  35734. void resized();
  35735. private:
  35736. Viewport viewport;
  35737. class PropertyHolderComponent;
  35738. PropertyHolderComponent* propertyHolderComponent;
  35739. String messageWhenEmpty;
  35740. void updatePropHolderLayout() const;
  35741. void updatePropHolderLayout (int width) const;
  35742. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyPanel);
  35743. };
  35744. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  35745. /*** End of inlined file: juce_PropertyPanel.h ***/
  35746. /**
  35747. A type of UI component that displays the parameters of an AudioProcessor as
  35748. a simple list of sliders.
  35749. This can be used for showing an editor for a processor that doesn't supply
  35750. its own custom editor.
  35751. @see AudioProcessor
  35752. */
  35753. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  35754. {
  35755. public:
  35756. GenericAudioProcessorEditor (AudioProcessor* owner);
  35757. ~GenericAudioProcessorEditor();
  35758. void paint (Graphics& g);
  35759. void resized();
  35760. private:
  35761. PropertyPanel panel;
  35762. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GenericAudioProcessorEditor);
  35763. };
  35764. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35765. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  35766. #endif
  35767. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  35768. /*** Start of inlined file: juce_Sampler.h ***/
  35769. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  35770. #define __JUCE_SAMPLER_JUCEHEADER__
  35771. /*** Start of inlined file: juce_Synthesiser.h ***/
  35772. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  35773. #define __JUCE_SYNTHESISER_JUCEHEADER__
  35774. /**
  35775. Describes one of the sounds that a Synthesiser can play.
  35776. A synthesiser can contain one or more sounds, and a sound can choose which
  35777. midi notes and channels can trigger it.
  35778. The SynthesiserSound is a passive class that just describes what the sound is -
  35779. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  35780. more than one SynthesiserVoice to play the same sound at the same time.
  35781. @see Synthesiser, SynthesiserVoice
  35782. */
  35783. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  35784. {
  35785. protected:
  35786. SynthesiserSound();
  35787. public:
  35788. /** Destructor. */
  35789. virtual ~SynthesiserSound();
  35790. /** Returns true if this sound should be played when a given midi note is pressed.
  35791. The Synthesiser will use this information when deciding which sounds to trigger
  35792. for a given note.
  35793. */
  35794. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  35795. /** Returns true if the sound should be triggered by midi events on a given channel.
  35796. The Synthesiser will use this information when deciding which sounds to trigger
  35797. for a given note.
  35798. */
  35799. virtual bool appliesToChannel (const int midiChannel) = 0;
  35800. /**
  35801. */
  35802. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  35803. private:
  35804. JUCE_LEAK_DETECTOR (SynthesiserSound);
  35805. };
  35806. /**
  35807. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  35808. A voice plays a single sound at a time, and a synthesiser holds an array of
  35809. voices so that it can play polyphonically.
  35810. @see Synthesiser, SynthesiserSound
  35811. */
  35812. class JUCE_API SynthesiserVoice
  35813. {
  35814. public:
  35815. /** Creates a voice. */
  35816. SynthesiserVoice();
  35817. /** Destructor. */
  35818. virtual ~SynthesiserVoice();
  35819. /** Returns the midi note that this voice is currently playing.
  35820. Returns a value less than 0 if no note is playing.
  35821. */
  35822. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  35823. /** Returns the sound that this voice is currently playing.
  35824. Returns 0 if it's not playing.
  35825. */
  35826. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  35827. /** Must return true if this voice object is capable of playing the given sound.
  35828. If there are different classes of sound, and different classes of voice, a voice can
  35829. choose which ones it wants to take on.
  35830. A typical implementation of this method may just return true if there's only one type
  35831. of voice and sound, or it might check the type of the sound object passed-in and
  35832. see if it's one that it understands.
  35833. */
  35834. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  35835. /** Called to start a new note.
  35836. This will be called during the rendering callback, so must be fast and thread-safe.
  35837. */
  35838. virtual void startNote (const int midiNoteNumber,
  35839. const float velocity,
  35840. SynthesiserSound* sound,
  35841. const int currentPitchWheelPosition) = 0;
  35842. /** Called to stop a note.
  35843. This will be called during the rendering callback, so must be fast and thread-safe.
  35844. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  35845. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  35846. and allow the synth to reassign it another sound.
  35847. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  35848. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  35849. finishes playing (during the rendering callback), it must make sure that it calls
  35850. clearCurrentNote().
  35851. */
  35852. virtual void stopNote (const bool allowTailOff) = 0;
  35853. /** Called to let the voice know that the pitch wheel has been moved.
  35854. This will be called during the rendering callback, so must be fast and thread-safe.
  35855. */
  35856. virtual void pitchWheelMoved (const int newValue) = 0;
  35857. /** Called to let the voice know that a midi controller has been moved.
  35858. This will be called during the rendering callback, so must be fast and thread-safe.
  35859. */
  35860. virtual void controllerMoved (const int controllerNumber,
  35861. const int newValue) = 0;
  35862. /** Renders the next block of data for this voice.
  35863. The output audio data must be added to the current contents of the buffer provided.
  35864. Only the region of the buffer between startSample and (startSample + numSamples)
  35865. should be altered by this method.
  35866. If the voice is currently silent, it should just return without doing anything.
  35867. If the sound that the voice is playing finishes during the course of this rendered
  35868. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  35869. The size of the blocks that are rendered can change each time it is called, and may
  35870. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  35871. the voice's methods will be called to tell it about note and controller events.
  35872. */
  35873. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  35874. int startSample,
  35875. int numSamples) = 0;
  35876. /** Returns true if the voice is currently playing a sound which is mapped to the given
  35877. midi channel.
  35878. If it's not currently playing, this will return false.
  35879. */
  35880. bool isPlayingChannel (int midiChannel) const;
  35881. /** Changes the voice's reference sample rate.
  35882. The rate is set so that subclasses know the output rate and can set their pitch
  35883. accordingly.
  35884. This method is called by the synth, and subclasses can access the current rate with
  35885. the currentSampleRate member.
  35886. */
  35887. void setCurrentPlaybackSampleRate (double newRate);
  35888. protected:
  35889. /** Returns the current target sample rate at which rendering is being done.
  35890. This is available for subclasses so they can pitch things correctly.
  35891. */
  35892. double getSampleRate() const { return currentSampleRate; }
  35893. /** Resets the state of this voice after a sound has finished playing.
  35894. The subclass must call this when it finishes playing a note and becomes available
  35895. to play new ones.
  35896. It must either call it in the stopNote() method, or if the voice is tailing off,
  35897. then it should call it later during the renderNextBlock method, as soon as it
  35898. finishes its tail-off.
  35899. It can also be called at any time during the render callback if the sound happens
  35900. to have finished, e.g. if it's playing a sample and the sample finishes.
  35901. */
  35902. void clearCurrentNote();
  35903. private:
  35904. friend class Synthesiser;
  35905. double currentSampleRate;
  35906. int currentlyPlayingNote;
  35907. uint32 noteOnTime;
  35908. SynthesiserSound::Ptr currentlyPlayingSound;
  35909. JUCE_LEAK_DETECTOR (SynthesiserVoice);
  35910. };
  35911. /**
  35912. Base class for a musical device that can play sounds.
  35913. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  35914. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  35915. which can play back one of these sounds.
  35916. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  35917. set of sounds, and a set of voices it can use to play them. If you only give it
  35918. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  35919. have available.
  35920. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  35921. events that go in will be scanned for note on/off messages, and these are used to
  35922. start and stop the voices playing the appropriate sounds.
  35923. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  35924. noteOff() and other controller methods.
  35925. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  35926. what the target playback rate is. This value is passed on to the voices so that
  35927. they can pitch their output correctly.
  35928. */
  35929. class JUCE_API Synthesiser
  35930. {
  35931. public:
  35932. /** Creates a new synthesiser.
  35933. You'll need to add some sounds and voices before it'll make any sound..
  35934. */
  35935. Synthesiser();
  35936. /** Destructor. */
  35937. virtual ~Synthesiser();
  35938. /** Deletes all voices. */
  35939. void clearVoices();
  35940. /** Returns the number of voices that have been added. */
  35941. int getNumVoices() const { return voices.size(); }
  35942. /** Returns one of the voices that have been added. */
  35943. SynthesiserVoice* getVoice (int index) const;
  35944. /** Adds a new voice to the synth.
  35945. All the voices should be the same class of object and are treated equally.
  35946. The object passed in will be managed by the synthesiser, which will delete
  35947. it later on when no longer needed. The caller should not retain a pointer to the
  35948. voice.
  35949. */
  35950. void addVoice (SynthesiserVoice* newVoice);
  35951. /** Deletes one of the voices. */
  35952. void removeVoice (int index);
  35953. /** Deletes all sounds. */
  35954. void clearSounds();
  35955. /** Returns the number of sounds that have been added to the synth. */
  35956. int getNumSounds() const { return sounds.size(); }
  35957. /** Returns one of the sounds. */
  35958. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  35959. /** Adds a new sound to the synthesiser.
  35960. The object passed in is reference counted, so will be deleted when it is removed
  35961. from the synthesiser, and when no voices are still using it.
  35962. */
  35963. void addSound (const SynthesiserSound::Ptr& newSound);
  35964. /** Removes and deletes one of the sounds. */
  35965. void removeSound (int index);
  35966. /** If set to true, then the synth will try to take over an existing voice if
  35967. it runs out and needs to play another note.
  35968. The value of this boolean is passed into findFreeVoice(), so the result will
  35969. depend on the implementation of this method.
  35970. */
  35971. void setNoteStealingEnabled (bool shouldStealNotes);
  35972. /** Returns true if note-stealing is enabled.
  35973. @see setNoteStealingEnabled
  35974. */
  35975. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  35976. /** Triggers a note-on event.
  35977. The default method here will find all the sounds that want to be triggered by
  35978. this note/channel. For each sound, it'll try to find a free voice, and use the
  35979. voice to start playing the sound.
  35980. Subclasses might want to override this if they need a more complex algorithm.
  35981. This method will be called automatically according to the midi data passed into
  35982. renderNextBlock(), but may be called explicitly too.
  35983. */
  35984. virtual void noteOn (int midiChannel,
  35985. int midiNoteNumber,
  35986. float velocity);
  35987. /** Triggers a note-off event.
  35988. This will turn off any voices that are playing a sound for the given note/channel.
  35989. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  35990. (if they can do). If this is false, the notes will all be cut off immediately.
  35991. This method will be called automatically according to the midi data passed into
  35992. renderNextBlock(), but may be called explicitly too.
  35993. */
  35994. virtual void noteOff (int midiChannel,
  35995. int midiNoteNumber,
  35996. bool allowTailOff);
  35997. /** Turns off all notes.
  35998. This will turn off any voices that are playing a sound on the given midi channel.
  35999. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  36000. which channel they're playing.
  36001. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  36002. (if they can do). If this is false, the notes will all be cut off immediately.
  36003. This method will be called automatically according to the midi data passed into
  36004. renderNextBlock(), but may be called explicitly too.
  36005. */
  36006. virtual void allNotesOff (int midiChannel,
  36007. bool allowTailOff);
  36008. /** Sends a pitch-wheel message.
  36009. This will send a pitch-wheel message to any voices that are playing sounds on
  36010. the given midi channel.
  36011. This method will be called automatically according to the midi data passed into
  36012. renderNextBlock(), but may be called explicitly too.
  36013. @param midiChannel the midi channel for the event
  36014. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  36015. */
  36016. virtual void handlePitchWheel (int midiChannel,
  36017. int wheelValue);
  36018. /** Sends a midi controller message.
  36019. This will send a midi controller message to any voices that are playing sounds on
  36020. the given midi channel.
  36021. This method will be called automatically according to the midi data passed into
  36022. renderNextBlock(), but may be called explicitly too.
  36023. @param midiChannel the midi channel for the event
  36024. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  36025. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  36026. */
  36027. virtual void handleController (int midiChannel,
  36028. int controllerNumber,
  36029. int controllerValue);
  36030. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  36031. render.
  36032. This value is propagated to the voices so that they can use it to render the correct
  36033. pitches.
  36034. */
  36035. void setCurrentPlaybackSampleRate (double sampleRate);
  36036. /** Creates the next block of audio output.
  36037. This will process the next numSamples of data from all the voices, and add that output
  36038. to the audio block supplied, starting from the offset specified. Note that the
  36039. data will be added to the current contents of the buffer, so you should clear it
  36040. before calling this method if necessary.
  36041. The midi events in the inputMidi buffer are parsed for note and controller events,
  36042. and these are used to trigger the voices. Note that the startSample offset applies
  36043. both to the audio output buffer and the midi input buffer, so any midi events
  36044. with timestamps outside the specified region will be ignored.
  36045. */
  36046. void renderNextBlock (AudioSampleBuffer& outputAudio,
  36047. const MidiBuffer& inputMidi,
  36048. int startSample,
  36049. int numSamples);
  36050. protected:
  36051. /** This is used to control access to the rendering callback and the note trigger methods. */
  36052. CriticalSection lock;
  36053. OwnedArray <SynthesiserVoice> voices;
  36054. ReferenceCountedArray <SynthesiserSound> sounds;
  36055. /** The last pitch-wheel values for each midi channel. */
  36056. int lastPitchWheelValues [16];
  36057. /** Searches through the voices to find one that's not currently playing, and which
  36058. can play the given sound.
  36059. Returns 0 if all voices are busy and stealing isn't enabled.
  36060. This can be overridden to implement custom voice-stealing algorithms.
  36061. */
  36062. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  36063. const bool stealIfNoneAvailable) const;
  36064. /** Starts a specified voice playing a particular sound.
  36065. You'll probably never need to call this, it's used internally by noteOn(), but
  36066. may be needed by subclasses for custom behaviours.
  36067. */
  36068. void startVoice (SynthesiserVoice* voice,
  36069. SynthesiserSound* sound,
  36070. int midiChannel,
  36071. int midiNoteNumber,
  36072. float velocity);
  36073. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  36074. // Temporary method here to cause a compiler error - note the new parameters for this method.
  36075. int findFreeVoice (const bool) const { return 0; }
  36076. #endif
  36077. private:
  36078. double sampleRate;
  36079. uint32 lastNoteOnCounter;
  36080. bool shouldStealNotes;
  36081. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Synthesiser);
  36082. };
  36083. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  36084. /*** End of inlined file: juce_Synthesiser.h ***/
  36085. /**
  36086. A subclass of SynthesiserSound that represents a sampled audio clip.
  36087. This is a pretty basic sampler, and just attempts to load the whole audio stream
  36088. into memory.
  36089. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36090. give it some SampledSound objects to play.
  36091. @see SamplerVoice, Synthesiser, SynthesiserSound
  36092. */
  36093. class JUCE_API SamplerSound : public SynthesiserSound
  36094. {
  36095. public:
  36096. /** Creates a sampled sound from an audio reader.
  36097. This will attempt to load the audio from the source into memory and store
  36098. it in this object.
  36099. @param name a name for the sample
  36100. @param source the audio to load. This object can be safely deleted by the
  36101. caller after this constructor returns
  36102. @param midiNotes the set of midi keys that this sound should be played on. This
  36103. is used by the SynthesiserSound::appliesToNote() method
  36104. @param midiNoteForNormalPitch the midi note at which the sample should be played
  36105. with its natural rate. All other notes will be pitched
  36106. up or down relative to this one
  36107. @param attackTimeSecs the attack (fade-in) time, in seconds
  36108. @param releaseTimeSecs the decay (fade-out) time, in seconds
  36109. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  36110. source, in seconds
  36111. */
  36112. SamplerSound (const String& name,
  36113. AudioFormatReader& source,
  36114. const BigInteger& midiNotes,
  36115. int midiNoteForNormalPitch,
  36116. double attackTimeSecs,
  36117. double releaseTimeSecs,
  36118. double maxSampleLengthSeconds);
  36119. /** Destructor. */
  36120. ~SamplerSound();
  36121. /** Returns the sample's name */
  36122. const String& getName() const { return name; }
  36123. /** Returns the audio sample data.
  36124. This could be 0 if there was a problem loading it.
  36125. */
  36126. AudioSampleBuffer* getAudioData() const { return data; }
  36127. bool appliesToNote (const int midiNoteNumber);
  36128. bool appliesToChannel (const int midiChannel);
  36129. private:
  36130. friend class SamplerVoice;
  36131. String name;
  36132. ScopedPointer <AudioSampleBuffer> data;
  36133. double sourceSampleRate;
  36134. BigInteger midiNotes;
  36135. int length, attackSamples, releaseSamples;
  36136. int midiRootNote;
  36137. JUCE_LEAK_DETECTOR (SamplerSound);
  36138. };
  36139. /**
  36140. A subclass of SynthesiserVoice that can play a SamplerSound.
  36141. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36142. give it some SampledSound objects to play.
  36143. @see SamplerSound, Synthesiser, SynthesiserVoice
  36144. */
  36145. class JUCE_API SamplerVoice : public SynthesiserVoice
  36146. {
  36147. public:
  36148. /** Creates a SamplerVoice.
  36149. */
  36150. SamplerVoice();
  36151. /** Destructor. */
  36152. ~SamplerVoice();
  36153. bool canPlaySound (SynthesiserSound* sound);
  36154. void startNote (const int midiNoteNumber,
  36155. const float velocity,
  36156. SynthesiserSound* sound,
  36157. const int currentPitchWheelPosition);
  36158. void stopNote (const bool allowTailOff);
  36159. void pitchWheelMoved (const int newValue);
  36160. void controllerMoved (const int controllerNumber,
  36161. const int newValue);
  36162. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  36163. private:
  36164. double pitchRatio;
  36165. double sourceSamplePosition;
  36166. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  36167. bool isInAttack, isInRelease;
  36168. JUCE_LEAK_DETECTOR (SamplerVoice);
  36169. };
  36170. #endif // __JUCE_SAMPLER_JUCEHEADER__
  36171. /*** End of inlined file: juce_Sampler.h ***/
  36172. #endif
  36173. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  36174. #endif
  36175. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36176. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  36177. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36178. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36179. /** Manages a list of ActionListeners, and can send them messages.
  36180. To quickly add methods to your class that can add/remove action
  36181. listeners and broadcast to them, you can derive from this.
  36182. @see ActionListener, ChangeListener
  36183. */
  36184. class JUCE_API ActionBroadcaster
  36185. {
  36186. public:
  36187. /** Creates an ActionBroadcaster. */
  36188. ActionBroadcaster();
  36189. /** Destructor. */
  36190. virtual ~ActionBroadcaster();
  36191. /** Adds a listener to the list.
  36192. Trying to add a listener that's already on the list will have no effect.
  36193. */
  36194. void addActionListener (ActionListener* listener);
  36195. /** Removes a listener from the list.
  36196. If the listener isn't on the list, this won't have any effect.
  36197. */
  36198. void removeActionListener (ActionListener* listener);
  36199. /** Removes all listeners from the list. */
  36200. void removeAllActionListeners();
  36201. /** Broadcasts a message to all the registered listeners.
  36202. @see ActionListener::actionListenerCallback
  36203. */
  36204. void sendActionMessage (const String& message) const;
  36205. private:
  36206. class CallbackReceiver : public MessageListener
  36207. {
  36208. public:
  36209. CallbackReceiver();
  36210. void handleMessage (const Message&);
  36211. ActionBroadcaster* owner;
  36212. };
  36213. friend class CallbackReceiver;
  36214. CallbackReceiver callback;
  36215. SortedSet <ActionListener*> actionListeners;
  36216. CriticalSection actionListenerLock;
  36217. JUCE_DECLARE_NON_COPYABLE (ActionBroadcaster);
  36218. };
  36219. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36220. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  36221. #endif
  36222. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  36223. #endif
  36224. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  36225. #endif
  36226. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  36227. #endif
  36228. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  36229. #endif
  36230. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  36231. #endif
  36232. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36233. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  36234. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36235. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36236. class InterprocessConnectionServer;
  36237. /**
  36238. Manages a simple two-way messaging connection to another process, using either
  36239. a socket or a named pipe as the transport medium.
  36240. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  36241. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  36242. and incoming messages will result in a callback via the messageReceived()
  36243. method.
  36244. To open a pipe and wait for another client to connect to it, use the createPipe()
  36245. method.
  36246. To act as a socket server and create connections for one or more client, see the
  36247. InterprocessConnectionServer class.
  36248. @see InterprocessConnectionServer, Socket, NamedPipe
  36249. */
  36250. class JUCE_API InterprocessConnection : public Thread,
  36251. private MessageListener
  36252. {
  36253. public:
  36254. /** Creates a connection.
  36255. Connections are created manually, connecting them with the connectToSocket()
  36256. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  36257. when a client wants to connect.
  36258. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  36259. connectionLost() and messageReceived() methods will
  36260. always be made using the message thread; if false,
  36261. these will be called immediately on the connection's
  36262. own thread.
  36263. @param magicMessageHeaderNumber a magic number to use in the header to check the
  36264. validity of the data blocks being sent and received. This
  36265. can be any number, but the sender and receiver must obviously
  36266. use matching values or they won't recognise each other.
  36267. */
  36268. InterprocessConnection (bool callbacksOnMessageThread = true,
  36269. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  36270. /** Destructor. */
  36271. ~InterprocessConnection();
  36272. /** Tries to connect this object to a socket.
  36273. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  36274. object waiting to receive client connections on this port number.
  36275. @param hostName the host computer, either a network address or name
  36276. @param portNumber the socket port number to try to connect to
  36277. @param timeOutMillisecs how long to keep trying before giving up
  36278. @returns true if the connection is established successfully
  36279. @see Socket
  36280. */
  36281. bool connectToSocket (const String& hostName,
  36282. int portNumber,
  36283. int timeOutMillisecs);
  36284. /** Tries to connect the object to an existing named pipe.
  36285. For this to work, another process on the same computer must already have opened
  36286. an InterprocessConnection object and used createPipe() to create a pipe for this
  36287. to connect to.
  36288. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36289. @returns true if it connects successfully.
  36290. @see createPipe, NamedPipe
  36291. */
  36292. bool connectToPipe (const String& pipeName,
  36293. int pipeReceiveMessageTimeoutMs = -1);
  36294. /** Tries to create a new pipe for other processes to connect to.
  36295. This creates a pipe with the given name, so that other processes can use
  36296. connectToPipe() to connect to the other end.
  36297. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36298. If another process is already using this pipe, this will fail and return false.
  36299. */
  36300. bool createPipe (const String& pipeName,
  36301. int pipeReceiveMessageTimeoutMs = -1);
  36302. /** Disconnects and closes any currently-open sockets or pipes. */
  36303. void disconnect();
  36304. /** True if a socket or pipe is currently active. */
  36305. bool isConnected() const;
  36306. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  36307. StreamingSocket* getSocket() const throw() { return socket; }
  36308. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  36309. NamedPipe* getPipe() const throw() { return pipe; }
  36310. /** Returns the name of the machine at the other end of this connection.
  36311. This will return an empty string if the other machine isn't known for
  36312. some reason.
  36313. */
  36314. const String getConnectedHostName() const;
  36315. /** Tries to send a message to the other end of this connection.
  36316. This will fail if it's not connected, or if there's some kind of write error. If
  36317. it succeeds, the connection object at the other end will receive the message by
  36318. a callback to its messageReceived() method.
  36319. @see messageReceived
  36320. */
  36321. bool sendMessage (const MemoryBlock& message);
  36322. /** Called when the connection is first connected.
  36323. If the connection was created with the callbacksOnMessageThread flag set, then
  36324. this will be called on the message thread; otherwise it will be called on a server
  36325. thread.
  36326. */
  36327. virtual void connectionMade() = 0;
  36328. /** Called when the connection is broken.
  36329. If the connection was created with the callbacksOnMessageThread flag set, then
  36330. this will be called on the message thread; otherwise it will be called on a server
  36331. thread.
  36332. */
  36333. virtual void connectionLost() = 0;
  36334. /** Called when a message arrives.
  36335. When the object at the other end of this connection sends us a message with sendMessage(),
  36336. this callback is used to deliver it to us.
  36337. If the connection was created with the callbacksOnMessageThread flag set, then
  36338. this will be called on the message thread; otherwise it will be called on a server
  36339. thread.
  36340. @see sendMessage
  36341. */
  36342. virtual void messageReceived (const MemoryBlock& message) = 0;
  36343. private:
  36344. CriticalSection pipeAndSocketLock;
  36345. ScopedPointer <StreamingSocket> socket;
  36346. ScopedPointer <NamedPipe> pipe;
  36347. bool callbackConnectionState;
  36348. const bool useMessageThread;
  36349. const uint32 magicMessageHeader;
  36350. int pipeReceiveMessageTimeout;
  36351. friend class InterprocessConnectionServer;
  36352. void initialiseWithSocket (StreamingSocket* socket_);
  36353. void initialiseWithPipe (NamedPipe* pipe_);
  36354. void handleMessage (const Message& message);
  36355. void connectionMadeInt();
  36356. void connectionLostInt();
  36357. void deliverDataInt (const MemoryBlock& data);
  36358. bool readNextMessageInt();
  36359. void run();
  36360. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnection);
  36361. };
  36362. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36363. /*** End of inlined file: juce_InterprocessConnection.h ***/
  36364. #endif
  36365. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36366. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  36367. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36368. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36369. /**
  36370. An object that waits for client sockets to connect to a port on this host, and
  36371. creates InterprocessConnection objects for each one.
  36372. To use this, create a class derived from it which implements the createConnectionObject()
  36373. method, so that it creates suitable connection objects for each client that tries
  36374. to connect.
  36375. @see InterprocessConnection
  36376. */
  36377. class JUCE_API InterprocessConnectionServer : private Thread
  36378. {
  36379. public:
  36380. /** Creates an uninitialised server object.
  36381. */
  36382. InterprocessConnectionServer();
  36383. /** Destructor. */
  36384. ~InterprocessConnectionServer();
  36385. /** Starts an internal thread which listens on the given port number.
  36386. While this is running, in another process tries to connect with the
  36387. InterprocessConnection::connectToSocket() method, this object will call
  36388. createConnectionObject() to create a connection to that client.
  36389. Use stop() to stop the thread running.
  36390. @see createConnectionObject, stop
  36391. */
  36392. bool beginWaitingForSocket (int portNumber);
  36393. /** Terminates the listener thread, if it's active.
  36394. @see beginWaitingForSocket
  36395. */
  36396. void stop();
  36397. protected:
  36398. /** Creates a suitable connection object for a client process that wants to
  36399. connect to this one.
  36400. This will be called by the listener thread when a client process tries
  36401. to connect, and must return a new InterprocessConnection object that will
  36402. then run as this end of the connection.
  36403. @see InterprocessConnection
  36404. */
  36405. virtual InterprocessConnection* createConnectionObject() = 0;
  36406. private:
  36407. ScopedPointer <StreamingSocket> socket;
  36408. void run();
  36409. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnectionServer);
  36410. };
  36411. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36412. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  36413. #endif
  36414. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  36415. #endif
  36416. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  36417. #endif
  36418. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  36419. #endif
  36420. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36421. /*** Start of inlined file: juce_MessageManager.h ***/
  36422. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36423. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36424. class Component;
  36425. class MessageManagerLock;
  36426. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  36427. */
  36428. typedef void* (MessageCallbackFunction) (void* userData);
  36429. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  36430. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  36431. */
  36432. class JUCE_API MessageManager
  36433. {
  36434. public:
  36435. /** Returns the global instance of the MessageManager. */
  36436. static MessageManager* getInstance() throw();
  36437. /** Runs the event dispatch loop until a stop message is posted.
  36438. This method is only intended to be run by the application's startup routine,
  36439. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  36440. @see stopDispatchLoop
  36441. */
  36442. void runDispatchLoop();
  36443. /** Sends a signal that the dispatch loop should terminate.
  36444. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  36445. will be interrupted and will return.
  36446. @see runDispatchLoop
  36447. */
  36448. void stopDispatchLoop();
  36449. /** Returns true if the stopDispatchLoop() method has been called.
  36450. */
  36451. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  36452. #if JUCE_MODAL_LOOPS_PERMITTED
  36453. /** Synchronously dispatches messages until a given time has elapsed.
  36454. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  36455. otherwise returns true.
  36456. */
  36457. bool runDispatchLoopUntil (int millisecondsToRunFor);
  36458. #endif
  36459. /** Calls a function using the message-thread.
  36460. This can be used by any thread to cause this function to be called-back
  36461. by the message thread. If it's the message-thread that's calling this method,
  36462. then the function will just be called; if another thread is calling, a message
  36463. will be posted to the queue, and this method will block until that message
  36464. is delivered, the function is called, and the result is returned.
  36465. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  36466. thread has a critical section locked, which an unrelated message callback then tries to lock
  36467. before the message thread gets round to processing this callback.
  36468. @param callback the function to call - its signature must be @code
  36469. void* myCallbackFunction (void*) @endcode
  36470. @param userData a user-defined pointer that will be passed to the function that gets called
  36471. @returns the value that the callback function returns.
  36472. @see MessageManagerLock
  36473. */
  36474. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  36475. void* userData);
  36476. /** Returns true if the caller-thread is the message thread. */
  36477. bool isThisTheMessageThread() const throw();
  36478. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  36479. (Best to ignore this method unless you really know what you're doing..)
  36480. @see getCurrentMessageThread
  36481. */
  36482. void setCurrentThreadAsMessageThread();
  36483. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  36484. (Best to ignore this method unless you really know what you're doing..)
  36485. @see setCurrentMessageThread
  36486. */
  36487. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  36488. /** Returns true if the caller thread has currenltly got the message manager locked.
  36489. see the MessageManagerLock class for more info about this.
  36490. This will be true if the caller is the message thread, because that automatically
  36491. gains a lock while a message is being dispatched.
  36492. */
  36493. bool currentThreadHasLockedMessageManager() const throw();
  36494. /** Sends a message to all other JUCE applications that are running.
  36495. @param messageText the string that will be passed to the actionListenerCallback()
  36496. method of the broadcast listeners in the other app.
  36497. @see registerBroadcastListener, ActionListener
  36498. */
  36499. static void broadcastMessage (const String& messageText);
  36500. /** Registers a listener to get told about broadcast messages.
  36501. The actionListenerCallback() callback's string parameter
  36502. is the message passed into broadcastMessage().
  36503. @see broadcastMessage
  36504. */
  36505. void registerBroadcastListener (ActionListener* listener);
  36506. /** Deregisters a broadcast listener. */
  36507. void deregisterBroadcastListener (ActionListener* listener);
  36508. /** @internal */
  36509. void deliverMessage (Message*);
  36510. /** @internal */
  36511. void deliverBroadcastMessage (const String&);
  36512. /** @internal */
  36513. ~MessageManager() throw();
  36514. private:
  36515. MessageManager() throw();
  36516. friend class MessageListener;
  36517. friend class ChangeBroadcaster;
  36518. friend class ActionBroadcaster;
  36519. friend class CallbackMessage;
  36520. static MessageManager* instance;
  36521. SortedSet <const MessageListener*> messageListeners;
  36522. ScopedPointer <ActionBroadcaster> broadcaster;
  36523. friend class JUCEApplication;
  36524. bool quitMessagePosted, quitMessageReceived;
  36525. Thread::ThreadID messageThreadId;
  36526. friend class MessageManagerLock;
  36527. Thread::ThreadID volatile threadWithLock;
  36528. CriticalSection lockingLock;
  36529. void postMessageToQueue (Message* message);
  36530. static bool postMessageToSystemQueue (Message*);
  36531. static void* exitModalLoopCallback (void*);
  36532. static void doPlatformSpecificInitialisation();
  36533. static void doPlatformSpecificShutdown();
  36534. static bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  36535. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager);
  36536. };
  36537. /** Used to make sure that the calling thread has exclusive access to the message loop.
  36538. Because it's not thread-safe to call any of the Component or other UI classes
  36539. from threads other than the message thread, one of these objects can be used to
  36540. lock the message loop and allow this to be done. The message thread will be
  36541. suspended for the lifetime of the MessageManagerLock object, so create one on
  36542. the stack like this: @code
  36543. void MyThread::run()
  36544. {
  36545. someData = 1234;
  36546. const MessageManagerLock mmLock;
  36547. // the event loop will now be locked so it's safe to make a few calls..
  36548. myComponent->setBounds (newBounds);
  36549. myComponent->repaint();
  36550. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  36551. }
  36552. @endcode
  36553. Obviously be careful not to create one of these and leave it lying around, or
  36554. your app will grind to a halt!
  36555. Another caveat is that using this in conjunction with other CriticalSections
  36556. can create lots of interesting ways of producing a deadlock! In particular, if
  36557. your message thread calls stopThread() for a thread that uses these locks,
  36558. you'll get an (occasional) deadlock..
  36559. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  36560. */
  36561. class JUCE_API MessageManagerLock
  36562. {
  36563. public:
  36564. /** Tries to acquire a lock on the message manager.
  36565. The constructor attempts to gain a lock on the message loop, and the lock will be
  36566. kept for the lifetime of this object.
  36567. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  36568. this method will keep checking whether the thread has been given the
  36569. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  36570. without gaining the lock. If you pass a thread, you must check whether the lock was
  36571. successful by calling lockWasGained(). If this is false, your thread is being told to
  36572. die, so you should take evasive action.
  36573. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  36574. careful when doing this, because it's very easy to deadlock if your message thread
  36575. attempts to call stopThread() on a thread just as that thread attempts to get the
  36576. message lock.
  36577. If the calling thread already has the lock, nothing will be done, so it's safe and
  36578. quick to use these locks recursively.
  36579. E.g.
  36580. @code
  36581. void run()
  36582. {
  36583. ...
  36584. while (! threadShouldExit())
  36585. {
  36586. MessageManagerLock mml (Thread::getCurrentThread());
  36587. if (! mml.lockWasGained())
  36588. return; // another thread is trying to kill us!
  36589. ..do some locked stuff here..
  36590. }
  36591. ..and now the MM is now unlocked..
  36592. }
  36593. @endcode
  36594. */
  36595. MessageManagerLock (Thread* threadToCheckForExitSignal = 0);
  36596. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  36597. instead of a thread.
  36598. See the MessageManagerLock (Thread*) constructor for details on how this works.
  36599. */
  36600. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  36601. /** Releases the current thread's lock on the message manager.
  36602. Make sure this object is created and deleted by the same thread,
  36603. otherwise there are no guarantees what will happen!
  36604. */
  36605. ~MessageManagerLock() throw();
  36606. /** Returns true if the lock was successfully acquired.
  36607. (See the constructor that takes a Thread for more info).
  36608. */
  36609. bool lockWasGained() const throw() { return locked; }
  36610. private:
  36611. class BlockingMessage;
  36612. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  36613. ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  36614. bool locked;
  36615. void init (Thread* thread, ThreadPoolJob* job);
  36616. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock);
  36617. };
  36618. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36619. /*** End of inlined file: juce_MessageManager.h ***/
  36620. #endif
  36621. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  36622. /*** Start of inlined file: juce_MultiTimer.h ***/
  36623. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  36624. #define __JUCE_MULTITIMER_JUCEHEADER__
  36625. /**
  36626. A type of timer class that can run multiple timers with different frequencies,
  36627. all of which share a single callback.
  36628. This class is very similar to the Timer class, but allows you run multiple
  36629. separate timers, where each one has a unique ID number. The methods in this
  36630. class are exactly equivalent to those in Timer, but with the addition of
  36631. this ID number.
  36632. To use it, you need to create a subclass of MultiTimer, implementing the
  36633. timerCallback() method. Then you can start timers with startTimer(), and
  36634. each time the callback is triggered, it passes in the ID of the timer that
  36635. caused it.
  36636. @see Timer
  36637. */
  36638. class JUCE_API MultiTimer
  36639. {
  36640. protected:
  36641. /** Creates a MultiTimer.
  36642. When created, no timers are running, so use startTimer() to start things off.
  36643. */
  36644. MultiTimer() throw();
  36645. /** Creates a copy of another timer.
  36646. Note that this timer will not contain any running timers, even if the one you're
  36647. copying from was running.
  36648. */
  36649. MultiTimer (const MultiTimer& other) throw();
  36650. public:
  36651. /** Destructor. */
  36652. virtual ~MultiTimer();
  36653. /** The user-defined callback routine that actually gets called by each of the
  36654. timers that are running.
  36655. It's perfectly ok to call startTimer() or stopTimer() from within this
  36656. callback to change the subsequent intervals.
  36657. */
  36658. virtual void timerCallback (int timerId) = 0;
  36659. /** Starts a timer and sets the length of interval required.
  36660. If the timer is already started, this will reset it, so the
  36661. time between calling this method and the next timer callback
  36662. will not be less than the interval length passed in.
  36663. @param timerId a unique Id number that identifies the timer to
  36664. start. This is the id that will be passed back
  36665. to the timerCallback() method when this timer is
  36666. triggered
  36667. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  36668. rounded up to 1)
  36669. */
  36670. void startTimer (int timerId, int intervalInMilliseconds) throw();
  36671. /** Stops a timer.
  36672. If a timer has been started with the given ID number, it will be cancelled.
  36673. No more callbacks will be made for the specified timer after this method returns.
  36674. If this is called from a different thread, any callbacks that may
  36675. be currently executing may be allowed to finish before the method
  36676. returns.
  36677. */
  36678. void stopTimer (int timerId) throw();
  36679. /** Checks whether a timer has been started for a specified ID.
  36680. @returns true if a timer with the given ID is running.
  36681. */
  36682. bool isTimerRunning (int timerId) const throw();
  36683. /** Returns the interval for a specified timer ID.
  36684. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  36685. is running for the ID number specified.
  36686. */
  36687. int getTimerInterval (int timerId) const throw();
  36688. private:
  36689. class MultiTimerCallback;
  36690. CriticalSection timerListLock;
  36691. OwnedArray <MultiTimerCallback> timers;
  36692. MultiTimer& operator= (const MultiTimer&);
  36693. };
  36694. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  36695. /*** End of inlined file: juce_MultiTimer.h ***/
  36696. #endif
  36697. #ifndef __JUCE_TIMER_JUCEHEADER__
  36698. #endif
  36699. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  36700. /*** Start of inlined file: juce_ArrowButton.h ***/
  36701. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  36702. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  36703. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  36704. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36705. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36706. /**
  36707. An effect filter that adds a drop-shadow behind the image's content.
  36708. (This will only work on images/components that aren't opaque, of course).
  36709. When added to a component, this effect will draw a soft-edged
  36710. shadow based on what gets drawn inside it. The shadow will also
  36711. be applied to the component's children.
  36712. For speed, this doesn't use a proper gaussian blur, but cheats by
  36713. using a simple bilinear filter. If you need a really high-quality
  36714. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  36715. @see Component::setComponentEffect
  36716. */
  36717. class JUCE_API DropShadowEffect : public ImageEffectFilter
  36718. {
  36719. public:
  36720. /** Creates a default drop-shadow effect.
  36721. To customise the shadow's appearance, use the setShadowProperties()
  36722. method.
  36723. */
  36724. DropShadowEffect();
  36725. /** Destructor. */
  36726. ~DropShadowEffect();
  36727. /** Sets up parameters affecting the shadow's appearance.
  36728. @param newRadius the (approximate) radius of the blur used
  36729. @param newOpacity the opacity with which the shadow is rendered
  36730. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  36731. component's contents
  36732. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  36733. component's contents
  36734. */
  36735. void setShadowProperties (float newRadius,
  36736. float newOpacity,
  36737. int newShadowOffsetX,
  36738. int newShadowOffsetY);
  36739. /** @internal */
  36740. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  36741. private:
  36742. int offsetX, offsetY;
  36743. float radius, opacity;
  36744. JUCE_LEAK_DETECTOR (DropShadowEffect);
  36745. };
  36746. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36747. /*** End of inlined file: juce_DropShadowEffect.h ***/
  36748. /**
  36749. A button with an arrow in it.
  36750. @see Button
  36751. */
  36752. class JUCE_API ArrowButton : public Button
  36753. {
  36754. public:
  36755. /** Creates an ArrowButton.
  36756. @param buttonName the name to give the button
  36757. @param arrowDirection the direction the arrow should point in, where 0.0 is
  36758. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  36759. @param arrowColour the colour to use for the arrow
  36760. */
  36761. ArrowButton (const String& buttonName,
  36762. float arrowDirection,
  36763. const Colour& arrowColour);
  36764. /** Destructor. */
  36765. ~ArrowButton();
  36766. protected:
  36767. /** @internal */
  36768. void paintButton (Graphics& g,
  36769. bool isMouseOverButton,
  36770. bool isButtonDown);
  36771. /** @internal */
  36772. void buttonStateChanged();
  36773. private:
  36774. Colour colour;
  36775. DropShadowEffect shadow;
  36776. Path path;
  36777. int offset;
  36778. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ArrowButton);
  36779. };
  36780. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  36781. /*** End of inlined file: juce_ArrowButton.h ***/
  36782. #endif
  36783. #ifndef __JUCE_BUTTON_JUCEHEADER__
  36784. #endif
  36785. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36786. /*** Start of inlined file: juce_DrawableButton.h ***/
  36787. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36788. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36789. /*** Start of inlined file: juce_Drawable.h ***/
  36790. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  36791. #define __JUCE_DRAWABLE_JUCEHEADER__
  36792. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  36793. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36794. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36795. /**
  36796. Expresses a coordinate as a dynamically evaluated expression.
  36797. @see RelativePoint, RelativeRectangle
  36798. */
  36799. class JUCE_API RelativeCoordinate
  36800. {
  36801. public:
  36802. /** Creates a zero coordinate. */
  36803. RelativeCoordinate();
  36804. RelativeCoordinate (const Expression& expression);
  36805. RelativeCoordinate (const RelativeCoordinate& other);
  36806. RelativeCoordinate& operator= (const RelativeCoordinate& other);
  36807. /** Creates an absolute position from the parent origin on either the X or Y axis.
  36808. @param absoluteDistanceFromOrigin the distance from the origin
  36809. */
  36810. RelativeCoordinate (double absoluteDistanceFromOrigin);
  36811. /** Recreates a coordinate from a string description.
  36812. The string will be parsed by ExpressionParser::parse().
  36813. @param stringVersion the expression to use
  36814. @see toString
  36815. */
  36816. RelativeCoordinate (const String& stringVersion);
  36817. /** Destructor. */
  36818. ~RelativeCoordinate();
  36819. bool operator== (const RelativeCoordinate& other) const throw();
  36820. bool operator!= (const RelativeCoordinate& other) const throw();
  36821. /** Calculates the absolute position of this coordinate.
  36822. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  36823. be needed to calculate the result.
  36824. */
  36825. double resolve (const Expression::Scope* evaluationScope) const;
  36826. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  36827. This will recursively check any coordinates upon which this one depends.
  36828. */
  36829. bool references (const String& coordName, const Expression::Scope* evaluationScope) const;
  36830. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  36831. bool isRecursive (const Expression::Scope* evaluationScope) const;
  36832. /** Returns true if this coordinate depends on any other coordinates for its position. */
  36833. bool isDynamic() const;
  36834. /** Changes the value of this coord to make it resolve to the specified position.
  36835. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  36836. or relative position to whatever value is necessary to make its resultant position
  36837. match the position that is provided.
  36838. */
  36839. void moveToAbsolute (double absoluteTargetPosition, const Expression::Scope* evaluationScope);
  36840. /** Returns the expression that defines this coordinate. */
  36841. const Expression& getExpression() const { return term; }
  36842. /** Returns a string which represents this coordinate.
  36843. For details of the string syntax, see the constructor notes.
  36844. */
  36845. const String toString() const;
  36846. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  36847. As well as avoiding using string literals in your code, using these preset values
  36848. has the advantage that all instances of the same string will share the same, reference-counted
  36849. String object, so if you have thousands of points which all refer to the same
  36850. anchor points, this can save a significant amount of memory allocation.
  36851. */
  36852. struct Strings
  36853. {
  36854. static const String parent; /**< "parent" */
  36855. static const String left; /**< "left" */
  36856. static const String right; /**< "right" */
  36857. static const String top; /**< "top" */
  36858. static const String bottom; /**< "bottom" */
  36859. static const String x; /**< "x" */
  36860. static const String y; /**< "y" */
  36861. static const String width; /**< "width" */
  36862. static const String height; /**< "height" */
  36863. };
  36864. struct StandardStrings
  36865. {
  36866. enum Type
  36867. {
  36868. left, right, top, bottom,
  36869. x, y, width, height,
  36870. parent,
  36871. unknown
  36872. };
  36873. static Type getTypeOf (const String& s) throw();
  36874. };
  36875. private:
  36876. Expression term;
  36877. };
  36878. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36879. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  36880. /*** Start of inlined file: juce_RelativeCoordinatePositioner.h ***/
  36881. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  36882. #define __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  36883. /*** Start of inlined file: juce_RelativePoint.h ***/
  36884. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  36885. #define __JUCE_RELATIVEPOINT_JUCEHEADER__
  36886. /**
  36887. An X-Y position stored as a pair of RelativeCoordinate values.
  36888. @see RelativeCoordinate, RelativeRectangle
  36889. */
  36890. class JUCE_API RelativePoint
  36891. {
  36892. public:
  36893. /** Creates a point at the origin. */
  36894. RelativePoint();
  36895. /** Creates an absolute point, relative to the origin. */
  36896. RelativePoint (const Point<float>& absolutePoint);
  36897. /** Creates an absolute point, relative to the origin. */
  36898. RelativePoint (float absoluteX, float absoluteY);
  36899. /** Creates an absolute point from two coordinates. */
  36900. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  36901. /** Creates a point from a stringified representation.
  36902. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  36903. strings is explained in the RelativeCoordinate class.
  36904. @see toString
  36905. */
  36906. RelativePoint (const String& stringVersion);
  36907. bool operator== (const RelativePoint& other) const throw();
  36908. bool operator!= (const RelativePoint& other) const throw();
  36909. /** Calculates the absolute position of this point.
  36910. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  36911. be needed to calculate the result.
  36912. */
  36913. const Point<float> resolve (const Expression::Scope* evaluationContext) const;
  36914. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  36915. Calling this will leave any anchor points unchanged, but will set any absolute
  36916. or relative positions to whatever values are necessary to make the resultant position
  36917. match the position that is provided.
  36918. */
  36919. void moveToAbsolute (const Point<float>& newPos, const Expression::Scope* evaluationContext);
  36920. /** Returns a string which represents this point.
  36921. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  36922. coordinates, see the RelativeCoordinate constructor notes.
  36923. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  36924. */
  36925. const String toString() const;
  36926. /** Returns true if this point depends on any other coordinates for its position. */
  36927. bool isDynamic() const;
  36928. // The actual X and Y coords...
  36929. RelativeCoordinate x, y;
  36930. };
  36931. #endif // __JUCE_RELATIVEPOINT_JUCEHEADER__
  36932. /*** End of inlined file: juce_RelativePoint.h ***/
  36933. /*** Start of inlined file: juce_MarkerList.h ***/
  36934. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  36935. #define __JUCE_MARKERLIST_JUCEHEADER__
  36936. class Component;
  36937. /**
  36938. Holds a set of named marker points along a one-dimensional axis.
  36939. This class is used to store sets of X and Y marker points in components.
  36940. @see Component::getMarkers().
  36941. */
  36942. class JUCE_API MarkerList
  36943. {
  36944. public:
  36945. /** Creates an empty marker list. */
  36946. MarkerList();
  36947. /** Creates a copy of another marker list. */
  36948. MarkerList (const MarkerList& other);
  36949. /** Copies another marker list to this one. */
  36950. MarkerList& operator= (const MarkerList& other);
  36951. /** Destructor. */
  36952. ~MarkerList();
  36953. /** Represents a marker in a MarkerList. */
  36954. class JUCE_API Marker
  36955. {
  36956. public:
  36957. /** Creates a copy of another Marker. */
  36958. Marker (const Marker& other);
  36959. /** Creates a Marker with a given name and position. */
  36960. Marker (const String& name, const RelativeCoordinate& position);
  36961. /** The marker's name. */
  36962. String name;
  36963. /** The marker's position.
  36964. The expression used to define the coordinate may use the names of other
  36965. markers, so that markers can be linked in arbitrary ways, but be careful
  36966. not to create recursive loops of markers whose positions are based on each
  36967. other! It can also refer to "parent.right" and "parent.bottom" so that you
  36968. can set markers which are relative to the size of the component that contains
  36969. them.
  36970. To resolve the coordinate, you can use the MarkerList::getMarkerPosition() method.
  36971. */
  36972. RelativeCoordinate position;
  36973. /** Returns true if both the names and positions of these two markers match. */
  36974. bool operator== (const Marker&) const throw();
  36975. /** Returns true if either the name or position of these two markers differ. */
  36976. bool operator!= (const Marker&) const throw();
  36977. };
  36978. /** Returns the number of markers in the list. */
  36979. int getNumMarkers() const throw();
  36980. /** Returns one of the markers in the list, by its index. */
  36981. const Marker* getMarker (int index) const throw();
  36982. /** Returns a named marker, or 0 if no such name is found.
  36983. Note that name comparisons are case-sensitive.
  36984. */
  36985. const Marker* getMarker (const String& name) const throw();
  36986. /** Evaluates the given marker and returns its absolute position.
  36987. The parent component must be supplied in case the marker's expression refers to
  36988. the size of its parent component.
  36989. */
  36990. double getMarkerPosition (const Marker& marker, Component* parentComponent) const;
  36991. /** Sets the position of a marker.
  36992. If the name already exists, then the existing marker is moved; if it doesn't exist, then a
  36993. new marker is added.
  36994. */
  36995. void setMarker (const String& name, const RelativeCoordinate& position);
  36996. /** Deletes the marker at the given list index. */
  36997. void removeMarker (int index);
  36998. /** Deletes the marker with the given name. */
  36999. void removeMarker (const String& name);
  37000. /** Returns true if all the markers in these two lists match exactly. */
  37001. bool operator== (const MarkerList& other) const throw();
  37002. /** Returns true if not all the markers in these two lists match exactly. */
  37003. bool operator!= (const MarkerList& other) const throw();
  37004. /**
  37005. A class for receiving events when changes are made to a MarkerList.
  37006. You can register a MarkerList::Listener with a MarkerList using the MarkerList::addListener()
  37007. method, and it will be called when markers are moved, added, or deleted.
  37008. @see MarkerList::addListener, MarkerList::removeListener
  37009. */
  37010. class JUCE_API Listener
  37011. {
  37012. public:
  37013. /** Destructor. */
  37014. virtual ~Listener() {}
  37015. /** Called when something in the given marker list changes. */
  37016. virtual void markersChanged (MarkerList* markerList) = 0;
  37017. /** Called when the given marker list is being deleted. */
  37018. virtual void markerListBeingDeleted (MarkerList* markerList);
  37019. };
  37020. /** Registers a listener that will be called when the markers are changed. */
  37021. void addListener (Listener* listener);
  37022. /** Deregisters a previously-registered listener. */
  37023. void removeListener (Listener* listener);
  37024. /** Synchronously calls markersChanged() on all the registered listeners. */
  37025. void markersHaveChanged();
  37026. /** Forms a wrapper around a ValueTree that can be used for storing a MarkerList. */
  37027. class ValueTreeWrapper
  37028. {
  37029. public:
  37030. ValueTreeWrapper (const ValueTree& state);
  37031. ValueTree& getState() throw() { return state; }
  37032. int getNumMarkers() const;
  37033. const ValueTree getMarkerState (int index) const;
  37034. const ValueTree getMarkerState (const String& name) const;
  37035. bool containsMarker (const ValueTree& state) const;
  37036. const MarkerList::Marker getMarker (const ValueTree& state) const;
  37037. void setMarker (const MarkerList::Marker& marker, UndoManager* undoManager);
  37038. void removeMarker (const ValueTree& state, UndoManager* undoManager);
  37039. void applyTo (MarkerList& markerList);
  37040. void readFrom (const MarkerList& markerList, UndoManager* undoManager);
  37041. static const Identifier markerTag, nameProperty, posProperty;
  37042. private:
  37043. ValueTree state;
  37044. };
  37045. private:
  37046. OwnedArray<Marker> markers;
  37047. ListenerList<Listener> listeners;
  37048. JUCE_LEAK_DETECTOR (MarkerList);
  37049. };
  37050. #endif // __JUCE_MARKERLIST_JUCEHEADER__
  37051. /*** End of inlined file: juce_MarkerList.h ***/
  37052. /**
  37053. Base class for Component::Positioners that are based upon relative coordinates.
  37054. */
  37055. class JUCE_API RelativeCoordinatePositionerBase : public Component::Positioner,
  37056. public ComponentListener,
  37057. public MarkerList::Listener
  37058. {
  37059. public:
  37060. RelativeCoordinatePositionerBase (Component& component_);
  37061. ~RelativeCoordinatePositionerBase();
  37062. void componentMovedOrResized (Component&, bool, bool);
  37063. void componentParentHierarchyChanged (Component&);
  37064. void componentChildrenChanged (Component& component);
  37065. void componentBeingDeleted (Component& component);
  37066. void markersChanged (MarkerList*);
  37067. void markerListBeingDeleted (MarkerList* markerList);
  37068. void apply();
  37069. bool addCoordinate (const RelativeCoordinate& coord);
  37070. bool addPoint (const RelativePoint& point);
  37071. /** Used for resolving a RelativeCoordinate expression in the context of a component. */
  37072. class ComponentScope : public Expression::Scope
  37073. {
  37074. public:
  37075. ComponentScope (Component& component_);
  37076. const Expression getSymbolValue (const String& symbol) const;
  37077. void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  37078. const String getScopeUID() const;
  37079. protected:
  37080. Component& component;
  37081. Component* findSiblingComponent (const String& componentID) const;
  37082. const MarkerList::Marker* findMarker (const String& name, MarkerList*& list) const;
  37083. private:
  37084. JUCE_DECLARE_NON_COPYABLE (ComponentScope);
  37085. };
  37086. protected:
  37087. virtual bool registerCoordinates() = 0;
  37088. virtual void applyToComponentBounds() = 0;
  37089. private:
  37090. class DependencyFinderScope;
  37091. friend class DependencyFinderScope;
  37092. Array <Component*> sourceComponents;
  37093. Array <MarkerList*> sourceMarkerLists;
  37094. bool registeredOk;
  37095. void registerComponentListener (Component& comp);
  37096. void registerMarkerListListener (MarkerList* const list);
  37097. void unregisterListeners();
  37098. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeCoordinatePositionerBase);
  37099. };
  37100. #endif // __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37101. /*** End of inlined file: juce_RelativeCoordinatePositioner.h ***/
  37102. /*** Start of inlined file: juce_ComponentBuilder.h ***/
  37103. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37104. #define __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37105. /**
  37106. Loads and maintains a tree of Components from a ValueTree that represents them.
  37107. To allow the state of a tree of components to be saved as a ValueTree and re-loaded,
  37108. this class lets you register a set of type-handlers for the different components that
  37109. are involved, and then uses these types to re-create a set of components from its
  37110. stored state.
  37111. Essentially, to use this, you need to create a ComponentBuilder with your ValueTree,
  37112. then use registerTypeHandler() to give it a set of type handlers that can cope with
  37113. all the items in your tree. Then you can call getComponent() to build the component.
  37114. Once you've got the component you can either take it and delete the ComponentBuilder
  37115. object, or if you keep the ComponentBuilder around, it'll monitor any changes in the
  37116. ValueTree and automatically update the component to reflect these changes.
  37117. */
  37118. class JUCE_API ComponentBuilder : public ValueTree::Listener
  37119. {
  37120. public:
  37121. /** Creates a ComponentBuilder that will use the given state.
  37122. Once you've created your builder, you should use registerTypeHandler() to register some
  37123. type handlers for it, and then you can call createComponent() or getManagedComponent()
  37124. to get the actual component.
  37125. */
  37126. explicit ComponentBuilder (const ValueTree& state);
  37127. /** Destructor. */
  37128. ~ComponentBuilder();
  37129. /** Returns the ValueTree that this builder is working with. */
  37130. ValueTree& getState() throw() { return state; }
  37131. /** Returns the ValueTree that this builder is working with. */
  37132. const ValueTree& getState() const throw() { return state; }
  37133. /** Returns the builder's component (creating it if necessary).
  37134. The first time that this method is called, the builder will attempt to create a component
  37135. from the ValueTree, so you must have registered some suitable type handlers before calling
  37136. this. If there's a problem and the component can't be created, this method returns 0.
  37137. The component that is returned is owned by this ComponentBuilder, so you can put it inside
  37138. your own parent components, but don't delete it! The ComponentBuilder will delete it automatically
  37139. when the builder is destroyed. If you want to get a component that you can delete yourself,
  37140. call createComponent() instead.
  37141. The ComponentBuilder will update this component if any changes are made to the ValueTree, so if
  37142. there's a chance that the tree might change, be careful not to keep any pointers to sub-components,
  37143. as they may be changed or removed.
  37144. */
  37145. Component* getManagedComponent();
  37146. /** Creates and returns a new instance of the component that the ValueTree represents.
  37147. The caller is responsible for using and deleting the object that is returned. Unlike
  37148. getManagedComponent(), the component that is returned will not be updated by the builder.
  37149. */
  37150. Component* createComponent();
  37151. /**
  37152. The class is a base class for objects that manage the loading of a type of component
  37153. from a ValueTree.
  37154. To store and re-load a tree of components as a ValueTree, each component type must have
  37155. a TypeHandler to represent it.
  37156. @see ComponentBuilder::registerTypeHandler(), Drawable::registerDrawableTypeHandlers()
  37157. */
  37158. class JUCE_API TypeHandler
  37159. {
  37160. public:
  37161. /** Creates a TypeHandler.
  37162. The valueTreeType must be the type name of the ValueTrees that this handler can parse.
  37163. */
  37164. explicit TypeHandler (const Identifier& valueTreeType);
  37165. /** Destructor. */
  37166. virtual ~TypeHandler();
  37167. /** Returns the type of the ValueTrees that this handler can parse. */
  37168. const Identifier& getType() const throw() { return valueTreeType; }
  37169. /** Returns the builder that this type is registered with. */
  37170. ComponentBuilder* getBuilder() const throw();
  37171. /** This method must create a new component from the given state, add it to the specified
  37172. parent component (which may be null), and return it.
  37173. The ValueTree will have been pre-checked to make sure that its type matches the type
  37174. that this handler supports.
  37175. There's no need to set the new Component's ID to match that of the state - the builder
  37176. will take care of that itself.
  37177. */
  37178. virtual Component* addNewComponentFromState (const ValueTree& state, Component* parent) = 0;
  37179. /** This method must update an existing component from a new ValueTree state.
  37180. A component that has been created with addNewComponentFromState() may need to be updated
  37181. if the ValueTree changes, so this method is used to do that. Your implementation must do
  37182. whatever's necessary to update the component from the new state provided.
  37183. The ValueTree will have been pre-checked to make sure that its type matches the type
  37184. that this handler supports, and the component will have been created by this type's
  37185. addNewComponentFromState() method.
  37186. */
  37187. virtual void updateComponentFromState (Component* component, const ValueTree& state) = 0;
  37188. private:
  37189. friend class ComponentBuilder;
  37190. ComponentBuilder* builder;
  37191. const Identifier valueTreeType;
  37192. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypeHandler);
  37193. };
  37194. /** Adds a type handler that the builder can use when trying to load components.
  37195. @see Drawable::registerDrawableTypeHandlers()
  37196. */
  37197. void registerTypeHandler (TypeHandler* type);
  37198. /** Tries to find a registered type handler that can load a component from the given ValueTree. */
  37199. TypeHandler* getHandlerForState (const ValueTree& state) const;
  37200. /** Returns the number of registered type handlers.
  37201. @see getHandler, registerTypeHandler
  37202. */
  37203. int getNumHandlers() const throw();
  37204. /** Returns one of the registered type handlers.
  37205. @see getNumHandlers, registerTypeHandler
  37206. */
  37207. TypeHandler* getHandler (int index) const throw();
  37208. /** This class is used when references to images need to be stored in ValueTrees.
  37209. An instance of an ImageProvider provides a mechanism for converting an Image to/from
  37210. a reference, which may be a file, URL, ID string, or whatever system is appropriate in
  37211. your app.
  37212. When you're loading components from a ValueTree that may need a way of loading images, you
  37213. should call ComponentBuilder::setImageProvider() to supply a suitable provider before
  37214. trying to load the component.
  37215. @see ComponentBuilder::setImageProvider()
  37216. */
  37217. class JUCE_API ImageProvider
  37218. {
  37219. public:
  37220. ImageProvider() {}
  37221. virtual ~ImageProvider() {}
  37222. /** Retrieves the image associated with this identifier, which could be any
  37223. kind of string, number, filename, etc.
  37224. The image that is returned will be owned by the caller, but it may come
  37225. from the ImageCache.
  37226. */
  37227. virtual const Image getImageForIdentifier (const var& imageIdentifier) = 0;
  37228. /** Returns an identifier to be used to refer to a given image.
  37229. This is used when a reference to an image is stored in a ValueTree.
  37230. */
  37231. virtual const var getIdentifierForImage (const Image& image) = 0;
  37232. };
  37233. /** Gives the builder an ImageProvider object that the type handlers can use when
  37234. loading images from stored references.
  37235. The object that is passed in is not owned by the builder, so the caller must delete
  37236. it when it is no longer needed, but not while the builder may still be using it. To
  37237. clear the image provider, just call setImageProvider (0).
  37238. */
  37239. void setImageProvider (ImageProvider* newImageProvider) throw();
  37240. /** Returns the current image provider that this builder is using, or 0 if none has been set. */
  37241. ImageProvider* getImageProvider() const throw();
  37242. /** Updates the children of a parent component by updating them from the children of
  37243. a given ValueTree.
  37244. */
  37245. void updateChildComponents (Component& parent, const ValueTree& children);
  37246. /** An identifier for the property of the ValueTrees that is used to store a unique ID
  37247. for that component.
  37248. */
  37249. static const Identifier idProperty;
  37250. /** @internal */
  37251. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& property);
  37252. /** @internal */
  37253. void valueTreeChildAdded (ValueTree& parentTree, ValueTree& childWhichHasBeenAdded);
  37254. /** @internal */
  37255. void valueTreeChildRemoved (ValueTree& parentTree, ValueTree& childWhichHasBeenRemoved);
  37256. /** @internal */
  37257. void valueTreeChildOrderChanged (ValueTree& parentTree);
  37258. /** @internal */
  37259. void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged);
  37260. private:
  37261. ValueTree state;
  37262. OwnedArray <TypeHandler> types;
  37263. ScopedPointer<Component> component;
  37264. ImageProvider* imageProvider;
  37265. #if JUCE_DEBUG
  37266. WeakReference<Component> componentRef;
  37267. #endif
  37268. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBuilder);
  37269. };
  37270. #endif // __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37271. /*** End of inlined file: juce_ComponentBuilder.h ***/
  37272. class DrawableComposite;
  37273. /**
  37274. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  37275. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37276. */
  37277. class JUCE_API Drawable : public Component
  37278. {
  37279. protected:
  37280. /** The base class can't be instantiated directly.
  37281. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37282. */
  37283. Drawable();
  37284. public:
  37285. /** Destructor. */
  37286. virtual ~Drawable();
  37287. /** Creates a deep copy of this Drawable object.
  37288. Use this to create a new copy of this and any sub-objects in the tree.
  37289. */
  37290. virtual Drawable* createCopy() const = 0;
  37291. /** Renders this Drawable object.
  37292. Note that the preferred way to render a drawable in future is by using it
  37293. as a component and adding it to a parent, so you might want to consider that
  37294. before using this method.
  37295. @see drawWithin
  37296. */
  37297. void draw (Graphics& g, float opacity,
  37298. const AffineTransform& transform = AffineTransform::identity) const;
  37299. /** Renders the Drawable at a given offset within the Graphics context.
  37300. The co-ordinates passed-in are used to translate the object relative to its own
  37301. origin before drawing it - this is basically a quick way of saying:
  37302. @code
  37303. draw (g, AffineTransform::translation (x, y)).
  37304. @endcode
  37305. Note that the preferred way to render a drawable in future is by using it
  37306. as a component and adding it to a parent, so you might want to consider that
  37307. before using this method.
  37308. */
  37309. void drawAt (Graphics& g, float x, float y, float opacity) const;
  37310. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  37311. changing its aspect-ratio.
  37312. The object can placed arbitrarily within the rectangle based on a Justification type,
  37313. and can either be made as big as possible, or just reduced to fit.
  37314. Note that the preferred way to render a drawable in future is by using it
  37315. as a component and adding it to a parent, so you might want to consider that
  37316. before using this method.
  37317. @param g the graphics context to render onto
  37318. @param destArea the target rectangle to fit the drawable into
  37319. @param placement defines the alignment and rescaling to use to fit
  37320. this object within the target rectangle.
  37321. @param opacity the opacity to use, in the range 0 to 1.0
  37322. */
  37323. void drawWithin (Graphics& g,
  37324. const Rectangle<float>& destArea,
  37325. const RectanglePlacement& placement,
  37326. float opacity) const;
  37327. /** Resets any transformations on this drawable, and positions its origin within
  37328. its parent component.
  37329. */
  37330. void setOriginWithOriginalSize (const Point<float>& originWithinParent);
  37331. /** Sets a transform for this drawable that will position it within the specified
  37332. area of its parent component.
  37333. */
  37334. void setTransformToFit (const Rectangle<float>& areaInParent, const RectanglePlacement& placement);
  37335. /** Returns the DrawableComposite that contains this object, if there is one. */
  37336. DrawableComposite* getParent() const;
  37337. /** Tries to turn some kind of image file into a drawable.
  37338. The data could be an image that the ImageFileFormat class understands, or it
  37339. could be SVG.
  37340. */
  37341. static Drawable* createFromImageData (const void* data, size_t numBytes);
  37342. /** Tries to turn a stream containing some kind of image data into a drawable.
  37343. The data could be an image that the ImageFileFormat class understands, or it
  37344. could be SVG.
  37345. */
  37346. static Drawable* createFromImageDataStream (InputStream& dataSource);
  37347. /** Tries to turn a file containing some kind of image data into a drawable.
  37348. The data could be an image that the ImageFileFormat class understands, or it
  37349. could be SVG.
  37350. */
  37351. static Drawable* createFromImageFile (const File& file);
  37352. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  37353. into a Drawable tree.
  37354. The object returned must be deleted by the caller. If something goes wrong
  37355. while parsing, it may return 0.
  37356. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  37357. implementation, but it can return the basic vector objects.
  37358. */
  37359. static Drawable* createFromSVG (const XmlElement& svgDocument);
  37360. /** Tries to create a Drawable from a previously-saved ValueTree.
  37361. The ValueTree must have been created by the createValueTree() method.
  37362. If there are any images used within the drawable, you'll need to provide a valid
  37363. ImageProvider object that can be used to retrieve these images from whatever type
  37364. of identifier is used to represent them.
  37365. Internally, this uses a ComponentBuilder, and registerDrawableTypeHandlers().
  37366. */
  37367. static Drawable* createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider);
  37368. /** Creates a ValueTree to represent this Drawable.
  37369. The ValueTree that is returned can be turned back into a Drawable with createFromValueTree().
  37370. If there are any images used in this drawable, you'll need to provide a valid ImageProvider
  37371. object that can be used to create storable representations of them.
  37372. */
  37373. virtual const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const = 0;
  37374. /** Returns the area that this drawble covers.
  37375. The result is expressed in this drawable's own coordinate space, and does not take
  37376. into account any transforms that may be applied to the component.
  37377. */
  37378. virtual const Rectangle<float> getDrawableBounds() const = 0;
  37379. /** Internal class used to manage ValueTrees that represent Drawables. */
  37380. class ValueTreeWrapperBase
  37381. {
  37382. public:
  37383. ValueTreeWrapperBase (const ValueTree& state);
  37384. ValueTree& getState() throw() { return state; }
  37385. const String getID() const;
  37386. void setID (const String& newID);
  37387. ValueTree state;
  37388. };
  37389. /** Registers a set of ComponentBuilder::TypeHandler objects that can be used to
  37390. load all the different Drawable types from a saved state.
  37391. @see ComponentBuilder::registerTypeHandler()
  37392. */
  37393. static void registerDrawableTypeHandlers (ComponentBuilder& componentBuilder);
  37394. protected:
  37395. friend class DrawableComposite;
  37396. friend class DrawableShape;
  37397. /** @internal */
  37398. void transformContextToCorrectOrigin (Graphics& g);
  37399. /** @internal */
  37400. void parentHierarchyChanged();
  37401. /** @internal */
  37402. void setBoundsToEnclose (const Rectangle<float>& area);
  37403. Point<int> originRelativeToComponent;
  37404. #ifndef DOXYGEN
  37405. /** Internal utility class used by Drawables. */
  37406. template <class DrawableType>
  37407. class Positioner : public RelativeCoordinatePositionerBase
  37408. {
  37409. public:
  37410. Positioner (DrawableType& component_)
  37411. : RelativeCoordinatePositionerBase (component_),
  37412. owner (component_)
  37413. {}
  37414. bool registerCoordinates() { return owner.registerCoordinates (*this); }
  37415. void applyToComponentBounds()
  37416. {
  37417. ComponentScope scope (getComponent());
  37418. owner.recalculateCoordinates (&scope);
  37419. }
  37420. void applyNewBounds (const Rectangle<int>&)
  37421. {
  37422. jassertfalse; // drawables can't be resized directly!
  37423. }
  37424. private:
  37425. DrawableType& owner;
  37426. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  37427. };
  37428. #endif
  37429. private:
  37430. void nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform);
  37431. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Drawable);
  37432. };
  37433. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  37434. /*** End of inlined file: juce_Drawable.h ***/
  37435. /**
  37436. A button that displays a Drawable.
  37437. Up to three Drawable objects can be given to this button, to represent the
  37438. 'normal', 'over' and 'down' states.
  37439. @see Button
  37440. */
  37441. class JUCE_API DrawableButton : public Button
  37442. {
  37443. public:
  37444. enum ButtonStyle
  37445. {
  37446. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  37447. ImageRaw, /**< The button will just display the images in their normal size and position.
  37448. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  37449. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  37450. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  37451. };
  37452. /** Creates a DrawableButton.
  37453. After creating one of these, use setImages() to specify the drawables to use.
  37454. @param buttonName the name to give the component
  37455. @param buttonStyle the layout to use
  37456. @see ButtonStyle, setButtonStyle, setImages
  37457. */
  37458. DrawableButton (const String& buttonName,
  37459. ButtonStyle buttonStyle);
  37460. /** Destructor. */
  37461. ~DrawableButton();
  37462. /** Sets up the images to draw for the various button states.
  37463. The button will keep its own internal copies of these drawables.
  37464. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  37465. will be made of the object passed-in if it is non-zero.
  37466. @param overImage the thing to draw for the button's 'over' state - if this is
  37467. zero, the button's normal image will be used when the mouse is
  37468. over it. An internal copy will be made of the object passed-in
  37469. if it is non-zero.
  37470. @param downImage the thing to draw for the button's 'down' state - if this is
  37471. zero, the 'over' image will be used instead (or the normal image
  37472. as a last resort). An internal copy will be made of the object
  37473. passed-in if it is non-zero.
  37474. @param disabledImage an image to draw when the button is disabled. If this is zero,
  37475. the normal image will be drawn with a reduced opacity instead.
  37476. An internal copy will be made of the object passed-in if it is
  37477. non-zero.
  37478. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  37479. state is 'on'. If this is 0, the normal image is used instead
  37480. @param overImageOn same as the overImage, but this is used when the button's toggle
  37481. state is 'on'. If this is 0, the normalImageOn is drawn instead
  37482. @param downImageOn same as the downImage, but this is used when the button's toggle
  37483. state is 'on'. If this is 0, the overImageOn is drawn instead
  37484. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  37485. state is 'on'. If this is 0, the normal image will be drawn instead
  37486. with a reduced opacity
  37487. */
  37488. void setImages (const Drawable* normalImage,
  37489. const Drawable* overImage = 0,
  37490. const Drawable* downImage = 0,
  37491. const Drawable* disabledImage = 0,
  37492. const Drawable* normalImageOn = 0,
  37493. const Drawable* overImageOn = 0,
  37494. const Drawable* downImageOn = 0,
  37495. const Drawable* disabledImageOn = 0);
  37496. /** Changes the button's style.
  37497. @see ButtonStyle
  37498. */
  37499. void setButtonStyle (ButtonStyle newStyle);
  37500. /** Changes the button's background colours.
  37501. The toggledOffColour is the colour to use when the button's toggle state
  37502. is off, and toggledOnColour when it's on.
  37503. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  37504. used to fill the background of the component.
  37505. For an ImageOnButtonBackground style, the colour is used to draw the
  37506. button's lozenge shape and exactly how the colour's used will depend
  37507. on the LookAndFeel.
  37508. */
  37509. void setBackgroundColours (const Colour& toggledOffColour,
  37510. const Colour& toggledOnColour);
  37511. /** Returns the current background colour being used.
  37512. @see setBackgroundColour
  37513. */
  37514. const Colour& getBackgroundColour() const throw();
  37515. /** Gives the button an optional amount of space around the edge of the drawable.
  37516. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  37517. ones on a button background. If the button is too small for the given gap, a
  37518. smaller gap will be used.
  37519. By default there's a gap of about 3 pixels.
  37520. */
  37521. void setEdgeIndent (int numPixelsIndent);
  37522. /** Returns the image that the button is currently displaying. */
  37523. Drawable* getCurrentImage() const throw();
  37524. Drawable* getNormalImage() const throw();
  37525. Drawable* getOverImage() const throw();
  37526. Drawable* getDownImage() const throw();
  37527. /** A set of colour IDs to use to change the colour of various aspects of the link.
  37528. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37529. methods.
  37530. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37531. */
  37532. enum ColourIds
  37533. {
  37534. textColourId = 0x1004010, /**< The colour to use for the URL text. */
  37535. };
  37536. protected:
  37537. /** @internal */
  37538. void paintButton (Graphics& g,
  37539. bool isMouseOverButton,
  37540. bool isButtonDown);
  37541. /** @internal */
  37542. void buttonStateChanged();
  37543. /** @internal */
  37544. void resized();
  37545. private:
  37546. ButtonStyle style;
  37547. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  37548. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  37549. Drawable* currentImage;
  37550. Colour backgroundOff, backgroundOn;
  37551. int edgeIndent;
  37552. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DrawableButton);
  37553. };
  37554. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  37555. /*** End of inlined file: juce_DrawableButton.h ***/
  37556. #endif
  37557. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37558. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  37559. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37560. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37561. /**
  37562. A button showing an underlined weblink, that will launch the link
  37563. when it's clicked.
  37564. @see Button
  37565. */
  37566. class JUCE_API HyperlinkButton : public Button
  37567. {
  37568. public:
  37569. /** Creates a HyperlinkButton.
  37570. @param linkText the text that will be displayed in the button - this is
  37571. also set as the Component's name, but the text can be
  37572. changed later with the Button::getButtonText() method
  37573. @param linkURL the URL to launch when the user clicks the button
  37574. */
  37575. HyperlinkButton (const String& linkText,
  37576. const URL& linkURL);
  37577. /** Destructor. */
  37578. ~HyperlinkButton();
  37579. /** Changes the font to use for the text.
  37580. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  37581. to match the size of the component.
  37582. */
  37583. void setFont (const Font& newFont,
  37584. bool resizeToMatchComponentHeight,
  37585. const Justification& justificationType = Justification::horizontallyCentred);
  37586. /** A set of colour IDs to use to change the colour of various aspects of the link.
  37587. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37588. methods.
  37589. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37590. */
  37591. enum ColourIds
  37592. {
  37593. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  37594. };
  37595. /** Changes the URL that the button will trigger. */
  37596. void setURL (const URL& newURL) throw();
  37597. /** Returns the URL that the button will trigger. */
  37598. const URL& getURL() const throw() { return url; }
  37599. /** Resizes the button horizontally to fit snugly around the text.
  37600. This won't affect the button's height.
  37601. */
  37602. void changeWidthToFitText();
  37603. protected:
  37604. /** @internal */
  37605. void clicked();
  37606. /** @internal */
  37607. void colourChanged();
  37608. /** @internal */
  37609. void paintButton (Graphics& g,
  37610. bool isMouseOverButton,
  37611. bool isButtonDown);
  37612. private:
  37613. URL url;
  37614. Font font;
  37615. bool resizeFont;
  37616. Justification justification;
  37617. const Font getFontToUse() const;
  37618. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HyperlinkButton);
  37619. };
  37620. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37621. /*** End of inlined file: juce_HyperlinkButton.h ***/
  37622. #endif
  37623. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  37624. /*** Start of inlined file: juce_ImageButton.h ***/
  37625. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  37626. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  37627. /**
  37628. As the title suggests, this is a button containing an image.
  37629. The colour and transparency of the image can be set to vary when the
  37630. button state changes.
  37631. @see Button, ShapeButton, TextButton
  37632. */
  37633. class JUCE_API ImageButton : public Button
  37634. {
  37635. public:
  37636. /** Creates an ImageButton.
  37637. Use setImage() to specify the image to use. The colours and opacities that
  37638. are specified here can be changed later using setDrawingOptions().
  37639. @param name the name to give the component
  37640. */
  37641. explicit ImageButton (const String& name);
  37642. /** Destructor. */
  37643. ~ImageButton();
  37644. /** Sets up the images to draw in various states.
  37645. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  37646. resized to the same dimensions as the normal image
  37647. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  37648. button when the button's size changes
  37649. @param preserveImageProportions if true then any rescaling of the image to fit
  37650. the button will keep the image's x and y proportions
  37651. correct - i.e. it won't distort its shape, although
  37652. this might create gaps around the edges
  37653. @param normalImage the image to use when the button is in its normal state.
  37654. button no longer needs it.
  37655. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  37656. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  37657. normal image - if this colour is transparent, no overlay
  37658. will be drawn. The overlay will be drawn over the top of the
  37659. image, so you can basically add a solid or semi-transparent
  37660. colour to the image to brighten or darken it
  37661. @param overImage the image to use when the mouse is over the button. If
  37662. you want to use the same image as was set in the normalImage
  37663. parameter, this value can be a null image.
  37664. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  37665. is over the button
  37666. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  37667. image when the mouse is over - if this colour is transparent,
  37668. no overlay will be drawn
  37669. @param downImage an image to use when the button is pressed down. If set
  37670. to a null image, the 'over' image will be drawn instead (or the
  37671. normal image if there isn't an 'over' image either).
  37672. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  37673. is pressed
  37674. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  37675. image when the button is pressed down - if this colour is
  37676. transparent, no overlay will be drawn
  37677. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  37678. whenever it's inside the button's bounding rectangle. If
  37679. set to values higher than 0, the mouse will only be
  37680. considered to be over the image when the value of the
  37681. image's alpha channel at that position is greater than
  37682. this level.
  37683. */
  37684. void setImages (bool resizeButtonNowToFitThisImage,
  37685. bool rescaleImagesWhenButtonSizeChanges,
  37686. bool preserveImageProportions,
  37687. const Image& normalImage,
  37688. float imageOpacityWhenNormal,
  37689. const Colour& overlayColourWhenNormal,
  37690. const Image& overImage,
  37691. float imageOpacityWhenOver,
  37692. const Colour& overlayColourWhenOver,
  37693. const Image& downImage,
  37694. float imageOpacityWhenDown,
  37695. const Colour& overlayColourWhenDown,
  37696. float hitTestAlphaThreshold = 0.0f);
  37697. /** Returns the currently set 'normal' image. */
  37698. const Image getNormalImage() const;
  37699. /** Returns the image that's drawn when the mouse is over the button.
  37700. If a valid 'over' image has been set, this will return it; otherwise it'll
  37701. just return the normal image.
  37702. */
  37703. const Image getOverImage() const;
  37704. /** Returns the image that's drawn when the button is held down.
  37705. If a valid 'down' image has been set, this will return it; otherwise it'll
  37706. return the 'over' image or normal image, depending on what's available.
  37707. */
  37708. const Image getDownImage() const;
  37709. protected:
  37710. /** @internal */
  37711. bool hitTest (int x, int y);
  37712. /** @internal */
  37713. void paintButton (Graphics& g,
  37714. bool isMouseOverButton,
  37715. bool isButtonDown);
  37716. private:
  37717. bool scaleImageToFit, preserveProportions;
  37718. unsigned char alphaThreshold;
  37719. int imageX, imageY, imageW, imageH;
  37720. Image normalImage, overImage, downImage;
  37721. float normalOpacity, overOpacity, downOpacity;
  37722. Colour normalOverlay, overOverlay, downOverlay;
  37723. const Image getCurrentImage() const;
  37724. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageButton);
  37725. };
  37726. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  37727. /*** End of inlined file: juce_ImageButton.h ***/
  37728. #endif
  37729. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  37730. /*** Start of inlined file: juce_ShapeButton.h ***/
  37731. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  37732. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  37733. /**
  37734. A button that contains a filled shape.
  37735. @see Button, ImageButton, TextButton, ArrowButton
  37736. */
  37737. class JUCE_API ShapeButton : public Button
  37738. {
  37739. public:
  37740. /** Creates a ShapeButton.
  37741. @param name a name to give the component - see Component::setName()
  37742. @param normalColour the colour to fill the shape with when the mouse isn't over
  37743. @param overColour the colour to use when the mouse is over the shape
  37744. @param downColour the colour to use when the button is in the pressed-down state
  37745. */
  37746. ShapeButton (const String& name,
  37747. const Colour& normalColour,
  37748. const Colour& overColour,
  37749. const Colour& downColour);
  37750. /** Destructor. */
  37751. ~ShapeButton();
  37752. /** Sets the shape to use.
  37753. @param newShape the shape to use
  37754. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  37755. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  37756. the button is resized
  37757. @param hasDropShadow if true, the button will be given a drop-shadow effect
  37758. */
  37759. void setShape (const Path& newShape,
  37760. bool resizeNowToFitThisShape,
  37761. bool maintainShapeProportions,
  37762. bool hasDropShadow);
  37763. /** Set the colours to use for drawing the shape.
  37764. @param normalColour the colour to fill the shape with when the mouse isn't over
  37765. @param overColour the colour to use when the mouse is over the shape
  37766. @param downColour the colour to use when the button is in the pressed-down state
  37767. */
  37768. void setColours (const Colour& normalColour,
  37769. const Colour& overColour,
  37770. const Colour& downColour);
  37771. /** Sets up an outline to draw around the shape.
  37772. @param outlineColour the colour to use
  37773. @param outlineStrokeWidth the thickness of line to draw
  37774. */
  37775. void setOutline (const Colour& outlineColour,
  37776. float outlineStrokeWidth);
  37777. protected:
  37778. /** @internal */
  37779. void paintButton (Graphics& g,
  37780. bool isMouseOverButton,
  37781. bool isButtonDown);
  37782. private:
  37783. Colour normalColour, overColour, downColour, outlineColour;
  37784. DropShadowEffect shadow;
  37785. Path shape;
  37786. bool maintainShapeProportions;
  37787. float outlineWidth;
  37788. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ShapeButton);
  37789. };
  37790. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  37791. /*** End of inlined file: juce_ShapeButton.h ***/
  37792. #endif
  37793. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  37794. #endif
  37795. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37796. /*** Start of inlined file: juce_ToggleButton.h ***/
  37797. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37798. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37799. /**
  37800. A button that can be toggled on/off.
  37801. All buttons can be toggle buttons, but this lets you create one of the
  37802. standard ones which has a tick-box and a text label next to it.
  37803. @see Button, DrawableButton, TextButton
  37804. */
  37805. class JUCE_API ToggleButton : public Button
  37806. {
  37807. public:
  37808. /** Creates a ToggleButton.
  37809. @param buttonText the text to put in the button (the component's name is also
  37810. initially set to this string, but these can be changed later
  37811. using the setName() and setButtonText() methods)
  37812. */
  37813. explicit ToggleButton (const String& buttonText = String::empty);
  37814. /** Destructor. */
  37815. ~ToggleButton();
  37816. /** Resizes the button to fit neatly around its current text.
  37817. The button's height won't be affected, only its width.
  37818. */
  37819. void changeWidthToFitText();
  37820. /** A set of colour IDs to use to change the colour of various aspects of the button.
  37821. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37822. methods.
  37823. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37824. */
  37825. enum ColourIds
  37826. {
  37827. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  37828. };
  37829. protected:
  37830. /** @internal */
  37831. void paintButton (Graphics& g,
  37832. bool isMouseOverButton,
  37833. bool isButtonDown);
  37834. /** @internal */
  37835. void colourChanged();
  37836. private:
  37837. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToggleButton);
  37838. };
  37839. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37840. /*** End of inlined file: juce_ToggleButton.h ***/
  37841. #endif
  37842. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37843. /*** Start of inlined file: juce_ToolbarButton.h ***/
  37844. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37845. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37846. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  37847. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  37848. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  37849. /*** Start of inlined file: juce_Toolbar.h ***/
  37850. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  37851. #define __JUCE_TOOLBAR_JUCEHEADER__
  37852. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  37853. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  37854. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  37855. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  37856. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  37857. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  37858. /**
  37859. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  37860. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  37861. derive your component from this class, and make sure that it is somewhere inside a
  37862. DragAndDropContainer component.
  37863. Note: If all that you need to do is to respond to files being drag-and-dropped from
  37864. the operating system onto your component, you don't need any of these classes: instead
  37865. see the FileDragAndDropTarget class.
  37866. @see DragAndDropContainer, FileDragAndDropTarget
  37867. */
  37868. class JUCE_API DragAndDropTarget
  37869. {
  37870. public:
  37871. /** Destructor. */
  37872. virtual ~DragAndDropTarget() {}
  37873. /** Callback to check whether this target is interested in the type of object being
  37874. dragged.
  37875. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  37876. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  37877. @returns true if this component wants to receive the other callbacks regarging this
  37878. type of object; if it returns false, no other callbacks will be made.
  37879. */
  37880. virtual bool isInterestedInDragSource (const String& sourceDescription,
  37881. Component* sourceComponent) = 0;
  37882. /** Callback to indicate that something is being dragged over this component.
  37883. This gets called when the user moves the mouse into this component while dragging
  37884. something.
  37885. Use this callback as a trigger to make your component repaint itself to give the
  37886. user feedback about whether the item can be dropped here or not.
  37887. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  37888. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  37889. @param x the mouse x position, relative to this component
  37890. @param y the mouse y position, relative to this component
  37891. @see itemDragExit
  37892. */
  37893. virtual void itemDragEnter (const String& sourceDescription,
  37894. Component* sourceComponent,
  37895. int x, int y);
  37896. /** Callback to indicate that the user is dragging something over this component.
  37897. This gets called when the user moves the mouse over this component while dragging
  37898. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  37899. this lets you know what happens in-between.
  37900. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  37901. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  37902. @param x the mouse x position, relative to this component
  37903. @param y the mouse y position, relative to this component
  37904. */
  37905. virtual void itemDragMove (const String& sourceDescription,
  37906. Component* sourceComponent,
  37907. int x, int y);
  37908. /** Callback to indicate that something has been dragged off the edge of this component.
  37909. This gets called when the user moves the mouse out of this component while dragging
  37910. something.
  37911. If you've used itemDragEnter() to repaint your component and give feedback, use this
  37912. as a signal to repaint it in its normal state.
  37913. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  37914. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  37915. @see itemDragEnter
  37916. */
  37917. virtual void itemDragExit (const String& sourceDescription,
  37918. Component* sourceComponent);
  37919. /** Callback to indicate that the user has dropped something onto this component.
  37920. When the user drops an item this get called, and you can use the description to
  37921. work out whether your object wants to deal with it or not.
  37922. Note that after this is called, the itemDragExit method may not be called, so you should
  37923. clean up in here if there's anything you need to do when the drag finishes.
  37924. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  37925. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  37926. @param x the mouse x position, relative to this component
  37927. @param y the mouse y position, relative to this component
  37928. */
  37929. virtual void itemDropped (const String& sourceDescription,
  37930. Component* sourceComponent,
  37931. int x, int y) = 0;
  37932. /** Overriding this allows the target to tell the drag container whether to
  37933. draw the drag image while the cursor is over it.
  37934. By default it returns true, but if you return false, then the normal drag
  37935. image will not be shown when the cursor is over this target.
  37936. */
  37937. virtual bool shouldDrawDragImageWhenOver();
  37938. };
  37939. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  37940. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  37941. /**
  37942. Enables drag-and-drop behaviour for a component and all its sub-components.
  37943. For a component to be able to make or receive drag-and-drop events, one of its parent
  37944. components must derive from this class. It's probably best for the top-level
  37945. component to implement it.
  37946. Then to start a drag operation, any sub-component can just call the startDragging()
  37947. method, and this object will take over, tracking the mouse and sending appropriate
  37948. callbacks to any child components derived from DragAndDropTarget which the mouse
  37949. moves over.
  37950. Note: If all that you need to do is to respond to files being drag-and-dropped from
  37951. the operating system onto your component, you don't need any of these classes: you can do this
  37952. simply by overriding Component::filesDropped().
  37953. @see DragAndDropTarget
  37954. */
  37955. class JUCE_API DragAndDropContainer
  37956. {
  37957. public:
  37958. /** Creates a DragAndDropContainer.
  37959. The object that derives from this class must also be a Component.
  37960. */
  37961. DragAndDropContainer();
  37962. /** Destructor. */
  37963. virtual ~DragAndDropContainer();
  37964. /** Begins a drag-and-drop operation.
  37965. This starts a drag-and-drop operation - call it when the user drags the
  37966. mouse in your drag-source component, and this object will track mouse
  37967. movements until the user lets go of the mouse button, and will send
  37968. appropriate messages to DragAndDropTarget objects that the mouse moves
  37969. over.
  37970. findParentDragContainerFor() is a handy method to call to find the
  37971. drag container to use for a component.
  37972. @param sourceDescription a string to use as the description of the thing being
  37973. dragged - this will be passed to the objects that might be
  37974. dropped-onto so they can decide if they want to handle it or
  37975. not
  37976. @param sourceComponent the component that is being dragged
  37977. @param dragImage the image to drag around underneath the mouse. If this is a null image,
  37978. a snapshot of the sourceComponent will be used instead.
  37979. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  37980. window, and can be dragged to DragAndDropTargets that are the
  37981. children of components other than this one.
  37982. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  37983. at which the image should be drawn from the mouse. If it isn't
  37984. specified, then the image will be centred around the mouse. If
  37985. an image hasn't been passed-in, this will be ignored.
  37986. */
  37987. void startDragging (const String& sourceDescription,
  37988. Component* sourceComponent,
  37989. const Image& dragImage = Image::null,
  37990. bool allowDraggingToOtherJuceWindows = false,
  37991. const Point<int>* imageOffsetFromMouse = 0);
  37992. /** Returns true if something is currently being dragged. */
  37993. bool isDragAndDropActive() const;
  37994. /** Returns the description of the thing that's currently being dragged.
  37995. If nothing's being dragged, this will return an empty string, otherwise it's the
  37996. string that was passed into startDragging().
  37997. @see startDragging
  37998. */
  37999. const String getCurrentDragDescription() const;
  38000. /** Utility to find the DragAndDropContainer for a given Component.
  38001. This will search up this component's parent hierarchy looking for the first
  38002. parent component which is a DragAndDropContainer.
  38003. It's useful when a component wants to call startDragging but doesn't know
  38004. the DragAndDropContainer it should to use.
  38005. Obviously this may return 0 if it doesn't find a suitable component.
  38006. */
  38007. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  38008. /** This performs a synchronous drag-and-drop of a set of files to some external
  38009. application.
  38010. You can call this function in response to a mouseDrag callback, and it will
  38011. block, running its own internal message loop and tracking the mouse, while it
  38012. uses a native operating system drag-and-drop operation to move or copy some
  38013. files to another application.
  38014. @param files a list of filenames to drag
  38015. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  38016. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  38017. @returns true if the files were successfully dropped somewhere, or false if it
  38018. was interrupted
  38019. @see performExternalDragDropOfText
  38020. */
  38021. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  38022. /** This performs a synchronous drag-and-drop of a block of text to some external
  38023. application.
  38024. You can call this function in response to a mouseDrag callback, and it will
  38025. block, running its own internal message loop and tracking the mouse, while it
  38026. uses a native operating system drag-and-drop operation to move or copy some
  38027. text to another application.
  38028. @param text the text to copy
  38029. @returns true if the text was successfully dropped somewhere, or false if it
  38030. was interrupted
  38031. @see performExternalDragDropOfFiles
  38032. */
  38033. static bool performExternalDragDropOfText (const String& text);
  38034. protected:
  38035. /** Override this if you want to be able to perform an external drag a set of files
  38036. when the user drags outside of this container component.
  38037. This method will be called when a drag operation moves outside the Juce-based window,
  38038. and if you want it to then perform a file drag-and-drop, add the filenames you want
  38039. to the array passed in, and return true.
  38040. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  38041. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  38042. @param files on return, the filenames you want to drag
  38043. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  38044. it must make a copy of them (see the performExternalDragDropOfFiles()
  38045. method)
  38046. @see performExternalDragDropOfFiles
  38047. */
  38048. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  38049. Component* dragSourceComponent,
  38050. StringArray& files,
  38051. bool& canMoveFiles);
  38052. private:
  38053. friend class DragImageComponent;
  38054. ScopedPointer <Component> dragImageComponent;
  38055. String currentDragDesc;
  38056. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DragAndDropContainer);
  38057. };
  38058. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38059. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  38060. class ToolbarItemComponent;
  38061. class ToolbarItemFactory;
  38062. /**
  38063. A toolbar component.
  38064. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  38065. and looks after their order and layout.
  38066. Items (icon buttons or other custom components) are added to a toolbar using a
  38067. ToolbarItemFactory - each type of item is given a unique ID number, and a
  38068. toolbar might contain more than one instance of a particular item type.
  38069. Toolbars can be interactively customised, allowing the user to drag the items
  38070. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  38071. component as a source of new items.
  38072. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  38073. */
  38074. class JUCE_API Toolbar : public Component,
  38075. public DragAndDropContainer,
  38076. public DragAndDropTarget,
  38077. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  38078. {
  38079. public:
  38080. /** Creates an empty toolbar component.
  38081. To add some icons or other components to your toolbar, you'll need to
  38082. create a ToolbarItemFactory class that can create a suitable set of
  38083. ToolbarItemComponents.
  38084. @see ToolbarItemFactory, ToolbarItemComponents
  38085. */
  38086. Toolbar();
  38087. /** Destructor.
  38088. Any items on the bar will be deleted when the toolbar is deleted.
  38089. */
  38090. ~Toolbar();
  38091. /** Changes the bar's orientation.
  38092. @see isVertical
  38093. */
  38094. void setVertical (bool shouldBeVertical);
  38095. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  38096. You can change the bar's orientation with setVertical().
  38097. */
  38098. bool isVertical() const throw() { return vertical; }
  38099. /** Returns the depth of the bar.
  38100. If the bar is horizontal, this will return its height; if it's vertical, it
  38101. will return its width.
  38102. @see getLength
  38103. */
  38104. int getThickness() const throw();
  38105. /** Returns the length of the bar.
  38106. If the bar is horizontal, this will return its width; if it's vertical, it
  38107. will return its height.
  38108. @see getThickness
  38109. */
  38110. int getLength() const throw();
  38111. /** Deletes all items from the bar.
  38112. */
  38113. void clear();
  38114. /** Adds an item to the toolbar.
  38115. The factory's ToolbarItemFactory::createItem() will be called by this method
  38116. to create the component that will actually be added to the bar.
  38117. The new item will be inserted at the specified index (if the index is -1, it
  38118. will be added to the right-hand or bottom end of the bar).
  38119. Once added, the component will be automatically deleted by this object when it
  38120. is no longer needed.
  38121. @see ToolbarItemFactory
  38122. */
  38123. void addItem (ToolbarItemFactory& factory,
  38124. int itemId,
  38125. int insertIndex = -1);
  38126. /** Deletes one of the items from the bar.
  38127. */
  38128. void removeToolbarItem (int itemIndex);
  38129. /** Returns the number of items currently on the toolbar.
  38130. @see getItemId, getItemComponent
  38131. */
  38132. int getNumItems() const throw();
  38133. /** Returns the ID of the item with the given index.
  38134. If the index is less than zero or greater than the number of items,
  38135. this will return 0.
  38136. @see getNumItems
  38137. */
  38138. int getItemId (int itemIndex) const throw();
  38139. /** Returns the component being used for the item with the given index.
  38140. If the index is less than zero or greater than the number of items,
  38141. this will return 0.
  38142. @see getNumItems
  38143. */
  38144. ToolbarItemComponent* getItemComponent (int itemIndex) const throw();
  38145. /** Clears this toolbar and adds to it the default set of items that the specified
  38146. factory creates.
  38147. @see ToolbarItemFactory::getDefaultItemSet
  38148. */
  38149. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  38150. /** Options for the way items should be displayed.
  38151. @see setStyle, getStyle
  38152. */
  38153. enum ToolbarItemStyle
  38154. {
  38155. iconsOnly, /**< Means that the toolbar should just contain icons. */
  38156. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  38157. textOnly /**< Means that the toolbar only display text labels for each item. */
  38158. };
  38159. /** Returns the toolbar's current style.
  38160. @see ToolbarItemStyle, setStyle
  38161. */
  38162. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  38163. /** Changes the toolbar's current style.
  38164. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  38165. */
  38166. void setStyle (const ToolbarItemStyle& newStyle);
  38167. /** Flags used by the showCustomisationDialog() method. */
  38168. enum CustomisationFlags
  38169. {
  38170. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  38171. show the "icons only" option on its choice of toolbar styles. */
  38172. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  38173. show the "icons with text" option on its choice of toolbar styles. */
  38174. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  38175. show the "text only" option on its choice of toolbar styles. */
  38176. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  38177. show a button to reset the toolbar to its default set of items. */
  38178. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  38179. };
  38180. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  38181. The dialog contains a ToolbarItemPalette and various controls for editing other
  38182. aspects of the toolbar. This method will block and run the dialog box modally,
  38183. returning when the user closes it.
  38184. The factory is used to determine the set of items that will be shown on the
  38185. palette.
  38186. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  38187. enum.
  38188. @see ToolbarItemPalette
  38189. */
  38190. void showCustomisationDialog (ToolbarItemFactory& factory,
  38191. int optionFlags = allCustomisationOptionsEnabled);
  38192. /** Turns on or off the toolbar's editing mode, in which its items can be
  38193. rearranged by the user.
  38194. (In most cases it's easier just to use showCustomisationDialog() instead of
  38195. trying to enable editing directly).
  38196. @see ToolbarItemPalette
  38197. */
  38198. void setEditingActive (bool editingEnabled);
  38199. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  38200. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38201. methods.
  38202. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38203. */
  38204. enum ColourIds
  38205. {
  38206. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  38207. more control over this, override LookAndFeel::paintToolbarBackground(). */
  38208. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  38209. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  38210. over them. */
  38211. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  38212. held down on them. */
  38213. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  38214. when the style is set to iconsWithText or textOnly. */
  38215. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  38216. the customisation dialog is active and the mouse moves over them. */
  38217. };
  38218. /** Returns a string that represents the toolbar's current set of items.
  38219. This lets you later restore the same item layout using restoreFromString().
  38220. @see restoreFromString
  38221. */
  38222. const String toString() const;
  38223. /** Restores a set of items that was previously stored in a string by the toString()
  38224. method.
  38225. The factory object is used to create any item components that are needed.
  38226. @see toString
  38227. */
  38228. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  38229. const String& savedVersion);
  38230. /** @internal */
  38231. void paint (Graphics& g);
  38232. /** @internal */
  38233. void resized();
  38234. /** @internal */
  38235. void buttonClicked (Button*);
  38236. /** @internal */
  38237. void mouseDown (const MouseEvent&);
  38238. /** @internal */
  38239. bool isInterestedInDragSource (const String&, Component*);
  38240. /** @internal */
  38241. void itemDragMove (const String&, Component*, int, int);
  38242. /** @internal */
  38243. void itemDragExit (const String&, Component*);
  38244. /** @internal */
  38245. void itemDropped (const String&, Component*, int, int);
  38246. /** @internal */
  38247. void updateAllItemPositions (bool animate);
  38248. /** @internal */
  38249. static ToolbarItemComponent* createItem (ToolbarItemFactory&, int itemId);
  38250. private:
  38251. ScopedPointer<Button> missingItemsButton;
  38252. bool vertical, isEditingActive;
  38253. ToolbarItemStyle toolbarStyle;
  38254. class MissingItemsComponent;
  38255. friend class MissingItemsComponent;
  38256. OwnedArray <ToolbarItemComponent> items;
  38257. friend class ItemDragAndDropOverlayComponent;
  38258. static const char* const toolbarDragDescriptor;
  38259. void addItemInternal (ToolbarItemFactory& factory, int itemId, int insertIndex);
  38260. ToolbarItemComponent* getNextActiveComponent (int index, int delta) const;
  38261. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Toolbar);
  38262. };
  38263. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  38264. /*** End of inlined file: juce_Toolbar.h ***/
  38265. class ItemDragAndDropOverlayComponent;
  38266. /**
  38267. A component that can be used as one of the items in a Toolbar.
  38268. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  38269. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  38270. class for further info about creating them.
  38271. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  38272. components too. To do this, set the value of isBeingUsedAsAButton to false when
  38273. calling the constructor, and override contentAreaChanged(), in which you can position
  38274. any sub-components you need to add.
  38275. To add basic buttons without writing a special subclass, have a look at the
  38276. ToolbarButton class.
  38277. @see ToolbarButton, Toolbar, ToolbarItemFactory
  38278. */
  38279. class JUCE_API ToolbarItemComponent : public Button
  38280. {
  38281. public:
  38282. /** Constructor.
  38283. @param itemId the ID of the type of toolbar item which this represents
  38284. @param labelText the text to display if the toolbar's style is set to
  38285. Toolbar::iconsWithText or Toolbar::textOnly
  38286. @param isBeingUsedAsAButton set this to false if you don't want the button
  38287. to draw itself with button over/down states when the mouse
  38288. moves over it or clicks
  38289. */
  38290. ToolbarItemComponent (int itemId,
  38291. const String& labelText,
  38292. bool isBeingUsedAsAButton);
  38293. /** Destructor. */
  38294. ~ToolbarItemComponent();
  38295. /** Returns the item type ID that this component represents.
  38296. This value is in the constructor.
  38297. */
  38298. int getItemId() const throw() { return itemId; }
  38299. /** Returns the toolbar that contains this component, or 0 if it's not currently
  38300. inside one.
  38301. */
  38302. Toolbar* getToolbar() const;
  38303. /** Returns true if this component is currently inside a toolbar which is vertical.
  38304. @see Toolbar::isVertical
  38305. */
  38306. bool isToolbarVertical() const;
  38307. /** Returns the current style setting of this item.
  38308. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  38309. @see setStyle, Toolbar::getStyle
  38310. */
  38311. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  38312. /** Changes the current style setting of this item.
  38313. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  38314. by the toolbar that holds this item.
  38315. @see setStyle, Toolbar::setStyle
  38316. */
  38317. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  38318. /** Returns the area of the component that should be used to display the button image or
  38319. other contents of the item.
  38320. This content area may change when the item's style changes, and may leave a space around the
  38321. edge of the component where the text label can be shown.
  38322. @see contentAreaChanged
  38323. */
  38324. const Rectangle<int> getContentArea() const throw() { return contentArea; }
  38325. /** This method must return the size criteria for this item, based on a given toolbar
  38326. size and orientation.
  38327. The preferredSize, minSize and maxSize values must all be set by your implementation
  38328. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  38329. toolbar, they refer to the item's height.
  38330. The preferredSize is the size that the component would like to be, and this must be
  38331. between the min and max sizes. For a fixed-size item, simply set all three variables to
  38332. the same value.
  38333. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  38334. Toolbar::getThickness().
  38335. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  38336. vertically.
  38337. */
  38338. virtual bool getToolbarItemSizes (int toolbarThickness,
  38339. bool isToolbarVertical,
  38340. int& preferredSize,
  38341. int& minSize,
  38342. int& maxSize) = 0;
  38343. /** Your subclass should use this method to draw its content area.
  38344. The graphics object that is passed-in will have been clipped and had its origin
  38345. moved to fit the content area as specified get getContentArea(). The width and height
  38346. parameters are the width and height of the content area.
  38347. If the component you're writing isn't a button, you can just do nothing in this method.
  38348. */
  38349. virtual void paintButtonArea (Graphics& g,
  38350. int width, int height,
  38351. bool isMouseOver, bool isMouseDown) = 0;
  38352. /** Callback to indicate that the content area of this item has changed.
  38353. This might be because the component was resized, or because the style changed and
  38354. the space needed for the text label is different.
  38355. See getContentArea() for a description of what the area is.
  38356. */
  38357. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  38358. /** Editing modes.
  38359. These are used by setEditingMode(), but will be rarely needed in user code.
  38360. */
  38361. enum ToolbarEditingMode
  38362. {
  38363. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  38364. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  38365. customisation mode, and the items can be dragged around. */
  38366. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  38367. dragged onto a toolbar to add it to that bar.*/
  38368. };
  38369. /** Changes the editing mode of this component.
  38370. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  38371. and is unlikely to be of much use in end-user-code.
  38372. */
  38373. void setEditingMode (const ToolbarEditingMode newMode);
  38374. /** Returns the current editing mode of this component.
  38375. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  38376. and is unlikely to be of much use in end-user-code.
  38377. */
  38378. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  38379. /** @internal */
  38380. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  38381. /** @internal */
  38382. void resized();
  38383. private:
  38384. friend class Toolbar;
  38385. friend class ItemDragAndDropOverlayComponent;
  38386. const int itemId;
  38387. ToolbarEditingMode mode;
  38388. Toolbar::ToolbarItemStyle toolbarStyle;
  38389. ScopedPointer <Component> overlayComp;
  38390. int dragOffsetX, dragOffsetY;
  38391. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  38392. Rectangle<int> contentArea;
  38393. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemComponent);
  38394. };
  38395. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  38396. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  38397. /**
  38398. A type of button designed to go on a toolbar.
  38399. This simple button can have two Drawable objects specified - one for normal
  38400. use and another one (optionally) for the button's "on" state if it's a
  38401. toggle button.
  38402. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  38403. */
  38404. class JUCE_API ToolbarButton : public ToolbarItemComponent
  38405. {
  38406. public:
  38407. /** Creates a ToolbarButton.
  38408. @param itemId the ID for this toolbar item type. This is passed through to the
  38409. ToolbarItemComponent constructor
  38410. @param labelText the text to display on the button (if the toolbar is using a style
  38411. that shows text labels). This is passed through to the
  38412. ToolbarItemComponent constructor
  38413. @param normalImage a drawable object that the button should use as its icon. The object
  38414. that is passed-in here will be kept by this object and will be
  38415. deleted when no longer needed or when this button is deleted.
  38416. @param toggledOnImage a drawable object that the button can use as its icon if the button
  38417. is in a toggled-on state (see the Button::getToggleState() method). If
  38418. 0 is passed-in here, then the normal image will be used instead, regardless
  38419. of the toggle state. The object that is passed-in here will be kept by
  38420. this object and will be deleted when no longer needed or when this button
  38421. is deleted.
  38422. */
  38423. ToolbarButton (int itemId,
  38424. const String& labelText,
  38425. Drawable* normalImage,
  38426. Drawable* toggledOnImage);
  38427. /** Destructor. */
  38428. ~ToolbarButton();
  38429. /** @internal */
  38430. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  38431. int& minSize, int& maxSize);
  38432. /** @internal */
  38433. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  38434. /** @internal */
  38435. void contentAreaChanged (const Rectangle<int>& newBounds);
  38436. /** @internal */
  38437. void buttonStateChanged();
  38438. /** @internal */
  38439. void resized();
  38440. /** @internal */
  38441. void enablementChanged();
  38442. private:
  38443. ScopedPointer<Drawable> normalImage, toggledOnImage;
  38444. Drawable* currentImage;
  38445. void updateDrawable();
  38446. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarButton);
  38447. };
  38448. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  38449. /*** End of inlined file: juce_ToolbarButton.h ***/
  38450. #endif
  38451. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  38452. /*** Start of inlined file: juce_CodeDocument.h ***/
  38453. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  38454. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  38455. class CodeDocumentLine;
  38456. /**
  38457. A class for storing and manipulating a source code file.
  38458. When using a CodeEditorComponent, it takes one of these as its source object.
  38459. The CodeDocument stores its content as an array of lines, which makes it
  38460. quick to insert and delete.
  38461. @see CodeEditorComponent
  38462. */
  38463. class JUCE_API CodeDocument
  38464. {
  38465. public:
  38466. /** Creates a new, empty document.
  38467. */
  38468. CodeDocument();
  38469. /** Destructor. */
  38470. ~CodeDocument();
  38471. /** A position in a code document.
  38472. Using this class you can find a position in a code document and quickly get its
  38473. character position, line, and index. By calling setPositionMaintained (true), the
  38474. position is automatically updated when text is inserted or deleted in the document,
  38475. so that it maintains its original place in the text.
  38476. */
  38477. class JUCE_API Position
  38478. {
  38479. public:
  38480. /** Creates an uninitialised postion.
  38481. Don't attempt to call any methods on this until you've given it an owner document
  38482. to refer to!
  38483. */
  38484. Position() throw();
  38485. /** Creates a position based on a line and index in a document.
  38486. Note that this index is NOT the column number, it's the number of characters from the
  38487. start of the line. The "column" number isn't quite the same, because if the line
  38488. contains any tab characters, the relationship of the index to its visual column depends on
  38489. the number of spaces per tab being used!
  38490. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  38491. they will be adjusted to keep them within its limits.
  38492. */
  38493. Position (const CodeDocument* ownerDocument,
  38494. int line, int indexInLine) throw();
  38495. /** Creates a position based on a character index in a document.
  38496. This position is placed at the specified number of characters from the start of the
  38497. document. The line and column are auto-calculated.
  38498. If the position is beyond the range of the document, it'll be adjusted to keep it
  38499. inside.
  38500. */
  38501. Position (const CodeDocument* ownerDocument,
  38502. int charactersFromStartOfDocument) throw();
  38503. /** Creates a copy of another position.
  38504. This will copy the position, but the new object will not be set to maintain its position,
  38505. even if the source object was set to do so.
  38506. */
  38507. Position (const Position& other) throw();
  38508. /** Destructor. */
  38509. ~Position();
  38510. Position& operator= (const Position& other);
  38511. bool operator== (const Position& other) const throw();
  38512. bool operator!= (const Position& other) const throw();
  38513. /** Points this object at a new position within the document.
  38514. If the position is beyond the range of the document, it'll be adjusted to keep it
  38515. inside.
  38516. @see getPosition, setLineAndIndex
  38517. */
  38518. void setPosition (int charactersFromStartOfDocument);
  38519. /** Returns the position as the number of characters from the start of the document.
  38520. @see setPosition, getLineNumber, getIndexInLine
  38521. */
  38522. int getPosition() const throw() { return characterPos; }
  38523. /** Moves the position to a new line and index within the line.
  38524. Note that the index is NOT the column at which the position appears in an editor.
  38525. If the line contains any tab characters, the relationship of the index to its
  38526. visual position depends on the number of spaces per tab being used!
  38527. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  38528. they will be adjusted to keep them within its limits.
  38529. */
  38530. void setLineAndIndex (int newLine, int newIndexInLine);
  38531. /** Returns the line number of this position.
  38532. The first line in the document is numbered zero, not one!
  38533. */
  38534. int getLineNumber() const throw() { return line; }
  38535. /** Returns the number of characters from the start of the line.
  38536. Note that this value is NOT the column at which the position appears in an editor.
  38537. If the line contains any tab characters, the relationship of the index to its
  38538. visual position depends on the number of spaces per tab being used!
  38539. */
  38540. int getIndexInLine() const throw() { return indexInLine; }
  38541. /** Allows the position to be automatically updated when the document changes.
  38542. If this is set to true, the positon will register with its document so that
  38543. when the document has text inserted or deleted, this position will be automatically
  38544. moved to keep it at the same position in the text.
  38545. */
  38546. void setPositionMaintained (bool isMaintained);
  38547. /** Moves the position forwards or backwards by the specified number of characters.
  38548. @see movedBy
  38549. */
  38550. void moveBy (int characterDelta);
  38551. /** Returns a position which is the same as this one, moved by the specified number of
  38552. characters.
  38553. @see moveBy
  38554. */
  38555. const Position movedBy (int characterDelta) const;
  38556. /** Returns a position which is the same as this one, moved up or down by the specified
  38557. number of lines.
  38558. @see movedBy
  38559. */
  38560. const Position movedByLines (int deltaLines) const;
  38561. /** Returns the character in the document at this position.
  38562. @see getLineText
  38563. */
  38564. const juce_wchar getCharacter() const;
  38565. /** Returns the line from the document that this position is within.
  38566. @see getCharacter, getLineNumber
  38567. */
  38568. const String getLineText() const;
  38569. private:
  38570. CodeDocument* owner;
  38571. int characterPos, line, indexInLine;
  38572. bool positionMaintained;
  38573. };
  38574. /** Returns the full text of the document. */
  38575. const String getAllContent() const;
  38576. /** Returns a section of the document's text. */
  38577. const String getTextBetween (const Position& start, const Position& end) const;
  38578. /** Returns a line from the document. */
  38579. const String getLine (int lineIndex) const throw();
  38580. /** Returns the number of characters in the document. */
  38581. int getNumCharacters() const throw();
  38582. /** Returns the number of lines in the document. */
  38583. int getNumLines() const throw() { return lines.size(); }
  38584. /** Returns the number of characters in the longest line of the document. */
  38585. int getMaximumLineLength() throw();
  38586. /** Deletes a section of the text.
  38587. This operation is undoable.
  38588. */
  38589. void deleteSection (const Position& startPosition, const Position& endPosition);
  38590. /** Inserts some text into the document at a given position.
  38591. This operation is undoable.
  38592. */
  38593. void insertText (const Position& position, const String& text);
  38594. /** Clears the document and replaces it with some new text.
  38595. This operation is undoable - if you're trying to completely reset the document, you
  38596. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  38597. */
  38598. void replaceAllContent (const String& newContent);
  38599. /** Replaces the editor's contents with the contents of a stream.
  38600. This will also reset the undo history and save point marker.
  38601. */
  38602. bool loadFromStream (InputStream& stream);
  38603. /** Writes the editor's current contents to a stream. */
  38604. bool writeToStream (OutputStream& stream);
  38605. /** Returns the preferred new-line characters for the document.
  38606. This will be either "\n", "\r\n", or (rarely) "\r".
  38607. @see setNewLineCharacters
  38608. */
  38609. const String getNewLineCharacters() const throw() { return newLineChars; }
  38610. /** Sets the new-line characters that the document should use.
  38611. The string must be either "\n", "\r\n", or (rarely) "\r".
  38612. @see getNewLineCharacters
  38613. */
  38614. void setNewLineCharacters (const String& newLine) throw();
  38615. /** Begins a new undo transaction.
  38616. The document itself will not call this internally, so relies on whatever is using the
  38617. document to periodically call this to break up the undo sequence into sensible chunks.
  38618. @see UndoManager::beginNewTransaction
  38619. */
  38620. void newTransaction();
  38621. /** Undo the last operation.
  38622. @see UndoManager::undo
  38623. */
  38624. void undo();
  38625. /** Redo the last operation.
  38626. @see UndoManager::redo
  38627. */
  38628. void redo();
  38629. /** Clears the undo history.
  38630. @see UndoManager::clearUndoHistory
  38631. */
  38632. void clearUndoHistory();
  38633. /** Returns the document's UndoManager */
  38634. UndoManager& getUndoManager() throw() { return undoManager; }
  38635. /** Makes a note that the document's current state matches the one that is saved.
  38636. After this has been called, hasChangedSinceSavePoint() will return false until
  38637. the document has been altered, and then it'll start returning true. If the document is
  38638. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  38639. will again return false.
  38640. @see hasChangedSinceSavePoint
  38641. */
  38642. void setSavePoint() throw();
  38643. /** Returns true if the state of the document differs from the state it was in when
  38644. setSavePoint() was last called.
  38645. @see setSavePoint
  38646. */
  38647. bool hasChangedSinceSavePoint() const throw();
  38648. /** Searches for a word-break. */
  38649. const Position findWordBreakAfter (const Position& position) const throw();
  38650. /** Searches for a word-break. */
  38651. const Position findWordBreakBefore (const Position& position) const throw();
  38652. /** An object that receives callbacks from the CodeDocument when its text changes.
  38653. @see CodeDocument::addListener, CodeDocument::removeListener
  38654. */
  38655. class JUCE_API Listener
  38656. {
  38657. public:
  38658. Listener() {}
  38659. virtual ~Listener() {}
  38660. /** Called by a CodeDocument when it is altered.
  38661. */
  38662. virtual void codeDocumentChanged (const Position& affectedTextStart,
  38663. const Position& affectedTextEnd) = 0;
  38664. };
  38665. /** Registers a listener object to receive callbacks when the document changes.
  38666. If the listener is already registered, this method has no effect.
  38667. @see removeListener
  38668. */
  38669. void addListener (Listener* listener) throw();
  38670. /** Deregisters a listener.
  38671. @see addListener
  38672. */
  38673. void removeListener (Listener* listener) throw();
  38674. /** Iterates the text in a CodeDocument.
  38675. This class lets you read characters from a CodeDocument. It's designed to be used
  38676. by a SyntaxAnalyser object.
  38677. @see CodeDocument, SyntaxAnalyser
  38678. */
  38679. class JUCE_API Iterator
  38680. {
  38681. public:
  38682. Iterator (CodeDocument* document);
  38683. Iterator (const Iterator& other);
  38684. Iterator& operator= (const Iterator& other) throw();
  38685. ~Iterator() throw();
  38686. /** Reads the next character and returns it.
  38687. @see peekNextChar
  38688. */
  38689. juce_wchar nextChar();
  38690. /** Reads the next character without advancing the current position. */
  38691. juce_wchar peekNextChar() const;
  38692. /** Advances the position by one character. */
  38693. void skip();
  38694. /** Returns the position of the next character as its position within the
  38695. whole document.
  38696. */
  38697. int getPosition() const throw() { return position; }
  38698. /** Skips over any whitespace characters until the next character is non-whitespace. */
  38699. void skipWhitespace();
  38700. /** Skips forward until the next character will be the first character on the next line */
  38701. void skipToEndOfLine();
  38702. /** Returns the line number of the next character. */
  38703. int getLine() const throw() { return line; }
  38704. /** Returns true if the iterator has reached the end of the document. */
  38705. bool isEOF() const throw();
  38706. private:
  38707. CodeDocument* document;
  38708. mutable String::CharPointerType charPointer;
  38709. int line, position;
  38710. };
  38711. private:
  38712. friend class CodeDocumentInsertAction;
  38713. friend class CodeDocumentDeleteAction;
  38714. friend class Iterator;
  38715. friend class Position;
  38716. OwnedArray <CodeDocumentLine> lines;
  38717. Array <Position*> positionsToMaintain;
  38718. UndoManager undoManager;
  38719. int currentActionIndex, indexOfSavedState;
  38720. int maximumLineLength;
  38721. ListenerList <Listener> listeners;
  38722. String newLineChars;
  38723. void sendListenerChangeMessage (int startLine, int endLine);
  38724. void insert (const String& text, int insertPos, bool undoable);
  38725. void remove (int startPos, int endPos, bool undoable);
  38726. void checkLastLineStatus();
  38727. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeDocument);
  38728. };
  38729. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  38730. /*** End of inlined file: juce_CodeDocument.h ***/
  38731. #endif
  38732. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38733. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  38734. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38735. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38736. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  38737. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  38738. #define __JUCE_CODETOKENISER_JUCEHEADER__
  38739. /**
  38740. A base class for tokenising code so that the syntax can be displayed in a
  38741. code editor.
  38742. @see CodeDocument, CodeEditorComponent
  38743. */
  38744. class JUCE_API CodeTokeniser
  38745. {
  38746. public:
  38747. CodeTokeniser() {}
  38748. virtual ~CodeTokeniser() {}
  38749. /** Reads the next token from the source and returns its token type.
  38750. This must leave the source pointing to the first character in the
  38751. next token.
  38752. */
  38753. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  38754. /** Returns a list of the names of the token types this analyser uses.
  38755. The index in this list must match the token type numbers that are
  38756. returned by readNextToken().
  38757. */
  38758. virtual const StringArray getTokenTypes() = 0;
  38759. /** Returns a suggested syntax highlighting colour for a specified
  38760. token type.
  38761. */
  38762. virtual const Colour getDefaultColour (int tokenType) = 0;
  38763. private:
  38764. JUCE_LEAK_DETECTOR (CodeTokeniser);
  38765. };
  38766. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  38767. /*** End of inlined file: juce_CodeTokeniser.h ***/
  38768. /**
  38769. A text editor component designed specifically for source code.
  38770. This is designed to handle syntax highlighting and fast editing of very large
  38771. files.
  38772. */
  38773. class JUCE_API CodeEditorComponent : public Component,
  38774. public TextInputTarget,
  38775. public Timer,
  38776. public ScrollBar::Listener,
  38777. public CodeDocument::Listener,
  38778. public AsyncUpdater
  38779. {
  38780. public:
  38781. /** Creates an editor for a document.
  38782. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  38783. The object that you pass in is not owned or deleted by the editor - you must
  38784. make sure that it doesn't get deleted while this component is still using it.
  38785. @see CodeDocument
  38786. */
  38787. CodeEditorComponent (CodeDocument& document,
  38788. CodeTokeniser* codeTokeniser);
  38789. /** Destructor. */
  38790. ~CodeEditorComponent();
  38791. /** Returns the code document that this component is editing. */
  38792. CodeDocument& getDocument() const throw() { return document; }
  38793. /** Loads the given content into the document.
  38794. This will completely reset the CodeDocument object, clear its undo history,
  38795. and fill it with this text.
  38796. */
  38797. void loadContent (const String& newContent);
  38798. /** Returns the standard character width. */
  38799. float getCharWidth() const throw() { return charWidth; }
  38800. /** Returns the height of a line of text, in pixels. */
  38801. int getLineHeight() const throw() { return lineHeight; }
  38802. /** Returns the number of whole lines visible on the screen,
  38803. This doesn't include a cut-off line that might be visible at the bottom if the
  38804. component's height isn't an exact multiple of the line-height.
  38805. */
  38806. int getNumLinesOnScreen() const throw() { return linesOnScreen; }
  38807. /** Returns the number of whole columns visible on the screen.
  38808. This doesn't include any cut-off columns at the right-hand edge.
  38809. */
  38810. int getNumColumnsOnScreen() const throw() { return columnsOnScreen; }
  38811. /** Returns the current caret position. */
  38812. const CodeDocument::Position getCaretPos() const { return caretPos; }
  38813. /** Moves the caret.
  38814. If selecting is true, the section of the document between the current
  38815. caret position and the new one will become selected. If false, any currently
  38816. selected region will be deselected.
  38817. */
  38818. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  38819. /** Returns the on-screen position of a character in the document.
  38820. The rectangle returned is relative to this component's top-left origin.
  38821. */
  38822. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const;
  38823. /** Finds the character at a given on-screen position.
  38824. The co-ordinates are relative to this component's top-left origin.
  38825. */
  38826. const CodeDocument::Position getPositionAt (int x, int y);
  38827. void cursorLeft (bool moveInWholeWordSteps, bool selecting);
  38828. void cursorRight (bool moveInWholeWordSteps, bool selecting);
  38829. void cursorDown (bool selecting);
  38830. void cursorUp (bool selecting);
  38831. void pageDown (bool selecting);
  38832. void pageUp (bool selecting);
  38833. void scrollDown();
  38834. void scrollUp();
  38835. void scrollToLine (int newFirstLineOnScreen);
  38836. void scrollBy (int deltaLines);
  38837. void scrollToColumn (int newFirstColumnOnScreen);
  38838. void scrollToKeepCaretOnScreen();
  38839. void goToStartOfDocument (bool selecting);
  38840. void goToStartOfLine (bool selecting);
  38841. void goToEndOfDocument (bool selecting);
  38842. void goToEndOfLine (bool selecting);
  38843. void deselectAll();
  38844. void selectAll();
  38845. void insertTextAtCaret (const String& textToInsert);
  38846. void insertTabAtCaret();
  38847. void cut();
  38848. void copy();
  38849. void copyThenCut();
  38850. void paste();
  38851. void backspace (bool moveInWholeWordSteps);
  38852. void deleteForward (bool moveInWholeWordSteps);
  38853. void undo();
  38854. void redo();
  38855. const Range<int> getHighlightedRegion() const;
  38856. void setHighlightedRegion (const Range<int>& newRange);
  38857. const String getTextInRange (const Range<int>& range) const;
  38858. /** Changes the current tab settings.
  38859. This lets you change the tab size and whether pressing the tab key inserts a
  38860. tab character, or its equivalent number of spaces.
  38861. */
  38862. void setTabSize (int numSpacesPerTab, bool insertSpacesInsteadOfTabCharacters);
  38863. /** Returns the current number of spaces per tab.
  38864. @see setTabSize
  38865. */
  38866. int getTabSize() const throw() { return spacesPerTab; }
  38867. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  38868. @see setTabSize
  38869. */
  38870. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  38871. /** Changes the font.
  38872. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  38873. */
  38874. void setFont (const Font& newFont);
  38875. /** Returns the font that the editor is using. */
  38876. const Font& getFont() const throw() { return font; }
  38877. /** Resets the syntax highlighting colours to the default ones provided by the
  38878. code tokeniser.
  38879. @see CodeTokeniser::getDefaultColour
  38880. */
  38881. void resetToDefaultColours();
  38882. /** Changes one of the syntax highlighting colours.
  38883. The token type values are dependent on the tokeniser being used - use
  38884. CodeTokeniser::getTokenTypes() to get a list of the token types.
  38885. @see getColourForTokenType
  38886. */
  38887. void setColourForTokenType (int tokenType, const Colour& colour);
  38888. /** Returns one of the syntax highlighting colours.
  38889. The token type values are dependent on the tokeniser being used - use
  38890. CodeTokeniser::getTokenTypes() to get a list of the token types.
  38891. @see setColourForTokenType
  38892. */
  38893. const Colour getColourForTokenType (int tokenType) const;
  38894. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  38895. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38896. methods.
  38897. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38898. */
  38899. enum ColourIds
  38900. {
  38901. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  38902. caretColourId = 0x1004501, /**< The colour to draw the caret. */
  38903. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  38904. selected text. */
  38905. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  38906. enabled. */
  38907. };
  38908. /** Changes the size of the scrollbars. */
  38909. void setScrollbarThickness (int thickness);
  38910. /** Returns the thickness of the scrollbars. */
  38911. int getScrollbarThickness() const throw() { return scrollbarThickness; }
  38912. /** @internal */
  38913. void resized();
  38914. /** @internal */
  38915. void paint (Graphics& g);
  38916. /** @internal */
  38917. bool keyPressed (const KeyPress& key);
  38918. /** @internal */
  38919. void mouseDown (const MouseEvent& e);
  38920. /** @internal */
  38921. void mouseDrag (const MouseEvent& e);
  38922. /** @internal */
  38923. void mouseUp (const MouseEvent& e);
  38924. /** @internal */
  38925. void mouseDoubleClick (const MouseEvent& e);
  38926. /** @internal */
  38927. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  38928. /** @internal */
  38929. void focusGained (FocusChangeType cause);
  38930. /** @internal */
  38931. void focusLost (FocusChangeType cause);
  38932. /** @internal */
  38933. void timerCallback();
  38934. /** @internal */
  38935. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  38936. /** @internal */
  38937. void handleAsyncUpdate();
  38938. /** @internal */
  38939. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  38940. const CodeDocument::Position& affectedTextEnd);
  38941. /** @internal */
  38942. bool isTextInputActive() const;
  38943. private:
  38944. CodeDocument& document;
  38945. Font font;
  38946. int firstLineOnScreen, gutter, spacesPerTab;
  38947. float charWidth;
  38948. int lineHeight, linesOnScreen, columnsOnScreen;
  38949. int scrollbarThickness, columnToTryToMaintain;
  38950. bool useSpacesForTabs;
  38951. double xOffset;
  38952. CodeDocument::Position caretPos;
  38953. CodeDocument::Position selectionStart, selectionEnd;
  38954. class CaretComponent;
  38955. friend class ScopedPointer <CaretComponent>;
  38956. ScopedPointer<CaretComponent> caret;
  38957. ScrollBar verticalScrollBar, horizontalScrollBar;
  38958. enum DragType
  38959. {
  38960. notDragging,
  38961. draggingSelectionStart,
  38962. draggingSelectionEnd
  38963. };
  38964. DragType dragType;
  38965. CodeTokeniser* codeTokeniser;
  38966. Array <Colour> coloursForTokenCategories;
  38967. class CodeEditorLine;
  38968. OwnedArray <CodeEditorLine> lines;
  38969. void rebuildLineTokens();
  38970. OwnedArray <CodeDocument::Iterator> cachedIterators;
  38971. void clearCachedIterators (int firstLineToBeInvalid);
  38972. void updateCachedIterators (int maxLineNum);
  38973. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  38974. void moveLineDelta (int delta, bool selecting);
  38975. void updateScrollBars();
  38976. void scrollToLineInternal (int line);
  38977. void scrollToColumnInternal (double column);
  38978. void newTransaction();
  38979. int indexToColumn (int line, int index) const throw();
  38980. int columnToIndex (int line, int column) const throw();
  38981. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeEditorComponent);
  38982. };
  38983. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38984. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  38985. #endif
  38986. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  38987. #endif
  38988. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  38989. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  38990. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  38991. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  38992. /**
  38993. A simple lexical analyser for syntax colouring of C++ code.
  38994. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  38995. */
  38996. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  38997. {
  38998. public:
  38999. CPlusPlusCodeTokeniser();
  39000. ~CPlusPlusCodeTokeniser();
  39001. enum TokenType
  39002. {
  39003. tokenType_error = 0,
  39004. tokenType_comment,
  39005. tokenType_builtInKeyword,
  39006. tokenType_identifier,
  39007. tokenType_integerLiteral,
  39008. tokenType_floatLiteral,
  39009. tokenType_stringLiteral,
  39010. tokenType_operator,
  39011. tokenType_bracket,
  39012. tokenType_punctuation,
  39013. tokenType_preprocessor
  39014. };
  39015. int readNextToken (CodeDocument::Iterator& source);
  39016. const StringArray getTokenTypes();
  39017. const Colour getDefaultColour (int tokenType);
  39018. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  39019. static bool isReservedKeyword (const String& token) throw();
  39020. private:
  39021. JUCE_LEAK_DETECTOR (CPlusPlusCodeTokeniser);
  39022. };
  39023. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  39024. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  39025. #endif
  39026. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  39027. #endif
  39028. #ifndef __JUCE_LABEL_JUCEHEADER__
  39029. #endif
  39030. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  39031. #endif
  39032. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  39033. /*** Start of inlined file: juce_ProgressBar.h ***/
  39034. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  39035. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  39036. /**
  39037. A progress bar component.
  39038. To use this, just create one and make it visible. It'll run its own timer
  39039. to keep an eye on a variable that you give it, and will automatically
  39040. redraw itself when the variable changes.
  39041. For an easy way of running a background task with a dialog box showing its
  39042. progress, see the ThreadWithProgressWindow class.
  39043. @see ThreadWithProgressWindow
  39044. */
  39045. class JUCE_API ProgressBar : public Component,
  39046. public SettableTooltipClient,
  39047. private Timer
  39048. {
  39049. public:
  39050. /** Creates a ProgressBar.
  39051. @param progress pass in a reference to a double that you're going to
  39052. update with your task's progress. The ProgressBar will
  39053. monitor the value of this variable and will redraw itself
  39054. when the value changes. The range is from 0 to 1.0. Obviously
  39055. you'd better be careful not to delete this variable while the
  39056. ProgressBar still exists!
  39057. */
  39058. explicit ProgressBar (double& progress);
  39059. /** Destructor. */
  39060. ~ProgressBar();
  39061. /** Turns the percentage display on or off.
  39062. By default this is on, and the progress bar will display a text string showing
  39063. its current percentage.
  39064. */
  39065. void setPercentageDisplay (bool shouldDisplayPercentage);
  39066. /** Gives the progress bar a string to display inside it.
  39067. If you call this, it will turn off the percentage display.
  39068. @see setPercentageDisplay
  39069. */
  39070. void setTextToDisplay (const String& text);
  39071. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  39072. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39073. methods.
  39074. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39075. */
  39076. enum ColourIds
  39077. {
  39078. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  39079. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  39080. classes will probably use variations on this colour. */
  39081. };
  39082. protected:
  39083. /** @internal */
  39084. void paint (Graphics& g);
  39085. /** @internal */
  39086. void lookAndFeelChanged();
  39087. /** @internal */
  39088. void visibilityChanged();
  39089. /** @internal */
  39090. void colourChanged();
  39091. private:
  39092. double& progress;
  39093. double currentValue;
  39094. bool displayPercentage;
  39095. String displayedMessage, currentMessage;
  39096. uint32 lastCallbackTime;
  39097. void timerCallback();
  39098. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProgressBar);
  39099. };
  39100. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  39101. /*** End of inlined file: juce_ProgressBar.h ***/
  39102. #endif
  39103. #ifndef __JUCE_SLIDER_JUCEHEADER__
  39104. /*** Start of inlined file: juce_Slider.h ***/
  39105. #ifndef __JUCE_SLIDER_JUCEHEADER__
  39106. #define __JUCE_SLIDER_JUCEHEADER__
  39107. #if JUCE_VC6
  39108. #define Listener LabelListener
  39109. #endif
  39110. /**
  39111. A slider control for changing a value.
  39112. The slider can be horizontal, vertical, or rotary, and can optionally have
  39113. a text-box inside it to show an editable display of the current value.
  39114. To use it, create a Slider object and use the setSliderStyle() method
  39115. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  39116. To define the values that it can be set to, see the setRange() and setValue() methods.
  39117. There are also lots of custom tweaks you can do by subclassing and overriding
  39118. some of the virtual methods, such as changing the scaling, changing the format of
  39119. the text display, custom ways of limiting the values, etc.
  39120. You can register Slider::Listener objects with a slider, and they'll be called when
  39121. the value changes.
  39122. @see Slider::Listener
  39123. */
  39124. class JUCE_API Slider : public Component,
  39125. public SettableTooltipClient,
  39126. public AsyncUpdater,
  39127. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  39128. public LabelListener,
  39129. public ValueListener
  39130. {
  39131. public:
  39132. /** Creates a slider.
  39133. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  39134. setRange(), etc.
  39135. */
  39136. explicit Slider (const String& componentName = String::empty);
  39137. /** Destructor. */
  39138. ~Slider();
  39139. /** The types of slider available.
  39140. @see setSliderStyle, setRotaryParameters
  39141. */
  39142. enum SliderStyle
  39143. {
  39144. LinearHorizontal, /**< A traditional horizontal slider. */
  39145. LinearVertical, /**< A traditional vertical slider. */
  39146. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  39147. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  39148. @see setRotaryParameters */
  39149. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  39150. @see setRotaryParameters */
  39151. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  39152. @see setRotaryParameters */
  39153. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  39154. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  39155. @see setMinValue, setMaxValue */
  39156. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  39157. @see setMinValue, setMaxValue */
  39158. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  39159. value, with the current value being somewhere between them.
  39160. @see setMinValue, setMaxValue */
  39161. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  39162. value, with the current value being somewhere between them.
  39163. @see setMinValue, setMaxValue */
  39164. };
  39165. /** Changes the type of slider interface being used.
  39166. @param newStyle the type of interface
  39167. @see setRotaryParameters, setVelocityBasedMode,
  39168. */
  39169. void setSliderStyle (SliderStyle newStyle);
  39170. /** Returns the slider's current style.
  39171. @see setSliderStyle
  39172. */
  39173. SliderStyle getSliderStyle() const throw() { return style; }
  39174. /** Changes the properties of a rotary slider.
  39175. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  39176. the slider's minimum value is represented
  39177. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  39178. the slider's maximum value is represented. This must be
  39179. greater than startAngleRadians
  39180. @param stopAtEnd if true, then when the slider is dragged around past the
  39181. minimum or maximum, it'll stop there; if false, it'll wrap
  39182. back to the opposite value
  39183. */
  39184. void setRotaryParameters (float startAngleRadians,
  39185. float endAngleRadians,
  39186. bool stopAtEnd);
  39187. /** Sets the distance the mouse has to move to drag the slider across
  39188. the full extent of its range.
  39189. This only applies when in modes like RotaryHorizontalDrag, where it's using
  39190. relative mouse movements to adjust the slider.
  39191. */
  39192. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  39193. /** Returns the current sensitivity value set by setMouseDragSensitivity(). */
  39194. int getMouseDragSensitivity() const throw() { return pixelsForFullDragExtent; }
  39195. /** Changes the way the the mouse is used when dragging the slider.
  39196. If true, this will turn on velocity-sensitive dragging, so that
  39197. the faster the mouse moves, the bigger the movement to the slider. This
  39198. helps when making accurate adjustments if the slider's range is quite large.
  39199. If false, the slider will just try to snap to wherever the mouse is.
  39200. */
  39201. void setVelocityBasedMode (bool isVelocityBased);
  39202. /** Returns true if velocity-based mode is active.
  39203. @see setVelocityBasedMode
  39204. */
  39205. bool getVelocityBasedMode() const throw() { return isVelocityBased; }
  39206. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  39207. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  39208. or if you're holding down ctrl.
  39209. @param sensitivity higher values than 1.0 increase the range of acceleration used
  39210. @param threshold the minimum number of pixels that the mouse needs to move for it
  39211. to be treated as a movement
  39212. @param offset values greater than 0.0 increase the minimum speed that will be used when
  39213. the threshold is reached
  39214. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  39215. key to toggle velocity-sensitive mode
  39216. */
  39217. void setVelocityModeParameters (double sensitivity = 1.0,
  39218. int threshold = 1,
  39219. double offset = 0.0,
  39220. bool userCanPressKeyToSwapMode = true);
  39221. /** Returns the velocity sensitivity setting.
  39222. @see setVelocityModeParameters
  39223. */
  39224. double getVelocitySensitivity() const throw() { return velocityModeSensitivity; }
  39225. /** Returns the velocity threshold setting.
  39226. @see setVelocityModeParameters
  39227. */
  39228. int getVelocityThreshold() const throw() { return velocityModeThreshold; }
  39229. /** Returns the velocity offset setting.
  39230. @see setVelocityModeParameters
  39231. */
  39232. double getVelocityOffset() const throw() { return velocityModeOffset; }
  39233. /** Returns the velocity user key setting.
  39234. @see setVelocityModeParameters
  39235. */
  39236. bool getVelocityModeIsSwappable() const throw() { return userKeyOverridesVelocity; }
  39237. /** Sets up a skew factor to alter the way values are distributed.
  39238. You may want to use a range of values on the slider where more accuracy
  39239. is required towards one end of the range, so this will logarithmically
  39240. spread the values across the length of the slider.
  39241. If the factor is < 1.0, the lower end of the range will fill more of the
  39242. slider's length; if the factor is > 1.0, the upper end of the range
  39243. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  39244. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  39245. method instead.
  39246. @see getSkewFactor, setSkewFactorFromMidPoint
  39247. */
  39248. void setSkewFactor (double factor);
  39249. /** Sets up a skew factor to alter the way values are distributed.
  39250. This allows you to specify the slider value that should appear in the
  39251. centre of the slider's visible range.
  39252. @see setSkewFactor, getSkewFactor
  39253. */
  39254. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  39255. /** Returns the current skew factor.
  39256. See setSkewFactor for more info.
  39257. @see setSkewFactor, setSkewFactorFromMidPoint
  39258. */
  39259. double getSkewFactor() const throw() { return skewFactor; }
  39260. /** Used by setIncDecButtonsMode().
  39261. */
  39262. enum IncDecButtonMode
  39263. {
  39264. incDecButtonsNotDraggable,
  39265. incDecButtonsDraggable_AutoDirection,
  39266. incDecButtonsDraggable_Horizontal,
  39267. incDecButtonsDraggable_Vertical
  39268. };
  39269. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  39270. can be dragged on the buttons to drag the values.
  39271. By default this is turned off. When enabled, clicking on the buttons still works
  39272. them as normal, but by holding down the mouse on a button and dragging it a little
  39273. distance, it flips into a mode where the value can be dragged. The drag direction can
  39274. either be set explicitly to be vertical or horizontal, or can be set to
  39275. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  39276. are side-by-side or above each other.
  39277. */
  39278. void setIncDecButtonsMode (IncDecButtonMode mode);
  39279. /** The position of the slider's text-entry box.
  39280. @see setTextBoxStyle
  39281. */
  39282. enum TextEntryBoxPosition
  39283. {
  39284. NoTextBox, /**< Doesn't display a text box. */
  39285. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  39286. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  39287. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  39288. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  39289. };
  39290. /** Changes the location and properties of the text-entry box.
  39291. @param newPosition where it should go (or NoTextBox to not have one at all)
  39292. @param isReadOnly if true, it's a read-only display
  39293. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  39294. room for the slider as well!
  39295. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  39296. room for the slider as well!
  39297. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  39298. */
  39299. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  39300. bool isReadOnly,
  39301. int textEntryBoxWidth,
  39302. int textEntryBoxHeight);
  39303. /** Returns the status of the text-box.
  39304. @see setTextBoxStyle
  39305. */
  39306. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  39307. /** Returns the width used for the text-box.
  39308. @see setTextBoxStyle
  39309. */
  39310. int getTextBoxWidth() const throw() { return textBoxWidth; }
  39311. /** Returns the height used for the text-box.
  39312. @see setTextBoxStyle
  39313. */
  39314. int getTextBoxHeight() const throw() { return textBoxHeight; }
  39315. /** Makes the text-box editable.
  39316. By default this is true, and the user can enter values into the textbox,
  39317. but it can be turned off if that's not suitable.
  39318. @see setTextBoxStyle, getValueFromText, getTextFromValue
  39319. */
  39320. void setTextBoxIsEditable (bool shouldBeEditable);
  39321. /** Returns true if the text-box is read-only.
  39322. @see setTextBoxStyle
  39323. */
  39324. bool isTextBoxEditable() const { return editableText; }
  39325. /** If the text-box is editable, this will give it the focus so that the user can
  39326. type directly into it.
  39327. This is basically the effect as the user clicking on it.
  39328. */
  39329. void showTextBox();
  39330. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  39331. focus away from it.
  39332. @param discardCurrentEditorContents if true, the slider's value will be left
  39333. unchanged; if false, the current contents of the
  39334. text editor will be used to set the slider position
  39335. before it is hidden.
  39336. */
  39337. void hideTextBox (bool discardCurrentEditorContents);
  39338. /** Changes the slider's current value.
  39339. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  39340. that are registered, and will synchronously call the valueChanged() method in case subclasses
  39341. want to handle it.
  39342. @param newValue the new value to set - this will be restricted by the
  39343. minimum and maximum range, and will be snapped to the
  39344. nearest interval if one has been set
  39345. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  39346. any Slider::Listeners or the valueChanged() method
  39347. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  39348. synchronously; if false, it will be asynchronous
  39349. */
  39350. void setValue (double newValue,
  39351. bool sendUpdateMessage = true,
  39352. bool sendMessageSynchronously = false);
  39353. /** Returns the slider's current value. */
  39354. double getValue() const;
  39355. /** Returns the Value object that represents the slider's current position.
  39356. You can use this Value object to connect the slider's position to external values or setters,
  39357. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  39358. your own Value object.
  39359. @see Value, getMaxValue, getMinValueObject
  39360. */
  39361. Value& getValueObject() { return currentValue; }
  39362. /** Sets the limits that the slider's value can take.
  39363. @param newMinimum the lowest value allowed
  39364. @param newMaximum the highest value allowed
  39365. @param newInterval the steps in which the value is allowed to increase - if this
  39366. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  39367. */
  39368. void setRange (double newMinimum,
  39369. double newMaximum,
  39370. double newInterval = 0);
  39371. /** Returns the current maximum value.
  39372. @see setRange
  39373. */
  39374. double getMaximum() const { return maximum; }
  39375. /** Returns the current minimum value.
  39376. @see setRange
  39377. */
  39378. double getMinimum() const { return minimum; }
  39379. /** Returns the current step-size for values.
  39380. @see setRange
  39381. */
  39382. double getInterval() const { return interval; }
  39383. /** For a slider with two or three thumbs, this returns the lower of its values.
  39384. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  39385. A slider with three values also uses the normal getValue() and setValue() methods to
  39386. control the middle value.
  39387. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  39388. */
  39389. double getMinValue() const;
  39390. /** For a slider with two or three thumbs, this returns the lower of its values.
  39391. You can use this Value object to connect the slider's position to external values or setters,
  39392. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  39393. your own Value object.
  39394. @see Value, getMinValue, getMaxValueObject
  39395. */
  39396. Value& getMinValueObject() throw() { return valueMin; }
  39397. /** For a slider with two or three thumbs, this sets the lower of its values.
  39398. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  39399. that are registered, and will synchronously call the valueChanged() method in case subclasses
  39400. want to handle it.
  39401. @param newValue the new value to set - this will be restricted by the
  39402. minimum and maximum range, and will be snapped to the nearest
  39403. interval if one has been set.
  39404. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  39405. any Slider::Listeners or the valueChanged() method
  39406. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  39407. synchronously; if false, it will be asynchronous
  39408. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  39409. max value (in a two-value slider) or the mid value (in a three-value
  39410. slider). If false, then if this value goes beyond those values,
  39411. it will push them along with it.
  39412. @see getMinValue, setMaxValue, setValue
  39413. */
  39414. void setMinValue (double newValue,
  39415. bool sendUpdateMessage = true,
  39416. bool sendMessageSynchronously = false,
  39417. bool allowNudgingOfOtherValues = false);
  39418. /** For a slider with two or three thumbs, this returns the higher of its values.
  39419. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  39420. A slider with three values also uses the normal getValue() and setValue() methods to
  39421. control the middle value.
  39422. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  39423. */
  39424. double getMaxValue() const;
  39425. /** For a slider with two or three thumbs, this returns the higher of its values.
  39426. You can use this Value object to connect the slider's position to external values or setters,
  39427. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  39428. your own Value object.
  39429. @see Value, getMaxValue, getMinValueObject
  39430. */
  39431. Value& getMaxValueObject() throw() { return valueMax; }
  39432. /** For a slider with two or three thumbs, this sets the lower of its values.
  39433. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  39434. that are registered, and will synchronously call the valueChanged() method in case subclasses
  39435. want to handle it.
  39436. @param newValue the new value to set - this will be restricted by the
  39437. minimum and maximum range, and will be snapped to the nearest
  39438. interval if one has been set.
  39439. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  39440. any Slider::Listeners or the valueChanged() method
  39441. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  39442. synchronously; if false, it will be asynchronous
  39443. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  39444. min value (in a two-value slider) or the mid value (in a three-value
  39445. slider). If false, then if this value goes beyond those values,
  39446. it will push them along with it.
  39447. @see getMaxValue, setMinValue, setValue
  39448. */
  39449. void setMaxValue (double newValue,
  39450. bool sendUpdateMessage = true,
  39451. bool sendMessageSynchronously = false,
  39452. bool allowNudgingOfOtherValues = false);
  39453. /** For a slider with two or three thumbs, this sets the minimum and maximum thumb positions.
  39454. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  39455. that are registered, and will synchronously call the valueChanged() method in case subclasses
  39456. want to handle it.
  39457. @param newMinValue the new minimum value to set - this will be snapped to the
  39458. nearest interval if one has been set.
  39459. @param newMaxValue the new minimum value to set - this will be snapped to the
  39460. nearest interval if one has been set.
  39461. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  39462. any Slider::Listeners or the valueChanged() method
  39463. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  39464. synchronously; if false, it will be asynchronous
  39465. @see setMaxValue, setMinValue, setValue
  39466. */
  39467. void setMinAndMaxValues (double newMinValue, double newMaxValue,
  39468. bool sendUpdateMessage = true,
  39469. bool sendMessageSynchronously = false);
  39470. /** A class for receiving callbacks from a Slider.
  39471. To be told when a slider's value changes, you can register a Slider::Listener
  39472. object using Slider::addListener().
  39473. @see Slider::addListener, Slider::removeListener
  39474. */
  39475. class JUCE_API Listener
  39476. {
  39477. public:
  39478. /** Destructor. */
  39479. virtual ~Listener() {}
  39480. /** Called when the slider's value is changed.
  39481. This may be caused by dragging it, or by typing in its text entry box,
  39482. or by a call to Slider::setValue().
  39483. You can find out the new value using Slider::getValue().
  39484. @see Slider::valueChanged
  39485. */
  39486. virtual void sliderValueChanged (Slider* slider) = 0;
  39487. /** Called when the slider is about to be dragged.
  39488. This is called when a drag begins, then it's followed by multiple calls
  39489. to sliderValueChanged(), and then sliderDragEnded() is called after the
  39490. user lets go.
  39491. @see sliderDragEnded, Slider::startedDragging
  39492. */
  39493. virtual void sliderDragStarted (Slider* slider);
  39494. /** Called after a drag operation has finished.
  39495. @see sliderDragStarted, Slider::stoppedDragging
  39496. */
  39497. virtual void sliderDragEnded (Slider* slider);
  39498. };
  39499. /** Adds a listener to be called when this slider's value changes. */
  39500. void addListener (Listener* listener);
  39501. /** Removes a previously-registered listener. */
  39502. void removeListener (Listener* listener);
  39503. /** This lets you choose whether double-clicking moves the slider to a given position.
  39504. By default this is turned off, but it's handy if you want a double-click to act
  39505. as a quick way of resetting a slider. Just pass in the value you want it to
  39506. go to when double-clicked.
  39507. @see getDoubleClickReturnValue
  39508. */
  39509. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  39510. double valueToSetOnDoubleClick);
  39511. /** Returns the values last set by setDoubleClickReturnValue() method.
  39512. Sets isEnabled to true if double-click is enabled, and returns the value
  39513. that was set.
  39514. @see setDoubleClickReturnValue
  39515. */
  39516. double getDoubleClickReturnValue (bool& isEnabled) const;
  39517. /** Tells the slider whether to keep sending change messages while the user
  39518. is dragging the slider.
  39519. If set to true, a change message will only be sent when the user has
  39520. dragged the slider and let go. If set to false (the default), then messages
  39521. will be continuously sent as they drag it while the mouse button is still
  39522. held down.
  39523. */
  39524. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  39525. /** This lets you change whether the slider thumb jumps to the mouse position
  39526. when you click.
  39527. By default, this is true. If it's false, then the slider moves with relative
  39528. motion when you drag it.
  39529. This only applies to linear bars, and won't affect two- or three- value
  39530. sliders.
  39531. */
  39532. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  39533. /** If enabled, this gives the slider a pop-up bubble which appears while the
  39534. slider is being dragged.
  39535. This can be handy if your slider doesn't have a text-box, so that users can
  39536. see the value just when they're changing it.
  39537. If you pass a component as the parentComponentToUse parameter, the pop-up
  39538. bubble will be added as a child of that component when it's needed. If you
  39539. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  39540. transparent window, so if you're using an OS that can't do transparent windows
  39541. you'll have to add it to a parent component instead).
  39542. */
  39543. void setPopupDisplayEnabled (bool isEnabled,
  39544. Component* parentComponentToUse);
  39545. /** If this is set to true, then right-clicking on the slider will pop-up
  39546. a menu to let the user change the way it works.
  39547. By default this is turned off, but when turned on, the menu will include
  39548. things like velocity sensitivity, and for rotary sliders, whether they
  39549. use a linear or rotary mouse-drag to move them.
  39550. */
  39551. void setPopupMenuEnabled (bool menuEnabled);
  39552. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  39553. By default it's enabled.
  39554. */
  39555. void setScrollWheelEnabled (bool enabled);
  39556. /** Returns a number to indicate which thumb is currently being dragged by the
  39557. mouse.
  39558. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  39559. the maximum-value thumb, or -1 if none is currently down.
  39560. */
  39561. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  39562. /** Callback to indicate that the user is about to start dragging the slider.
  39563. @see Slider::Listener::sliderDragStarted
  39564. */
  39565. virtual void startedDragging();
  39566. /** Callback to indicate that the user has just stopped dragging the slider.
  39567. @see Slider::Listener::sliderDragEnded
  39568. */
  39569. virtual void stoppedDragging();
  39570. /** Callback to indicate that the user has just moved the slider.
  39571. @see Slider::Listener::sliderValueChanged
  39572. */
  39573. virtual void valueChanged();
  39574. /** Subclasses can override this to convert a text string to a value.
  39575. When the user enters something into the text-entry box, this method is
  39576. called to convert it to a value.
  39577. The default routine just tries to convert it to a double.
  39578. @see getTextFromValue
  39579. */
  39580. virtual double getValueFromText (const String& text);
  39581. /** Turns the slider's current value into a text string.
  39582. Subclasses can override this to customise the formatting of the text-entry box.
  39583. The default implementation just turns the value into a string, using
  39584. a number of decimal places based on the range interval. If a suffix string
  39585. has been set using setTextValueSuffix(), this will be appended to the text.
  39586. @see getValueFromText
  39587. */
  39588. virtual const String getTextFromValue (double value);
  39589. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  39590. a string.
  39591. This is used by the default implementation of getTextFromValue(), and is just
  39592. appended to the numeric value. For more advanced formatting, you can override
  39593. getTextFromValue() and do something else.
  39594. */
  39595. void setTextValueSuffix (const String& suffix);
  39596. /** Returns the suffix that was set by setTextValueSuffix(). */
  39597. const String getTextValueSuffix() const;
  39598. /** Allows a user-defined mapping of distance along the slider to its value.
  39599. The default implementation for this performs the skewing operation that
  39600. can be set up in the setSkewFactor() method. Override it if you need
  39601. some kind of custom mapping instead, but make sure you also implement the
  39602. inverse function in valueToProportionOfLength().
  39603. @param proportion a value 0 to 1.0, indicating a distance along the slider
  39604. @returns the slider value that is represented by this position
  39605. @see valueToProportionOfLength
  39606. */
  39607. virtual double proportionOfLengthToValue (double proportion);
  39608. /** Allows a user-defined mapping of value to the position of the slider along its length.
  39609. The default implementation for this performs the skewing operation that
  39610. can be set up in the setSkewFactor() method. Override it if you need
  39611. some kind of custom mapping instead, but make sure you also implement the
  39612. inverse function in proportionOfLengthToValue().
  39613. @param value a valid slider value, between the range of values specified in
  39614. setRange()
  39615. @returns a value 0 to 1.0 indicating the distance along the slider that
  39616. represents this value
  39617. @see proportionOfLengthToValue
  39618. */
  39619. virtual double valueToProportionOfLength (double value);
  39620. /** Returns the X or Y coordinate of a value along the slider's length.
  39621. If the slider is horizontal, this will be the X coordinate of the given
  39622. value, relative to the left of the slider. If it's vertical, then this will
  39623. be the Y coordinate, relative to the top of the slider.
  39624. If the slider is rotary, this will throw an assertion and return 0. If the
  39625. value is out-of-range, it will be constrained to the length of the slider.
  39626. */
  39627. float getPositionOfValue (double value);
  39628. /** This can be overridden to allow the slider to snap to user-definable values.
  39629. If overridden, it will be called when the user tries to move the slider to
  39630. a given position, and allows a subclass to sanity-check this value, possibly
  39631. returning a different value to use instead.
  39632. @param attemptedValue the value the user is trying to enter
  39633. @param userIsDragging true if the user is dragging with the mouse; false if
  39634. they are entering the value using the text box
  39635. @returns the value to use instead
  39636. */
  39637. virtual double snapValue (double attemptedValue, bool userIsDragging);
  39638. /** This can be called to force the text box to update its contents.
  39639. (Not normally needed, as this is done automatically).
  39640. */
  39641. void updateText();
  39642. /** True if the slider moves horizontally. */
  39643. bool isHorizontal() const;
  39644. /** True if the slider moves vertically. */
  39645. bool isVertical() const;
  39646. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  39647. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39648. methods.
  39649. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39650. */
  39651. enum ColourIds
  39652. {
  39653. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  39654. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  39655. and feel class how this is used. */
  39656. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  39657. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  39658. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  39659. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  39660. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  39661. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  39662. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  39663. };
  39664. protected:
  39665. /** @internal */
  39666. void labelTextChanged (Label*);
  39667. /** @internal */
  39668. void paint (Graphics& g);
  39669. /** @internal */
  39670. void resized();
  39671. /** @internal */
  39672. void mouseDown (const MouseEvent& e);
  39673. /** @internal */
  39674. void mouseUp (const MouseEvent& e);
  39675. /** @internal */
  39676. void mouseDrag (const MouseEvent& e);
  39677. /** @internal */
  39678. void mouseDoubleClick (const MouseEvent& e);
  39679. /** @internal */
  39680. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39681. /** @internal */
  39682. void modifierKeysChanged (const ModifierKeys& modifiers);
  39683. /** @internal */
  39684. void buttonClicked (Button* button);
  39685. /** @internal */
  39686. void lookAndFeelChanged();
  39687. /** @internal */
  39688. void enablementChanged();
  39689. /** @internal */
  39690. void focusOfChildComponentChanged (FocusChangeType cause);
  39691. /** @internal */
  39692. void handleAsyncUpdate();
  39693. /** @internal */
  39694. void colourChanged();
  39695. /** @internal */
  39696. void valueChanged (Value& value);
  39697. /** Returns the best number of decimal places to use when displaying numbers.
  39698. This is calculated from the slider's interval setting.
  39699. */
  39700. int getNumDecimalPlacesToDisplay() const throw() { return numDecimalPlaces; }
  39701. private:
  39702. ListenerList <Listener> listeners;
  39703. Value currentValue, valueMin, valueMax;
  39704. double lastCurrentValue, lastValueMin, lastValueMax;
  39705. double minimum, maximum, interval, doubleClickReturnValue;
  39706. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  39707. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  39708. int velocityModeThreshold;
  39709. float rotaryStart, rotaryEnd;
  39710. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  39711. int mouseDragStartX, mouseDragStartY;
  39712. int sliderRegionStart, sliderRegionSize;
  39713. int sliderBeingDragged;
  39714. int pixelsForFullDragExtent;
  39715. Rectangle<int> sliderRect;
  39716. String textSuffix;
  39717. SliderStyle style;
  39718. TextEntryBoxPosition textBoxPos;
  39719. int textBoxWidth, textBoxHeight;
  39720. IncDecButtonMode incDecButtonMode;
  39721. bool editableText : 1, doubleClickToValue : 1;
  39722. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  39723. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  39724. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  39725. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  39726. ScopedPointer<Label> valueBox;
  39727. ScopedPointer<Button> incButton, decButton;
  39728. class PopupDisplayComponent;
  39729. friend class PopupDisplayComponent;
  39730. friend class ScopedPointer <PopupDisplayComponent>;
  39731. ScopedPointer <PopupDisplayComponent> popupDisplay;
  39732. Component* parentForPopupDisplay;
  39733. float getLinearSliderPos (double value);
  39734. void restoreMouseIfHidden();
  39735. void sendDragStart();
  39736. void sendDragEnd();
  39737. double constrainedValue (double value) const;
  39738. void triggerChangeMessage (bool synchronous);
  39739. bool incDecDragDirectionIsHorizontal() const;
  39740. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Slider);
  39741. };
  39742. /** This typedef is just for compatibility with old code - newer code should use the Slider::Listener class directly. */
  39743. typedef Slider::Listener SliderListener;
  39744. #if JUCE_VC6
  39745. #undef Listener
  39746. #endif
  39747. #endif // __JUCE_SLIDER_JUCEHEADER__
  39748. /*** End of inlined file: juce_Slider.h ***/
  39749. #endif
  39750. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  39751. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  39752. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  39753. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  39754. /**
  39755. A component that displays a strip of column headings for a table, and allows these
  39756. to be resized, dragged around, etc.
  39757. This is just the component that goes at the top of a table. You can use it
  39758. directly for custom components, or to create a simple table, use the
  39759. TableListBox class.
  39760. To use one of these, create it and use addColumn() to add all the columns that you need.
  39761. Each column must be given a unique ID number that's used to refer to it.
  39762. @see TableListBox, TableHeaderComponent::Listener
  39763. */
  39764. class JUCE_API TableHeaderComponent : public Component,
  39765. private AsyncUpdater
  39766. {
  39767. public:
  39768. /** Creates an empty table header.
  39769. */
  39770. TableHeaderComponent();
  39771. /** Destructor. */
  39772. ~TableHeaderComponent();
  39773. /** A combination of these flags are passed into the addColumn() method to specify
  39774. the properties of a column.
  39775. */
  39776. enum ColumnPropertyFlags
  39777. {
  39778. 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. */
  39779. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  39780. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  39781. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  39782. 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. */
  39783. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  39784. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  39785. /** This set of default flags is used as the default parameter value in addColumn(). */
  39786. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  39787. /** A quick way of combining flags for a column that's not resizable. */
  39788. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  39789. /** A quick way of combining flags for a column that's not resizable or sortable. */
  39790. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  39791. /** A quick way of combining flags for a column that's not sortable. */
  39792. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  39793. };
  39794. /** Adds a column to the table.
  39795. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  39796. registered listeners.
  39797. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  39798. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  39799. a unique ID. This is used to identify the column later on, after the user may have
  39800. changed the order that they appear in
  39801. @param width the initial width of the column, in pixels
  39802. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  39803. if the 'resizable' flag is specified for this column
  39804. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  39805. if the 'resizable' flag is specified for this column
  39806. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  39807. properties of this column
  39808. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  39809. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  39810. all columns, not just the index amongst those that are currently visible
  39811. */
  39812. void addColumn (const String& columnName,
  39813. int columnId,
  39814. int width,
  39815. int minimumWidth = 30,
  39816. int maximumWidth = -1,
  39817. int propertyFlags = defaultFlags,
  39818. int insertIndex = -1);
  39819. /** Removes a column with the given ID.
  39820. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  39821. registered listeners.
  39822. */
  39823. void removeColumn (int columnIdToRemove);
  39824. /** Deletes all columns from the table.
  39825. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  39826. registered listeners.
  39827. */
  39828. void removeAllColumns();
  39829. /** Returns the number of columns in the table.
  39830. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  39831. return the total number of columns, including hidden ones.
  39832. @see isColumnVisible
  39833. */
  39834. int getNumColumns (bool onlyCountVisibleColumns) const;
  39835. /** Returns the name for a column.
  39836. @see setColumnName
  39837. */
  39838. const String getColumnName (int columnId) const;
  39839. /** Changes the name of a column. */
  39840. void setColumnName (int columnId, const String& newName);
  39841. /** Moves a column to a different index in the table.
  39842. @param columnId the column to move
  39843. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  39844. */
  39845. void moveColumn (int columnId, int newVisibleIndex);
  39846. /** Returns the width of one of the columns.
  39847. */
  39848. int getColumnWidth (int columnId) const;
  39849. /** Changes the width of a column.
  39850. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  39851. */
  39852. void setColumnWidth (int columnId, int newWidth);
  39853. /** Shows or hides a column.
  39854. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  39855. @see isColumnVisible
  39856. */
  39857. void setColumnVisible (int columnId, bool shouldBeVisible);
  39858. /** Returns true if this column is currently visible.
  39859. @see setColumnVisible
  39860. */
  39861. bool isColumnVisible (int columnId) const;
  39862. /** Changes the column which is the sort column.
  39863. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  39864. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  39865. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  39866. @see getSortColumnId, isSortedForwards, reSortTable
  39867. */
  39868. void setSortColumnId (int columnId, bool sortForwards);
  39869. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  39870. @see setSortColumnId, isSortedForwards
  39871. */
  39872. int getSortColumnId() const;
  39873. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  39874. @see setSortColumnId
  39875. */
  39876. bool isSortedForwards() const;
  39877. /** Triggers a re-sort of the table according to the current sort-column.
  39878. If you modifiy the table's contents, you can call this to signal that the table needs
  39879. to be re-sorted.
  39880. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  39881. tableSortOrderChanged() method of any listeners).
  39882. */
  39883. void reSortTable();
  39884. /** Returns the total width of all the visible columns in the table.
  39885. */
  39886. int getTotalWidth() const;
  39887. /** Returns the index of a given column.
  39888. If there's no such column ID, this will return -1.
  39889. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  39890. otherwise it'll return the index amongst all the columns, including any hidden ones.
  39891. */
  39892. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  39893. /** Returns the ID of the column at a given index.
  39894. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  39895. otherwise it'll count it amongst all the columns, including any hidden ones.
  39896. If the index is out-of-range, it'll return 0.
  39897. */
  39898. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  39899. /** Returns the rectangle containing of one of the columns.
  39900. The index is an index from 0 to the number of columns that are currently visible (hidden
  39901. ones are not counted). It returns a rectangle showing the position of the column relative
  39902. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  39903. */
  39904. const Rectangle<int> getColumnPosition (int index) const;
  39905. /** Finds the column ID at a given x-position in the component.
  39906. If there is a column at this point this returns its ID, or if not, it will return 0.
  39907. */
  39908. int getColumnIdAtX (int xToFind) const;
  39909. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  39910. entire width of the component.
  39911. By default this is disabled. Turning it on also means that when resizing a column, those
  39912. on the right will be squashed to fit.
  39913. */
  39914. void setStretchToFitActive (bool shouldStretchToFit);
  39915. /** Returns true if stretch-to-fit has been enabled.
  39916. @see setStretchToFitActive
  39917. */
  39918. bool isStretchToFitActive() const;
  39919. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  39920. specified width, keeping their relative proportions the same.
  39921. If the minimum widths of the columns are too wide to fit into this space, it may
  39922. actually end up wider.
  39923. */
  39924. void resizeAllColumnsToFit (int targetTotalWidth);
  39925. /** Enables or disables the pop-up menu.
  39926. The default menu allows the user to show or hide columns. You can add custom
  39927. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  39928. By default the menu is enabled.
  39929. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  39930. */
  39931. void setPopupMenuActive (bool hasMenu);
  39932. /** Returns true if the pop-up menu is enabled.
  39933. @see setPopupMenuActive
  39934. */
  39935. bool isPopupMenuActive() const;
  39936. /** Returns a string that encapsulates the table's current layout.
  39937. This can be restored later using restoreFromString(). It saves the order of
  39938. the columns, the currently-sorted column, and the widths.
  39939. @see restoreFromString
  39940. */
  39941. const String toString() const;
  39942. /** Restores the state of the table, based on a string previously created with
  39943. toString().
  39944. @see toString
  39945. */
  39946. void restoreFromString (const String& storedVersion);
  39947. /**
  39948. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  39949. You can register one of these objects for table events using TableHeaderComponent::addListener()
  39950. and TableHeaderComponent::removeListener().
  39951. @see TableHeaderComponent
  39952. */
  39953. class JUCE_API Listener
  39954. {
  39955. public:
  39956. Listener() {}
  39957. /** Destructor. */
  39958. virtual ~Listener() {}
  39959. /** This is called when some of the table's columns are added, removed, hidden,
  39960. or rearranged.
  39961. */
  39962. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  39963. /** This is called when one or more of the table's columns are resized.
  39964. */
  39965. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  39966. /** This is called when the column by which the table should be sorted is changed.
  39967. */
  39968. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  39969. /** This is called when the user begins or ends dragging one of the columns around.
  39970. When the user starts dragging a column, this is called with the ID of that
  39971. column. When they finish dragging, it is called again with 0 as the ID.
  39972. */
  39973. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  39974. int columnIdNowBeingDragged);
  39975. };
  39976. /** Adds a listener to be informed about things that happen to the header. */
  39977. void addListener (Listener* newListener);
  39978. /** Removes a previously-registered listener. */
  39979. void removeListener (Listener* listenerToRemove);
  39980. /** This can be overridden to handle a mouse-click on one of the column headers.
  39981. The default implementation will use this click to call getSortColumnId() and
  39982. change the sort order.
  39983. */
  39984. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  39985. /** This can be overridden to add custom items to the pop-up menu.
  39986. If you override this, you should call the superclass's method to add its
  39987. column show/hide items, if you want them on the menu as well.
  39988. Then to handle the result, override reactToMenuItem().
  39989. @see reactToMenuItem
  39990. */
  39991. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  39992. /** Override this to handle any custom items that you have added to the
  39993. pop-up menu with an addMenuItems() override.
  39994. If the menuReturnId isn't one of your own custom menu items, you'll need to
  39995. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  39996. handle the items that it had added.
  39997. @see addMenuItems
  39998. */
  39999. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  40000. /** @internal */
  40001. void paint (Graphics& g);
  40002. /** @internal */
  40003. void resized();
  40004. /** @internal */
  40005. void mouseMove (const MouseEvent&);
  40006. /** @internal */
  40007. void mouseEnter (const MouseEvent&);
  40008. /** @internal */
  40009. void mouseExit (const MouseEvent&);
  40010. /** @internal */
  40011. void mouseDown (const MouseEvent&);
  40012. /** @internal */
  40013. void mouseDrag (const MouseEvent&);
  40014. /** @internal */
  40015. void mouseUp (const MouseEvent&);
  40016. /** @internal */
  40017. const MouseCursor getMouseCursor();
  40018. /** Can be overridden for more control over the pop-up menu behaviour. */
  40019. virtual void showColumnChooserMenu (int columnIdClicked);
  40020. private:
  40021. struct ColumnInfo
  40022. {
  40023. String name;
  40024. int id, propertyFlags, width, minimumWidth, maximumWidth;
  40025. double lastDeliberateWidth;
  40026. bool isVisible() const;
  40027. };
  40028. OwnedArray <ColumnInfo> columns;
  40029. Array <Listener*> listeners;
  40030. ScopedPointer <Component> dragOverlayComp;
  40031. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  40032. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  40033. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  40034. ColumnInfo* getInfoForId (int columnId) const;
  40035. int visibleIndexToTotalIndex (int visibleIndex) const;
  40036. void sendColumnsChanged();
  40037. void handleAsyncUpdate();
  40038. void beginDrag (const MouseEvent&);
  40039. void endDrag (int finalIndex);
  40040. int getResizeDraggerAt (int mouseX) const;
  40041. void updateColumnUnderMouse (int x, int y);
  40042. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  40043. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableHeaderComponent);
  40044. };
  40045. /** This typedef is just for compatibility with old code - newer code should use the TableHeaderComponent::Listener class directly. */
  40046. typedef TableHeaderComponent::Listener TableHeaderListener;
  40047. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  40048. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  40049. #endif
  40050. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  40051. /*** Start of inlined file: juce_TableListBox.h ***/
  40052. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  40053. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  40054. /**
  40055. One of these is used by a TableListBox as the data model for the table's contents.
  40056. The virtual methods that you override in this class take care of drawing the
  40057. table cells, and reacting to events.
  40058. @see TableListBox
  40059. */
  40060. class JUCE_API TableListBoxModel
  40061. {
  40062. public:
  40063. TableListBoxModel() {}
  40064. /** Destructor. */
  40065. virtual ~TableListBoxModel() {}
  40066. /** This must return the number of rows currently in the table.
  40067. If the number of rows changes, you must call TableListBox::updateContent() to
  40068. cause it to refresh the list.
  40069. */
  40070. virtual int getNumRows() = 0;
  40071. /** This must draw the background behind one of the rows in the table.
  40072. The graphics context has its origin at the row's top-left, and your method
  40073. should fill the area specified by the width and height parameters.
  40074. */
  40075. virtual void paintRowBackground (Graphics& g,
  40076. int rowNumber,
  40077. int width, int height,
  40078. bool rowIsSelected) = 0;
  40079. /** This must draw one of the cells.
  40080. The graphics context's origin will already be set to the top-left of the cell,
  40081. whose size is specified by (width, height).
  40082. */
  40083. virtual void paintCell (Graphics& g,
  40084. int rowNumber,
  40085. int columnId,
  40086. int width, int height,
  40087. bool rowIsSelected) = 0;
  40088. /** This is used to create or update a custom component to go in a cell.
  40089. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  40090. and handle mouse clicks with cellClicked().
  40091. This method will be called whenever a custom component might need to be updated - e.g.
  40092. when the table is changed, or TableListBox::updateContent() is called.
  40093. If you don't need a custom component for the specified cell, then return 0.
  40094. If you do want a custom component, and the existingComponentToUpdate is null, then
  40095. this method must create a new component suitable for the cell, and return it.
  40096. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  40097. by this method. In this case, the method must either update it to make sure it's correctly representing
  40098. the given cell (which may be different from the one that the component was created for), or it can
  40099. delete this component and return a new one.
  40100. */
  40101. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  40102. Component* existingComponentToUpdate);
  40103. /** This callback is made when the user clicks on one of the cells in the table.
  40104. The mouse event's coordinates will be relative to the entire table row.
  40105. @see cellDoubleClicked, backgroundClicked
  40106. */
  40107. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  40108. /** This callback is made when the user clicks on one of the cells in the table.
  40109. The mouse event's coordinates will be relative to the entire table row.
  40110. @see cellClicked, backgroundClicked
  40111. */
  40112. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  40113. /** This can be overridden to react to the user double-clicking on a part of the list where
  40114. there are no rows.
  40115. @see cellClicked
  40116. */
  40117. virtual void backgroundClicked();
  40118. /** This callback is made when the table's sort order is changed.
  40119. This could be because the user has clicked a column header, or because the
  40120. TableHeaderComponent::setSortColumnId() method was called.
  40121. If you implement this, your method should re-sort the table using the given
  40122. column as the key.
  40123. */
  40124. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  40125. /** Returns the best width for one of the columns.
  40126. If you implement this method, you should measure the width of all the items
  40127. in this column, and return the best size.
  40128. Returning 0 means that the column shouldn't be changed.
  40129. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  40130. */
  40131. virtual int getColumnAutoSizeWidth (int columnId);
  40132. /** Returns a tooltip for a particular cell in the table.
  40133. */
  40134. virtual const String getCellTooltip (int rowNumber, int columnId);
  40135. /** Override this to be informed when rows are selected or deselected.
  40136. @see ListBox::selectedRowsChanged()
  40137. */
  40138. virtual void selectedRowsChanged (int lastRowSelected);
  40139. /** Override this to be informed when the delete key is pressed.
  40140. @see ListBox::deleteKeyPressed()
  40141. */
  40142. virtual void deleteKeyPressed (int lastRowSelected);
  40143. /** Override this to be informed when the return key is pressed.
  40144. @see ListBox::returnKeyPressed()
  40145. */
  40146. virtual void returnKeyPressed (int lastRowSelected);
  40147. /** Override this to be informed when the list is scrolled.
  40148. This might be caused by the user moving the scrollbar, or by programmatic changes
  40149. to the list position.
  40150. */
  40151. virtual void listWasScrolled();
  40152. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  40153. If this returns a non-empty name then when the user drags a row, the table will try to
  40154. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  40155. drag-and-drop operation, using this string as the source description, and the listbox
  40156. itself as the source component.
  40157. @see DragAndDropContainer::startDragging
  40158. */
  40159. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  40160. };
  40161. /**
  40162. A table of cells, using a TableHeaderComponent as its header.
  40163. This component makes it easy to create a table by providing a TableListBoxModel as
  40164. the data source.
  40165. @see TableListBoxModel, TableHeaderComponent
  40166. */
  40167. class JUCE_API TableListBox : public ListBox,
  40168. private ListBoxModel,
  40169. private TableHeaderComponent::Listener
  40170. {
  40171. public:
  40172. /** Creates a TableListBox.
  40173. The model pointer passed-in can be null, in which case you can set it later
  40174. with setModel().
  40175. */
  40176. TableListBox (const String& componentName = String::empty,
  40177. TableListBoxModel* model = 0);
  40178. /** Destructor. */
  40179. ~TableListBox();
  40180. /** Changes the TableListBoxModel that is being used for this table.
  40181. */
  40182. void setModel (TableListBoxModel* newModel);
  40183. /** Returns the model currently in use. */
  40184. TableListBoxModel* getModel() const { return model; }
  40185. /** Returns the header component being used in this table. */
  40186. TableHeaderComponent& getHeader() const { return *header; }
  40187. /** Sets the header component to use for the table.
  40188. The table will take ownership of the component that you pass in, and will delete it
  40189. when it's no longer needed.
  40190. */
  40191. void setHeader (TableHeaderComponent* newHeader);
  40192. /** Changes the height of the table header component.
  40193. @see getHeaderHeight
  40194. */
  40195. void setHeaderHeight (int newHeight);
  40196. /** Returns the height of the table header.
  40197. @see setHeaderHeight
  40198. */
  40199. int getHeaderHeight() const;
  40200. /** Resizes a column to fit its contents.
  40201. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  40202. and applies that to the column.
  40203. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  40204. */
  40205. void autoSizeColumn (int columnId);
  40206. /** Calls autoSizeColumn() for all columns in the table. */
  40207. void autoSizeAllColumns();
  40208. /** Enables or disables the auto size options on the popup menu.
  40209. By default, these are enabled.
  40210. */
  40211. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  40212. /** True if the auto-size options should be shown on the menu.
  40213. @see setAutoSizeMenuOptionsShown
  40214. */
  40215. bool isAutoSizeMenuOptionShown() const;
  40216. /** Returns the position of one of the cells in the table.
  40217. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  40218. the table component's top-left. The row number isn't checked to see if it's
  40219. in-range, but the column ID must exist or this will return an empty rectangle.
  40220. If relativeToComponentTopLeft is false, the co-ords are relative to the
  40221. top-left of the table's top-left cell.
  40222. */
  40223. const Rectangle<int> getCellPosition (int columnId, int rowNumber,
  40224. bool relativeToComponentTopLeft) const;
  40225. /** Returns the component that currently represents a given cell.
  40226. If the component for this cell is off-screen or if the position is out-of-range,
  40227. this may return 0.
  40228. @see getCellPosition
  40229. */
  40230. Component* getCellComponent (int columnId, int rowNumber) const;
  40231. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  40232. @see ListBox::scrollToEnsureRowIsOnscreen
  40233. */
  40234. void scrollToEnsureColumnIsOnscreen (int columnId);
  40235. /** @internal */
  40236. int getNumRows();
  40237. /** @internal */
  40238. void paintListBoxItem (int, Graphics&, int, int, bool);
  40239. /** @internal */
  40240. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  40241. /** @internal */
  40242. void selectedRowsChanged (int lastRowSelected);
  40243. /** @internal */
  40244. void deleteKeyPressed (int currentSelectedRow);
  40245. /** @internal */
  40246. void returnKeyPressed (int currentSelectedRow);
  40247. /** @internal */
  40248. void backgroundClicked();
  40249. /** @internal */
  40250. void listWasScrolled();
  40251. /** @internal */
  40252. void tableColumnsChanged (TableHeaderComponent*);
  40253. /** @internal */
  40254. void tableColumnsResized (TableHeaderComponent*);
  40255. /** @internal */
  40256. void tableSortOrderChanged (TableHeaderComponent*);
  40257. /** @internal */
  40258. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  40259. /** @internal */
  40260. void resized();
  40261. private:
  40262. TableHeaderComponent* header;
  40263. TableListBoxModel* model;
  40264. int columnIdNowBeingDragged;
  40265. bool autoSizeOptionsShown;
  40266. void updateColumnComponents() const;
  40267. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBox);
  40268. };
  40269. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  40270. /*** End of inlined file: juce_TableListBox.h ***/
  40271. #endif
  40272. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  40273. #endif
  40274. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  40275. #endif
  40276. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  40277. #endif
  40278. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40279. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  40280. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40281. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40282. /**
  40283. A factory object which can create ToolbarItemComponent objects.
  40284. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  40285. that it can create.
  40286. Each type of item is identified by a unique ID, and multiple instances of an
  40287. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  40288. bars).
  40289. @see Toolbar, ToolbarItemComponent, ToolbarButton
  40290. */
  40291. class JUCE_API ToolbarItemFactory
  40292. {
  40293. public:
  40294. ToolbarItemFactory();
  40295. /** Destructor. */
  40296. virtual ~ToolbarItemFactory();
  40297. /** A set of reserved item ID values, used for the built-in item types.
  40298. */
  40299. enum SpecialItemIds
  40300. {
  40301. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  40302. can be placed between sets of items to break them into groups. */
  40303. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  40304. items.*/
  40305. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  40306. either side of it, filling any available space. */
  40307. };
  40308. /** Must return a list of the IDs for all the item types that this factory can create.
  40309. The ids should be added to the array that is passed-in.
  40310. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  40311. and the predefined IDs in the SpecialItemIds enum.
  40312. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  40313. to this list if you want your toolbar to be able to contain those items.
  40314. The list returned here is used by the ToolbarItemPalette class to obtain its list
  40315. of available items, and their order on the palette will reflect the order in which
  40316. they appear on this list.
  40317. @see ToolbarItemPalette
  40318. */
  40319. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  40320. /** Must return the set of items that should be added to a toolbar as its default set.
  40321. This method is used by Toolbar::addDefaultItems() to determine which items to
  40322. create.
  40323. The items that your method adds to the array that is passed-in will be added to the
  40324. toolbar in the same order. Items can appear in the list more than once.
  40325. */
  40326. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  40327. /** Must create an instance of one of the items that the factory lists in its
  40328. getAllToolbarItemIds() method.
  40329. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  40330. method, except for the built-in item types from the SpecialItemIds enum, which
  40331. are created internally by the toolbar code.
  40332. Try not to keep a pointer to the object that is returned, as it will be deleted
  40333. automatically by the toolbar, and remember that multiple instances of the same
  40334. item type are likely to exist at the same time.
  40335. */
  40336. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  40337. };
  40338. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40339. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  40340. #endif
  40341. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  40342. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  40343. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  40344. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  40345. /**
  40346. A component containing a list of toolbar items, which the user can drag onto
  40347. a toolbar to add them.
  40348. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  40349. which automatically shows one of these in a dialog box with lots of extra controls.
  40350. @see Toolbar
  40351. */
  40352. class JUCE_API ToolbarItemPalette : public Component,
  40353. public DragAndDropContainer
  40354. {
  40355. public:
  40356. /** Creates a palette of items for a given factory, with the aim of adding them
  40357. to the specified toolbar.
  40358. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  40359. set of items that are shown in this palette.
  40360. The toolbar and factory must not be deleted while this object exists.
  40361. */
  40362. ToolbarItemPalette (ToolbarItemFactory& factory,
  40363. Toolbar* toolbar);
  40364. /** Destructor. */
  40365. ~ToolbarItemPalette();
  40366. /** @internal */
  40367. void resized();
  40368. private:
  40369. ToolbarItemFactory& factory;
  40370. Toolbar* toolbar;
  40371. Viewport viewport;
  40372. OwnedArray <ToolbarItemComponent> items;
  40373. friend class Toolbar;
  40374. void replaceComponent (ToolbarItemComponent* comp);
  40375. void addComponent (int itemId, int index);
  40376. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemPalette);
  40377. };
  40378. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  40379. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  40380. #endif
  40381. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  40382. /*** Start of inlined file: juce_TreeView.h ***/
  40383. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  40384. #define __JUCE_TREEVIEW_JUCEHEADER__
  40385. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  40386. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  40387. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  40388. /**
  40389. Components derived from this class can have files dropped onto them by an external application.
  40390. @see DragAndDropContainer
  40391. */
  40392. class JUCE_API FileDragAndDropTarget
  40393. {
  40394. public:
  40395. /** Destructor. */
  40396. virtual ~FileDragAndDropTarget() {}
  40397. /** Callback to check whether this target is interested in the set of files being offered.
  40398. Note that this will be called repeatedly when the user is dragging the mouse around over your
  40399. component, so don't do anything time-consuming in here, like opening the files to have a look
  40400. inside them!
  40401. @param files the set of (absolute) pathnames of the files that the user is dragging
  40402. @returns true if this component wants to receive the other callbacks regarging this
  40403. type of object; if it returns false, no other callbacks will be made.
  40404. */
  40405. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  40406. /** Callback to indicate that some files are being dragged over this component.
  40407. This gets called when the user moves the mouse into this component while dragging.
  40408. Use this callback as a trigger to make your component repaint itself to give the
  40409. user feedback about whether the files can be dropped here or not.
  40410. @param files the set of (absolute) pathnames of the files that the user is dragging
  40411. @param x the mouse x position, relative to this component
  40412. @param y the mouse y position, relative to this component
  40413. */
  40414. virtual void fileDragEnter (const StringArray& files, int x, int y);
  40415. /** Callback to indicate that the user is dragging some files over this component.
  40416. This gets called when the user moves the mouse over this component while dragging.
  40417. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  40418. this lets you know what happens in-between.
  40419. @param files the set of (absolute) pathnames of the files that the user is dragging
  40420. @param x the mouse x position, relative to this component
  40421. @param y the mouse y position, relative to this component
  40422. */
  40423. virtual void fileDragMove (const StringArray& files, int x, int y);
  40424. /** Callback to indicate that the mouse has moved away from this component.
  40425. This gets called when the user moves the mouse out of this component while dragging
  40426. the files.
  40427. If you've used fileDragEnter() to repaint your component and give feedback, use this
  40428. as a signal to repaint it in its normal state.
  40429. @param files the set of (absolute) pathnames of the files that the user is dragging
  40430. */
  40431. virtual void fileDragExit (const StringArray& files);
  40432. /** Callback to indicate that the user has dropped the files onto this component.
  40433. When the user drops the files, this get called, and you can use the files in whatever
  40434. way is appropriate.
  40435. Note that after this is called, the fileDragExit method may not be called, so you should
  40436. clean up in here if there's anything you need to do when the drag finishes.
  40437. @param files the set of (absolute) pathnames of the files that the user is dragging
  40438. @param x the mouse x position, relative to this component
  40439. @param y the mouse y position, relative to this component
  40440. */
  40441. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  40442. };
  40443. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  40444. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  40445. class TreeView;
  40446. /**
  40447. An item in a treeview.
  40448. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  40449. own sub-items.
  40450. To implement an item that contains sub-items, override the itemOpennessChanged()
  40451. method so that when it is opened, it adds the new sub-items to itself using the
  40452. addSubItem method. Depending on the nature of the item it might choose to only
  40453. do this the first time it's opened, or it might want to refresh itself each time.
  40454. It also has the option of deleting its sub-items when it is closed, or leaving them
  40455. in place.
  40456. */
  40457. class JUCE_API TreeViewItem
  40458. {
  40459. public:
  40460. /** Constructor. */
  40461. TreeViewItem();
  40462. /** Destructor. */
  40463. virtual ~TreeViewItem();
  40464. /** Returns the number of sub-items that have been added to this item.
  40465. Note that this doesn't mean much if the node isn't open.
  40466. @see getSubItem, mightContainSubItems, addSubItem
  40467. */
  40468. int getNumSubItems() const throw();
  40469. /** Returns one of the item's sub-items.
  40470. Remember that the object returned might get deleted at any time when its parent
  40471. item is closed or refreshed, depending on the nature of the items you're using.
  40472. @see getNumSubItems
  40473. */
  40474. TreeViewItem* getSubItem (int index) const throw();
  40475. /** Removes any sub-items. */
  40476. void clearSubItems();
  40477. /** Adds a sub-item.
  40478. @param newItem the object to add to the item's sub-item list. Once added, these can be
  40479. found using getSubItem(). When the items are later removed with
  40480. removeSubItem() (or when this item is deleted), they will be deleted.
  40481. @param insertPosition the index which the new item should have when it's added. If this
  40482. value is less than 0, the item will be added to the end of the list.
  40483. */
  40484. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  40485. /** Removes one of the sub-items.
  40486. @param index the item to remove
  40487. @param deleteItem if true, the item that is removed will also be deleted.
  40488. */
  40489. void removeSubItem (int index, bool deleteItem = true);
  40490. /** Returns the TreeView to which this item belongs. */
  40491. TreeView* getOwnerView() const throw() { return ownerView; }
  40492. /** Returns the item within which this item is contained. */
  40493. TreeViewItem* getParentItem() const throw() { return parentItem; }
  40494. /** True if this item is currently open in the treeview. */
  40495. bool isOpen() const throw();
  40496. /** Opens or closes the item.
  40497. When opened or closed, the item's itemOpennessChanged() method will be called,
  40498. and a subclass should use this callback to create and add any sub-items that
  40499. it needs to.
  40500. @see itemOpennessChanged, mightContainSubItems
  40501. */
  40502. void setOpen (bool shouldBeOpen);
  40503. /** True if this item is currently selected.
  40504. Use this when painting the node, to decide whether to draw it as selected or not.
  40505. */
  40506. bool isSelected() const throw();
  40507. /** Selects or deselects the item.
  40508. This will cause a callback to itemSelectionChanged()
  40509. */
  40510. void setSelected (bool shouldBeSelected,
  40511. bool deselectOtherItemsFirst);
  40512. /** Returns the rectangle that this item occupies.
  40513. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  40514. top-left of the TreeView comp, so this will depend on the scroll-position of
  40515. the tree. If false, it is relative to the top-left of the topmost item in the
  40516. tree (so this would be unaffected by scrolling the view).
  40517. */
  40518. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const throw();
  40519. /** Sends a signal to the treeview to make it refresh itself.
  40520. Call this if your items have changed and you want the tree to update to reflect
  40521. this.
  40522. */
  40523. void treeHasChanged() const throw();
  40524. /** Sends a repaint message to redraw just this item.
  40525. Note that you should only call this if you want to repaint a superficial change. If
  40526. you're altering the tree's nodes, you should instead call treeHasChanged().
  40527. */
  40528. void repaintItem() const;
  40529. /** Returns the row number of this item in the tree.
  40530. The row number of an item will change according to which items are open.
  40531. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  40532. */
  40533. int getRowNumberInTree() const throw();
  40534. /** Returns true if all the item's parent nodes are open.
  40535. This is useful to check whether the item might actually be visible or not.
  40536. */
  40537. bool areAllParentsOpen() const throw();
  40538. /** Changes whether lines are drawn to connect any sub-items to this item.
  40539. By default, line-drawing is turned on.
  40540. */
  40541. void setLinesDrawnForSubItems (bool shouldDrawLines) throw();
  40542. /** Tells the tree whether this item can potentially be opened.
  40543. If your item could contain sub-items, this should return true; if it returns
  40544. false then the tree will not try to open the item. This determines whether or
  40545. not the item will be drawn with a 'plus' button next to it.
  40546. */
  40547. virtual bool mightContainSubItems() = 0;
  40548. /** Returns a string to uniquely identify this item.
  40549. If you're planning on using the TreeView::getOpennessState() method, then
  40550. these strings will be used to identify which nodes are open. The string
  40551. should be unique amongst the item's sibling items, but it's ok for there
  40552. to be duplicates at other levels of the tree.
  40553. If you're not going to store the state, then it's ok not to bother implementing
  40554. this method.
  40555. */
  40556. virtual const String getUniqueName() const;
  40557. /** Called when an item is opened or closed.
  40558. When setOpen() is called and the item has specified that it might
  40559. have sub-items with the mightContainSubItems() method, this method
  40560. is called to let the item create or manage its sub-items.
  40561. So when this is called with isNowOpen set to true (i.e. when the item is being
  40562. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  40563. refresh its sub-item list.
  40564. When this is called with isNowOpen set to false, the subclass might want
  40565. to use clearSubItems() to save on space, or it might choose to leave them,
  40566. depending on the nature of the tree.
  40567. You could also use this callback as a trigger to start a background process
  40568. which asynchronously creates sub-items and adds them, if that's more
  40569. appropriate for the task in hand.
  40570. @see mightContainSubItems
  40571. */
  40572. virtual void itemOpennessChanged (bool isNowOpen);
  40573. /** Must return the width required by this item.
  40574. If your item needs to have a particular width in pixels, return that value; if
  40575. you'd rather have it just fill whatever space is available in the treeview,
  40576. return -1.
  40577. If all your items return -1, no horizontal scrollbar will be shown, but if any
  40578. items have fixed widths and extend beyond the width of the treeview, a
  40579. scrollbar will appear.
  40580. Each item can be a different width, but if they change width, you should call
  40581. treeHasChanged() to update the tree.
  40582. */
  40583. virtual int getItemWidth() const { return -1; }
  40584. /** Must return the height required by this item.
  40585. This is the height in pixels that the item will take up. Items in the tree
  40586. can be different heights, but if they change height, you should call
  40587. treeHasChanged() to update the tree.
  40588. */
  40589. virtual int getItemHeight() const { return 20; }
  40590. /** You can override this method to return false if you don't want to allow the
  40591. user to select this item.
  40592. */
  40593. virtual bool canBeSelected() const { return true; }
  40594. /** Creates a component that will be used to represent this item.
  40595. You don't have to implement this method - if it returns 0 then no component
  40596. will be used for the item, and you can just draw it using the paintItem()
  40597. callback. But if you do return a component, it will be positioned in the
  40598. treeview so that it can be used to represent this item.
  40599. The component returned will be managed by the treeview, so always return
  40600. a new component, and don't keep a reference to it, as the treeview will
  40601. delete it later when it goes off the screen or is no longer needed. Also
  40602. bear in mind that if the component keeps a reference to the item that
  40603. created it, that item could be deleted before the component. Its position
  40604. and size will be completely managed by the tree, so don't attempt to move it
  40605. around.
  40606. Something you may want to do with your component is to give it a pointer to
  40607. the TreeView that created it. This is perfectly safe, and there's no danger
  40608. of it becoming a dangling pointer because the TreeView will always delete
  40609. the component before it is itself deleted.
  40610. As long as you stick to these rules you can return whatever kind of
  40611. component you like. It's most useful if you're doing things like drag-and-drop
  40612. of items, or want to use a Label component to edit item names, etc.
  40613. */
  40614. virtual Component* createItemComponent() { return 0; }
  40615. /** Draws the item's contents.
  40616. You can choose to either implement this method and draw each item, or you
  40617. can use createItemComponent() to create a component that will represent the
  40618. item.
  40619. If all you need in your tree is to be able to draw the items and detect when
  40620. the user selects or double-clicks one of them, it's probably enough to
  40621. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  40622. complicated interactions, you may need to use createItemComponent() instead.
  40623. @param g the graphics context to draw into
  40624. @param width the width of the area available for drawing
  40625. @param height the height of the area available for drawing
  40626. */
  40627. virtual void paintItem (Graphics& g, int width, int height);
  40628. /** Draws the item's open/close button.
  40629. If you don't implement this method, the default behaviour is to
  40630. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  40631. it for custom effects.
  40632. */
  40633. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  40634. /** Called when the user clicks on this item.
  40635. If you're using createItemComponent() to create a custom component for the
  40636. item, the mouse-clicks might not make it through to the treeview, but this
  40637. is how you find out about clicks when just drawing each item individually.
  40638. The associated mouse-event details are passed in, so you can find out about
  40639. which button, where it was, etc.
  40640. @see itemDoubleClicked
  40641. */
  40642. virtual void itemClicked (const MouseEvent& e);
  40643. /** Called when the user double-clicks on this item.
  40644. If you're using createItemComponent() to create a custom component for the
  40645. item, the mouse-clicks might not make it through to the treeview, but this
  40646. is how you find out about clicks when just drawing each item individually.
  40647. The associated mouse-event details are passed in, so you can find out about
  40648. which button, where it was, etc.
  40649. If not overridden, the base class method here will open or close the item as
  40650. if the 'plus' button had been clicked.
  40651. @see itemClicked
  40652. */
  40653. virtual void itemDoubleClicked (const MouseEvent& e);
  40654. /** Called when the item is selected or deselected.
  40655. Use this if you want to do something special when the item's selectedness
  40656. changes. By default it'll get repainted when this happens.
  40657. */
  40658. virtual void itemSelectionChanged (bool isNowSelected);
  40659. /** The item can return a tool tip string here if it wants to.
  40660. @see TooltipClient
  40661. */
  40662. virtual const String getTooltip();
  40663. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  40664. If this returns a non-empty name then when the user drags an item, the treeview will
  40665. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  40666. a drag-and-drop operation, using this string as the source description, with the treeview
  40667. itself as the source component.
  40668. If you need more complex drag-and-drop behaviour, you can use custom components for
  40669. the items, and use those to trigger the drag.
  40670. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  40671. isInterestedInFileDrag(), etc.
  40672. @see DragAndDropContainer::startDragging
  40673. */
  40674. virtual const String getDragSourceDescription();
  40675. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  40676. method and return true.
  40677. If you return true and allow some files to be dropped, you'll also need to implement the
  40678. filesDropped() method to do something with them.
  40679. Note that this will be called often, so make your implementation very quick! There's
  40680. certainly no time to try opening the files and having a think about what's inside them!
  40681. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  40682. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  40683. */
  40684. virtual bool isInterestedInFileDrag (const StringArray& files);
  40685. /** When files are dropped into this item, this callback is invoked.
  40686. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  40687. The insertIndex value indicates where in the list of sub-items the files were dropped.
  40688. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  40689. */
  40690. virtual void filesDropped (const StringArray& files, int insertIndex);
  40691. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  40692. If you implement this method, you'll also need to implement itemDropped() in order to handle
  40693. the items when they are dropped.
  40694. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  40695. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  40696. */
  40697. virtual bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  40698. /** When a things are dropped into this item, this callback is invoked.
  40699. For this to work, you need to have also implemented isInterestedInDragSource().
  40700. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  40701. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  40702. */
  40703. virtual void itemDropped (const String& sourceDescription, Component* sourceComponent, int insertIndex);
  40704. /** Sets a flag to indicate that the item wants to be allowed
  40705. to draw all the way across to the left edge of the treeview.
  40706. By default this is false, which means that when the paintItem()
  40707. method is called, its graphics context is clipped to only allow
  40708. drawing within the item's rectangle. If this flag is set to true,
  40709. then the graphics context isn't clipped on its left side, so it
  40710. can draw all the way across to the left margin. Note that the
  40711. context will still have its origin in the same place though, so
  40712. the coordinates of anything to its left will be negative. It's
  40713. mostly useful if you want to draw a wider bar behind the
  40714. highlighted item.
  40715. */
  40716. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  40717. /** Saves the current state of open/closed nodes so it can be restored later.
  40718. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  40719. and records it as XML. To identify node objects it uses the
  40720. TreeViewItem::getUniqueName() method to create named paths. This
  40721. means that the same state of open/closed nodes can be restored to a
  40722. completely different instance of the tree, as long as it contains nodes
  40723. whose unique names are the same.
  40724. You'd normally want to use TreeView::getOpennessState() rather than call it
  40725. for a specific item, but this can be handy if you need to briefly save the state
  40726. for a section of the tree.
  40727. The caller is responsible for deleting the object that is returned.
  40728. @see TreeView::getOpennessState, restoreOpennessState
  40729. */
  40730. XmlElement* getOpennessState() const throw();
  40731. /** Restores the openness of this item and all its sub-items from a saved state.
  40732. See TreeView::restoreOpennessState for more details.
  40733. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  40734. for a specific item, but this can be handy if you need to briefly save the state
  40735. for a section of the tree.
  40736. @see TreeView::restoreOpennessState, getOpennessState
  40737. */
  40738. void restoreOpennessState (const XmlElement& xml) throw();
  40739. /** Returns the index of this item in its parent's sub-items. */
  40740. int getIndexInParent() const throw();
  40741. /** Returns true if this item is the last of its parent's sub-itens. */
  40742. bool isLastOfSiblings() const throw();
  40743. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  40744. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  40745. The string takes the form of a path, constructed from the getUniqueName() of this
  40746. item and all its parents, so these must all be correctly implemented for it to work.
  40747. @see TreeView::findItemFromIdentifierString, getUniqueName
  40748. */
  40749. const String getItemIdentifierString() const;
  40750. /**
  40751. This handy class takes a copy of a TreeViewItem's openness when you create it,
  40752. and restores that openness state when its destructor is called.
  40753. This can very handy when you're refreshing sub-items - e.g.
  40754. @code
  40755. void MyTreeViewItem::updateChildItems()
  40756. {
  40757. OpennessRestorer openness (*this); // saves the openness state here..
  40758. clearSubItems();
  40759. // add a bunch of sub-items here which may or may not be the same as the ones that
  40760. // were previously there
  40761. addSubItem (...
  40762. // ..and at this point, the old openness is restored, so any items that haven't
  40763. // changed will have their old openness retained.
  40764. }
  40765. @endcode
  40766. */
  40767. class OpennessRestorer
  40768. {
  40769. public:
  40770. OpennessRestorer (TreeViewItem& treeViewItem);
  40771. ~OpennessRestorer();
  40772. private:
  40773. TreeViewItem& treeViewItem;
  40774. ScopedPointer <XmlElement> oldOpenness;
  40775. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpennessRestorer);
  40776. };
  40777. private:
  40778. TreeView* ownerView;
  40779. TreeViewItem* parentItem;
  40780. OwnedArray <TreeViewItem> subItems;
  40781. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  40782. int uid;
  40783. bool selected : 1;
  40784. bool redrawNeeded : 1;
  40785. bool drawLinesInside : 1;
  40786. bool drawsInLeftMargin : 1;
  40787. unsigned int openness : 2;
  40788. friend class TreeView;
  40789. friend class TreeViewContentComponent;
  40790. void updatePositions (int newY);
  40791. int getIndentX() const throw();
  40792. void setOwnerView (TreeView* newOwner) throw();
  40793. void paintRecursively (Graphics& g, int width);
  40794. TreeViewItem* getTopLevelItem() throw();
  40795. TreeViewItem* findItemRecursively (int y) throw();
  40796. TreeViewItem* getDeepestOpenParentItem() throw();
  40797. int getNumRows() const throw();
  40798. TreeViewItem* getItemOnRow (int index) throw();
  40799. void deselectAllRecursively();
  40800. int countSelectedItemsRecursively (int depth) const throw();
  40801. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  40802. TreeViewItem* getNextVisibleItem (bool recurse) const throw();
  40803. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  40804. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewItem);
  40805. };
  40806. /**
  40807. A tree-view component.
  40808. Use one of these to hold and display a structure of TreeViewItem objects.
  40809. */
  40810. class JUCE_API TreeView : public Component,
  40811. public SettableTooltipClient,
  40812. public FileDragAndDropTarget,
  40813. public DragAndDropTarget,
  40814. private AsyncUpdater
  40815. {
  40816. public:
  40817. /** Creates an empty treeview.
  40818. Once you've got a treeview component, you'll need to give it something to
  40819. display, using the setRootItem() method.
  40820. */
  40821. TreeView (const String& componentName = String::empty);
  40822. /** Destructor. */
  40823. ~TreeView();
  40824. /** Sets the item that is displayed in the treeview.
  40825. A tree has a single root item which contains as many sub-items as it needs. If
  40826. you want the tree to contain a number of root items, you should still use a single
  40827. root item above these, but hide it using setRootItemVisible().
  40828. You can pass in 0 to this method to clear the tree and remove its current root item.
  40829. The object passed in will not be deleted by the treeview, it's up to the caller
  40830. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  40831. this item until you've removed it from the tree, either by calling setRootItem (0),
  40832. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  40833. to delete it.
  40834. */
  40835. void setRootItem (TreeViewItem* newRootItem);
  40836. /** Returns the tree's root item.
  40837. This will be the last object passed to setRootItem(), or 0 if none has been set.
  40838. */
  40839. TreeViewItem* getRootItem() const throw() { return rootItem; }
  40840. /** This will remove and delete the current root item.
  40841. It's a convenient way of deleting the item and calling setRootItem (0).
  40842. */
  40843. void deleteRootItem();
  40844. /** Changes whether the tree's root item is shown or not.
  40845. If the root item is hidden, only its sub-items will be shown in the treeview - this
  40846. lets you make the tree look as if it's got many root items. If it's hidden, this call
  40847. will also make sure the root item is open (otherwise the treeview would look empty).
  40848. */
  40849. void setRootItemVisible (bool shouldBeVisible);
  40850. /** Returns true if the root item is visible.
  40851. @see setRootItemVisible
  40852. */
  40853. bool isRootItemVisible() const throw() { return rootItemVisible; }
  40854. /** Sets whether items are open or closed by default.
  40855. Normally, items are closed until the user opens them, but you can use this
  40856. to make them default to being open until explicitly closed.
  40857. @see areItemsOpenByDefault
  40858. */
  40859. void setDefaultOpenness (bool isOpenByDefault);
  40860. /** Returns true if the tree's items default to being open.
  40861. @see setDefaultOpenness
  40862. */
  40863. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  40864. /** This sets a flag to indicate that the tree can be used for multi-selection.
  40865. You can always select multiple items internally by calling the
  40866. TreeViewItem::setSelected() method, but this flag indicates whether the user
  40867. is allowed to multi-select by clicking on the tree.
  40868. By default it is disabled.
  40869. @see isMultiSelectEnabled
  40870. */
  40871. void setMultiSelectEnabled (bool canMultiSelect);
  40872. /** Returns whether multi-select has been enabled for the tree.
  40873. @see setMultiSelectEnabled
  40874. */
  40875. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  40876. /** Sets a flag to indicate whether to hide the open/close buttons.
  40877. @see areOpenCloseButtonsVisible
  40878. */
  40879. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  40880. /** Returns whether open/close buttons are shown.
  40881. @see setOpenCloseButtonsVisible
  40882. */
  40883. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  40884. /** Deselects any items that are currently selected. */
  40885. void clearSelectedItems();
  40886. /** Returns the number of items that are currently selected.
  40887. If maximumDepthToSearchTo is >= 0, it lets you specify a maximum depth to which the
  40888. tree will be recursed.
  40889. @see getSelectedItem, clearSelectedItems
  40890. */
  40891. int getNumSelectedItems (int maximumDepthToSearchTo = -1) const throw();
  40892. /** Returns one of the selected items in the tree.
  40893. @param index the index, 0 to (getNumSelectedItems() - 1)
  40894. */
  40895. TreeViewItem* getSelectedItem (int index) const throw();
  40896. /** Returns the number of rows the tree is using.
  40897. This will depend on which items are open.
  40898. @see TreeViewItem::getRowNumberInTree()
  40899. */
  40900. int getNumRowsInTree() const;
  40901. /** Returns the item on a particular row of the tree.
  40902. If the index is out of range, this will return 0.
  40903. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  40904. */
  40905. TreeViewItem* getItemOnRow (int index) const;
  40906. /** Returns the item that contains a given y position.
  40907. The y is relative to the top of the TreeView component.
  40908. */
  40909. TreeViewItem* getItemAt (int yPosition) const throw();
  40910. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  40911. void scrollToKeepItemVisible (TreeViewItem* item);
  40912. /** Returns the treeview's Viewport object. */
  40913. Viewport* getViewport() const throw();
  40914. /** Returns the number of pixels by which each nested level of the tree is indented.
  40915. @see setIndentSize
  40916. */
  40917. int getIndentSize() const throw() { return indentSize; }
  40918. /** Changes the distance by which each nested level of the tree is indented.
  40919. @see getIndentSize
  40920. */
  40921. void setIndentSize (int newIndentSize);
  40922. /** Searches the tree for an item with the specified identifier.
  40923. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  40924. If no such item exists, this will return false. If the item is found, all of its items
  40925. will be automatically opened.
  40926. */
  40927. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  40928. /** Saves the current state of open/closed nodes so it can be restored later.
  40929. This takes a snapshot of which nodes have been explicitly opened or closed,
  40930. and records it as XML. To identify node objects it uses the
  40931. TreeViewItem::getUniqueName() method to create named paths. This
  40932. means that the same state of open/closed nodes can be restored to a
  40933. completely different instance of the tree, as long as it contains nodes
  40934. whose unique names are the same.
  40935. The caller is responsible for deleting the object that is returned.
  40936. @param alsoIncludeScrollPosition if this is true, the state will also
  40937. include information about where the
  40938. tree has been scrolled to vertically,
  40939. so this can also be restored
  40940. @see restoreOpennessState
  40941. */
  40942. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  40943. /** Restores a previously saved arrangement of open/closed nodes.
  40944. This will try to restore a snapshot of the tree's state that was created by
  40945. the getOpennessState() method. If any of the nodes named in the original
  40946. XML aren't present in this tree, they will be ignored.
  40947. @see getOpennessState
  40948. */
  40949. void restoreOpennessState (const XmlElement& newState);
  40950. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  40951. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40952. methods.
  40953. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40954. */
  40955. enum ColourIds
  40956. {
  40957. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  40958. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  40959. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  40960. };
  40961. /** @internal */
  40962. void paint (Graphics& g);
  40963. /** @internal */
  40964. void resized();
  40965. /** @internal */
  40966. bool keyPressed (const KeyPress& key);
  40967. /** @internal */
  40968. void colourChanged();
  40969. /** @internal */
  40970. void enablementChanged();
  40971. /** @internal */
  40972. bool isInterestedInFileDrag (const StringArray& files);
  40973. /** @internal */
  40974. void fileDragEnter (const StringArray& files, int x, int y);
  40975. /** @internal */
  40976. void fileDragMove (const StringArray& files, int x, int y);
  40977. /** @internal */
  40978. void fileDragExit (const StringArray& files);
  40979. /** @internal */
  40980. void filesDropped (const StringArray& files, int x, int y);
  40981. /** @internal */
  40982. bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  40983. /** @internal */
  40984. void itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y);
  40985. /** @internal */
  40986. void itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y);
  40987. /** @internal */
  40988. void itemDragExit (const String& sourceDescription, Component* sourceComponent);
  40989. /** @internal */
  40990. void itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y);
  40991. private:
  40992. friend class TreeViewItem;
  40993. friend class TreeViewContentComponent;
  40994. class TreeViewport;
  40995. class InsertPointHighlight;
  40996. class TargetGroupHighlight;
  40997. friend class ScopedPointer<TreeViewport>;
  40998. friend class ScopedPointer<InsertPointHighlight>;
  40999. friend class ScopedPointer<TargetGroupHighlight>;
  41000. ScopedPointer<TreeViewport> viewport;
  41001. CriticalSection nodeAlterationLock;
  41002. TreeViewItem* rootItem;
  41003. ScopedPointer<InsertPointHighlight> dragInsertPointHighlight;
  41004. ScopedPointer<TargetGroupHighlight> dragTargetGroupHighlight;
  41005. int indentSize;
  41006. bool defaultOpenness : 1;
  41007. bool needsRecalculating : 1;
  41008. bool rootItemVisible : 1;
  41009. bool multiSelectEnabled : 1;
  41010. bool openCloseButtonsVisible : 1;
  41011. void itemsChanged() throw();
  41012. void handleAsyncUpdate();
  41013. void moveSelectedRow (int delta);
  41014. void updateButtonUnderMouse (const MouseEvent& e);
  41015. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw();
  41016. void hideDragHighlight() throw();
  41017. void handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  41018. void handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  41019. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  41020. const StringArray& files, const String& sourceDescription,
  41021. Component* sourceComponent) const throw();
  41022. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeView);
  41023. };
  41024. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  41025. /*** End of inlined file: juce_TreeView.h ***/
  41026. #endif
  41027. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41028. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  41029. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41030. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41031. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  41032. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41033. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41034. /*** Start of inlined file: juce_FileFilter.h ***/
  41035. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  41036. #define __JUCE_FILEFILTER_JUCEHEADER__
  41037. /**
  41038. Interface for deciding which files are suitable for something.
  41039. For example, this is used by DirectoryContentsList to select which files
  41040. go into the list.
  41041. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  41042. */
  41043. class JUCE_API FileFilter
  41044. {
  41045. public:
  41046. /** Creates a filter with the given description.
  41047. The description can be returned later with the getDescription() method.
  41048. */
  41049. FileFilter (const String& filterDescription);
  41050. /** Destructor. */
  41051. virtual ~FileFilter();
  41052. /** Returns the description that the filter was created with. */
  41053. const String& getDescription() const throw();
  41054. /** Should return true if this file is suitable for inclusion in whatever context
  41055. the object is being used.
  41056. */
  41057. virtual bool isFileSuitable (const File& file) const = 0;
  41058. /** Should return true if this directory is suitable for inclusion in whatever context
  41059. the object is being used.
  41060. */
  41061. virtual bool isDirectorySuitable (const File& file) const = 0;
  41062. protected:
  41063. String description;
  41064. };
  41065. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  41066. /*** End of inlined file: juce_FileFilter.h ***/
  41067. /**
  41068. A class to asynchronously scan for details about the files in a directory.
  41069. This keeps a list of files and some information about them, using a background
  41070. thread to scan for more files. As files are found, it broadcasts change messages
  41071. to tell any listeners.
  41072. @see FileListComponent, FileBrowserComponent
  41073. */
  41074. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  41075. public TimeSliceClient
  41076. {
  41077. public:
  41078. /** Creates a directory list.
  41079. To set the directory it should point to, use setDirectory(), which will
  41080. also start it scanning for files on the background thread.
  41081. When the background thread finds and adds new files to this list, the
  41082. ChangeBroadcaster class will send a change message, so you can register
  41083. listeners and update them when the list changes.
  41084. @param fileFilter an optional filter to select which files are
  41085. included in the list. If this is 0, then all files
  41086. and directories are included. Make sure that the
  41087. filter doesn't get deleted during the lifetime of this
  41088. object
  41089. @param threadToUse a thread object that this list can use
  41090. to scan for files as a background task. Make sure
  41091. that the thread you give it has been started, or you
  41092. won't get any files!
  41093. */
  41094. DirectoryContentsList (const FileFilter* fileFilter,
  41095. TimeSliceThread& threadToUse);
  41096. /** Destructor. */
  41097. ~DirectoryContentsList();
  41098. /** Sets the directory to look in for files.
  41099. If the directory that's passed in is different to the current one, this will
  41100. also start the background thread scanning it for files.
  41101. */
  41102. void setDirectory (const File& directory,
  41103. bool includeDirectories,
  41104. bool includeFiles);
  41105. /** Returns the directory that's currently being used. */
  41106. const File& getDirectory() const;
  41107. /** Clears the list, and stops the thread scanning for files. */
  41108. void clear();
  41109. /** Clears the list and restarts scanning the directory for files. */
  41110. void refresh();
  41111. /** True if the background thread hasn't yet finished scanning for files. */
  41112. bool isStillLoading() const;
  41113. /** Tells the list whether or not to ignore hidden files.
  41114. By default these are ignored.
  41115. */
  41116. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  41117. /** Returns true if hidden files are ignored.
  41118. @see setIgnoresHiddenFiles
  41119. */
  41120. bool ignoresHiddenFiles() const;
  41121. /** Contains cached information about one of the files in a DirectoryContentsList.
  41122. */
  41123. struct FileInfo
  41124. {
  41125. /** The filename.
  41126. This isn't a full pathname, it's just the last part of the path, same as you'd
  41127. get from File::getFileName().
  41128. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  41129. */
  41130. String filename;
  41131. /** File size in bytes. */
  41132. int64 fileSize;
  41133. /** File modification time.
  41134. As supplied by File::getLastModificationTime().
  41135. */
  41136. Time modificationTime;
  41137. /** File creation time.
  41138. As supplied by File::getCreationTime().
  41139. */
  41140. Time creationTime;
  41141. /** True if the file is a directory. */
  41142. bool isDirectory;
  41143. /** True if the file is read-only. */
  41144. bool isReadOnly;
  41145. };
  41146. /** Returns the number of files currently available in the list.
  41147. The info about one of these files can be retrieved with getFileInfo() or
  41148. getFile().
  41149. Obviously as the background thread runs and scans the directory for files, this
  41150. number will change.
  41151. @see getFileInfo, getFile
  41152. */
  41153. int getNumFiles() const;
  41154. /** Returns the cached information about one of the files in the list.
  41155. If the index is in-range, this will return true and will copy the file's details
  41156. to the structure that is passed-in.
  41157. If it returns false, then the index wasn't in range, and the structure won't
  41158. be affected.
  41159. @see getNumFiles, getFile
  41160. */
  41161. bool getFileInfo (int index, FileInfo& resultInfo) const;
  41162. /** Returns one of the files in the list.
  41163. @param index should be less than getNumFiles(). If this is out-of-range, the
  41164. return value will be File::nonexistent
  41165. @see getNumFiles, getFileInfo
  41166. */
  41167. const File getFile (int index) const;
  41168. /** Returns the file filter being used.
  41169. The filter is specified in the constructor.
  41170. */
  41171. const FileFilter* getFilter() const { return fileFilter; }
  41172. /** @internal */
  41173. int useTimeSlice();
  41174. /** @internal */
  41175. TimeSliceThread& getTimeSliceThread() { return thread; }
  41176. /** @internal */
  41177. static int compareElements (const DirectoryContentsList::FileInfo* first,
  41178. const DirectoryContentsList::FileInfo* second);
  41179. private:
  41180. File root;
  41181. const FileFilter* fileFilter;
  41182. TimeSliceThread& thread;
  41183. int fileTypeFlags;
  41184. CriticalSection fileListLock;
  41185. OwnedArray <FileInfo> files;
  41186. ScopedPointer <DirectoryIterator> fileFindHandle;
  41187. bool volatile shouldStop;
  41188. void changed();
  41189. bool checkNextFile (bool& hasChanged);
  41190. bool addFile (const File& file, bool isDir,
  41191. const int64 fileSize, const Time& modTime,
  41192. const Time& creationTime, bool isReadOnly);
  41193. void setTypeFlags (int newFlags);
  41194. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsList);
  41195. };
  41196. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41197. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  41198. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  41199. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41200. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41201. /**
  41202. A listener for user selection events in a file browser.
  41203. This is used by a FileBrowserComponent or FileListComponent.
  41204. */
  41205. class JUCE_API FileBrowserListener
  41206. {
  41207. public:
  41208. /** Destructor. */
  41209. virtual ~FileBrowserListener();
  41210. /** Callback when the user selects a different file in the browser. */
  41211. virtual void selectionChanged() = 0;
  41212. /** Callback when the user clicks on a file in the browser. */
  41213. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  41214. /** Callback when the user double-clicks on a file in the browser. */
  41215. virtual void fileDoubleClicked (const File& file) = 0;
  41216. };
  41217. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41218. /*** End of inlined file: juce_FileBrowserListener.h ***/
  41219. /**
  41220. A base class for components that display a list of the files in a directory.
  41221. @see DirectoryContentsList
  41222. */
  41223. class JUCE_API DirectoryContentsDisplayComponent
  41224. {
  41225. public:
  41226. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  41227. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  41228. /** Destructor. */
  41229. virtual ~DirectoryContentsDisplayComponent();
  41230. /** Returns the number of files the user has got selected.
  41231. @see getSelectedFile
  41232. */
  41233. virtual int getNumSelectedFiles() const = 0;
  41234. /** Returns one of the files that the user has currently selected.
  41235. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  41236. @see getNumSelectedFiles
  41237. */
  41238. virtual const File getSelectedFile (int index) const = 0;
  41239. /** Deselects any selected files. */
  41240. virtual void deselectAllFiles() = 0;
  41241. /** Scrolls this view to the top. */
  41242. virtual void scrollToTop() = 0;
  41243. /** Adds a listener to be told when files are selected or clicked.
  41244. @see removeListener
  41245. */
  41246. void addListener (FileBrowserListener* listener);
  41247. /** Removes a listener.
  41248. @see addListener
  41249. */
  41250. void removeListener (FileBrowserListener* listener);
  41251. /** A set of colour IDs to use to change the colour of various aspects of the list.
  41252. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41253. methods.
  41254. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41255. */
  41256. enum ColourIds
  41257. {
  41258. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  41259. textColourId = 0x1000541, /**< The colour for the text. */
  41260. };
  41261. /** @internal */
  41262. void sendSelectionChangeMessage();
  41263. /** @internal */
  41264. void sendDoubleClickMessage (const File& file);
  41265. /** @internal */
  41266. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  41267. protected:
  41268. DirectoryContentsList& fileList;
  41269. ListenerList <FileBrowserListener> listeners;
  41270. private:
  41271. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsDisplayComponent);
  41272. };
  41273. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41274. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  41275. #endif
  41276. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41277. #endif
  41278. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  41279. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  41280. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  41281. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  41282. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  41283. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  41284. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  41285. /**
  41286. Base class for components that live inside a file chooser dialog box and
  41287. show previews of the files that get selected.
  41288. One of these allows special extra information to be displayed for files
  41289. in a dialog box as the user selects them. Each time the current file or
  41290. directory is changed, the selectedFileChanged() method will be called
  41291. to allow it to update itself appropriately.
  41292. @see FileChooser, ImagePreviewComponent
  41293. */
  41294. class JUCE_API FilePreviewComponent : public Component
  41295. {
  41296. public:
  41297. /** Creates a FilePreviewComponent. */
  41298. FilePreviewComponent();
  41299. /** Destructor. */
  41300. ~FilePreviewComponent();
  41301. /** Called to indicate that the user's currently selected file has changed.
  41302. @param newSelectedFile the newly selected file or directory, which may be
  41303. File::nonexistent if none is selected.
  41304. */
  41305. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  41306. private:
  41307. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilePreviewComponent);
  41308. };
  41309. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  41310. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  41311. /**
  41312. A component for browsing and selecting a file or directory to open or save.
  41313. This contains a FileListComponent and adds various boxes and controls for
  41314. navigating and selecting a file. It can work in different modes so that it can
  41315. be used for loading or saving a file, or for choosing a directory.
  41316. @see FileChooserDialogBox, FileChooser, FileListComponent
  41317. */
  41318. class JUCE_API FileBrowserComponent : public Component,
  41319. public ChangeBroadcaster,
  41320. private FileBrowserListener,
  41321. private TextEditorListener,
  41322. private ButtonListener,
  41323. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  41324. private FileFilter
  41325. {
  41326. public:
  41327. /** Various options for the browser.
  41328. A combination of these is passed into the FileBrowserComponent constructor.
  41329. */
  41330. enum FileChooserFlags
  41331. {
  41332. openMode = 1, /**< specifies that the component should allow the user to
  41333. choose an existing file with the intention of opening it. */
  41334. saveMode = 2, /**< specifies that the component should allow the user to specify
  41335. the name of a file that will be used to save something. */
  41336. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  41337. conjunction with canSelectDirectories). */
  41338. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  41339. conjuction with canSelectFiles). */
  41340. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  41341. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  41342. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  41343. };
  41344. /** Creates a FileBrowserComponent.
  41345. @param flags A combination of flags from the FileChooserFlags enumeration,
  41346. used to specify the component's behaviour. The flags must contain
  41347. either openMode or saveMode, and canSelectFiles and/or
  41348. canSelectDirectories.
  41349. @param initialFileOrDirectory The file or directory that should be selected when
  41350. the component begins. If this is File::nonexistent,
  41351. a default directory will be chosen.
  41352. @param fileFilter an optional filter to use to determine which files
  41353. are shown. If this is 0 then all files are displayed. Note
  41354. that a pointer is kept internally to this object, so
  41355. make sure that it is not deleted before the browser object
  41356. is deleted.
  41357. @param previewComp an optional preview component that will be used to
  41358. show previews of files that the user selects
  41359. */
  41360. FileBrowserComponent (int flags,
  41361. const File& initialFileOrDirectory,
  41362. const FileFilter* fileFilter,
  41363. FilePreviewComponent* previewComp);
  41364. /** Destructor. */
  41365. ~FileBrowserComponent();
  41366. /** Returns the number of files that the user has got selected.
  41367. If multiple select isn't active, this will only be 0 or 1. To get the complete
  41368. list of files they've chosen, pass an index to getCurrentFile().
  41369. */
  41370. int getNumSelectedFiles() const throw();
  41371. /** Returns one of the files that the user has chosen.
  41372. If the box has multi-select enabled, the index lets you specify which of the files
  41373. to get - see getNumSelectedFiles() to find out how many files were chosen.
  41374. @see getHighlightedFile
  41375. */
  41376. const File getSelectedFile (int index) const throw();
  41377. /** Deselects any files that are currently selected.
  41378. */
  41379. void deselectAllFiles();
  41380. /** Returns true if the currently selected file(s) are usable.
  41381. This can be used to decide whether the user can press "ok" for the
  41382. current file. What it does depends on the mode, so for example in an "open"
  41383. mode, this only returns true if a file has been selected and if it exists.
  41384. In a "save" mode, a non-existent file would also be valid.
  41385. */
  41386. bool currentFileIsValid() const;
  41387. /** This returns the last item in the view that the user has highlighted.
  41388. This may be different from getCurrentFile(), which returns the value
  41389. that is shown in the filename box, and if there are multiple selections,
  41390. this will only return one of them.
  41391. @see getSelectedFile
  41392. */
  41393. const File getHighlightedFile() const throw();
  41394. /** Returns the directory whose contents are currently being shown in the listbox. */
  41395. const File getRoot() const;
  41396. /** Changes the directory that's being shown in the listbox. */
  41397. void setRoot (const File& newRootDirectory);
  41398. /** Equivalent to pressing the "up" button to browse the parent directory. */
  41399. void goUp();
  41400. /** Refreshes the directory that's currently being listed. */
  41401. void refresh();
  41402. /** Changes the filter that's being used to sift the files. */
  41403. void setFileFilter (const FileFilter* newFileFilter);
  41404. /** Returns a verb to describe what should happen when the file is accepted.
  41405. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  41406. mode, it'll be "Save", etc.
  41407. */
  41408. virtual const String getActionVerb() const;
  41409. /** Returns true if the saveMode flag was set when this component was created.
  41410. */
  41411. bool isSaveMode() const throw();
  41412. /** Adds a listener to be told when the user selects and clicks on files.
  41413. @see removeListener
  41414. */
  41415. void addListener (FileBrowserListener* listener);
  41416. /** Removes a listener.
  41417. @see addListener
  41418. */
  41419. void removeListener (FileBrowserListener* listener);
  41420. /** @internal */
  41421. void resized();
  41422. /** @internal */
  41423. void buttonClicked (Button* b);
  41424. /** @internal */
  41425. void comboBoxChanged (ComboBox*);
  41426. /** @internal */
  41427. void textEditorTextChanged (TextEditor& editor);
  41428. /** @internal */
  41429. void textEditorReturnKeyPressed (TextEditor& editor);
  41430. /** @internal */
  41431. void textEditorEscapeKeyPressed (TextEditor& editor);
  41432. /** @internal */
  41433. void textEditorFocusLost (TextEditor& editor);
  41434. /** @internal */
  41435. bool keyPressed (const KeyPress& key);
  41436. /** @internal */
  41437. void selectionChanged();
  41438. /** @internal */
  41439. void fileClicked (const File& f, const MouseEvent& e);
  41440. /** @internal */
  41441. void fileDoubleClicked (const File& f);
  41442. /** @internal */
  41443. bool isFileSuitable (const File& file) const;
  41444. /** @internal */
  41445. bool isDirectorySuitable (const File&) const;
  41446. /** @internal */
  41447. FilePreviewComponent* getPreviewComponent() const throw();
  41448. protected:
  41449. /** Returns a list of names and paths for the default places the user might want to look.
  41450. Use an empty string to indicate a section break.
  41451. */
  41452. virtual void getRoots (StringArray& rootNames, StringArray& rootPaths);
  41453. private:
  41454. ScopedPointer <DirectoryContentsList> fileList;
  41455. const FileFilter* fileFilter;
  41456. int flags;
  41457. File currentRoot;
  41458. Array<File> chosenFiles;
  41459. ListenerList <FileBrowserListener> listeners;
  41460. ScopedPointer<DirectoryContentsDisplayComponent> fileListComponent;
  41461. FilePreviewComponent* previewComp;
  41462. ComboBox currentPathBox;
  41463. TextEditor filenameBox;
  41464. Label fileLabel;
  41465. ScopedPointer<Button> goUpButton;
  41466. TimeSliceThread thread;
  41467. void sendListenerChangeMessage();
  41468. bool isFileOrDirSuitable (const File& f) const;
  41469. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBrowserComponent);
  41470. };
  41471. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  41472. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  41473. #endif
  41474. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41475. #endif
  41476. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  41477. /*** Start of inlined file: juce_FileChooser.h ***/
  41478. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  41479. #define __JUCE_FILECHOOSER_JUCEHEADER__
  41480. /**
  41481. Creates a dialog box to choose a file or directory to load or save.
  41482. To use a FileChooser:
  41483. - create one (as a local stack variable is the neatest way)
  41484. - call one of its browseFor.. methods
  41485. - if this returns true, the user has selected a file, so you can retrieve it
  41486. with the getResult() method.
  41487. e.g. @code
  41488. void loadMooseFile()
  41489. {
  41490. FileChooser myChooser ("Please select the moose you want to load...",
  41491. File::getSpecialLocation (File::userHomeDirectory),
  41492. "*.moose");
  41493. if (myChooser.browseForFileToOpen())
  41494. {
  41495. File mooseFile (myChooser.getResult());
  41496. loadMoose (mooseFile);
  41497. }
  41498. }
  41499. @endcode
  41500. */
  41501. class JUCE_API FileChooser
  41502. {
  41503. public:
  41504. /** Creates a FileChooser.
  41505. After creating one of these, use one of the browseFor... methods to display it.
  41506. @param dialogBoxTitle a text string to display in the dialog box to
  41507. tell the user what's going on
  41508. @param initialFileOrDirectory the file or directory that should be selected when
  41509. the dialog box opens. If this parameter is set to
  41510. File::nonexistent, a sensible default directory
  41511. will be used instead.
  41512. @param filePatternsAllowed a set of file patterns to specify which files can be
  41513. selected - each pattern should be separated by a
  41514. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  41515. empty string means that all files are allowed
  41516. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  41517. possible; if false, then a Juce-based browser dialog
  41518. box will always be used
  41519. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  41520. */
  41521. FileChooser (const String& dialogBoxTitle,
  41522. const File& initialFileOrDirectory = File::nonexistent,
  41523. const String& filePatternsAllowed = String::empty,
  41524. bool useOSNativeDialogBox = true);
  41525. /** Destructor. */
  41526. ~FileChooser();
  41527. /** Shows a dialog box to choose a file to open.
  41528. This will display the dialog box modally, using an "open file" mode, so that
  41529. it won't allow non-existent files or directories to be chosen.
  41530. @param previewComponent an optional component to display inside the dialog
  41531. box to show special info about the files that the user
  41532. is browsing. The component will not be deleted by this
  41533. object, so the caller must take care of it.
  41534. @returns true if the user selected a file, in which case, use the getResult()
  41535. method to find out what it was. Returns false if they cancelled instead.
  41536. @see browseForFileToSave, browseForDirectory
  41537. */
  41538. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  41539. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  41540. The files that are returned can be obtained by calling getResults(). See
  41541. browseForFileToOpen() for more info about the behaviour of this method.
  41542. */
  41543. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  41544. /** Shows a dialog box to choose a file to save.
  41545. This will display the dialog box modally, using an "save file" mode, so it
  41546. will allow non-existent files to be chosen, but not directories.
  41547. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  41548. the user if they're sure they want to overwrite a file that already
  41549. exists
  41550. @returns true if the user chose a file and pressed 'ok', in which case, use
  41551. the getResult() method to find out what the file was. Returns false
  41552. if they cancelled instead.
  41553. @see browseForFileToOpen, browseForDirectory
  41554. */
  41555. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  41556. /** Shows a dialog box to choose a directory.
  41557. This will display the dialog box modally, using an "open directory" mode, so it
  41558. will only allow directories to be returned, not files.
  41559. @returns true if the user chose a directory and pressed 'ok', in which case, use
  41560. the getResult() method to find out what they chose. Returns false
  41561. if they cancelled instead.
  41562. @see browseForFileToOpen, browseForFileToSave
  41563. */
  41564. bool browseForDirectory();
  41565. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  41566. The files that are returned can be obtained by calling getResults(). See
  41567. browseForFileToOpen() for more info about the behaviour of this method.
  41568. */
  41569. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  41570. /** Returns the last file that was chosen by one of the browseFor methods.
  41571. After calling the appropriate browseFor... method, this method lets you
  41572. find out what file or directory they chose.
  41573. Note that the file returned is only valid if the browse method returned true (i.e.
  41574. if the user pressed 'ok' rather than cancelling).
  41575. If you're using a multiple-file select, then use the getResults() method instead,
  41576. to obtain the list of all files chosen.
  41577. @see getResults
  41578. */
  41579. const File getResult() const;
  41580. /** Returns a list of all the files that were chosen during the last call to a
  41581. browse method.
  41582. This array may be empty if no files were chosen, or can contain multiple entries
  41583. if multiple files were chosen.
  41584. @see getResult
  41585. */
  41586. const Array<File>& getResults() const;
  41587. private:
  41588. String title, filters;
  41589. File startingFile;
  41590. Array<File> results;
  41591. bool useNativeDialogBox;
  41592. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  41593. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  41594. FilePreviewComponent* previewComponent);
  41595. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  41596. const String& filters, bool selectsDirectories, bool selectsFiles,
  41597. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  41598. FilePreviewComponent* previewComponent);
  41599. JUCE_LEAK_DETECTOR (FileChooser);
  41600. };
  41601. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  41602. /*** End of inlined file: juce_FileChooser.h ***/
  41603. #endif
  41604. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  41605. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  41606. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  41607. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  41608. /*** Start of inlined file: juce_ResizableWindow.h ***/
  41609. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  41610. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  41611. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  41612. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  41613. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  41614. /*** Start of inlined file: juce_DropShadower.h ***/
  41615. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  41616. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  41617. /**
  41618. Adds a drop-shadow to a component.
  41619. This object creates and manages a set of components which sit around a
  41620. component, creating a gaussian shadow around it. The components will track
  41621. the position of the component and if it's brought to the front they'll also
  41622. follow this.
  41623. For desktop windows you don't need to use this class directly - just
  41624. set the Component::windowHasDropShadow flag when calling
  41625. Component::addToDesktop(), and the system will create one of these if it's
  41626. needed (which it obviously isn't on the Mac, for example).
  41627. */
  41628. class JUCE_API DropShadower : public ComponentListener
  41629. {
  41630. public:
  41631. /** Creates a DropShadower.
  41632. @param alpha the opacity of the shadows, from 0 to 1.0
  41633. @param xOffset the horizontal displacement of the shadow, in pixels
  41634. @param yOffset the vertical displacement of the shadow, in pixels
  41635. @param blurRadius the radius of the blur to use for creating the shadow
  41636. */
  41637. DropShadower (float alpha = 0.5f,
  41638. int xOffset = 1,
  41639. int yOffset = 5,
  41640. float blurRadius = 10.0f);
  41641. /** Destructor. */
  41642. virtual ~DropShadower();
  41643. /** Attaches the DropShadower to the component you want to shadow. */
  41644. void setOwner (Component* componentToFollow);
  41645. /** @internal */
  41646. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  41647. /** @internal */
  41648. void componentBroughtToFront (Component& component);
  41649. /** @internal */
  41650. void componentParentHierarchyChanged (Component& component);
  41651. /** @internal */
  41652. void componentVisibilityChanged (Component& component);
  41653. private:
  41654. Component* owner;
  41655. OwnedArray<Component> shadowWindows;
  41656. Image shadowImageSections[12];
  41657. const int xOffset, yOffset;
  41658. const float alpha, blurRadius;
  41659. bool reentrant;
  41660. void updateShadows();
  41661. void setShadowImage (const Image& src, int num, int w, int h, int sx, int sy);
  41662. void bringShadowWindowsToFront();
  41663. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DropShadower);
  41664. };
  41665. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  41666. /*** End of inlined file: juce_DropShadower.h ***/
  41667. /**
  41668. A base class for top-level windows.
  41669. This class is used for components that are considered a major part of your
  41670. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  41671. etc. Things like menus that pop up briefly aren't derived from it.
  41672. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  41673. could itself be the child of another component.
  41674. The class manages a list of all instances of top-level windows that are in use,
  41675. and each one is also given the concept of being "active". The active window is
  41676. one that is actively being used by the user. This isn't quite the same as the
  41677. component with the keyboard focus, because there may be a popup menu or other
  41678. temporary window which gets keyboard focus while the active top level window is
  41679. unchanged.
  41680. A top-level window also has an optional drop-shadow.
  41681. @see ResizableWindow, DocumentWindow, DialogWindow
  41682. */
  41683. class JUCE_API TopLevelWindow : public Component
  41684. {
  41685. public:
  41686. /** Creates a TopLevelWindow.
  41687. @param name the name to give the component
  41688. @param addToDesktop if true, the window will be automatically added to the
  41689. desktop; if false, you can use it as a child component
  41690. */
  41691. TopLevelWindow (const String& name, bool addToDesktop);
  41692. /** Destructor. */
  41693. ~TopLevelWindow();
  41694. /** True if this is currently the TopLevelWindow that is actively being used.
  41695. This isn't quite the same as having keyboard focus, because the focus may be
  41696. on a child component or a temporary pop-up menu, etc, while this window is
  41697. still considered to be active.
  41698. @see activeWindowStatusChanged
  41699. */
  41700. bool isActiveWindow() const throw() { return windowIsActive_; }
  41701. /** This will set the bounds of the window so that it's centred in front of another
  41702. window.
  41703. If your app has a few windows open and want to pop up a dialog box for one of
  41704. them, you can use this to show it in front of the relevent parent window, which
  41705. is a bit neater than just having it appear in the middle of the screen.
  41706. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  41707. be used instead. If no window is focused, it'll just default to the middle of the
  41708. screen.
  41709. */
  41710. void centreAroundComponent (Component* componentToCentreAround,
  41711. int width, int height);
  41712. /** Turns the drop-shadow on and off. */
  41713. void setDropShadowEnabled (bool useShadow);
  41714. /** Sets whether an OS-native title bar will be used, or a Juce one.
  41715. @see isUsingNativeTitleBar
  41716. */
  41717. void setUsingNativeTitleBar (bool useNativeTitleBar);
  41718. /** Returns true if the window is currently using an OS-native title bar.
  41719. @see setUsingNativeTitleBar
  41720. */
  41721. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  41722. /** Returns the number of TopLevelWindow objects currently in use.
  41723. @see getTopLevelWindow
  41724. */
  41725. static int getNumTopLevelWindows() throw();
  41726. /** Returns one of the TopLevelWindow objects currently in use.
  41727. The index is 0 to (getNumTopLevelWindows() - 1).
  41728. */
  41729. static TopLevelWindow* getTopLevelWindow (int index) throw();
  41730. /** Returns the currently-active top level window.
  41731. There might not be one, of course, so this can return 0.
  41732. */
  41733. static TopLevelWindow* getActiveTopLevelWindow() throw();
  41734. /** @internal */
  41735. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  41736. protected:
  41737. /** This callback happens when this window becomes active or inactive.
  41738. @see isActiveWindow
  41739. */
  41740. virtual void activeWindowStatusChanged();
  41741. /** @internal */
  41742. void focusOfChildComponentChanged (FocusChangeType cause);
  41743. /** @internal */
  41744. void parentHierarchyChanged();
  41745. /** @internal */
  41746. virtual int getDesktopWindowStyleFlags() const;
  41747. /** @internal */
  41748. void recreateDesktopWindow();
  41749. /** @internal */
  41750. void visibilityChanged();
  41751. private:
  41752. friend class TopLevelWindowManager;
  41753. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  41754. ScopedPointer <DropShadower> shadower;
  41755. void setWindowActive (bool isNowActive);
  41756. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TopLevelWindow);
  41757. };
  41758. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  41759. /*** End of inlined file: juce_TopLevelWindow.h ***/
  41760. /*** Start of inlined file: juce_ComponentDragger.h ***/
  41761. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  41762. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  41763. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  41764. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  41765. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  41766. /**
  41767. A class that imposes restrictions on a Component's size or position.
  41768. This is used by classes such as ResizableCornerComponent,
  41769. ResizableBorderComponent and ResizableWindow.
  41770. The base class can impose some basic size and position limits, but you can
  41771. also subclass this for custom uses.
  41772. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  41773. */
  41774. class JUCE_API ComponentBoundsConstrainer
  41775. {
  41776. public:
  41777. /** When first created, the object will not impose any restrictions on the components. */
  41778. ComponentBoundsConstrainer() throw();
  41779. /** Destructor. */
  41780. virtual ~ComponentBoundsConstrainer();
  41781. /** Imposes a minimum width limit. */
  41782. void setMinimumWidth (int minimumWidth) throw();
  41783. /** Returns the current minimum width. */
  41784. int getMinimumWidth() const throw() { return minW; }
  41785. /** Imposes a maximum width limit. */
  41786. void setMaximumWidth (int maximumWidth) throw();
  41787. /** Returns the current maximum width. */
  41788. int getMaximumWidth() const throw() { return maxW; }
  41789. /** Imposes a minimum height limit. */
  41790. void setMinimumHeight (int minimumHeight) throw();
  41791. /** Returns the current minimum height. */
  41792. int getMinimumHeight() const throw() { return minH; }
  41793. /** Imposes a maximum height limit. */
  41794. void setMaximumHeight (int maximumHeight) throw();
  41795. /** Returns the current maximum height. */
  41796. int getMaximumHeight() const throw() { return maxH; }
  41797. /** Imposes a minimum width and height limit. */
  41798. void setMinimumSize (int minimumWidth,
  41799. int minimumHeight) throw();
  41800. /** Imposes a maximum width and height limit. */
  41801. void setMaximumSize (int maximumWidth,
  41802. int maximumHeight) throw();
  41803. /** Set all the maximum and minimum dimensions. */
  41804. void setSizeLimits (int minimumWidth,
  41805. int minimumHeight,
  41806. int maximumWidth,
  41807. int maximumHeight) throw();
  41808. /** Sets the amount by which the component is allowed to go off-screen.
  41809. The values indicate how many pixels must remain on-screen when dragged off
  41810. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  41811. when the component goes off the top of the screen, its y-position will be
  41812. clipped so that there are always at least 10 pixels on-screen. In other words,
  41813. the lowest y-position it can take would be (10 - the component's height).
  41814. If you pass 0 or less for one of these amounts, the component is allowed
  41815. to move beyond that edge completely, with no restrictions at all.
  41816. If you pass a very large number (i.e. larger that the dimensions of the
  41817. component itself), then the component won't be allowed to overlap that
  41818. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  41819. the component will bump into the left side of the screen and go no further.
  41820. */
  41821. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  41822. int minimumWhenOffTheLeft,
  41823. int minimumWhenOffTheBottom,
  41824. int minimumWhenOffTheRight) throw();
  41825. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  41826. int getMinimumWhenOffTheTop() const throw() { return minOffTop; }
  41827. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  41828. int getMinimumWhenOffTheLeft() const throw() { return minOffLeft; }
  41829. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  41830. int getMinimumWhenOffTheBottom() const throw() { return minOffBottom; }
  41831. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  41832. int getMinimumWhenOffTheRight() const throw() { return minOffRight; }
  41833. /** Specifies a width-to-height ratio that the resizer should always maintain.
  41834. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  41835. will always be maintained as this multiple of the height.
  41836. @see setResizeLimits
  41837. */
  41838. void setFixedAspectRatio (double widthOverHeight) throw();
  41839. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  41840. If no aspect ratio is being enforced, this will return 0.
  41841. */
  41842. double getFixedAspectRatio() const throw();
  41843. /** This callback changes the given co-ordinates to impose whatever the current
  41844. constraints are set to be.
  41845. @param bounds the target position that should be examined and adjusted
  41846. @param previousBounds the component's current size
  41847. @param limits the region in which the component can be positioned
  41848. @param isStretchingTop whether the top edge of the component is being resized
  41849. @param isStretchingLeft whether the left edge of the component is being resized
  41850. @param isStretchingBottom whether the bottom edge of the component is being resized
  41851. @param isStretchingRight whether the right edge of the component is being resized
  41852. */
  41853. virtual void checkBounds (Rectangle<int>& bounds,
  41854. const Rectangle<int>& previousBounds,
  41855. const Rectangle<int>& limits,
  41856. bool isStretchingTop,
  41857. bool isStretchingLeft,
  41858. bool isStretchingBottom,
  41859. bool isStretchingRight);
  41860. /** This callback happens when the resizer is about to start dragging. */
  41861. virtual void resizeStart();
  41862. /** This callback happens when the resizer has finished dragging. */
  41863. virtual void resizeEnd();
  41864. /** Checks the given bounds, and then sets the component to the corrected size. */
  41865. void setBoundsForComponent (Component* component,
  41866. const Rectangle<int>& bounds,
  41867. bool isStretchingTop,
  41868. bool isStretchingLeft,
  41869. bool isStretchingBottom,
  41870. bool isStretchingRight);
  41871. /** Performs a check on the current size of a component, and moves or resizes
  41872. it if it fails the constraints.
  41873. */
  41874. void checkComponentBounds (Component* component);
  41875. /** Called by setBoundsForComponent() to apply a new constrained size to a
  41876. component.
  41877. By default this just calls setBounds(), but it virtual in case it's needed for
  41878. extremely cunning purposes.
  41879. */
  41880. virtual void applyBoundsToComponent (Component* component,
  41881. const Rectangle<int>& bounds);
  41882. private:
  41883. int minW, maxW, minH, maxH;
  41884. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  41885. double aspectRatio;
  41886. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBoundsConstrainer);
  41887. };
  41888. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  41889. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  41890. /**
  41891. An object to take care of the logic for dragging components around with the mouse.
  41892. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  41893. then in your mouseDrag() callback, call dragComponent().
  41894. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  41895. to limit the component's position and keep it on-screen.
  41896. e.g. @code
  41897. class MyDraggableComp
  41898. {
  41899. ComponentDragger myDragger;
  41900. void mouseDown (const MouseEvent& e)
  41901. {
  41902. myDragger.startDraggingComponent (this, e);
  41903. }
  41904. void mouseDrag (const MouseEvent& e)
  41905. {
  41906. myDragger.dragComponent (this, e, 0);
  41907. }
  41908. };
  41909. @endcode
  41910. */
  41911. class JUCE_API ComponentDragger
  41912. {
  41913. public:
  41914. /** Creates a ComponentDragger. */
  41915. ComponentDragger();
  41916. /** Destructor. */
  41917. virtual ~ComponentDragger();
  41918. /** Call this from your component's mouseDown() method, to prepare for dragging.
  41919. @param componentToDrag the component that you want to drag
  41920. @param e the mouse event that is triggering the drag
  41921. @see dragComponent
  41922. */
  41923. void startDraggingComponent (Component* componentToDrag,
  41924. const MouseEvent& e);
  41925. /** Call this from your mouseDrag() callback to move the component.
  41926. This will move the component, but will first check the validity of the
  41927. component's new position using the checkPosition() method, which you
  41928. can override if you need to enforce special positioning limits on the
  41929. component.
  41930. @param componentToDrag the component that you want to drag
  41931. @param e the current mouse-drag event
  41932. @param constrainer an optional constrainer object that should be used
  41933. to apply limits to the component's position. Pass
  41934. null if you don't want to contrain the movement.
  41935. @see startDraggingComponent
  41936. */
  41937. void dragComponent (Component* componentToDrag,
  41938. const MouseEvent& e,
  41939. ComponentBoundsConstrainer* constrainer);
  41940. private:
  41941. Point<int> mouseDownWithinTarget;
  41942. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentDragger);
  41943. };
  41944. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  41945. /*** End of inlined file: juce_ComponentDragger.h ***/
  41946. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  41947. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  41948. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  41949. /**
  41950. A component that resizes its parent component when dragged.
  41951. This component forms a frame around the edge of a component, allowing it to
  41952. be dragged by the edges or corners to resize it - like the way windows are
  41953. resized in MSWindows or Linux.
  41954. To use it, just add it to your component, making it fill the entire parent component
  41955. (there's a mouse hit-test that only traps mouse-events which land around the
  41956. edge of the component, so it's even ok to put it on top of any other components
  41957. you're using). Make sure you rescale the resizer component to fill the parent
  41958. each time the parent's size changes.
  41959. @see ResizableCornerComponent
  41960. */
  41961. class JUCE_API ResizableBorderComponent : public Component
  41962. {
  41963. public:
  41964. /** Creates a resizer.
  41965. Pass in the target component which you want to be resized when this one is
  41966. dragged.
  41967. The target component will usually be a parent of the resizer component, but this
  41968. isn't mandatory.
  41969. Remember that when the target component is resized, it'll need to move and
  41970. resize this component to keep it in place, as this won't happen automatically.
  41971. If the constrainer parameter is non-zero, then this object will be used to enforce
  41972. limits on the size and position that the component can be stretched to. Make sure
  41973. that the constrainer isn't deleted while still in use by this object.
  41974. @see ComponentBoundsConstrainer
  41975. */
  41976. ResizableBorderComponent (Component* componentToResize,
  41977. ComponentBoundsConstrainer* constrainer);
  41978. /** Destructor. */
  41979. ~ResizableBorderComponent();
  41980. /** Specifies how many pixels wide the draggable edges of this component are.
  41981. @see getBorderThickness
  41982. */
  41983. void setBorderThickness (const BorderSize<int>& newBorderSize);
  41984. /** Returns the number of pixels wide that the draggable edges of this component are.
  41985. @see setBorderThickness
  41986. */
  41987. const BorderSize<int> getBorderThickness() const;
  41988. /** Represents the different sections of a resizable border, which allow it to
  41989. resized in different ways.
  41990. */
  41991. class Zone
  41992. {
  41993. public:
  41994. enum Zones
  41995. {
  41996. centre = 0,
  41997. left = 1,
  41998. top = 2,
  41999. right = 4,
  42000. bottom = 8
  42001. };
  42002. /** Creates a Zone from a combination of the flags in \enum Zones. */
  42003. explicit Zone (int zoneFlags = 0) throw();
  42004. Zone (const Zone& other) throw();
  42005. Zone& operator= (const Zone& other) throw();
  42006. bool operator== (const Zone& other) const throw();
  42007. bool operator!= (const Zone& other) const throw();
  42008. /** Given a point within a rectangle with a resizable border, this returns the
  42009. zone that the point lies within.
  42010. */
  42011. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  42012. const BorderSize<int>& border,
  42013. const Point<int>& position);
  42014. /** Returns an appropriate mouse-cursor for this resize zone. */
  42015. const MouseCursor getMouseCursor() const throw();
  42016. /** Returns true if dragging this zone will move the enire object without resizing it. */
  42017. bool isDraggingWholeObject() const throw() { return zone == centre; }
  42018. /** Returns true if dragging this zone will move the object's left edge. */
  42019. bool isDraggingLeftEdge() const throw() { return (zone & left) != 0; }
  42020. /** Returns true if dragging this zone will move the object's right edge. */
  42021. bool isDraggingRightEdge() const throw() { return (zone & right) != 0; }
  42022. /** Returns true if dragging this zone will move the object's top edge. */
  42023. bool isDraggingTopEdge() const throw() { return (zone & top) != 0; }
  42024. /** Returns true if dragging this zone will move the object's bottom edge. */
  42025. bool isDraggingBottomEdge() const throw() { return (zone & bottom) != 0; }
  42026. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  42027. applies to.
  42028. */
  42029. template <typename ValueType>
  42030. const Rectangle<ValueType> resizeRectangleBy (Rectangle<ValueType> original,
  42031. const Point<ValueType>& distance) const throw()
  42032. {
  42033. if (isDraggingWholeObject())
  42034. return original + distance;
  42035. if (isDraggingLeftEdge())
  42036. original.setLeft (jmin (original.getRight(), original.getX() + distance.getX()));
  42037. if (isDraggingRightEdge())
  42038. original.setWidth (jmax (ValueType(), original.getWidth() + distance.getX()));
  42039. if (isDraggingTopEdge())
  42040. original.setTop (jmin (original.getBottom(), original.getY() + distance.getY()));
  42041. if (isDraggingBottomEdge())
  42042. original.setHeight (jmax (ValueType(), original.getHeight() + distance.getY()));
  42043. return original;
  42044. }
  42045. /** Returns the raw flags for this zone. */
  42046. int getZoneFlags() const throw() { return zone; }
  42047. private:
  42048. int zone;
  42049. };
  42050. protected:
  42051. /** @internal */
  42052. void paint (Graphics& g);
  42053. /** @internal */
  42054. void mouseEnter (const MouseEvent& e);
  42055. /** @internal */
  42056. void mouseMove (const MouseEvent& e);
  42057. /** @internal */
  42058. void mouseDown (const MouseEvent& e);
  42059. /** @internal */
  42060. void mouseDrag (const MouseEvent& e);
  42061. /** @internal */
  42062. void mouseUp (const MouseEvent& e);
  42063. /** @internal */
  42064. bool hitTest (int x, int y);
  42065. private:
  42066. WeakReference<Component> component;
  42067. ComponentBoundsConstrainer* constrainer;
  42068. BorderSize<int> borderSize;
  42069. Rectangle<int> originalBounds;
  42070. Zone mouseZone;
  42071. void updateMouseZone (const MouseEvent& e);
  42072. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableBorderComponent);
  42073. };
  42074. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  42075. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  42076. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  42077. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  42078. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  42079. /** A component that resizes a parent component when dragged.
  42080. This is the small triangular stripey resizer component you get in the bottom-right
  42081. of windows (more commonly on the Mac than Windows). Put one in the corner of
  42082. a larger component and it will automatically resize its parent when it gets dragged
  42083. around.
  42084. @see ResizableFrameComponent
  42085. */
  42086. class JUCE_API ResizableCornerComponent : public Component
  42087. {
  42088. public:
  42089. /** Creates a resizer.
  42090. Pass in the target component which you want to be resized when this one is
  42091. dragged.
  42092. The target component will usually be a parent of the resizer component, but this
  42093. isn't mandatory.
  42094. Remember that when the target component is resized, it'll need to move and
  42095. resize this component to keep it in place, as this won't happen automatically.
  42096. If the constrainer parameter is non-zero, then this object will be used to enforce
  42097. limits on the size and position that the component can be stretched to. Make sure
  42098. that the constrainer isn't deleted while still in use by this object. If you
  42099. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  42100. @see ComponentBoundsConstrainer
  42101. */
  42102. ResizableCornerComponent (Component* componentToResize,
  42103. ComponentBoundsConstrainer* constrainer);
  42104. /** Destructor. */
  42105. ~ResizableCornerComponent();
  42106. protected:
  42107. /** @internal */
  42108. void paint (Graphics& g);
  42109. /** @internal */
  42110. void mouseDown (const MouseEvent& e);
  42111. /** @internal */
  42112. void mouseDrag (const MouseEvent& e);
  42113. /** @internal */
  42114. void mouseUp (const MouseEvent& e);
  42115. /** @internal */
  42116. bool hitTest (int x, int y);
  42117. private:
  42118. WeakReference<Component> component;
  42119. ComponentBoundsConstrainer* constrainer;
  42120. Rectangle<int> originalBounds;
  42121. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableCornerComponent);
  42122. };
  42123. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  42124. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  42125. /**
  42126. A base class for top-level windows that can be dragged around and resized.
  42127. To add content to the window, use its setContentOwned() or setContentNonOwned() methods
  42128. to give it a component that will remain positioned inside it (leaving a gap around
  42129. the edges for a border).
  42130. It's not advisable to add child components directly to a ResizableWindow: put them
  42131. inside your content component instead. And overriding methods like resized(), moved(), etc
  42132. is also not recommended - instead override these methods for your content component.
  42133. (If for some obscure reason you do need to override these methods, always remember to
  42134. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  42135. decorations correctly).
  42136. By default resizing isn't enabled - use the setResizable() method to enable it and
  42137. to choose the style of resizing to use.
  42138. @see TopLevelWindow
  42139. */
  42140. class JUCE_API ResizableWindow : public TopLevelWindow
  42141. {
  42142. public:
  42143. /** Creates a ResizableWindow.
  42144. This constructor doesn't specify a background colour, so the LookAndFeel's default
  42145. background colour will be used.
  42146. @param name the name to give the component
  42147. @param addToDesktop if true, the window will be automatically added to the
  42148. desktop; if false, you can use it as a child component
  42149. */
  42150. ResizableWindow (const String& name,
  42151. bool addToDesktop);
  42152. /** Creates a ResizableWindow.
  42153. @param name the name to give the component
  42154. @param backgroundColour the colour to use for filling the window's background.
  42155. @param addToDesktop if true, the window will be automatically added to the
  42156. desktop; if false, you can use it as a child component
  42157. */
  42158. ResizableWindow (const String& name,
  42159. const Colour& backgroundColour,
  42160. bool addToDesktop);
  42161. /** Destructor.
  42162. If a content component has been set with setContentOwned(), it will be deleted.
  42163. */
  42164. ~ResizableWindow();
  42165. /** Returns the colour currently being used for the window's background.
  42166. As a convenience the window will fill itself with this colour, but you
  42167. can override the paint() method if you need more customised behaviour.
  42168. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  42169. @see setBackgroundColour
  42170. */
  42171. const Colour getBackgroundColour() const throw();
  42172. /** Changes the colour currently being used for the window's background.
  42173. As a convenience the window will fill itself with this colour, but you
  42174. can override the paint() method if you need more customised behaviour.
  42175. Note that the opaque state of this window is altered by this call to reflect
  42176. the opacity of the colour passed-in. On window systems which can't support
  42177. semi-transparent windows this might cause problems, (though it's unlikely you'll
  42178. be using this class as a base for a semi-transparent component anyway).
  42179. You can also use the ResizableWindow::backgroundColourId colour id to set
  42180. this colour.
  42181. @see getBackgroundColour
  42182. */
  42183. void setBackgroundColour (const Colour& newColour);
  42184. /** Make the window resizable or fixed.
  42185. @param shouldBeResizable whether it's resizable at all
  42186. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  42187. bottom-right; if false, it'll use a ResizableBorderComponent
  42188. around the edge
  42189. @see setResizeLimits, isResizable
  42190. */
  42191. void setResizable (bool shouldBeResizable,
  42192. bool useBottomRightCornerResizer);
  42193. /** True if resizing is enabled.
  42194. @see setResizable
  42195. */
  42196. bool isResizable() const throw();
  42197. /** This sets the maximum and minimum sizes for the window.
  42198. If the window's current size is outside these limits, it will be resized to
  42199. make sure it's within them.
  42200. Calling setBounds() on the component will bypass any size checking - it's only when
  42201. the window is being resized by the user that these values are enforced.
  42202. @see setResizable, setFixedAspectRatio
  42203. */
  42204. void setResizeLimits (int newMinimumWidth,
  42205. int newMinimumHeight,
  42206. int newMaximumWidth,
  42207. int newMaximumHeight) throw();
  42208. /** Returns the bounds constrainer object that this window is using.
  42209. You can access this to change its properties.
  42210. */
  42211. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  42212. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  42213. A pointer to the object you pass in will be kept, but it won't be deleted
  42214. by this object, so it's the caller's responsiblity to manage it.
  42215. If you pass 0, then no contraints will be placed on the positioning of the window.
  42216. */
  42217. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  42218. /** Calls the window's setBounds method, after first checking these bounds
  42219. with the current constrainer.
  42220. @see setConstrainer
  42221. */
  42222. void setBoundsConstrained (const Rectangle<int>& bounds);
  42223. /** Returns true if the window is currently in full-screen mode.
  42224. @see setFullScreen
  42225. */
  42226. bool isFullScreen() const;
  42227. /** Puts the window into full-screen mode, or restores it to its normal size.
  42228. If true, the window will become full-screen; if false, it will return to the
  42229. last size it was before being made full-screen.
  42230. @see isFullScreen
  42231. */
  42232. void setFullScreen (bool shouldBeFullScreen);
  42233. /** Returns true if the window is currently minimised.
  42234. @see setMinimised
  42235. */
  42236. bool isMinimised() const;
  42237. /** Minimises the window, or restores it to its previous position and size.
  42238. When being un-minimised, it'll return to the last position and size it
  42239. was in before being minimised.
  42240. @see isMinimised
  42241. */
  42242. void setMinimised (bool shouldMinimise);
  42243. /** Returns a string which encodes the window's current size and position.
  42244. This string will encapsulate the window's size, position, and whether it's
  42245. in full-screen mode. It's intended for letting your application save and
  42246. restore a window's position.
  42247. Use the restoreWindowStateFromString() to restore from a saved state.
  42248. @see restoreWindowStateFromString
  42249. */
  42250. const String getWindowStateAsString();
  42251. /** Restores the window to a previously-saved size and position.
  42252. This restores the window's size, positon and full-screen status from an
  42253. string that was previously created with the getWindowStateAsString()
  42254. method.
  42255. @returns false if the string wasn't a valid window state
  42256. @see getWindowStateAsString
  42257. */
  42258. bool restoreWindowStateFromString (const String& previousState);
  42259. /** Returns the current content component.
  42260. This will be the component set by setContentOwned() or setContentNonOwned, or 0 if none
  42261. has yet been specified.
  42262. @see setContentOwned, setContentNonOwned
  42263. */
  42264. Component* getContentComponent() const throw() { return contentComponent; }
  42265. /** Changes the current content component.
  42266. This sets a component that will be placed in the centre of the ResizableWindow,
  42267. (leaving a space around the edge for the border).
  42268. You should never add components directly to a ResizableWindow (or any of its subclasses)
  42269. with addChildComponent(). Instead, add them to the content component.
  42270. @param newContentComponent the new component to use - this component will be deleted when it's
  42271. no longer needed (i.e. when the window is deleted or a new content
  42272. component is set for it). To set a component that this window will not
  42273. delete, call setContentNonOwned() instead.
  42274. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  42275. such that it always fits around the size of the content component. If false,
  42276. the new content will be resized to fit the current space available.
  42277. */
  42278. void setContentOwned (Component* newContentComponent,
  42279. bool resizeToFitWhenContentChangesSize);
  42280. /** Changes the current content component.
  42281. This sets a component that will be placed in the centre of the ResizableWindow,
  42282. (leaving a space around the edge for the border).
  42283. You should never add components directly to a ResizableWindow (or any of its subclasses)
  42284. with addChildComponent(). Instead, add them to the content component.
  42285. @param newContentComponent the new component to use - this component will NOT be deleted by this
  42286. component, so it's the caller's responsibility to manage its lifetime (it's
  42287. ok to delete it while this window is still using it). To set a content
  42288. component that the window will delete, call setContentOwned() instead.
  42289. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  42290. such that it always fits around the size of the content component. If false,
  42291. the new content will be resized to fit the current space available.
  42292. */
  42293. void setContentNonOwned (Component* newContentComponent,
  42294. bool resizeToFitWhenContentChangesSize);
  42295. /** Removes the current content component.
  42296. If the previous content component was added with setContentOwned(), it will also be deleted. If
  42297. it was added with setContentNonOwned(), it will simply be removed from this component.
  42298. */
  42299. void clearContentComponent();
  42300. /** Changes the window so that the content component ends up with the specified size.
  42301. This is basically a setSize call on the window, but which adds on the borders,
  42302. so you can specify the content component's target size.
  42303. */
  42304. void setContentComponentSize (int width, int height);
  42305. /** Returns the width of the frame to use around the window.
  42306. @see getContentComponentBorder
  42307. */
  42308. virtual const BorderSize<int> getBorderThickness();
  42309. /** Returns the insets to use when positioning the content component.
  42310. @see getBorderThickness
  42311. */
  42312. virtual const BorderSize<int> getContentComponentBorder();
  42313. /** A set of colour IDs to use to change the colour of various aspects of the window.
  42314. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42315. methods.
  42316. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42317. */
  42318. enum ColourIds
  42319. {
  42320. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  42321. };
  42322. /** @deprecated - use setContentOwned() and setContentNonOwned() instead. */
  42323. JUCE_DEPRECATED (void setContentComponent (Component* newContentComponent,
  42324. bool deleteOldOne = true,
  42325. bool resizeToFit = false));
  42326. protected:
  42327. /** @internal */
  42328. void paint (Graphics& g);
  42329. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  42330. void moved();
  42331. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  42332. void resized();
  42333. /** @internal */
  42334. void mouseDown (const MouseEvent& e);
  42335. /** @internal */
  42336. void mouseDrag (const MouseEvent& e);
  42337. /** @internal */
  42338. void lookAndFeelChanged();
  42339. /** @internal */
  42340. void childBoundsChanged (Component* child);
  42341. /** @internal */
  42342. void parentSizeChanged();
  42343. /** @internal */
  42344. void visibilityChanged();
  42345. /** @internal */
  42346. void activeWindowStatusChanged();
  42347. /** @internal */
  42348. int getDesktopWindowStyleFlags() const;
  42349. #if JUCE_DEBUG
  42350. /** Overridden to warn people about adding components directly to this component
  42351. instead of using setContentOwned().
  42352. If you know what you're doing and are sure you really want to add a component, specify
  42353. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  42354. */
  42355. void addChildComponent (Component* child, int zOrder = -1);
  42356. /** Overridden to warn people about adding components directly to this component
  42357. instead of using setContentOwned().
  42358. If you know what you're doing and are sure you really want to add a component, specify
  42359. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  42360. */
  42361. void addAndMakeVisible (Component* child, int zOrder = -1);
  42362. #endif
  42363. ScopedPointer <ResizableCornerComponent> resizableCorner;
  42364. ScopedPointer <ResizableBorderComponent> resizableBorder;
  42365. private:
  42366. Component::SafePointer <Component> contentComponent;
  42367. bool ownsContentComponent, resizeToFitContent, fullscreen;
  42368. ComponentDragger dragger;
  42369. Rectangle<int> lastNonFullScreenPos;
  42370. ComponentBoundsConstrainer defaultConstrainer;
  42371. ComponentBoundsConstrainer* constrainer;
  42372. #if JUCE_DEBUG
  42373. bool hasBeenResized;
  42374. #endif
  42375. void updateLastPos();
  42376. void setContent (Component* newComp, bool takeOwnership, bool resizeToFit);
  42377. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  42378. // The parameters for these methods have changed - please update your code!
  42379. JUCE_DEPRECATED (void getBorderThickness (int& left, int& top, int& right, int& bottom));
  42380. JUCE_DEPRECATED (void getContentComponentBorder (int& left, int& top, int& right, int& bottom));
  42381. #endif
  42382. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableWindow);
  42383. };
  42384. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  42385. /*** End of inlined file: juce_ResizableWindow.h ***/
  42386. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  42387. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  42388. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  42389. /**
  42390. A glyph from a particular font, with a particular size, style,
  42391. typeface and position.
  42392. @see GlyphArrangement, Font
  42393. */
  42394. class JUCE_API PositionedGlyph
  42395. {
  42396. public:
  42397. PositionedGlyph (const PositionedGlyph& other);
  42398. /** Returns the character the glyph represents. */
  42399. juce_wchar getCharacter() const { return character; }
  42400. /** Checks whether the glyph is actually empty. */
  42401. bool isWhitespace() const { return CharacterFunctions::isWhitespace (character); }
  42402. /** Returns the position of the glyph's left-hand edge. */
  42403. float getLeft() const { return x; }
  42404. /** Returns the position of the glyph's right-hand edge. */
  42405. float getRight() const { return x + w; }
  42406. /** Returns the y position of the glyph's baseline. */
  42407. float getBaselineY() const { return y; }
  42408. /** Returns the y position of the top of the glyph. */
  42409. float getTop() const { return y - font.getAscent(); }
  42410. /** Returns the y position of the bottom of the glyph. */
  42411. float getBottom() const { return y + font.getDescent(); }
  42412. /** Returns the bounds of the glyph. */
  42413. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  42414. /** Shifts the glyph's position by a relative amount. */
  42415. void moveBy (float deltaX, float deltaY);
  42416. /** Draws the glyph into a graphics context. */
  42417. void draw (const Graphics& g) const;
  42418. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  42419. void draw (const Graphics& g, const AffineTransform& transform) const;
  42420. /** Returns the path for this glyph.
  42421. @param path the glyph's outline will be appended to this path
  42422. */
  42423. void createPath (Path& path) const;
  42424. /** Checks to see if a point lies within this glyph. */
  42425. bool hitTest (float x, float y) const;
  42426. private:
  42427. friend class GlyphArrangement;
  42428. float x, y, w;
  42429. Font font;
  42430. juce_wchar character;
  42431. int glyph;
  42432. PositionedGlyph (float x, float y, float w, const Font& font, juce_wchar character, int glyph);
  42433. JUCE_LEAK_DETECTOR (PositionedGlyph);
  42434. };
  42435. /**
  42436. A set of glyphs, each with a position.
  42437. You can create a GlyphArrangement, text to it and then draw it onto a
  42438. graphics context. It's used internally by the text methods in the
  42439. Graphics class, but can be used directly if more control is needed.
  42440. @see Font, PositionedGlyph
  42441. */
  42442. class JUCE_API GlyphArrangement
  42443. {
  42444. public:
  42445. /** Creates an empty arrangement. */
  42446. GlyphArrangement();
  42447. /** Takes a copy of another arrangement. */
  42448. GlyphArrangement (const GlyphArrangement& other);
  42449. /** Copies another arrangement onto this one.
  42450. To add another arrangement without clearing this one, use addGlyphArrangement().
  42451. */
  42452. GlyphArrangement& operator= (const GlyphArrangement& other);
  42453. /** Destructor. */
  42454. ~GlyphArrangement();
  42455. /** Returns the total number of glyphs in the arrangement. */
  42456. int getNumGlyphs() const throw() { return glyphs.size(); }
  42457. /** Returns one of the glyphs from the arrangement.
  42458. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  42459. careful not to pass an out-of-range index here, as it
  42460. doesn't do any bounds-checking.
  42461. */
  42462. PositionedGlyph& getGlyph (int index) const;
  42463. /** Clears all text from the arrangement and resets it.
  42464. */
  42465. void clear();
  42466. /** Appends a line of text to the arrangement.
  42467. This will add the text as a single line, where x is the left-hand edge of the
  42468. first character, and y is the position for the text's baseline.
  42469. If the text contains new-lines or carriage-returns, this will ignore them - use
  42470. addJustifiedText() to add multi-line arrangements.
  42471. */
  42472. void addLineOfText (const Font& font,
  42473. const String& text,
  42474. float x, float y);
  42475. /** Adds a line of text, truncating it if it's wider than a specified size.
  42476. This is the same as addLineOfText(), but if the line's width exceeds the value
  42477. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  42478. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  42479. */
  42480. void addCurtailedLineOfText (const Font& font,
  42481. const String& text,
  42482. float x, float y,
  42483. float maxWidthPixels,
  42484. bool useEllipsis);
  42485. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  42486. This will add text to the arrangement, breaking it into new lines either where there
  42487. is a new-line or carriage-return character in the text, or where a line's width
  42488. exceeds the value set in maxLineWidth.
  42489. Each line that is added will be laid out using the flags set in horizontalLayout, so
  42490. the lines can be left- or right-justified, or centred horizontally in the space
  42491. between x and (x + maxLineWidth).
  42492. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  42493. lines will be placed below it, separated by a distance of font.getHeight().
  42494. */
  42495. void addJustifiedText (const Font& font,
  42496. const String& text,
  42497. float x, float y,
  42498. float maxLineWidth,
  42499. const Justification& horizontalLayout);
  42500. /** Tries to fit some text withing a given space.
  42501. This does its best to make the given text readable within the specified rectangle,
  42502. so it useful for labelling things.
  42503. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  42504. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  42505. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  42506. it's been truncated.
  42507. A Justification parameter lets you specify how the text is laid out within the rectangle,
  42508. both horizontally and vertically.
  42509. @see Graphics::drawFittedText
  42510. */
  42511. void addFittedText (const Font& font,
  42512. const String& text,
  42513. float x, float y, float width, float height,
  42514. const Justification& layout,
  42515. int maximumLinesToUse,
  42516. float minimumHorizontalScale = 0.7f);
  42517. /** Appends another glyph arrangement to this one. */
  42518. void addGlyphArrangement (const GlyphArrangement& other);
  42519. /** Draws this glyph arrangement to a graphics context.
  42520. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  42521. method, which renders the glyphs as filled vectors.
  42522. */
  42523. void draw (const Graphics& g) const;
  42524. /** Draws this glyph arrangement to a graphics context.
  42525. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  42526. method for non-transformed arrangements.
  42527. */
  42528. void draw (const Graphics& g, const AffineTransform& transform) const;
  42529. /** Converts the set of glyphs into a path.
  42530. @param path the glyphs' outlines will be appended to this path
  42531. */
  42532. void createPath (Path& path) const;
  42533. /** Looks for a glyph that contains the given co-ordinate.
  42534. @returns the index of the glyph, or -1 if none were found.
  42535. */
  42536. int findGlyphIndexAt (float x, float y) const;
  42537. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  42538. @param startIndex the first glyph to test
  42539. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  42540. startIndex will be included
  42541. @param includeWhitespace if true, the extent of any whitespace characters will also
  42542. be taken into account
  42543. */
  42544. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  42545. /** Shifts a set of glyphs by a given amount.
  42546. @param startIndex the first glyph to transform
  42547. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  42548. startIndex will be used
  42549. @param deltaX the amount to add to their x-positions
  42550. @param deltaY the amount to add to their y-positions
  42551. */
  42552. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  42553. float deltaX, float deltaY);
  42554. /** Removes a set of glyphs from the arrangement.
  42555. @param startIndex the first glyph to remove
  42556. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  42557. startIndex will be deleted
  42558. */
  42559. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  42560. /** Expands or compresses a set of glyphs horizontally.
  42561. @param startIndex the first glyph to transform
  42562. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  42563. startIndex will be used
  42564. @param horizontalScaleFactor how much to scale their horizontal width by
  42565. */
  42566. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  42567. float horizontalScaleFactor);
  42568. /** Justifies a set of glyphs within a given space.
  42569. This moves the glyphs as a block so that the whole thing is located within the
  42570. given rectangle with the specified layout.
  42571. If the Justification::horizontallyJustified flag is specified, each line will
  42572. be stretched out to fill the specified width.
  42573. */
  42574. void justifyGlyphs (int startIndex, int numGlyphs,
  42575. float x, float y, float width, float height,
  42576. const Justification& justification);
  42577. private:
  42578. OwnedArray <PositionedGlyph> glyphs;
  42579. int insertEllipsis (const Font& font, float maxXPos, int startIndex, int endIndex);
  42580. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  42581. const Justification& justification, float minimumHorizontalScale);
  42582. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  42583. JUCE_LEAK_DETECTOR (GlyphArrangement);
  42584. };
  42585. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  42586. /*** End of inlined file: juce_GlyphArrangement.h ***/
  42587. /*** Start of inlined file: juce_AlertWindow.h ***/
  42588. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  42589. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  42590. /*** Start of inlined file: juce_TextLayout.h ***/
  42591. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  42592. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  42593. class Graphics;
  42594. /**
  42595. A laid-out arrangement of text.
  42596. You can add text in different fonts to a TextLayout object, then call its
  42597. layout() method to word-wrap it into lines. The layout can then be drawn
  42598. using a graphics context.
  42599. It's handy if you've got a message to display, because you can format it,
  42600. measure the extent of the layout, and then create a suitably-sized window
  42601. to show it in.
  42602. @see Font, Graphics::drawFittedText, GlyphArrangement
  42603. */
  42604. class JUCE_API TextLayout
  42605. {
  42606. public:
  42607. /** Creates an empty text layout.
  42608. Text can then be appended using the appendText() method.
  42609. */
  42610. TextLayout();
  42611. /** Creates a copy of another layout object. */
  42612. TextLayout (const TextLayout& other);
  42613. /** Creates a text layout from an initial string and font. */
  42614. TextLayout (const String& text, const Font& font);
  42615. /** Destructor. */
  42616. ~TextLayout();
  42617. /** Copies another layout onto this one. */
  42618. TextLayout& operator= (const TextLayout& layoutToCopy);
  42619. /** Clears the layout, removing all its text. */
  42620. void clear();
  42621. /** Adds a string to the end of the arrangement.
  42622. The string will be broken onto new lines wherever it contains
  42623. carriage-returns or linefeeds. After adding it, you can call layout()
  42624. to wrap long lines into a paragraph and justify it.
  42625. */
  42626. void appendText (const String& textToAppend,
  42627. const Font& fontToUse);
  42628. /** Replaces all the text with a new string.
  42629. This is equivalent to calling clear() followed by appendText().
  42630. */
  42631. void setText (const String& newText,
  42632. const Font& fontToUse);
  42633. /** Returns true if the layout has not had any text added yet. */
  42634. bool isEmpty() const;
  42635. /** Breaks the text up to form a paragraph with the given width.
  42636. @param maximumWidth any text wider than this will be split
  42637. across multiple lines
  42638. @param justification how the lines are to be laid-out horizontally
  42639. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  42640. width that keeps all the lines of text at a
  42641. similar length - this is good when you're displaying
  42642. a short message and don't want it to get split
  42643. onto two lines with only a couple of words on
  42644. the second line, which looks untidy.
  42645. */
  42646. void layout (int maximumWidth,
  42647. const Justification& justification,
  42648. bool attemptToBalanceLineLengths);
  42649. /** Returns the overall width of the entire text layout. */
  42650. int getWidth() const;
  42651. /** Returns the overall height of the entire text layout. */
  42652. int getHeight() const;
  42653. /** Returns the total number of lines of text. */
  42654. int getNumLines() const { return totalLines; }
  42655. /** Returns the width of a particular line of text.
  42656. @param lineNumber the line, from 0 to (getNumLines() - 1)
  42657. */
  42658. int getLineWidth (int lineNumber) const;
  42659. /** Renders the text at a specified position using a graphics context.
  42660. */
  42661. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  42662. /** Renders the text within a specified rectangle using a graphics context.
  42663. The justification flags dictate how the block of text should be positioned
  42664. within the rectangle.
  42665. */
  42666. void drawWithin (Graphics& g,
  42667. int x, int y, int w, int h,
  42668. const Justification& layoutFlags) const;
  42669. private:
  42670. class Token;
  42671. friend class OwnedArray <Token>;
  42672. OwnedArray <Token> tokens;
  42673. int totalLines;
  42674. JUCE_LEAK_DETECTOR (TextLayout);
  42675. };
  42676. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  42677. /*** End of inlined file: juce_TextLayout.h ***/
  42678. /** A window that displays a message and has buttons for the user to react to it.
  42679. For simple dialog boxes with just a couple of buttons on them, there are
  42680. some static methods for running these.
  42681. For more complex dialogs, an AlertWindow can be created, then it can have some
  42682. buttons and components added to it, and its runModalLoop() method is then used to
  42683. show it. The value returned by runModalLoop() shows which button the
  42684. user pressed to dismiss the box.
  42685. @see ThreadWithProgressWindow
  42686. */
  42687. class JUCE_API AlertWindow : public TopLevelWindow,
  42688. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  42689. {
  42690. public:
  42691. /** The type of icon to show in the dialog box. */
  42692. enum AlertIconType
  42693. {
  42694. NoIcon, /**< No icon will be shown on the dialog box. */
  42695. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  42696. user to answer a question. */
  42697. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  42698. warning about something and shouldn't be ignored. */
  42699. InfoIcon /**< An icon that indicates that the dialog box is just
  42700. giving the user some information, which doesn't require
  42701. a response from them. */
  42702. };
  42703. /** Creates an AlertWindow.
  42704. @param title the headline to show at the top of the dialog box
  42705. @param message a longer, more descriptive message to show underneath the
  42706. headline
  42707. @param iconType the type of icon to display
  42708. @param associatedComponent if this is non-null, it specifies the component that the
  42709. alert window should be associated with. Depending on the look
  42710. and feel, this might be used for positioning of the alert window.
  42711. */
  42712. AlertWindow (const String& title,
  42713. const String& message,
  42714. AlertIconType iconType,
  42715. Component* associatedComponent = 0);
  42716. /** Destroys the AlertWindow */
  42717. ~AlertWindow();
  42718. /** Returns the type of alert icon that was specified when the window
  42719. was created. */
  42720. AlertIconType getAlertType() const throw() { return alertIconType; }
  42721. /** Changes the dialog box's message.
  42722. This will also resize the window to fit the new message if required.
  42723. */
  42724. void setMessage (const String& message);
  42725. /** Adds a button to the window.
  42726. @param name the text to show on the button
  42727. @param returnValue the value that should be returned from runModalLoop()
  42728. if this is the button that the user presses.
  42729. @param shortcutKey1 an optional key that can be pressed to trigger this button
  42730. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  42731. */
  42732. void addButton (const String& name,
  42733. int returnValue,
  42734. const KeyPress& shortcutKey1 = KeyPress(),
  42735. const KeyPress& shortcutKey2 = KeyPress());
  42736. /** Returns the number of buttons that the window currently has. */
  42737. int getNumButtons() const;
  42738. /** Invokes a click of one of the buttons. */
  42739. void triggerButtonClick (const String& buttonName);
  42740. /** Adds a textbox to the window for entering strings.
  42741. @param name an internal name for the text-box. This is the name to pass to
  42742. the getTextEditorContents() method to find out what the
  42743. user typed-in.
  42744. @param initialContents a string to show in the text box when it's first shown
  42745. @param onScreenLabel if this is non-empty, it will be displayed next to the
  42746. text-box to label it.
  42747. @param isPasswordBox if true, the text editor will display asterisks instead of
  42748. the actual text
  42749. @see getTextEditorContents
  42750. */
  42751. void addTextEditor (const String& name,
  42752. const String& initialContents,
  42753. const String& onScreenLabel = String::empty,
  42754. bool isPasswordBox = false);
  42755. /** Returns the contents of a named textbox.
  42756. After showing an AlertWindow that contains a text editor, this can be
  42757. used to find out what the user has typed into it.
  42758. @param nameOfTextEditor the name of the text box that you're interested in
  42759. @see addTextEditor
  42760. */
  42761. const String getTextEditorContents (const String& nameOfTextEditor) const;
  42762. /** Returns a pointer to a textbox that was added with addTextEditor(). */
  42763. TextEditor* getTextEditor (const String& nameOfTextEditor) const;
  42764. /** Adds a drop-down list of choices to the box.
  42765. After the box has been shown, the getComboBoxComponent() method can
  42766. be used to find out which item the user picked.
  42767. @param name the label to use for the drop-down list
  42768. @param items the list of items to show in it
  42769. @param onScreenLabel if this is non-empty, it will be displayed next to the
  42770. combo-box to label it.
  42771. @see getComboBoxComponent
  42772. */
  42773. void addComboBox (const String& name,
  42774. const StringArray& items,
  42775. const String& onScreenLabel = String::empty);
  42776. /** Returns a drop-down list that was added to the AlertWindow.
  42777. @param nameOfList the name that was passed into the addComboBox() method
  42778. when creating the drop-down
  42779. @returns the ComboBox component, or 0 if none was found for the given name.
  42780. */
  42781. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  42782. /** Adds a block of text.
  42783. This is handy for adding a multi-line note next to a textbox or combo-box,
  42784. to provide more details about what's going on.
  42785. */
  42786. void addTextBlock (const String& text);
  42787. /** Adds a progress-bar to the window.
  42788. @param progressValue a variable that will be repeatedly checked while the
  42789. dialog box is visible, to see how far the process has
  42790. got. The value should be in the range 0 to 1.0
  42791. */
  42792. void addProgressBarComponent (double& progressValue);
  42793. /** Adds a user-defined component to the dialog box.
  42794. @param component the component to add - its size should be set up correctly
  42795. before it is passed in. The caller is responsible for deleting
  42796. the component later on - the AlertWindow won't delete it.
  42797. */
  42798. void addCustomComponent (Component* component);
  42799. /** Returns the number of custom components in the dialog box.
  42800. @see getCustomComponent, addCustomComponent
  42801. */
  42802. int getNumCustomComponents() const;
  42803. /** Returns one of the custom components in the dialog box.
  42804. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  42805. will return 0
  42806. @see getNumCustomComponents, addCustomComponent
  42807. */
  42808. Component* getCustomComponent (int index) const;
  42809. /** Removes one of the custom components in the dialog box.
  42810. Note that this won't delete it, it just removes the component from the window
  42811. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  42812. will return 0
  42813. @returns the component that was removed (or null)
  42814. @see getNumCustomComponents, addCustomComponent
  42815. */
  42816. Component* removeCustomComponent (int index);
  42817. /** Returns true if the window contains any components other than just buttons.*/
  42818. bool containsAnyExtraComponents() const;
  42819. // easy-to-use message box functions:
  42820. /** Shows a dialog box that just has a message and a single button to get rid of it.
  42821. If the callback parameter is null, the box is shown modally, and the method will
  42822. block until the user has clicked the button (or pressed the escape or return keys).
  42823. If the callback parameter is non-null, the box will be displayed and placed into a
  42824. modal state, but this method will return immediately, and the callback will be invoked
  42825. later when the user dismisses the box.
  42826. @param iconType the type of icon to show
  42827. @param title the headline to show at the top of the box
  42828. @param message a longer, more descriptive message to show underneath the
  42829. headline
  42830. @param buttonText the text to show in the button - if this string is empty, the
  42831. default string "ok" (or a localised version) will be used.
  42832. @param associatedComponent if this is non-null, it specifies the component that the
  42833. alert window should be associated with. Depending on the look
  42834. and feel, this might be used for positioning of the alert window.
  42835. */
  42836. #if JUCE_MODAL_LOOPS_PERMITTED
  42837. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  42838. const String& title,
  42839. const String& message,
  42840. const String& buttonText = String::empty,
  42841. Component* associatedComponent = 0);
  42842. #endif
  42843. /** Shows a dialog box that just has a message and a single button to get rid of it.
  42844. If the callback parameter is null, the box is shown modally, and the method will
  42845. block until the user has clicked the button (or pressed the escape or return keys).
  42846. If the callback parameter is non-null, the box will be displayed and placed into a
  42847. modal state, but this method will return immediately, and the callback will be invoked
  42848. later when the user dismisses the box.
  42849. @param iconType the type of icon to show
  42850. @param title the headline to show at the top of the box
  42851. @param message a longer, more descriptive message to show underneath the
  42852. headline
  42853. @param buttonText the text to show in the button - if this string is empty, the
  42854. default string "ok" (or a localised version) will be used.
  42855. @param associatedComponent if this is non-null, it specifies the component that the
  42856. alert window should be associated with. Depending on the look
  42857. and feel, this might be used for positioning of the alert window.
  42858. */
  42859. static void JUCE_CALLTYPE showMessageBoxAsync (AlertIconType iconType,
  42860. const String& title,
  42861. const String& message,
  42862. const String& buttonText = String::empty,
  42863. Component* associatedComponent = 0);
  42864. /** Shows a dialog box with two buttons.
  42865. Ideal for ok/cancel or yes/no choices. The return key can also be used
  42866. to trigger the first button, and the escape key for the second button.
  42867. If the callback parameter is null, the box is shown modally, and the method will
  42868. block until the user has clicked the button (or pressed the escape or return keys).
  42869. If the callback parameter is non-null, the box will be displayed and placed into a
  42870. modal state, but this method will return immediately, and the callback will be invoked
  42871. later when the user dismisses the box.
  42872. @param iconType the type of icon to show
  42873. @param title the headline to show at the top of the box
  42874. @param message a longer, more descriptive message to show underneath the
  42875. headline
  42876. @param button1Text the text to show in the first button - if this string is
  42877. empty, the default string "ok" (or a localised version of it)
  42878. will be used.
  42879. @param button2Text the text to show in the second button - if this string is
  42880. empty, the default string "cancel" (or a localised version of it)
  42881. will be used.
  42882. @param associatedComponent if this is non-null, it specifies the component that the
  42883. alert window should be associated with. Depending on the look
  42884. and feel, this might be used for positioning of the alert window.
  42885. @param callback if this is non-null, the menu will be launched asynchronously,
  42886. returning immediately, and the callback will receive a call to its
  42887. modalStateFinished() when the box is dismissed, with its parameter
  42888. being 1 if the ok button was pressed, or 0 for cancel, The callback object
  42889. will be owned and deleted by the system, so make sure that it works
  42890. safely and doesn't keep any references to objects that might be deleted
  42891. before it gets called.
  42892. @returns true if button 1 was clicked, false if it was button 2. If the callback parameter
  42893. is not null, the method always returns false, and the user's choice is delivered
  42894. later by the callback.
  42895. */
  42896. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  42897. const String& title,
  42898. const String& message,
  42899. #if JUCE_MODAL_LOOPS_PERMITTED
  42900. const String& button1Text = String::empty,
  42901. const String& button2Text = String::empty,
  42902. Component* associatedComponent = 0,
  42903. ModalComponentManager::Callback* callback = 0);
  42904. #else
  42905. const String& button1Text,
  42906. const String& button2Text,
  42907. Component* associatedComponent,
  42908. ModalComponentManager::Callback* callback);
  42909. #endif
  42910. /** Shows a dialog box with three buttons.
  42911. Ideal for yes/no/cancel boxes.
  42912. The escape key can be used to trigger the third button.
  42913. If the callback parameter is null, the box is shown modally, and the method will
  42914. block until the user has clicked the button (or pressed the escape or return keys).
  42915. If the callback parameter is non-null, the box will be displayed and placed into a
  42916. modal state, but this method will return immediately, and the callback will be invoked
  42917. later when the user dismisses the box.
  42918. @param iconType the type of icon to show
  42919. @param title the headline to show at the top of the box
  42920. @param message a longer, more descriptive message to show underneath the
  42921. headline
  42922. @param button1Text the text to show in the first button - if an empty string, then
  42923. "yes" will be used (or a localised version of it)
  42924. @param button2Text the text to show in the first button - if an empty string, then
  42925. "no" will be used (or a localised version of it)
  42926. @param button3Text the text to show in the first button - if an empty string, then
  42927. "cancel" will be used (or a localised version of it)
  42928. @param associatedComponent if this is non-null, it specifies the component that the
  42929. alert window should be associated with. Depending on the look
  42930. and feel, this might be used for positioning of the alert window.
  42931. @param callback if this is non-null, the menu will be launched asynchronously,
  42932. returning immediately, and the callback will receive a call to its
  42933. modalStateFinished() when the box is dismissed, with its parameter
  42934. being 1 if the "yes" button was pressed, 2 for the "no" button, or 0
  42935. if it was cancelled, The callback object will be owned and deleted by the
  42936. system, so make sure that it works safely and doesn't keep any references
  42937. to objects that might be deleted before it gets called.
  42938. @returns If the callback parameter has been set, this returns 0. Otherwise, it
  42939. returns one of the following values:
  42940. - 0 if the third button was pressed (normally used for 'cancel')
  42941. - 1 if the first button was pressed (normally used for 'yes')
  42942. - 2 if the middle button was pressed (normally used for 'no')
  42943. */
  42944. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  42945. const String& title,
  42946. const String& message,
  42947. #if JUCE_MODAL_LOOPS_PERMITTED
  42948. const String& button1Text = String::empty,
  42949. const String& button2Text = String::empty,
  42950. const String& button3Text = String::empty,
  42951. Component* associatedComponent = 0,
  42952. ModalComponentManager::Callback* callback = 0);
  42953. #else
  42954. const String& button1Text,
  42955. const String& button2Text,
  42956. const String& button3Text,
  42957. Component* associatedComponent,
  42958. ModalComponentManager::Callback* callback);
  42959. #endif
  42960. /** Shows an operating-system native dialog box.
  42961. @param title the title to use at the top
  42962. @param bodyText the longer message to show
  42963. @param isOkCancel if true, this will show an ok/cancel box, if false,
  42964. it'll show a box with just an ok button
  42965. @returns true if the ok button was pressed, false if they pressed cancel.
  42966. */
  42967. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  42968. const String& bodyText,
  42969. bool isOkCancel);
  42970. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  42971. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42972. methods.
  42973. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42974. */
  42975. enum ColourIds
  42976. {
  42977. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  42978. textColourId = 0x1001810, /**< The colour for the text. */
  42979. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  42980. };
  42981. protected:
  42982. /** @internal */
  42983. void paint (Graphics& g);
  42984. /** @internal */
  42985. void mouseDown (const MouseEvent& e);
  42986. /** @internal */
  42987. void mouseDrag (const MouseEvent& e);
  42988. /** @internal */
  42989. bool keyPressed (const KeyPress& key);
  42990. /** @internal */
  42991. void buttonClicked (Button* button);
  42992. /** @internal */
  42993. void lookAndFeelChanged();
  42994. /** @internal */
  42995. void userTriedToCloseWindow();
  42996. /** @internal */
  42997. int getDesktopWindowStyleFlags() const;
  42998. private:
  42999. String text;
  43000. TextLayout textLayout;
  43001. AlertIconType alertIconType;
  43002. ComponentBoundsConstrainer constrainer;
  43003. ComponentDragger dragger;
  43004. Rectangle<int> textArea;
  43005. OwnedArray<TextButton> buttons;
  43006. OwnedArray<TextEditor> textBoxes;
  43007. OwnedArray<ComboBox> comboBoxes;
  43008. OwnedArray<ProgressBar> progressBars;
  43009. Array<Component*> customComps;
  43010. OwnedArray<Component> textBlocks;
  43011. Array<Component*> allComps;
  43012. StringArray textboxNames, comboBoxNames;
  43013. Font font;
  43014. Component* associatedComponent;
  43015. void updateLayout (bool onlyIncreaseSize);
  43016. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AlertWindow);
  43017. };
  43018. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  43019. /*** End of inlined file: juce_AlertWindow.h ***/
  43020. /**
  43021. A file open/save dialog box.
  43022. This is a Juce-based file dialog box; to use a native file chooser, see the
  43023. FileChooser class.
  43024. To use one of these, create it and call its show() method. e.g.
  43025. @code
  43026. {
  43027. WildcardFileFilter wildcardFilter ("*.foo", "Foo files");
  43028. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  43029. File::nonexistent,
  43030. &wildcardFilter,
  43031. 0);
  43032. FileChooserDialogBox dialogBox ("Open some kind of file",
  43033. "Please choose some kind of file that you want to open...",
  43034. browser,
  43035. getLookAndFeel().alertWindowBackground);
  43036. if (dialogBox.show())
  43037. {
  43038. File selectedFile = browser.getCurrentFile();
  43039. ...
  43040. }
  43041. }
  43042. @endcode
  43043. @see FileChooser
  43044. */
  43045. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  43046. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  43047. public FileBrowserListener
  43048. {
  43049. public:
  43050. /** Creates a file chooser box.
  43051. @param title the main title to show at the top of the box
  43052. @param instructions an optional longer piece of text to show below the title in
  43053. a smaller font, describing in more detail what's required.
  43054. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  43055. box. Make sure you delete this after (but not before!) the
  43056. dialog box has been deleted.
  43057. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  43058. if they try to select a file that already exists. (This
  43059. flag is only used when saving files)
  43060. @param backgroundColour the background colour for the top level window
  43061. @see FileBrowserComponent, FilePreviewComponent
  43062. */
  43063. FileChooserDialogBox (const String& title,
  43064. const String& instructions,
  43065. FileBrowserComponent& browserComponent,
  43066. bool warnAboutOverwritingExistingFiles,
  43067. const Colour& backgroundColour);
  43068. /** Destructor. */
  43069. ~FileChooserDialogBox();
  43070. #if JUCE_MODAL_LOOPS_PERMITTED
  43071. /** Displays and runs the dialog box modally.
  43072. This will show the box with the specified size, returning true if the user
  43073. pressed 'ok', or false if they cancelled.
  43074. Leave the width or height as 0 to use the default size
  43075. */
  43076. bool show (int width = 0, int height = 0);
  43077. /** Displays and runs the dialog box modally.
  43078. This will show the box with the specified size at the specified location,
  43079. returning true if the user pressed 'ok', or false if they cancelled.
  43080. Leave the width or height as 0 to use the default size.
  43081. */
  43082. bool showAt (int x, int y, int width, int height);
  43083. #endif
  43084. /** Sets the size of this dialog box to its default and positions it either in the
  43085. centre of the screen, or centred around a component that is provided.
  43086. */
  43087. void centreWithDefaultSize (Component* componentToCentreAround = 0);
  43088. /** A set of colour IDs to use to change the colour of various aspects of the box.
  43089. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43090. methods.
  43091. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43092. */
  43093. enum ColourIds
  43094. {
  43095. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  43096. };
  43097. /** @internal */
  43098. void buttonClicked (Button* button);
  43099. /** @internal */
  43100. void closeButtonPressed();
  43101. /** @internal */
  43102. void selectionChanged();
  43103. /** @internal */
  43104. void fileClicked (const File& file, const MouseEvent& e);
  43105. /** @internal */
  43106. void fileDoubleClicked (const File& file);
  43107. private:
  43108. class ContentComponent;
  43109. ContentComponent* content;
  43110. const bool warnAboutOverwritingExistingFiles;
  43111. void okButtonPressed();
  43112. void createNewFolder();
  43113. void createNewFolderConfirmed (const String& name);
  43114. static void okToOverwriteFileCallback (int result, FileChooserDialogBox*);
  43115. static void createNewFolderCallback (int result, FileChooserDialogBox*, Component::SafePointer<AlertWindow>);
  43116. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileChooserDialogBox);
  43117. };
  43118. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  43119. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  43120. #endif
  43121. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  43122. #endif
  43123. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43124. /*** Start of inlined file: juce_FileListComponent.h ***/
  43125. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43126. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43127. /**
  43128. A component that displays the files in a directory as a listbox.
  43129. This implements the DirectoryContentsDisplayComponent base class so that
  43130. it can be used in a FileBrowserComponent.
  43131. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  43132. class and the FileBrowserListener class.
  43133. @see DirectoryContentsList, FileTreeComponent
  43134. */
  43135. class JUCE_API FileListComponent : public ListBox,
  43136. public DirectoryContentsDisplayComponent,
  43137. private ListBoxModel,
  43138. private ChangeListener
  43139. {
  43140. public:
  43141. /** Creates a listbox to show the contents of a specified directory.
  43142. */
  43143. FileListComponent (DirectoryContentsList& listToShow);
  43144. /** Destructor. */
  43145. ~FileListComponent();
  43146. /** Returns the number of files the user has got selected.
  43147. @see getSelectedFile
  43148. */
  43149. int getNumSelectedFiles() const;
  43150. /** Returns one of the files that the user has currently selected.
  43151. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  43152. @see getNumSelectedFiles
  43153. */
  43154. const File getSelectedFile (int index = 0) const;
  43155. /** Deselects any files that are currently selected. */
  43156. void deselectAllFiles();
  43157. /** Scrolls to the top of the list. */
  43158. void scrollToTop();
  43159. /** @internal */
  43160. void changeListenerCallback (ChangeBroadcaster*);
  43161. /** @internal */
  43162. int getNumRows();
  43163. /** @internal */
  43164. void paintListBoxItem (int, Graphics&, int, int, bool);
  43165. /** @internal */
  43166. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  43167. /** @internal */
  43168. void selectedRowsChanged (int lastRowSelected);
  43169. /** @internal */
  43170. void deleteKeyPressed (int currentSelectedRow);
  43171. /** @internal */
  43172. void returnKeyPressed (int currentSelectedRow);
  43173. private:
  43174. File lastDirectory;
  43175. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListComponent);
  43176. };
  43177. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43178. /*** End of inlined file: juce_FileListComponent.h ***/
  43179. #endif
  43180. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43181. /*** Start of inlined file: juce_FilenameComponent.h ***/
  43182. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43183. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43184. class FilenameComponent;
  43185. /**
  43186. Listens for events happening to a FilenameComponent.
  43187. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  43188. register one of these objects for event callbacks when the filename is changed.
  43189. @see FilenameComponent
  43190. */
  43191. class JUCE_API FilenameComponentListener
  43192. {
  43193. public:
  43194. /** Destructor. */
  43195. virtual ~FilenameComponentListener() {}
  43196. /** This method is called after the FilenameComponent's file has been changed. */
  43197. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  43198. };
  43199. /**
  43200. Shows a filename as an editable text box, with a 'browse' button and a
  43201. drop-down list for recently selected files.
  43202. A handy component for dialogue boxes where you want the user to be able to
  43203. select a file or directory.
  43204. Attach an FilenameComponentListener using the addListener() method, and it will
  43205. get called each time the user changes the filename, either by browsing for a file
  43206. and clicking 'ok', or by typing a new filename into the box and pressing return.
  43207. @see FileChooser, ComboBox
  43208. */
  43209. class JUCE_API FilenameComponent : public Component,
  43210. public SettableTooltipClient,
  43211. public FileDragAndDropTarget,
  43212. private AsyncUpdater,
  43213. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  43214. private ComboBoxListener
  43215. {
  43216. public:
  43217. /** Creates a FilenameComponent.
  43218. @param name the name for this component.
  43219. @param currentFile the file to initially show in the box
  43220. @param canEditFilename if true, the user can manually edit the filename; if false,
  43221. they can only change it by browsing for a new file
  43222. @param isDirectory if true, the file will be treated as a directory, and
  43223. an appropriate directory browser used
  43224. @param isForSaving if true, the file browser will allow non-existent files to
  43225. be picked, as the file is assumed to be used for saving rather
  43226. than loading
  43227. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  43228. If an empty string is passed in, then the pattern is assumed to be "*"
  43229. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  43230. to any filenames that are entered or chosen
  43231. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  43232. will only appear if the initial file isn't valid)
  43233. */
  43234. FilenameComponent (const String& name,
  43235. const File& currentFile,
  43236. bool canEditFilename,
  43237. bool isDirectory,
  43238. bool isForSaving,
  43239. const String& fileBrowserWildcard,
  43240. const String& enforcedSuffix,
  43241. const String& textWhenNothingSelected);
  43242. /** Destructor. */
  43243. ~FilenameComponent();
  43244. /** Returns the currently displayed filename. */
  43245. const File getCurrentFile() const;
  43246. /** Changes the current filename.
  43247. If addToRecentlyUsedList is true, the filename will also be added to the
  43248. drop-down list of recent files.
  43249. If sendChangeNotification is false, then the listeners won't be told of the
  43250. change.
  43251. */
  43252. void setCurrentFile (File newFile,
  43253. bool addToRecentlyUsedList,
  43254. bool sendChangeNotification = true);
  43255. /** Changes whether the use can type into the filename box.
  43256. */
  43257. void setFilenameIsEditable (bool shouldBeEditable);
  43258. /** Sets a file or directory to be the default starting point for the browser to show.
  43259. This is only used if the current file hasn't been set.
  43260. */
  43261. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  43262. /** Returns all the entries on the recent files list.
  43263. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  43264. state of this list.
  43265. @see setRecentlyUsedFilenames
  43266. */
  43267. const StringArray getRecentlyUsedFilenames() const;
  43268. /** Sets all the entries on the recent files list.
  43269. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  43270. state of this list.
  43271. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  43272. */
  43273. void setRecentlyUsedFilenames (const StringArray& filenames);
  43274. /** Adds an entry to the recently-used files dropdown list.
  43275. If the file is already in the list, it will be moved to the top. A limit
  43276. is also placed on the number of items that are kept in the list.
  43277. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  43278. */
  43279. void addRecentlyUsedFile (const File& file);
  43280. /** Changes the limit for the number of files that will be stored in the recent-file list.
  43281. */
  43282. void setMaxNumberOfRecentFiles (int newMaximum);
  43283. /** Changes the text shown on the 'browse' button.
  43284. By default this button just says "..." but you can change it. The button itself
  43285. can be changed using the look-and-feel classes, so it might not actually have any
  43286. text on it.
  43287. */
  43288. void setBrowseButtonText (const String& browseButtonText);
  43289. /** Adds a listener that will be called when the selected file is changed. */
  43290. void addListener (FilenameComponentListener* listener);
  43291. /** Removes a previously-registered listener. */
  43292. void removeListener (FilenameComponentListener* listener);
  43293. /** Gives the component a tooltip. */
  43294. void setTooltip (const String& newTooltip);
  43295. /** @internal */
  43296. void paintOverChildren (Graphics& g);
  43297. /** @internal */
  43298. void resized();
  43299. /** @internal */
  43300. void lookAndFeelChanged();
  43301. /** @internal */
  43302. bool isInterestedInFileDrag (const StringArray& files);
  43303. /** @internal */
  43304. void filesDropped (const StringArray& files, int, int);
  43305. /** @internal */
  43306. void fileDragEnter (const StringArray& files, int, int);
  43307. /** @internal */
  43308. void fileDragExit (const StringArray& files);
  43309. private:
  43310. ComboBox filenameBox;
  43311. String lastFilename;
  43312. ScopedPointer<Button> browseButton;
  43313. int maxRecentFiles;
  43314. bool isDir, isSaving, isFileDragOver;
  43315. String wildcard, enforcedSuffix, browseButtonText;
  43316. ListenerList <FilenameComponentListener> listeners;
  43317. File defaultBrowseFile;
  43318. void comboBoxChanged (ComboBox*);
  43319. void buttonClicked (Button* button);
  43320. void handleAsyncUpdate();
  43321. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilenameComponent);
  43322. };
  43323. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43324. /*** End of inlined file: juce_FilenameComponent.h ***/
  43325. #endif
  43326. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  43327. #endif
  43328. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  43329. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  43330. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  43331. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  43332. /**
  43333. Shows a set of file paths in a list, allowing them to be added, removed or
  43334. re-ordered.
  43335. @see FileSearchPath
  43336. */
  43337. class JUCE_API FileSearchPathListComponent : public Component,
  43338. public SettableTooltipClient,
  43339. public FileDragAndDropTarget,
  43340. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  43341. private ListBoxModel
  43342. {
  43343. public:
  43344. /** Creates an empty FileSearchPathListComponent. */
  43345. FileSearchPathListComponent();
  43346. /** Destructor. */
  43347. ~FileSearchPathListComponent();
  43348. /** Returns the path as it is currently shown. */
  43349. const FileSearchPath& getPath() const throw() { return path; }
  43350. /** Changes the current path. */
  43351. void setPath (const FileSearchPath& newPath);
  43352. /** Sets a file or directory to be the default starting point for the browser to show.
  43353. This is only used if the current file hasn't been set.
  43354. */
  43355. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  43356. /** A set of colour IDs to use to change the colour of various aspects of the label.
  43357. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43358. methods.
  43359. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43360. */
  43361. enum ColourIds
  43362. {
  43363. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  43364. Make this transparent if you don't want the background to be filled. */
  43365. };
  43366. /** @internal */
  43367. int getNumRows();
  43368. /** @internal */
  43369. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  43370. /** @internal */
  43371. void deleteKeyPressed (int lastRowSelected);
  43372. /** @internal */
  43373. void returnKeyPressed (int lastRowSelected);
  43374. /** @internal */
  43375. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  43376. /** @internal */
  43377. void selectedRowsChanged (int lastRowSelected);
  43378. /** @internal */
  43379. void resized();
  43380. /** @internal */
  43381. void paint (Graphics& g);
  43382. /** @internal */
  43383. bool isInterestedInFileDrag (const StringArray& files);
  43384. /** @internal */
  43385. void filesDropped (const StringArray& files, int, int);
  43386. /** @internal */
  43387. void buttonClicked (Button* button);
  43388. private:
  43389. FileSearchPath path;
  43390. File defaultBrowseTarget;
  43391. ListBox listBox;
  43392. TextButton addButton, removeButton, changeButton;
  43393. DrawableButton upButton, downButton;
  43394. void changed();
  43395. void updateButtons();
  43396. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileSearchPathListComponent);
  43397. };
  43398. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  43399. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  43400. #endif
  43401. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  43402. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  43403. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  43404. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  43405. /**
  43406. A component that displays the files in a directory as a treeview.
  43407. This implements the DirectoryContentsDisplayComponent base class so that
  43408. it can be used in a FileBrowserComponent.
  43409. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  43410. class and the FileBrowserListener class.
  43411. @see DirectoryContentsList, FileListComponent
  43412. */
  43413. class JUCE_API FileTreeComponent : public TreeView,
  43414. public DirectoryContentsDisplayComponent
  43415. {
  43416. public:
  43417. /** Creates a listbox to show the contents of a specified directory.
  43418. */
  43419. FileTreeComponent (DirectoryContentsList& listToShow);
  43420. /** Destructor. */
  43421. ~FileTreeComponent();
  43422. /** Returns the number of files the user has got selected.
  43423. @see getSelectedFile
  43424. */
  43425. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  43426. /** Returns one of the files that the user has currently selected.
  43427. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  43428. @see getNumSelectedFiles
  43429. */
  43430. const File getSelectedFile (int index = 0) const;
  43431. /** Deselects any files that are currently selected. */
  43432. void deselectAllFiles();
  43433. /** Scrolls the list to the top. */
  43434. void scrollToTop();
  43435. /** Setting a name for this allows tree items to be dragged.
  43436. The string that you pass in here will be returned by the getDragSourceDescription()
  43437. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  43438. */
  43439. void setDragAndDropDescription (const String& description);
  43440. /** Returns the last value that was set by setDragAndDropDescription().
  43441. */
  43442. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  43443. private:
  43444. String dragAndDropDescription;
  43445. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileTreeComponent);
  43446. };
  43447. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  43448. /*** End of inlined file: juce_FileTreeComponent.h ***/
  43449. #endif
  43450. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  43451. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  43452. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  43453. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  43454. /**
  43455. A simple preview component that shows thumbnails of image files.
  43456. @see FileChooserDialogBox, FilePreviewComponent
  43457. */
  43458. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  43459. private Timer
  43460. {
  43461. public:
  43462. /** Creates an ImagePreviewComponent. */
  43463. ImagePreviewComponent();
  43464. /** Destructor. */
  43465. ~ImagePreviewComponent();
  43466. /** @internal */
  43467. void selectedFileChanged (const File& newSelectedFile);
  43468. /** @internal */
  43469. void paint (Graphics& g);
  43470. /** @internal */
  43471. void timerCallback();
  43472. private:
  43473. File fileToLoad;
  43474. Image currentThumbnail;
  43475. String currentDetails;
  43476. void getThumbSize (int& w, int& h) const;
  43477. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImagePreviewComponent);
  43478. };
  43479. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  43480. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  43481. #endif
  43482. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  43483. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  43484. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  43485. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  43486. /**
  43487. A type of FileFilter that works by wildcard pattern matching.
  43488. This filter only allows files that match one of the specified patterns, but
  43489. allows all directories through.
  43490. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  43491. */
  43492. class JUCE_API WildcardFileFilter : public FileFilter
  43493. {
  43494. public:
  43495. /**
  43496. Creates a wildcard filter for one or more patterns.
  43497. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  43498. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  43499. or .aiff.
  43500. The description is a name to show the user in a list of possible patterns, so
  43501. for the wav/aiff example, your description might be "audio files".
  43502. */
  43503. WildcardFileFilter (const String& fileWildcardPatterns,
  43504. const String& directoryWildcardPatterns,
  43505. const String& description);
  43506. /** Destructor. */
  43507. ~WildcardFileFilter();
  43508. /** Returns true if the filename matches one of the patterns specified. */
  43509. bool isFileSuitable (const File& file) const;
  43510. /** This always returns true. */
  43511. bool isDirectorySuitable (const File& file) const;
  43512. private:
  43513. StringArray fileWildcards, directoryWildcards;
  43514. static void parse (const String& pattern, StringArray& result);
  43515. static bool match (const File& file, const StringArray& wildcards);
  43516. JUCE_LEAK_DETECTOR (WildcardFileFilter);
  43517. };
  43518. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  43519. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  43520. #endif
  43521. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  43522. #endif
  43523. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  43524. #endif
  43525. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  43526. #endif
  43527. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  43528. #endif
  43529. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  43530. #endif
  43531. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  43532. #endif
  43533. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  43534. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  43535. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  43536. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  43537. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  43538. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  43539. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  43540. /**
  43541. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  43542. command in a ApplicationCommandManager.
  43543. Normally, you won't actually create a KeyPressMappingSet directly, because
  43544. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  43545. you'd create yourself an ApplicationCommandManager, and call its
  43546. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  43547. KeyPressMappingSet.
  43548. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  43549. to the top-level component for which you want to handle keystrokes. So for example:
  43550. @code
  43551. class MyMainWindow : public Component
  43552. {
  43553. ApplicationCommandManager* myCommandManager;
  43554. public:
  43555. MyMainWindow()
  43556. {
  43557. myCommandManager = new ApplicationCommandManager();
  43558. // first, make sure the command manager has registered all the commands that its
  43559. // targets can perform..
  43560. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  43561. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  43562. // this will use the command manager to initialise the KeyPressMappingSet with
  43563. // the default keypresses that were specified when the targets added their commands
  43564. // to the manager.
  43565. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  43566. // having set up the default key-mappings, you might now want to load the last set
  43567. // of mappings that the user configured.
  43568. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  43569. // Now tell our top-level window to send any keypresses that arrive to the
  43570. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  43571. addKeyListener (myCommandManager->getKeyMappings());
  43572. }
  43573. ...
  43574. }
  43575. @endcode
  43576. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  43577. register to be told when a command or mapping is added, removed, etc.
  43578. There's also a UI component called KeyMappingEditorComponent that can be used
  43579. to easily edit the key mappings.
  43580. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  43581. */
  43582. class JUCE_API KeyPressMappingSet : public KeyListener,
  43583. public ChangeBroadcaster,
  43584. public FocusChangeListener
  43585. {
  43586. public:
  43587. /** Creates a KeyPressMappingSet for a given command manager.
  43588. Normally, you won't actually create a KeyPressMappingSet directly, because
  43589. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  43590. best thing to do is to create your ApplicationCommandManager, and use the
  43591. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  43592. When a suitable keypress happens, the manager's invoke() method will be
  43593. used to invoke the appropriate command.
  43594. @see ApplicationCommandManager
  43595. */
  43596. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  43597. /** Creates an copy of a KeyPressMappingSet. */
  43598. KeyPressMappingSet (const KeyPressMappingSet& other);
  43599. /** Destructor. */
  43600. ~KeyPressMappingSet();
  43601. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  43602. /** Returns a list of keypresses that are assigned to a particular command.
  43603. @param commandID the command's ID
  43604. */
  43605. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  43606. /** Assigns a keypress to a command.
  43607. If the keypress is already assigned to a different command, it will first be
  43608. removed from that command, to avoid it triggering multiple functions.
  43609. @param commandID the ID of the command that you want to add a keypress to. If
  43610. this is 0, the keypress will be removed from anything that it
  43611. was previously assigned to, but not re-assigned
  43612. @param newKeyPress the new key-press
  43613. @param insertIndex if this is less than zero, the key will be appended to the
  43614. end of the list of keypresses; otherwise the new keypress will
  43615. be inserted into the existing list at this index
  43616. */
  43617. void addKeyPress (CommandID commandID,
  43618. const KeyPress& newKeyPress,
  43619. int insertIndex = -1);
  43620. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  43621. @see resetToDefaultMapping
  43622. */
  43623. void resetToDefaultMappings();
  43624. /** Resets all key-mappings to the defaults for a particular command.
  43625. @see resetToDefaultMappings
  43626. */
  43627. void resetToDefaultMapping (CommandID commandID);
  43628. /** Removes all keypresses that are assigned to any commands. */
  43629. void clearAllKeyPresses();
  43630. /** Removes all keypresses that are assigned to a particular command. */
  43631. void clearAllKeyPresses (CommandID commandID);
  43632. /** Removes one of the keypresses that are assigned to a command.
  43633. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  43634. which the keyPressIndex refers.
  43635. */
  43636. void removeKeyPress (CommandID commandID, int keyPressIndex);
  43637. /** Removes a keypress from any command that it may be assigned to.
  43638. */
  43639. void removeKeyPress (const KeyPress& keypress);
  43640. /** Returns true if the given command is linked to this key. */
  43641. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const throw();
  43642. /** Looks for a command that corresponds to a keypress.
  43643. @returns the UID of the command or 0 if none was found
  43644. */
  43645. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  43646. /** Tries to recreate the mappings from a previously stored state.
  43647. The XML passed in must have been created by the createXml() method.
  43648. If the stored state makes any reference to commands that aren't
  43649. currently available, these will be ignored.
  43650. If the set of mappings being loaded was a set of differences (using createXml (true)),
  43651. then this will call resetToDefaultMappings() and then merge the saved mappings
  43652. on top. If the saved set was created with createXml (false), then this method
  43653. will first clear all existing mappings and load the saved ones as a complete set.
  43654. @returns true if it manages to load the XML correctly
  43655. @see createXml
  43656. */
  43657. bool restoreFromXml (const XmlElement& xmlVersion);
  43658. /** Creates an XML representation of the current mappings.
  43659. This will produce a lump of XML that can be later reloaded using
  43660. restoreFromXml() to recreate the current mapping state.
  43661. The object that is returned must be deleted by the caller.
  43662. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  43663. will be saved into the XML. If it's true, then the XML will
  43664. only store the differences between the current mappings and
  43665. the default mappings you'd get from calling resetToDefaultMappings().
  43666. The advantage of saving a set of differences from the default is that
  43667. if you change the default mappings (in a new version of your app, for
  43668. example), then these will be merged into a user's saved preferences.
  43669. @see restoreFromXml
  43670. */
  43671. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  43672. /** @internal */
  43673. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  43674. /** @internal */
  43675. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  43676. /** @internal */
  43677. void globalFocusChanged (Component* focusedComponent);
  43678. private:
  43679. ApplicationCommandManager* commandManager;
  43680. struct CommandMapping
  43681. {
  43682. CommandID commandID;
  43683. Array <KeyPress> keypresses;
  43684. bool wantsKeyUpDownCallbacks;
  43685. };
  43686. OwnedArray <CommandMapping> mappings;
  43687. struct KeyPressTime
  43688. {
  43689. KeyPress key;
  43690. uint32 timeWhenPressed;
  43691. };
  43692. OwnedArray <KeyPressTime> keysDown;
  43693. void handleMessage (const Message& message);
  43694. void invokeCommand (const CommandID commandID,
  43695. const KeyPress& keyPress,
  43696. const bool isKeyDown,
  43697. const int millisecsSinceKeyPressed,
  43698. Component* const originatingComponent) const;
  43699. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  43700. JUCE_LEAK_DETECTOR (KeyPressMappingSet);
  43701. };
  43702. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  43703. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  43704. /**
  43705. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  43706. object.
  43707. @see KeyPressMappingSet
  43708. */
  43709. class JUCE_API KeyMappingEditorComponent : public Component
  43710. {
  43711. public:
  43712. /** Creates a KeyMappingEditorComponent.
  43713. @param mappingSet this is the set of mappings to display and edit. Make sure the
  43714. mappings object is not deleted before this component!
  43715. @param showResetToDefaultButton if true, then at the bottom of the list, the
  43716. component will include a 'reset to defaults' button.
  43717. */
  43718. KeyMappingEditorComponent (KeyPressMappingSet& mappingSet,
  43719. bool showResetToDefaultButton);
  43720. /** Destructor. */
  43721. virtual ~KeyMappingEditorComponent();
  43722. /** Sets up the colours to use for parts of the component.
  43723. @param mainBackground colour to use for most of the background
  43724. @param textColour colour to use for the text
  43725. */
  43726. void setColours (const Colour& mainBackground,
  43727. const Colour& textColour);
  43728. /** Returns the KeyPressMappingSet that this component is acting upon. */
  43729. KeyPressMappingSet& getMappings() const throw() { return mappings; }
  43730. /** Can be overridden if some commands need to be excluded from the list.
  43731. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  43732. method to decide what to return, but you can override it to handle special cases.
  43733. */
  43734. virtual bool shouldCommandBeIncluded (CommandID commandID);
  43735. /** Can be overridden to indicate that some commands are shown as read-only.
  43736. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  43737. method to decide what to return, but you can override it to handle special cases.
  43738. */
  43739. virtual bool isCommandReadOnly (CommandID commandID);
  43740. /** This can be overridden to let you change the format of the string used
  43741. to describe a keypress.
  43742. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  43743. keys that are triggered by something else externally. If you override the
  43744. method, be sure to let the base class's method handle keys you're not
  43745. interested in.
  43746. */
  43747. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  43748. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  43749. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43750. methods.
  43751. To change the colours of the menu that pops up
  43752. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43753. */
  43754. enum ColourIds
  43755. {
  43756. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  43757. textColourId = 0x100ad01, /**< The colour for the text. */
  43758. };
  43759. /** @internal */
  43760. void parentHierarchyChanged();
  43761. /** @internal */
  43762. void resized();
  43763. private:
  43764. KeyPressMappingSet& mappings;
  43765. TreeView tree;
  43766. TextButton resetButton;
  43767. class TopLevelItem;
  43768. class ChangeKeyButton;
  43769. class MappingItem;
  43770. class CategoryItem;
  43771. class ItemComponent;
  43772. friend class TopLevelItem;
  43773. friend class OwnedArray <ChangeKeyButton>;
  43774. friend class ScopedPointer<TopLevelItem>;
  43775. ScopedPointer<TopLevelItem> treeItem;
  43776. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KeyMappingEditorComponent);
  43777. };
  43778. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  43779. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  43780. #endif
  43781. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  43782. #endif
  43783. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  43784. #endif
  43785. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  43786. #endif
  43787. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  43788. #endif
  43789. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  43790. #endif
  43791. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  43792. #endif
  43793. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  43794. #endif
  43795. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  43796. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  43797. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  43798. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  43799. /** An object that watches for any movement of a component or any of its parent components.
  43800. This makes it easy to check when a component is moved relative to its top-level
  43801. peer window. The normal Component::moved() method is only called when a component
  43802. moves relative to its immediate parent, and sometimes you want to know if any of
  43803. components higher up the tree have moved (which of course will affect the overall
  43804. position of all their sub-components).
  43805. It also includes a callback that lets you know when the top-level peer is changed.
  43806. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  43807. because they need to keep their custom windows in the right place and respond to
  43808. changes in the peer.
  43809. */
  43810. class JUCE_API ComponentMovementWatcher : public ComponentListener
  43811. {
  43812. public:
  43813. /** Creates a ComponentMovementWatcher to watch a given target component. */
  43814. ComponentMovementWatcher (Component* component);
  43815. /** Destructor. */
  43816. ~ComponentMovementWatcher();
  43817. /** This callback happens when the component that is being watched is moved
  43818. relative to its top-level peer window, or when it is resized. */
  43819. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  43820. /** This callback happens when the component's top-level peer is changed. */
  43821. virtual void componentPeerChanged() = 0;
  43822. /** This callback happens when the component's visibility state changes, possibly due to
  43823. one of its parents being made visible or invisible.
  43824. */
  43825. virtual void componentVisibilityChanged() = 0;
  43826. /** @internal */
  43827. void componentParentHierarchyChanged (Component& component);
  43828. /** @internal */
  43829. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  43830. /** @internal */
  43831. void componentBeingDeleted (Component& component);
  43832. /** @internal */
  43833. void componentVisibilityChanged (Component& component);
  43834. private:
  43835. WeakReference<Component> component;
  43836. ComponentPeer* lastPeer;
  43837. Array <Component*> registeredParentComps;
  43838. bool reentrant, wasShowing;
  43839. Rectangle<int> lastBounds;
  43840. void unregister();
  43841. void registerWithParentComps();
  43842. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentMovementWatcher);
  43843. };
  43844. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  43845. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  43846. #endif
  43847. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  43848. /*** Start of inlined file: juce_GroupComponent.h ***/
  43849. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  43850. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  43851. /**
  43852. A component that draws an outline around itself and has an optional title at
  43853. the top, for drawing an outline around a group of controls.
  43854. */
  43855. class JUCE_API GroupComponent : public Component
  43856. {
  43857. public:
  43858. /** Creates a GroupComponent.
  43859. @param componentName the name to give the component
  43860. @param labelText the text to show at the top of the outline
  43861. */
  43862. GroupComponent (const String& componentName = String::empty,
  43863. const String& labelText = String::empty);
  43864. /** Destructor. */
  43865. ~GroupComponent();
  43866. /** Changes the text that's shown at the top of the component. */
  43867. void setText (const String& newText);
  43868. /** Returns the currently displayed text label. */
  43869. const String getText() const;
  43870. /** Sets the positioning of the text label.
  43871. (The default is Justification::left)
  43872. @see getTextLabelPosition
  43873. */
  43874. void setTextLabelPosition (const Justification& justification);
  43875. /** Returns the current text label position.
  43876. @see setTextLabelPosition
  43877. */
  43878. const Justification getTextLabelPosition() const throw() { return justification; }
  43879. /** A set of colour IDs to use to change the colour of various aspects of the component.
  43880. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43881. methods.
  43882. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43883. */
  43884. enum ColourIds
  43885. {
  43886. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  43887. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  43888. };
  43889. /** @internal */
  43890. void paint (Graphics& g);
  43891. /** @internal */
  43892. void enablementChanged();
  43893. /** @internal */
  43894. void colourChanged();
  43895. private:
  43896. String text;
  43897. Justification justification;
  43898. JUCE_DECLARE_NON_COPYABLE (GroupComponent);
  43899. };
  43900. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  43901. /*** End of inlined file: juce_GroupComponent.h ***/
  43902. #endif
  43903. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  43904. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  43905. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  43906. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  43907. /*** Start of inlined file: juce_TabbedComponent.h ***/
  43908. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  43909. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  43910. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  43911. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  43912. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  43913. class TabbedButtonBar;
  43914. /** In a TabbedButtonBar, this component is used for each of the buttons.
  43915. If you want to create a TabbedButtonBar with custom tab components, derive
  43916. your component from this class, and override the TabbedButtonBar::createTabButton()
  43917. method to create it instead of the default one.
  43918. @see TabbedButtonBar
  43919. */
  43920. class JUCE_API TabBarButton : public Button
  43921. {
  43922. public:
  43923. /** Creates the tab button. */
  43924. TabBarButton (const String& name, TabbedButtonBar& ownerBar);
  43925. /** Destructor. */
  43926. ~TabBarButton();
  43927. /** Chooses the best length for the tab, given the specified depth.
  43928. If the tab is horizontal, this should return its width, and the depth
  43929. specifies its height. If it's vertical, it should return the height, and
  43930. the depth is actually its width.
  43931. */
  43932. virtual int getBestTabLength (int depth);
  43933. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  43934. void clicked (const ModifierKeys& mods);
  43935. bool hitTest (int x, int y);
  43936. protected:
  43937. friend class TabbedButtonBar;
  43938. TabbedButtonBar& owner;
  43939. int overlapPixels;
  43940. DropShadowEffect shadow;
  43941. /** Returns an area of the component that's safe to draw in.
  43942. This deals with the orientation of the tabs, which affects which side is
  43943. touching the tabbed box's content component.
  43944. */
  43945. const Rectangle<int> getActiveArea();
  43946. /** Returns this tab's index in its tab bar. */
  43947. int getIndex() const;
  43948. private:
  43949. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabBarButton);
  43950. };
  43951. /**
  43952. A vertical or horizontal bar containing tabs that you can select.
  43953. You can use one of these to generate things like a dialog box that has
  43954. tabbed pages you can flip between. Attach a ChangeListener to the
  43955. button bar to be told when the user changes the page.
  43956. An easier method than doing this is to use a TabbedComponent, which
  43957. contains its own TabbedButtonBar and which takes care of the layout
  43958. and other housekeeping.
  43959. @see TabbedComponent
  43960. */
  43961. class JUCE_API TabbedButtonBar : public Component,
  43962. public ChangeBroadcaster
  43963. {
  43964. public:
  43965. /** The placement of the tab-bar
  43966. @see setOrientation, getOrientation
  43967. */
  43968. enum Orientation
  43969. {
  43970. TabsAtTop,
  43971. TabsAtBottom,
  43972. TabsAtLeft,
  43973. TabsAtRight
  43974. };
  43975. /** Creates a TabbedButtonBar with a given placement.
  43976. You can change the orientation later if you need to.
  43977. */
  43978. TabbedButtonBar (Orientation orientation);
  43979. /** Destructor. */
  43980. ~TabbedButtonBar();
  43981. /** Changes the bar's orientation.
  43982. This won't change the bar's actual size - you'll need to do that yourself,
  43983. but this determines which direction the tabs go in, and which side they're
  43984. stuck to.
  43985. */
  43986. void setOrientation (Orientation orientation);
  43987. /** Returns the current orientation.
  43988. @see setOrientation
  43989. */
  43990. Orientation getOrientation() const throw() { return orientation; }
  43991. /** Changes the minimum scale factor to which the tabs can be compressed when trying to
  43992. fit a lot of tabs on-screen.
  43993. */
  43994. void setMinimumTabScaleFactor (double newMinimumScale);
  43995. /** Deletes all the tabs from the bar.
  43996. @see addTab
  43997. */
  43998. void clearTabs();
  43999. /** Adds a tab to the bar.
  44000. Tabs are added in left-to-right reading order.
  44001. If this is the first tab added, it'll also be automatically selected.
  44002. */
  44003. void addTab (const String& tabName,
  44004. const Colour& tabBackgroundColour,
  44005. int insertIndex = -1);
  44006. /** Changes the name of one of the tabs. */
  44007. void setTabName (int tabIndex,
  44008. const String& newName);
  44009. /** Gets rid of one of the tabs. */
  44010. void removeTab (int tabIndex);
  44011. /** Moves a tab to a new index in the list.
  44012. Pass -1 as the index to move it to the end of the list.
  44013. */
  44014. void moveTab (int currentIndex, int newIndex);
  44015. /** Returns the number of tabs in the bar. */
  44016. int getNumTabs() const;
  44017. /** Returns a list of all the tab names in the bar. */
  44018. const StringArray getTabNames() const;
  44019. /** Changes the currently selected tab.
  44020. This will send a change message and cause a synchronous callback to
  44021. the currentTabChanged() method. (But if the given tab is already selected,
  44022. nothing will be done).
  44023. To deselect all the tabs, use an index of -1.
  44024. */
  44025. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  44026. /** Returns the name of the currently selected tab.
  44027. This could be an empty string if none are selected.
  44028. */
  44029. const String getCurrentTabName() const;
  44030. /** Returns the index of the currently selected tab.
  44031. This could return -1 if none are selected.
  44032. */
  44033. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  44034. /** Returns the button for a specific tab.
  44035. The button that is returned may be deleted later by this component, so don't hang
  44036. on to the pointer that is returned. A null pointer may be returned if the index is
  44037. out of range.
  44038. */
  44039. TabBarButton* getTabButton (int index) const;
  44040. /** Returns the index of a TabBarButton if it belongs to this bar. */
  44041. int indexOfTabButton (const TabBarButton* button) const;
  44042. /** Callback method to indicate the selected tab has been changed.
  44043. @see setCurrentTabIndex
  44044. */
  44045. virtual void currentTabChanged (int newCurrentTabIndex,
  44046. const String& newCurrentTabName);
  44047. /** Callback method to indicate that the user has right-clicked on a tab.
  44048. (Or ctrl-clicked on the Mac)
  44049. */
  44050. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  44051. /** Returns the colour of a tab.
  44052. This is the colour that was specified in addTab().
  44053. */
  44054. const Colour getTabBackgroundColour (int tabIndex);
  44055. /** Changes the background colour of a tab.
  44056. @see addTab, getTabBackgroundColour
  44057. */
  44058. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  44059. /** A set of colour IDs to use to change the colour of various aspects of the component.
  44060. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44061. methods.
  44062. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44063. */
  44064. enum ColourIds
  44065. {
  44066. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  44067. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  44068. the look and feel will choose an appropriate colour. */
  44069. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  44070. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  44071. this isn't specified, the look and feel will choose an appropriate
  44072. colour. */
  44073. };
  44074. /** @internal */
  44075. void resized();
  44076. /** @internal */
  44077. void lookAndFeelChanged();
  44078. protected:
  44079. /** This creates one of the tabs.
  44080. If you need to use custom tab components, you can override this method and
  44081. return your own class instead of the default.
  44082. */
  44083. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  44084. private:
  44085. Orientation orientation;
  44086. struct TabInfo
  44087. {
  44088. ScopedPointer<TabBarButton> component;
  44089. String name;
  44090. Colour colour;
  44091. };
  44092. OwnedArray <TabInfo> tabs;
  44093. double minimumScale;
  44094. int currentTabIndex;
  44095. class BehindFrontTabComp;
  44096. friend class BehindFrontTabComp;
  44097. friend class ScopedPointer<BehindFrontTabComp>;
  44098. ScopedPointer<BehindFrontTabComp> behindFrontTab;
  44099. ScopedPointer<Button> extraTabsButton;
  44100. void showExtraItemsMenu();
  44101. static void extraItemsMenuCallback (int, TabbedButtonBar*);
  44102. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedButtonBar);
  44103. };
  44104. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  44105. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  44106. /**
  44107. A component with a TabbedButtonBar along one of its sides.
  44108. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  44109. with addTab(), and this will take care of showing the pages for you when the
  44110. user clicks on a different tab.
  44111. @see TabbedButtonBar
  44112. */
  44113. class JUCE_API TabbedComponent : public Component
  44114. {
  44115. public:
  44116. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  44117. Once created, add some tabs with the addTab() method.
  44118. */
  44119. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  44120. /** Destructor. */
  44121. ~TabbedComponent();
  44122. /** Changes the placement of the tabs.
  44123. This will rearrange the layout to place the tabs along the appropriate
  44124. side of this component, and will shift the content component accordingly.
  44125. @see TabbedButtonBar::setOrientation
  44126. */
  44127. void setOrientation (TabbedButtonBar::Orientation orientation);
  44128. /** Returns the current tab placement.
  44129. @see setOrientation, TabbedButtonBar::getOrientation
  44130. */
  44131. TabbedButtonBar::Orientation getOrientation() const throw();
  44132. /** Specifies how many pixels wide or high the tab-bar should be.
  44133. If the tabs are placed along the top or bottom, this specified the height
  44134. of the bar; if they're along the left or right edges, it'll be the width
  44135. of the bar.
  44136. */
  44137. void setTabBarDepth (int newDepth);
  44138. /** Returns the current thickness of the tab bar.
  44139. @see setTabBarDepth
  44140. */
  44141. int getTabBarDepth() const throw() { return tabDepth; }
  44142. /** Specifies the thickness of an outline that should be drawn around the content component.
  44143. If this thickness is > 0, a line will be drawn around the three sides of the content
  44144. component which don't touch the tab-bar, and the content component will be inset by this amount.
  44145. To set the colour of the line, use setColour (outlineColourId, ...).
  44146. */
  44147. void setOutline (int newThickness);
  44148. /** Specifies a gap to leave around the edge of the content component.
  44149. Each edge of the content component will be indented by the given number of pixels.
  44150. */
  44151. void setIndent (int indentThickness);
  44152. /** Removes all the tabs from the bar.
  44153. @see TabbedButtonBar::clearTabs
  44154. */
  44155. void clearTabs();
  44156. /** Adds a tab to the tab-bar.
  44157. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  44158. is true, it will be deleted when the tab is removed or when this object is
  44159. deleted.
  44160. @see TabbedButtonBar::addTab
  44161. */
  44162. void addTab (const String& tabName,
  44163. const Colour& tabBackgroundColour,
  44164. Component* contentComponent,
  44165. bool deleteComponentWhenNotNeeded,
  44166. int insertIndex = -1);
  44167. /** Changes the name of one of the tabs. */
  44168. void setTabName (int tabIndex, const String& newName);
  44169. /** Gets rid of one of the tabs. */
  44170. void removeTab (int tabIndex);
  44171. /** Returns the number of tabs in the bar. */
  44172. int getNumTabs() const;
  44173. /** Returns a list of all the tab names in the bar. */
  44174. const StringArray getTabNames() const;
  44175. /** Returns the content component that was added for the given index.
  44176. Be sure not to use or delete the components that are returned, as this may interfere
  44177. with the TabbedComponent's use of them.
  44178. */
  44179. Component* getTabContentComponent (int tabIndex) const throw();
  44180. /** Returns the colour of one of the tabs. */
  44181. const Colour getTabBackgroundColour (int tabIndex) const throw();
  44182. /** Changes the background colour of one of the tabs. */
  44183. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  44184. /** Changes the currently-selected tab.
  44185. To deselect all the tabs, pass -1 as the index.
  44186. @see TabbedButtonBar::setCurrentTabIndex
  44187. */
  44188. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  44189. /** Returns the index of the currently selected tab.
  44190. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  44191. */
  44192. int getCurrentTabIndex() const;
  44193. /** Returns the name of the currently selected tab.
  44194. @see addTab, TabbedButtonBar::getCurrentTabName()
  44195. */
  44196. const String getCurrentTabName() const;
  44197. /** Returns the current component that's filling the panel.
  44198. This will return 0 if there isn't one.
  44199. */
  44200. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  44201. /** Callback method to indicate the selected tab has been changed.
  44202. @see setCurrentTabIndex
  44203. */
  44204. virtual void currentTabChanged (int newCurrentTabIndex,
  44205. const String& newCurrentTabName);
  44206. /** Callback method to indicate that the user has right-clicked on a tab.
  44207. (Or ctrl-clicked on the Mac)
  44208. */
  44209. virtual void popupMenuClickOnTab (int tabIndex,
  44210. const String& tabName);
  44211. /** Returns the tab button bar component that is being used.
  44212. */
  44213. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  44214. /** A set of colour IDs to use to change the colour of various aspects of the component.
  44215. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44216. methods.
  44217. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44218. */
  44219. enum ColourIds
  44220. {
  44221. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  44222. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  44223. (See setOutline) */
  44224. };
  44225. /** @internal */
  44226. void paint (Graphics& g);
  44227. /** @internal */
  44228. void resized();
  44229. /** @internal */
  44230. void lookAndFeelChanged();
  44231. protected:
  44232. /** This creates one of the tab buttons.
  44233. If you need to use custom tab components, you can override this method and
  44234. return your own class instead of the default.
  44235. */
  44236. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  44237. /** @internal */
  44238. ScopedPointer<TabbedButtonBar> tabs;
  44239. private:
  44240. Array <WeakReference<Component> > contentComponents;
  44241. WeakReference<Component> panelComponent;
  44242. int tabDepth;
  44243. int outlineThickness, edgeIndent;
  44244. class ButtonBar;
  44245. friend class ButtonBar;
  44246. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  44247. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedComponent);
  44248. };
  44249. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  44250. /*** End of inlined file: juce_TabbedComponent.h ***/
  44251. /*** Start of inlined file: juce_DocumentWindow.h ***/
  44252. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  44253. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  44254. /*** Start of inlined file: juce_MenuBarModel.h ***/
  44255. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  44256. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  44257. /**
  44258. A class for controlling MenuBar components.
  44259. This class is used to tell a MenuBar what menus to show, and to respond
  44260. to a menu being selected.
  44261. @see MenuBarModel::Listener, MenuBarComponent, PopupMenu
  44262. */
  44263. class JUCE_API MenuBarModel : private AsyncUpdater,
  44264. private ApplicationCommandManagerListener
  44265. {
  44266. public:
  44267. MenuBarModel() throw();
  44268. /** Destructor. */
  44269. virtual ~MenuBarModel();
  44270. /** Call this when some of your menu items have changed.
  44271. This method will cause a callback to any MenuBarListener objects that
  44272. are registered with this model.
  44273. If this model is displaying items from an ApplicationCommandManager, you
  44274. can use the setApplicationCommandManagerToWatch() method to cause
  44275. change messages to be sent automatically when the ApplicationCommandManager
  44276. is changed.
  44277. @see addListener, removeListener, MenuBarListener
  44278. */
  44279. void menuItemsChanged();
  44280. /** Tells the menu bar to listen to the specified command manager, and to update
  44281. itself when the commands change.
  44282. This will also allow it to flash a menu name when a command from that menu
  44283. is invoked using a keystroke.
  44284. */
  44285. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) throw();
  44286. /** A class to receive callbacks when a MenuBarModel changes.
  44287. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  44288. */
  44289. class JUCE_API Listener
  44290. {
  44291. public:
  44292. /** Destructor. */
  44293. virtual ~Listener() {}
  44294. /** This callback is made when items are changed in the menu bar model.
  44295. */
  44296. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  44297. /** This callback is made when an application command is invoked that
  44298. is represented by one of the items in the menu bar model.
  44299. */
  44300. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  44301. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  44302. };
  44303. /** Registers a listener for callbacks when the menu items in this model change.
  44304. The listener object will get callbacks when this object's menuItemsChanged()
  44305. method is called.
  44306. @see removeListener
  44307. */
  44308. void addListener (Listener* listenerToAdd) throw();
  44309. /** Removes a listener.
  44310. @see addListener
  44311. */
  44312. void removeListener (Listener* listenerToRemove) throw();
  44313. /** This method must return a list of the names of the menus. */
  44314. virtual const StringArray getMenuBarNames() = 0;
  44315. /** This should return the popup menu to display for a given top-level menu.
  44316. @param topLevelMenuIndex the index of the top-level menu to show
  44317. @param menuName the name of the top-level menu item to show
  44318. */
  44319. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  44320. const String& menuName) = 0;
  44321. /** This is called when a menu item has been clicked on.
  44322. @param menuItemID the item ID of the PopupMenu item that was selected
  44323. @param topLevelMenuIndex the index of the top-level menu from which the item was
  44324. chosen (just in case you've used duplicate ID numbers
  44325. on more than one of the popup menus)
  44326. */
  44327. virtual void menuItemSelected (int menuItemID,
  44328. int topLevelMenuIndex) = 0;
  44329. #if JUCE_MAC || DOXYGEN
  44330. /** MAC ONLY - Sets the model that is currently being shown as the main
  44331. menu bar at the top of the screen on the Mac.
  44332. You can pass 0 to stop the current model being displayed. Be careful
  44333. not to delete a model while it is being used.
  44334. An optional extra menu can be specified, containing items to add to the top of
  44335. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  44336. an apple, it's the one next to it, with your application's name at the top
  44337. and the services menu etc on it). When one of these items is selected, the
  44338. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  44339. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  44340. object then newMenuBarModel must be non-null.
  44341. */
  44342. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  44343. const PopupMenu* extraAppleMenuItems = 0);
  44344. /** MAC ONLY - Returns the menu model that is currently being shown as
  44345. the main menu bar.
  44346. */
  44347. static MenuBarModel* getMacMainMenu();
  44348. #endif
  44349. /** @internal */
  44350. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  44351. /** @internal */
  44352. void applicationCommandListChanged();
  44353. /** @internal */
  44354. void handleAsyncUpdate();
  44355. private:
  44356. ApplicationCommandManager* manager;
  44357. ListenerList <Listener> listeners;
  44358. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarModel);
  44359. };
  44360. /** This typedef is just for compatibility with old code - newer code should use the MenuBarModel::Listener class directly. */
  44361. typedef MenuBarModel::Listener MenuBarModelListener;
  44362. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  44363. /*** End of inlined file: juce_MenuBarModel.h ***/
  44364. /**
  44365. A resizable window with a title bar and maximise, minimise and close buttons.
  44366. This subclass of ResizableWindow creates a fairly standard type of window with
  44367. a title bar and various buttons. The name of the component is shown in the
  44368. title bar, and an icon can optionally be specified with setIcon().
  44369. All the methods available to a ResizableWindow are also available to this,
  44370. so it can easily be made resizable, minimised, maximised, etc.
  44371. It's not advisable to add child components directly to a DocumentWindow: put them
  44372. inside your content component instead. And overriding methods like resized(), moved(), etc
  44373. is also not recommended - instead override these methods for your content component.
  44374. (If for some obscure reason you do need to override these methods, always remember to
  44375. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  44376. decorations correctly).
  44377. You can also automatically add a menu bar to the window, using the setMenuBar()
  44378. method.
  44379. @see ResizableWindow, DialogWindow
  44380. */
  44381. class JUCE_API DocumentWindow : public ResizableWindow
  44382. {
  44383. public:
  44384. /** The set of available button-types that can be put on the title bar.
  44385. @see setTitleBarButtonsRequired
  44386. */
  44387. enum TitleBarButtons
  44388. {
  44389. minimiseButton = 1,
  44390. maximiseButton = 2,
  44391. closeButton = 4,
  44392. /** A combination of all the buttons above. */
  44393. allButtons = 7
  44394. };
  44395. /** Creates a DocumentWindow.
  44396. @param name the name to give the component - this is also
  44397. the title shown at the top of the window. To change
  44398. this later, use setName()
  44399. @param backgroundColour the colour to use for filling the window's background.
  44400. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  44401. should be shown on the title bar. This value is a bitwise
  44402. combination of values from the TitleBarButtons enum. Note
  44403. that it can be "allButtons" to get them all. You
  44404. can change this later with the setTitleBarButtonsRequired()
  44405. method, which can also specify where they are positioned.
  44406. @param addToDesktop if true, the window will be automatically added to the
  44407. desktop; if false, you can use it as a child component
  44408. @see TitleBarButtons
  44409. */
  44410. DocumentWindow (const String& name,
  44411. const Colour& backgroundColour,
  44412. int requiredButtons,
  44413. bool addToDesktop = true);
  44414. /** Destructor.
  44415. If a content component has been set with setContentOwned(), it will be deleted.
  44416. */
  44417. ~DocumentWindow();
  44418. /** Changes the component's name.
  44419. (This is overridden from Component::setName() to cause a repaint, as
  44420. the name is what gets drawn across the window's title bar).
  44421. */
  44422. void setName (const String& newName);
  44423. /** Sets an icon to show in the title bar, next to the title.
  44424. A copy is made internally of the image, so the caller can delete the
  44425. image after calling this. If 0 is passed-in, any existing icon will be
  44426. removed.
  44427. */
  44428. void setIcon (const Image& imageToUse);
  44429. /** Changes the height of the title-bar. */
  44430. void setTitleBarHeight (int newHeight);
  44431. /** Returns the current title bar height. */
  44432. int getTitleBarHeight() const;
  44433. /** Changes the set of title-bar buttons being shown.
  44434. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  44435. should be shown on the title bar. This value is a bitwise
  44436. combination of values from the TitleBarButtons enum. Note
  44437. that it can be "allButtons" to get them all.
  44438. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  44439. left side of the bar; if false, they'll be placed at the right
  44440. */
  44441. void setTitleBarButtonsRequired (int requiredButtons,
  44442. bool positionTitleBarButtonsOnLeft);
  44443. /** Sets whether the title should be centred within the window.
  44444. If true, the title text is shown in the middle of the title-bar; if false,
  44445. it'll be shown at the left of the bar.
  44446. */
  44447. void setTitleBarTextCentred (bool textShouldBeCentred);
  44448. /** Creates a menu inside this window.
  44449. @param menuBarModel this specifies a MenuBarModel that should be used to
  44450. generate the contents of a menu bar that will be placed
  44451. just below the title bar, and just above any content
  44452. component. If this value is zero, any existing menu bar
  44453. will be removed from the component; if non-zero, one will
  44454. be added if it's required.
  44455. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  44456. or less to use the look-and-feel's default size.
  44457. */
  44458. void setMenuBar (MenuBarModel* menuBarModel,
  44459. int menuBarHeight = 0);
  44460. /** Returns the current menu bar component, or null if there isn't one.
  44461. This is probably a MenuBarComponent, unless a custom one has been set using
  44462. setMenuBarComponent().
  44463. */
  44464. Component* getMenuBarComponent() const throw();
  44465. /** Replaces the current menu bar with a custom component.
  44466. The component will be owned and deleted by the document window.
  44467. */
  44468. void setMenuBarComponent (Component* newMenuBarComponent);
  44469. /** This method is called when the user tries to close the window.
  44470. This is triggered by the user clicking the close button, or using some other
  44471. OS-specific key shortcut or OS menu for getting rid of a window.
  44472. If the window is just a pop-up, you should override this closeButtonPressed()
  44473. method and make it delete the window in whatever way is appropriate for your
  44474. app. E.g. you might just want to call "delete this".
  44475. If your app is centred around this window such that the whole app should quit when
  44476. the window is closed, then you will probably want to use this method as an opportunity
  44477. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  44478. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  44479. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  44480. or closing it via the taskbar icon on Windows).
  44481. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  44482. redirects it to call this method, so any methods of closing the window that are
  44483. caught by userTriedToCloseWindow() will also end up here).
  44484. */
  44485. virtual void closeButtonPressed();
  44486. /** Callback that is triggered when the minimise button is pressed.
  44487. The default implementation of this calls ResizableWindow::setMinimised(), but
  44488. you can override it to do more customised behaviour.
  44489. */
  44490. virtual void minimiseButtonPressed();
  44491. /** Callback that is triggered when the maximise button is pressed, or when the
  44492. title-bar is double-clicked.
  44493. The default implementation of this calls ResizableWindow::setFullScreen(), but
  44494. you can override it to do more customised behaviour.
  44495. */
  44496. virtual void maximiseButtonPressed();
  44497. /** Returns the close button, (or 0 if there isn't one). */
  44498. Button* getCloseButton() const throw();
  44499. /** Returns the minimise button, (or 0 if there isn't one). */
  44500. Button* getMinimiseButton() const throw();
  44501. /** Returns the maximise button, (or 0 if there isn't one). */
  44502. Button* getMaximiseButton() const throw();
  44503. /** A set of colour IDs to use to change the colour of various aspects of the window.
  44504. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44505. methods.
  44506. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44507. */
  44508. enum ColourIds
  44509. {
  44510. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  44511. and feel class how this is used. */
  44512. };
  44513. /** @internal */
  44514. void paint (Graphics& g);
  44515. /** @internal */
  44516. void resized();
  44517. /** @internal */
  44518. void lookAndFeelChanged();
  44519. /** @internal */
  44520. const BorderSize<int> getBorderThickness();
  44521. /** @internal */
  44522. const BorderSize<int> getContentComponentBorder();
  44523. /** @internal */
  44524. void mouseDoubleClick (const MouseEvent& e);
  44525. /** @internal */
  44526. void userTriedToCloseWindow();
  44527. /** @internal */
  44528. void activeWindowStatusChanged();
  44529. /** @internal */
  44530. int getDesktopWindowStyleFlags() const;
  44531. /** @internal */
  44532. void parentHierarchyChanged();
  44533. /** @internal */
  44534. const Rectangle<int> getTitleBarArea();
  44535. private:
  44536. int titleBarHeight, menuBarHeight, requiredButtons;
  44537. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  44538. ScopedPointer <Button> titleBarButtons [3];
  44539. Image titleBarIcon;
  44540. ScopedPointer <Component> menuBar;
  44541. MenuBarModel* menuBarModel;
  44542. class ButtonListenerProxy;
  44543. friend class ScopedPointer <ButtonListenerProxy>;
  44544. ScopedPointer <ButtonListenerProxy> buttonListener;
  44545. void repaintTitleBar();
  44546. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DocumentWindow);
  44547. };
  44548. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  44549. /*** End of inlined file: juce_DocumentWindow.h ***/
  44550. class MultiDocumentPanel;
  44551. class MDITabbedComponentInternal;
  44552. /**
  44553. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  44554. component.
  44555. It's like a normal DocumentWindow but has some extra functionality to make sure
  44556. everything works nicely inside a MultiDocumentPanel.
  44557. @see MultiDocumentPanel
  44558. */
  44559. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  44560. {
  44561. public:
  44562. /**
  44563. */
  44564. MultiDocumentPanelWindow (const Colour& backgroundColour);
  44565. /** Destructor. */
  44566. ~MultiDocumentPanelWindow();
  44567. /** @internal */
  44568. void maximiseButtonPressed();
  44569. /** @internal */
  44570. void closeButtonPressed();
  44571. /** @internal */
  44572. void activeWindowStatusChanged();
  44573. /** @internal */
  44574. void broughtToFront();
  44575. private:
  44576. void updateOrder();
  44577. MultiDocumentPanel* getOwner() const throw();
  44578. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanelWindow);
  44579. };
  44580. /**
  44581. A component that contains a set of other components either in floating windows
  44582. or tabs.
  44583. This acts as a panel that can be used to hold a set of open document windows, with
  44584. different layout modes.
  44585. Use addDocument() and closeDocument() to add or remove components from the
  44586. panel - never use any of the Component methods to access the panel's child
  44587. components directly, as these are managed internally.
  44588. */
  44589. class JUCE_API MultiDocumentPanel : public Component,
  44590. private ComponentListener
  44591. {
  44592. public:
  44593. /** Creates an empty panel.
  44594. Use addDocument() and closeDocument() to add or remove components from the
  44595. panel - never use any of the Component methods to access the panel's child
  44596. components directly, as these are managed internally.
  44597. */
  44598. MultiDocumentPanel();
  44599. /** Destructor.
  44600. When deleted, this will call closeAllDocuments (false) to make sure all its
  44601. components are deleted. If you need to make sure all documents are saved
  44602. before closing, then you should call closeAllDocuments (true) and check that
  44603. it returns true before deleting the panel.
  44604. */
  44605. ~MultiDocumentPanel();
  44606. /** Tries to close all the documents.
  44607. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  44608. be called for each open document, and any of these calls fails, this method
  44609. will stop and return false, leaving some documents still open.
  44610. If checkItsOkToCloseFirst is false, then all documents will be closed
  44611. unconditionally.
  44612. @see closeDocument
  44613. */
  44614. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  44615. /** Adds a document component to the panel.
  44616. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  44617. this will fail and return false. (If it does fail, the component passed-in will not be
  44618. deleted, even if deleteWhenRemoved was set to true).
  44619. The MultiDocumentPanel will deal with creating a window border to go around your component,
  44620. so just pass in the bare content component here, no need to give it a ResizableWindow
  44621. or DocumentWindow.
  44622. @param component the component to add
  44623. @param backgroundColour the background colour to use to fill the component's
  44624. window or tab
  44625. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  44626. or closeAllDocuments(), then it will be deleted. If false, then
  44627. the caller must handle the component's deletion
  44628. */
  44629. bool addDocument (Component* component,
  44630. const Colour& backgroundColour,
  44631. bool deleteWhenRemoved);
  44632. /** Closes one of the documents.
  44633. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  44634. be called, and if it fails, this method will return false without closing the
  44635. document.
  44636. If checkItsOkToCloseFirst is false, then the documents will be closed
  44637. unconditionally.
  44638. The component will be deleted if the deleteWhenRemoved parameter was set to
  44639. true when it was added with addDocument.
  44640. @see addDocument, closeAllDocuments
  44641. */
  44642. bool closeDocument (Component* component,
  44643. bool checkItsOkToCloseFirst);
  44644. /** Returns the number of open document windows.
  44645. @see getDocument
  44646. */
  44647. int getNumDocuments() const throw();
  44648. /** Returns one of the open documents.
  44649. The order of the documents in this array may change when they are added, removed
  44650. or moved around.
  44651. @see getNumDocuments
  44652. */
  44653. Component* getDocument (int index) const throw();
  44654. /** Returns the document component that is currently focused or on top.
  44655. If currently using floating windows, then this will be the component in the currently
  44656. active window, or the top component if none are active.
  44657. If it's currently in tabbed mode, then it'll return the component in the active tab.
  44658. @see setActiveDocument
  44659. */
  44660. Component* getActiveDocument() const throw();
  44661. /** Makes one of the components active and brings it to the top.
  44662. @see getActiveDocument
  44663. */
  44664. void setActiveDocument (Component* component);
  44665. /** Callback which gets invoked when the currently-active document changes. */
  44666. virtual void activeDocumentChanged();
  44667. /** Sets a limit on how many windows can be open at once.
  44668. If this is zero or less there's no limit (the default). addDocument() will fail
  44669. if this number is exceeded.
  44670. */
  44671. void setMaximumNumDocuments (int maximumNumDocuments);
  44672. /** Sets an option to make the document fullscreen if there's only one document open.
  44673. If set to true, then if there's only one document, it'll fill the whole of this
  44674. component without tabs or a window border. If false, then tabs or a window
  44675. will always be shown, even if there's only one document. If there's more than
  44676. one document open, then this option makes no difference.
  44677. */
  44678. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  44679. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  44680. */
  44681. bool isFullscreenWhenOneDocument() const throw();
  44682. /** The different layout modes available. */
  44683. enum LayoutMode
  44684. {
  44685. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  44686. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  44687. };
  44688. /** Changes the panel's mode.
  44689. @see LayoutMode, getLayoutMode
  44690. */
  44691. void setLayoutMode (LayoutMode newLayoutMode);
  44692. /** Returns the current layout mode. */
  44693. LayoutMode getLayoutMode() const throw() { return mode; }
  44694. /** Sets the background colour for the whole panel.
  44695. Each document has its own background colour, but this is the one used to fill the areas
  44696. behind them.
  44697. */
  44698. void setBackgroundColour (const Colour& newBackgroundColour);
  44699. /** Returns the current background colour.
  44700. @see setBackgroundColour
  44701. */
  44702. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  44703. /** A subclass must override this to say whether its currently ok for a document
  44704. to be closed.
  44705. This method is called by closeDocument() and closeAllDocuments() to indicate that
  44706. a document should be saved if possible, ready for it to be closed.
  44707. If this method returns true, then it means the document is ok and can be closed.
  44708. If it returns false, then it means that the closeDocument() method should stop
  44709. and not close.
  44710. Normally, you'd use this method to ask the user if they want to save any changes,
  44711. then return true if the save operation went ok. If the user cancelled the save
  44712. operation you could return false here to abort the close operation.
  44713. If your component is based on the FileBasedDocument class, then you'd probably want
  44714. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  44715. FileBasedDocument::savedOk
  44716. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  44717. */
  44718. virtual bool tryToCloseDocument (Component* component) = 0;
  44719. /** Creates a new window to be used for a document.
  44720. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  44721. but you might want to override it to return a custom component.
  44722. */
  44723. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  44724. /** @internal */
  44725. void paint (Graphics& g);
  44726. /** @internal */
  44727. void resized();
  44728. /** @internal */
  44729. void componentNameChanged (Component&);
  44730. private:
  44731. LayoutMode mode;
  44732. Array <Component*> components;
  44733. ScopedPointer<TabbedComponent> tabComponent;
  44734. Colour backgroundColour;
  44735. int maximumNumDocuments, numDocsBeforeTabsUsed;
  44736. friend class MultiDocumentPanelWindow;
  44737. friend class MDITabbedComponentInternal;
  44738. Component* getContainerComp (Component* c) const;
  44739. void updateOrder();
  44740. void addWindow (Component* component);
  44741. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanel);
  44742. };
  44743. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  44744. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  44745. #endif
  44746. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  44747. #endif
  44748. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  44749. #endif
  44750. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  44751. /*** Start of inlined file: juce_ResizableEdgeComponent.h ***/
  44752. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  44753. #define __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  44754. /**
  44755. A component that resizes its parent component when dragged.
  44756. This component forms a bar along one edge of a component, allowing it to
  44757. be dragged by that edges to resize it.
  44758. To use it, just add it to your component, positioning it along the appropriate
  44759. edge. Make sure you reposition the resizer component each time the parent's size
  44760. changes, to keep it in the correct position.
  44761. @see ResizbleBorderComponent, ResizableCornerComponent
  44762. */
  44763. class JUCE_API ResizableEdgeComponent : public Component
  44764. {
  44765. public:
  44766. enum Edge
  44767. {
  44768. leftEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's left-hand edge. */
  44769. rightEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's right-hand edge. */
  44770. topEdge, /**< Indicates a horizontal bar that can be dragged up/down to move the top of the component. */
  44771. bottomEdge /**< Indicates a horizontal bar that can be dragged up/down to move the bottom of the component. */
  44772. };
  44773. /** Creates a resizer bar.
  44774. Pass in the target component which you want to be resized when this one is
  44775. dragged. The target component will usually be this component's parent, but this
  44776. isn't mandatory.
  44777. Remember that when the target component is resized, it'll need to move and
  44778. resize this component to keep it in place, as this won't happen automatically.
  44779. If the constrainer parameter is non-zero, then this object will be used to enforce
  44780. limits on the size and position that the component can be stretched to. Make sure
  44781. that the constrainer isn't deleted while still in use by this object.
  44782. @see ComponentBoundsConstrainer
  44783. */
  44784. ResizableEdgeComponent (Component* componentToResize,
  44785. ComponentBoundsConstrainer* constrainer,
  44786. Edge edgeToResize);
  44787. /** Destructor. */
  44788. ~ResizableEdgeComponent();
  44789. bool isVertical() const throw();
  44790. protected:
  44791. /** @internal */
  44792. void paint (Graphics& g);
  44793. /** @internal */
  44794. void mouseDown (const MouseEvent& e);
  44795. /** @internal */
  44796. void mouseDrag (const MouseEvent& e);
  44797. /** @internal */
  44798. void mouseUp (const MouseEvent& e);
  44799. private:
  44800. WeakReference<Component> component;
  44801. ComponentBoundsConstrainer* constrainer;
  44802. Rectangle<int> originalBounds;
  44803. const Edge edge;
  44804. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableEdgeComponent);
  44805. };
  44806. #endif // __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  44807. /*** End of inlined file: juce_ResizableEdgeComponent.h ***/
  44808. #endif
  44809. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  44810. #endif
  44811. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  44812. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  44813. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  44814. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  44815. /**
  44816. For laying out a set of components, where the components have preferred sizes
  44817. and size limits, but where they are allowed to stretch to fill the available
  44818. space.
  44819. For example, if you have a component containing several other components, and
  44820. each one should be given a share of the total size, you could use one of these
  44821. to resize the child components when the parent component is resized. Then
  44822. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  44823. A StretchableLayoutManager operates only in one dimension, so if you have a set
  44824. of components stacked vertically on top of each other, you'd use one to manage their
  44825. heights. To build up complex arrangements of components, e.g. for applications
  44826. with multiple nested panels, you would use more than one StretchableLayoutManager.
  44827. E.g. by using two (one vertical, one horizontal), you could create a resizable
  44828. spreadsheet-style table.
  44829. E.g.
  44830. @code
  44831. class MyComp : public Component
  44832. {
  44833. StretchableLayoutManager myLayout;
  44834. MyComp()
  44835. {
  44836. myLayout.setItemLayout (0, // for item 0
  44837. 50, 100, // must be between 50 and 100 pixels in size
  44838. -0.6); // and its preferred size is 60% of the total available space
  44839. myLayout.setItemLayout (1, // for item 1
  44840. -0.2, -0.6, // size must be between 20% and 60% of the available space
  44841. 50); // and its preferred size is 50 pixels
  44842. }
  44843. void resized()
  44844. {
  44845. // make a list of two of our child components that we want to reposition
  44846. Component* comps[] = { myComp1, myComp2 };
  44847. // this will position the 2 components, one above the other, to fit
  44848. // vertically into the rectangle provided.
  44849. myLayout.layOutComponents (comps, 2,
  44850. 0, 0, getWidth(), getHeight(),
  44851. true);
  44852. }
  44853. };
  44854. @endcode
  44855. @see StretchableLayoutResizerBar
  44856. */
  44857. class JUCE_API StretchableLayoutManager
  44858. {
  44859. public:
  44860. /** Creates an empty layout.
  44861. You'll need to add some item properties to the layout before it can be used
  44862. to resize things - see setItemLayout().
  44863. */
  44864. StretchableLayoutManager();
  44865. /** Destructor. */
  44866. ~StretchableLayoutManager();
  44867. /** For a numbered item, this sets its size limits and preferred size.
  44868. @param itemIndex the index of the item to change.
  44869. @param minimumSize the minimum size that this item is allowed to be - a positive number
  44870. indicates an absolute size in pixels. A negative number indicates a
  44871. proportion of the available space (e.g -0.5 is 50%)
  44872. @param maximumSize the maximum size that this item is allowed to be - a positive number
  44873. indicates an absolute size in pixels. A negative number indicates a
  44874. proportion of the available space
  44875. @param preferredSize the size that this item would like to be, if there's enough room. A
  44876. positive number indicates an absolute size in pixels. A negative number
  44877. indicates a proportion of the available space
  44878. @see getItemLayout
  44879. */
  44880. void setItemLayout (int itemIndex,
  44881. double minimumSize,
  44882. double maximumSize,
  44883. double preferredSize);
  44884. /** For a numbered item, this returns its size limits and preferred size.
  44885. @param itemIndex the index of the item.
  44886. @param minimumSize the minimum size that this item is allowed to be - a positive number
  44887. indicates an absolute size in pixels. A negative number indicates a
  44888. proportion of the available space (e.g -0.5 is 50%)
  44889. @param maximumSize the maximum size that this item is allowed to be - a positive number
  44890. indicates an absolute size in pixels. A negative number indicates a
  44891. proportion of the available space
  44892. @param preferredSize the size that this item would like to be, if there's enough room. A
  44893. positive number indicates an absolute size in pixels. A negative number
  44894. indicates a proportion of the available space
  44895. @returns false if the item's properties hadn't been set
  44896. @see setItemLayout
  44897. */
  44898. bool getItemLayout (int itemIndex,
  44899. double& minimumSize,
  44900. double& maximumSize,
  44901. double& preferredSize) const;
  44902. /** Clears all the properties that have been set with setItemLayout() and resets
  44903. this object to its initial state.
  44904. */
  44905. void clearAllItems();
  44906. /** Takes a set of components that correspond to the layout's items, and positions
  44907. them to fill a space.
  44908. This will try to give each item its preferred size, whether that's a relative size
  44909. or an absolute one.
  44910. @param components an array of components that correspond to each of the
  44911. numbered items that the StretchableLayoutManager object
  44912. has been told about with setItemLayout()
  44913. @param numComponents the number of components in the array that is passed-in. This
  44914. should be the same as the number of items this object has been
  44915. told about.
  44916. @param x the left of the rectangle in which the components should
  44917. be laid out
  44918. @param y the top of the rectangle in which the components should
  44919. be laid out
  44920. @param width the width of the rectangle in which the components should
  44921. be laid out
  44922. @param height the height of the rectangle in which the components should
  44923. be laid out
  44924. @param vertically if true, the components will be positioned in a vertical stack,
  44925. so that they fill the height of the rectangle. If false, they
  44926. will be placed side-by-side in a horizontal line, filling the
  44927. available width
  44928. @param resizeOtherDimension if true, this means that the components will have their
  44929. other dimension resized to fit the space - i.e. if the 'vertically'
  44930. parameter is true, their x-positions and widths are adjusted to fit
  44931. the x and width parameters; if 'vertically' is false, their y-positions
  44932. and heights are adjusted to fit the y and height parameters.
  44933. */
  44934. void layOutComponents (Component** components,
  44935. int numComponents,
  44936. int x, int y, int width, int height,
  44937. bool vertically,
  44938. bool resizeOtherDimension);
  44939. /** Returns the current position of one of the items.
  44940. This is only a valid call after layOutComponents() has been called, as it
  44941. returns the last position that this item was placed at. If the layout was
  44942. vertical, the value returned will be the y position of the top of the item,
  44943. relative to the top of the rectangle in which the items were placed (so for
  44944. example, item 0 will always have position of 0, even in the rectangle passed
  44945. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  44946. the position returned is the item's left-hand position, again relative to the
  44947. x position of the rectangle used.
  44948. @see getItemCurrentSize, setItemPosition
  44949. */
  44950. int getItemCurrentPosition (int itemIndex) const;
  44951. /** Returns the current size of one of the items.
  44952. This is only meaningful after layOutComponents() has been called, as it
  44953. returns the last size that this item was given. If the layout was done
  44954. vertically, it'll return the item's height in pixels; if it was horizontal,
  44955. it'll return its width.
  44956. @see getItemCurrentRelativeSize
  44957. */
  44958. int getItemCurrentAbsoluteSize (int itemIndex) const;
  44959. /** Returns the current size of one of the items.
  44960. This is only meaningful after layOutComponents() has been called, as it
  44961. returns the last size that this item was given. If the layout was done
  44962. vertically, it'll return a negative value representing the item's height relative
  44963. to the last size used for laying the components out; if the layout was done
  44964. horizontally it'll be the proportion of its width.
  44965. @see getItemCurrentAbsoluteSize
  44966. */
  44967. double getItemCurrentRelativeSize (int itemIndex) const;
  44968. /** Moves one of the items, shifting along any other items as necessary in
  44969. order to get it to the desired position.
  44970. Calling this method will also update the preferred sizes of the items it
  44971. shuffles along, so that they reflect their new positions.
  44972. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  44973. about when it's dragged).
  44974. @param itemIndex the item to move
  44975. @param newPosition the absolute position that you'd like this item to move
  44976. to. The item might not be able to always reach exactly this position,
  44977. because other items may have minimum sizes that constrain how
  44978. far it can go
  44979. */
  44980. void setItemPosition (int itemIndex,
  44981. int newPosition);
  44982. private:
  44983. struct ItemLayoutProperties
  44984. {
  44985. int itemIndex;
  44986. int currentSize;
  44987. double minSize, maxSize, preferredSize;
  44988. };
  44989. OwnedArray <ItemLayoutProperties> items;
  44990. int totalSize;
  44991. static int sizeToRealSize (double size, int totalSpace);
  44992. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  44993. void setTotalSize (int newTotalSize);
  44994. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  44995. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  44996. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  44997. void updatePrefSizesToMatchCurrentPositions();
  44998. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutManager);
  44999. };
  45000. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  45001. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  45002. #endif
  45003. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45004. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  45005. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45006. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45007. /**
  45008. A component that acts as one of the vertical or horizontal bars you see being
  45009. used to resize panels in a window.
  45010. One of these acts with a StretchableLayoutManager to resize the other components.
  45011. @see StretchableLayoutManager
  45012. */
  45013. class JUCE_API StretchableLayoutResizerBar : public Component
  45014. {
  45015. public:
  45016. /** Creates a resizer bar for use on a specified layout.
  45017. @param layoutToUse the layout that will be affected when this bar
  45018. is dragged
  45019. @param itemIndexInLayout the item index in the layout that corresponds to
  45020. this bar component. You'll need to set up the item
  45021. properties in a suitable way for a divider bar, e.g.
  45022. for an 8-pixel wide bar which, you could call
  45023. myLayout->setItemLayout (barIndex, 8, 8, 8)
  45024. @param isBarVertical true if it's an upright bar that you drag left and
  45025. right; false for a horizontal one that you drag up and
  45026. down
  45027. */
  45028. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  45029. int itemIndexInLayout,
  45030. bool isBarVertical);
  45031. /** Destructor. */
  45032. ~StretchableLayoutResizerBar();
  45033. /** This is called when the bar is dragged.
  45034. This method must update the positions of any components whose position is
  45035. determined by the StretchableLayoutManager, because they might have just
  45036. moved.
  45037. The default implementation calls the resized() method of this component's
  45038. parent component, because that's often where you're likely to apply the
  45039. layout, but it can be overridden for more specific needs.
  45040. */
  45041. virtual void hasBeenMoved();
  45042. /** @internal */
  45043. void paint (Graphics& g);
  45044. /** @internal */
  45045. void mouseDown (const MouseEvent& e);
  45046. /** @internal */
  45047. void mouseDrag (const MouseEvent& e);
  45048. private:
  45049. StretchableLayoutManager* layout;
  45050. int itemIndex, mouseDownPos;
  45051. bool isVertical;
  45052. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutResizerBar);
  45053. };
  45054. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45055. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  45056. #endif
  45057. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45058. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  45059. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45060. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45061. /**
  45062. A utility class for fitting a set of objects whose sizes can vary between
  45063. a minimum and maximum size, into a space.
  45064. This is a trickier algorithm than it would first seem, so I've put it in this
  45065. class to allow it to be shared by various bits of code.
  45066. To use it, create one of these objects, call addItem() to add the list of items
  45067. you need, then call resizeToFit(), which will change all their sizes. You can
  45068. then retrieve the new sizes with getItemSize() and getNumItems().
  45069. It's currently used by the TableHeaderComponent for stretching out the table
  45070. headings to fill the table's width.
  45071. */
  45072. class StretchableObjectResizer
  45073. {
  45074. public:
  45075. /** Creates an empty object resizer. */
  45076. StretchableObjectResizer();
  45077. /** Destructor. */
  45078. ~StretchableObjectResizer();
  45079. /** Adds an item to the list.
  45080. The order parameter lets you specify groups of items that are resized first when some
  45081. space needs to be found. Those items with an order of 0 will be the first ones to be
  45082. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  45083. will then try resizing the items with an order of 1, then 2, and so on.
  45084. */
  45085. void addItem (double currentSize,
  45086. double minSize,
  45087. double maxSize,
  45088. int order = 0);
  45089. /** Resizes all the items to fit this amount of space.
  45090. This will attempt to fit them in without exceeding each item's miniumum and
  45091. maximum sizes. In cases where none of the items can be expanded or enlarged any
  45092. further, the final size may be greater or less than the size passed in.
  45093. After calling this method, you can retrieve the new sizes with the getItemSize()
  45094. method.
  45095. */
  45096. void resizeToFit (double targetSize);
  45097. /** Returns the number of items that have been added. */
  45098. int getNumItems() const throw() { return items.size(); }
  45099. /** Returns the size of one of the items. */
  45100. double getItemSize (int index) const throw();
  45101. private:
  45102. struct Item
  45103. {
  45104. double size;
  45105. double minSize;
  45106. double maxSize;
  45107. int order;
  45108. };
  45109. OwnedArray <Item> items;
  45110. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableObjectResizer);
  45111. };
  45112. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45113. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  45114. #endif
  45115. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  45116. #endif
  45117. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  45118. #endif
  45119. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  45120. #endif
  45121. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  45122. /*** Start of inlined file: juce_LookAndFeel.h ***/
  45123. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  45124. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  45125. class ToggleButton;
  45126. class TextButton;
  45127. class AlertWindow;
  45128. class TextLayout;
  45129. class ScrollBar;
  45130. class BubbleComponent;
  45131. class ComboBox;
  45132. class Button;
  45133. class FilenameComponent;
  45134. class DocumentWindow;
  45135. class ResizableWindow;
  45136. class GroupComponent;
  45137. class MenuBarComponent;
  45138. class DropShadower;
  45139. class GlyphArrangement;
  45140. class PropertyComponent;
  45141. class TableHeaderComponent;
  45142. class Toolbar;
  45143. class ToolbarItemComponent;
  45144. class PopupMenu;
  45145. class ProgressBar;
  45146. class FileBrowserComponent;
  45147. class DirectoryContentsDisplayComponent;
  45148. class FilePreviewComponent;
  45149. class ImageButton;
  45150. class CallOutBox;
  45151. class Drawable;
  45152. /**
  45153. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  45154. can be used to apply different 'skins' to the application.
  45155. */
  45156. class JUCE_API LookAndFeel
  45157. {
  45158. public:
  45159. /** Creates the default JUCE look and feel. */
  45160. LookAndFeel();
  45161. /** Destructor. */
  45162. virtual ~LookAndFeel();
  45163. /** Returns the current default look-and-feel for a component to use when it
  45164. hasn't got one explicitly set.
  45165. @see setDefaultLookAndFeel
  45166. */
  45167. static LookAndFeel& getDefaultLookAndFeel() throw();
  45168. /** Changes the default look-and-feel.
  45169. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  45170. set to 0, it will revert to using the default one. The
  45171. object passed-in must be deleted by the caller when
  45172. it's no longer needed.
  45173. @see getDefaultLookAndFeel
  45174. */
  45175. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  45176. /** Looks for a colour that has been registered with the given colour ID number.
  45177. If a colour has been set for this ID number using setColour(), then it is
  45178. returned. If none has been set, it will just return Colours::black.
  45179. The colour IDs for various purposes are stored as enums in the components that
  45180. they are relevent to - for an example, see Slider::ColourIds,
  45181. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  45182. If you're looking up a colour for use in drawing a component, it's usually
  45183. best not to call this directly, but to use the Component::findColour() method
  45184. instead. That will first check whether a suitable colour has been registered
  45185. directly with the component, and will fall-back on calling the component's
  45186. LookAndFeel's findColour() method if none is found.
  45187. @see setColour, Component::findColour, Component::setColour
  45188. */
  45189. const Colour findColour (int colourId) const throw();
  45190. /** Registers a colour to be used for a particular purpose.
  45191. For more details, see the comments for findColour().
  45192. @see findColour, Component::findColour, Component::setColour
  45193. */
  45194. void setColour (int colourId, const Colour& colour) throw();
  45195. /** Returns true if the specified colour ID has been explicitly set using the
  45196. setColour() method.
  45197. */
  45198. bool isColourSpecified (int colourId) const throw();
  45199. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  45200. /** Allows you to change the default sans-serif font.
  45201. If you need to supply your own Typeface object for any of the default fonts, rather
  45202. than just supplying the name (e.g. if you want to use an embedded font), then
  45203. you should instead override getTypefaceForFont() to create and return the typeface.
  45204. */
  45205. void setDefaultSansSerifTypefaceName (const String& newName);
  45206. /** Override this to get the chance to swap a component's mouse cursor for a
  45207. customised one.
  45208. */
  45209. virtual const MouseCursor getMouseCursorFor (Component& component);
  45210. /** Draws the lozenge-shaped background for a standard button. */
  45211. virtual void drawButtonBackground (Graphics& g,
  45212. Button& button,
  45213. const Colour& backgroundColour,
  45214. bool isMouseOverButton,
  45215. bool isButtonDown);
  45216. virtual const Font getFontForTextButton (TextButton& button);
  45217. /** Draws the text for a TextButton. */
  45218. virtual void drawButtonText (Graphics& g,
  45219. TextButton& button,
  45220. bool isMouseOverButton,
  45221. bool isButtonDown);
  45222. /** Draws the contents of a standard ToggleButton. */
  45223. virtual void drawToggleButton (Graphics& g,
  45224. ToggleButton& button,
  45225. bool isMouseOverButton,
  45226. bool isButtonDown);
  45227. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  45228. virtual void drawTickBox (Graphics& g,
  45229. Component& component,
  45230. float x, float y, float w, float h,
  45231. bool ticked,
  45232. bool isEnabled,
  45233. bool isMouseOverButton,
  45234. bool isButtonDown);
  45235. /* AlertWindow handling..
  45236. */
  45237. virtual AlertWindow* createAlertWindow (const String& title,
  45238. const String& message,
  45239. const String& button1,
  45240. const String& button2,
  45241. const String& button3,
  45242. AlertWindow::AlertIconType iconType,
  45243. int numButtons,
  45244. Component* associatedComponent);
  45245. virtual void drawAlertBox (Graphics& g,
  45246. AlertWindow& alert,
  45247. const Rectangle<int>& textArea,
  45248. TextLayout& textLayout);
  45249. virtual int getAlertBoxWindowFlags();
  45250. virtual int getAlertWindowButtonHeight();
  45251. virtual const Font getAlertWindowMessageFont();
  45252. virtual const Font getAlertWindowFont();
  45253. /** Draws a progress bar.
  45254. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  45255. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  45256. isn't known). It can use the current time as a basis for playing an animation.
  45257. (Used by progress bars in AlertWindow).
  45258. */
  45259. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  45260. int width, int height,
  45261. double progress, const String& textToShow);
  45262. // Draws a small image that spins to indicate that something's happening..
  45263. // This method should use the current time to animate itself, so just keep
  45264. // repainting it every so often.
  45265. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  45266. int x, int y, int w, int h);
  45267. /** Draws one of the buttons on a scrollbar.
  45268. @param g the context to draw into
  45269. @param scrollbar the bar itself
  45270. @param width the width of the button
  45271. @param height the height of the button
  45272. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  45273. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  45274. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  45275. @param isButtonDown whether the mouse button's held down
  45276. */
  45277. virtual void drawScrollbarButton (Graphics& g,
  45278. ScrollBar& scrollbar,
  45279. int width, int height,
  45280. int buttonDirection,
  45281. bool isScrollbarVertical,
  45282. bool isMouseOverButton,
  45283. bool isButtonDown);
  45284. /** Draws the thumb area of a scrollbar.
  45285. @param g the context to draw into
  45286. @param scrollbar the bar itself
  45287. @param x the x position of the left edge of the thumb area to draw in
  45288. @param y the y position of the top edge of the thumb area to draw in
  45289. @param width the width of the thumb area to draw in
  45290. @param height the height of the thumb area to draw in
  45291. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  45292. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  45293. thumb, or its x position for horizontal bars
  45294. @param thumbSize for vertical bars, the height of the thumb, or its width for
  45295. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  45296. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  45297. currently dragging the thumb
  45298. @param isMouseDown whether the mouse is currently dragging the scrollbar
  45299. */
  45300. virtual void drawScrollbar (Graphics& g,
  45301. ScrollBar& scrollbar,
  45302. int x, int y,
  45303. int width, int height,
  45304. bool isScrollbarVertical,
  45305. int thumbStartPosition,
  45306. int thumbSize,
  45307. bool isMouseOver,
  45308. bool isMouseDown);
  45309. /** Returns the component effect to use for a scrollbar */
  45310. virtual ImageEffectFilter* getScrollbarEffect();
  45311. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  45312. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  45313. /** Returns the default thickness to use for a scrollbar. */
  45314. virtual int getDefaultScrollbarWidth();
  45315. /** Returns the length in pixels to use for a scrollbar button. */
  45316. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  45317. /** Returns a tick shape for use in yes/no boxes, etc. */
  45318. virtual const Path getTickShape (float height);
  45319. /** Returns a cross shape for use in yes/no boxes, etc. */
  45320. virtual const Path getCrossShape (float height);
  45321. /** Draws the + or - box in a treeview. */
  45322. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  45323. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  45324. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  45325. // These return a pointer to an internally cached drawable - make sure you don't keep
  45326. // a copy of this pointer anywhere, as it may become invalid in the future.
  45327. virtual const Drawable* getDefaultFolderImage();
  45328. virtual const Drawable* getDefaultDocumentFileImage();
  45329. virtual void createFileChooserHeaderText (const String& title,
  45330. const String& instructions,
  45331. GlyphArrangement& destArrangement,
  45332. int width);
  45333. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  45334. const String& filename, Image* icon,
  45335. const String& fileSizeDescription,
  45336. const String& fileTimeDescription,
  45337. bool isDirectory,
  45338. bool isItemSelected,
  45339. int itemIndex,
  45340. DirectoryContentsDisplayComponent& component);
  45341. virtual Button* createFileBrowserGoUpButton();
  45342. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  45343. DirectoryContentsDisplayComponent* fileListComponent,
  45344. FilePreviewComponent* previewComp,
  45345. ComboBox* currentPathBox,
  45346. TextEditor* filenameBox,
  45347. Button* goUpButton);
  45348. virtual void drawBubble (Graphics& g,
  45349. float tipX, float tipY,
  45350. float boxX, float boxY, float boxW, float boxH);
  45351. /** Fills the background of a popup menu component. */
  45352. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  45353. /** Draws one of the items in a popup menu. */
  45354. virtual void drawPopupMenuItem (Graphics& g,
  45355. int width, int height,
  45356. bool isSeparator,
  45357. bool isActive,
  45358. bool isHighlighted,
  45359. bool isTicked,
  45360. bool hasSubMenu,
  45361. const String& text,
  45362. const String& shortcutKeyText,
  45363. Image* image,
  45364. const Colour* const textColour);
  45365. /** Returns the size and style of font to use in popup menus. */
  45366. virtual const Font getPopupMenuFont();
  45367. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  45368. int width, int height,
  45369. bool isScrollUpArrow);
  45370. /** Finds the best size for an item in a popup menu. */
  45371. virtual void getIdealPopupMenuItemSize (const String& text,
  45372. bool isSeparator,
  45373. int standardMenuItemHeight,
  45374. int& idealWidth,
  45375. int& idealHeight);
  45376. virtual int getMenuWindowFlags();
  45377. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  45378. bool isMouseOverBar,
  45379. MenuBarComponent& menuBar);
  45380. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  45381. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  45382. virtual void drawMenuBarItem (Graphics& g,
  45383. int width, int height,
  45384. int itemIndex,
  45385. const String& itemText,
  45386. bool isMouseOverItem,
  45387. bool isMenuOpen,
  45388. bool isMouseOverBar,
  45389. MenuBarComponent& menuBar);
  45390. virtual void drawComboBox (Graphics& g, int width, int height,
  45391. bool isButtonDown,
  45392. int buttonX, int buttonY,
  45393. int buttonW, int buttonH,
  45394. ComboBox& box);
  45395. virtual const Font getComboBoxFont (ComboBox& box);
  45396. virtual Label* createComboBoxTextBox (ComboBox& box);
  45397. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  45398. virtual void drawLabel (Graphics& g, Label& label);
  45399. virtual void drawLinearSlider (Graphics& g,
  45400. int x, int y,
  45401. int width, int height,
  45402. float sliderPos,
  45403. float minSliderPos,
  45404. float maxSliderPos,
  45405. const Slider::SliderStyle style,
  45406. Slider& slider);
  45407. virtual void drawLinearSliderBackground (Graphics& g,
  45408. int x, int y,
  45409. int width, int height,
  45410. float sliderPos,
  45411. float minSliderPos,
  45412. float maxSliderPos,
  45413. const Slider::SliderStyle style,
  45414. Slider& slider);
  45415. virtual void drawLinearSliderThumb (Graphics& g,
  45416. int x, int y,
  45417. int width, int height,
  45418. float sliderPos,
  45419. float minSliderPos,
  45420. float maxSliderPos,
  45421. const Slider::SliderStyle style,
  45422. Slider& slider);
  45423. virtual int getSliderThumbRadius (Slider& slider);
  45424. virtual void drawRotarySlider (Graphics& g,
  45425. int x, int y,
  45426. int width, int height,
  45427. float sliderPosProportional,
  45428. float rotaryStartAngle,
  45429. float rotaryEndAngle,
  45430. Slider& slider);
  45431. virtual Button* createSliderButton (bool isIncrement);
  45432. virtual Label* createSliderTextBox (Slider& slider);
  45433. virtual ImageEffectFilter* getSliderEffect();
  45434. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  45435. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  45436. virtual Button* createFilenameComponentBrowseButton (const String& text);
  45437. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  45438. ComboBox* filenameBox, Button* browseButton);
  45439. virtual void drawCornerResizer (Graphics& g,
  45440. int w, int h,
  45441. bool isMouseOver,
  45442. bool isMouseDragging);
  45443. virtual void drawResizableFrame (Graphics& g,
  45444. int w, int h,
  45445. const BorderSize<int>& borders);
  45446. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  45447. const BorderSize<int>& border,
  45448. ResizableWindow& window);
  45449. virtual void drawResizableWindowBorder (Graphics& g,
  45450. int w, int h,
  45451. const BorderSize<int>& border,
  45452. ResizableWindow& window);
  45453. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  45454. Graphics& g, int w, int h,
  45455. int titleSpaceX, int titleSpaceW,
  45456. const Image* icon,
  45457. bool drawTitleTextOnLeft);
  45458. virtual Button* createDocumentWindowButton (int buttonType);
  45459. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  45460. int titleBarX, int titleBarY,
  45461. int titleBarW, int titleBarH,
  45462. Button* minimiseButton,
  45463. Button* maximiseButton,
  45464. Button* closeButton,
  45465. bool positionTitleBarButtonsOnLeft);
  45466. virtual int getDefaultMenuBarHeight();
  45467. virtual DropShadower* createDropShadowerForComponent (Component* component);
  45468. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  45469. int w, int h,
  45470. bool isVerticalBar,
  45471. bool isMouseOver,
  45472. bool isMouseDragging);
  45473. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  45474. const String& text,
  45475. const Justification& position,
  45476. GroupComponent& group);
  45477. virtual void createTabButtonShape (Path& p,
  45478. int width, int height,
  45479. int tabIndex,
  45480. const String& text,
  45481. Button& button,
  45482. TabbedButtonBar::Orientation orientation,
  45483. bool isMouseOver,
  45484. bool isMouseDown,
  45485. bool isFrontTab);
  45486. virtual void fillTabButtonShape (Graphics& g,
  45487. const Path& path,
  45488. const Colour& preferredBackgroundColour,
  45489. int tabIndex,
  45490. const String& text,
  45491. Button& button,
  45492. TabbedButtonBar::Orientation orientation,
  45493. bool isMouseOver,
  45494. bool isMouseDown,
  45495. bool isFrontTab);
  45496. virtual void drawTabButtonText (Graphics& g,
  45497. int x, int y, int w, int h,
  45498. const Colour& preferredBackgroundColour,
  45499. int tabIndex,
  45500. const String& text,
  45501. Button& button,
  45502. TabbedButtonBar::Orientation orientation,
  45503. bool isMouseOver,
  45504. bool isMouseDown,
  45505. bool isFrontTab);
  45506. virtual int getTabButtonOverlap (int tabDepth);
  45507. virtual int getTabButtonSpaceAroundImage();
  45508. virtual int getTabButtonBestWidth (int tabIndex,
  45509. const String& text,
  45510. int tabDepth,
  45511. Button& button);
  45512. virtual void drawTabButton (Graphics& g,
  45513. int w, int h,
  45514. const Colour& preferredColour,
  45515. int tabIndex,
  45516. const String& text,
  45517. Button& button,
  45518. TabbedButtonBar::Orientation orientation,
  45519. bool isMouseOver,
  45520. bool isMouseDown,
  45521. bool isFrontTab);
  45522. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  45523. int w, int h,
  45524. TabbedButtonBar& tabBar,
  45525. TabbedButtonBar::Orientation orientation);
  45526. virtual Button* createTabBarExtrasButton();
  45527. virtual void drawImageButton (Graphics& g, Image* image,
  45528. int imageX, int imageY, int imageW, int imageH,
  45529. const Colour& overlayColour,
  45530. float imageOpacity,
  45531. ImageButton& button);
  45532. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  45533. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  45534. int width, int height,
  45535. bool isMouseOver, bool isMouseDown,
  45536. int columnFlags);
  45537. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  45538. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  45539. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  45540. bool isMouseOver, bool isMouseDown,
  45541. ToolbarItemComponent& component);
  45542. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  45543. const String& text, ToolbarItemComponent& component);
  45544. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  45545. bool isOpen, int width, int height);
  45546. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  45547. PropertyComponent& component);
  45548. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  45549. PropertyComponent& component);
  45550. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  45551. virtual void drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path);
  45552. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  45553. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  45554. /**
  45555. */
  45556. virtual void playAlertSound();
  45557. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  45558. static void drawGlassSphere (Graphics& g,
  45559. float x, float y,
  45560. float diameter,
  45561. const Colour& colour,
  45562. float outlineThickness) throw();
  45563. static void drawGlassPointer (Graphics& g,
  45564. float x, float y,
  45565. float diameter,
  45566. const Colour& colour, float outlineThickness,
  45567. int direction) throw();
  45568. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  45569. static void drawGlassLozenge (Graphics& g,
  45570. float x, float y,
  45571. float width, float height,
  45572. const Colour& colour,
  45573. float outlineThickness,
  45574. float cornerSize,
  45575. bool flatOnLeft, bool flatOnRight,
  45576. bool flatOnTop, bool flatOnBottom) throw();
  45577. static Drawable* loadDrawableFromData (const void* data, size_t numBytes);
  45578. private:
  45579. friend JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  45580. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  45581. Array <int> colourIds;
  45582. Array <Colour> colours;
  45583. // default typeface names
  45584. String defaultSans, defaultSerif, defaultFixed;
  45585. ScopedPointer<Drawable> folderImage, documentImage;
  45586. void drawShinyButtonShape (Graphics& g,
  45587. float x, float y, float w, float h, float maxCornerSize,
  45588. const Colour& baseColour,
  45589. float strokeWidth,
  45590. bool flatOnLeft,
  45591. bool flatOnRight,
  45592. bool flatOnTop,
  45593. bool flatOnBottom) throw();
  45594. // This has been deprecated - see the new parameter list..
  45595. virtual int drawFileBrowserRow (Graphics&, int, int, const String&, Image*, const String&, const String&, bool, bool, int) { return 0; }
  45596. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LookAndFeel);
  45597. };
  45598. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  45599. /*** End of inlined file: juce_LookAndFeel.h ***/
  45600. #endif
  45601. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  45602. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  45603. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  45604. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  45605. /**
  45606. The original Juce look-and-feel.
  45607. */
  45608. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  45609. {
  45610. public:
  45611. /** Creates the default JUCE look and feel. */
  45612. OldSchoolLookAndFeel();
  45613. /** Destructor. */
  45614. virtual ~OldSchoolLookAndFeel();
  45615. /** Draws the lozenge-shaped background for a standard button. */
  45616. virtual void drawButtonBackground (Graphics& g,
  45617. Button& button,
  45618. const Colour& backgroundColour,
  45619. bool isMouseOverButton,
  45620. bool isButtonDown);
  45621. /** Draws the contents of a standard ToggleButton. */
  45622. virtual void drawToggleButton (Graphics& g,
  45623. ToggleButton& button,
  45624. bool isMouseOverButton,
  45625. bool isButtonDown);
  45626. virtual void drawTickBox (Graphics& g,
  45627. Component& component,
  45628. float x, float y, float w, float h,
  45629. bool ticked,
  45630. bool isEnabled,
  45631. bool isMouseOverButton,
  45632. bool isButtonDown);
  45633. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  45634. int width, int height,
  45635. double progress, const String& textToShow);
  45636. virtual void drawScrollbarButton (Graphics& g,
  45637. ScrollBar& scrollbar,
  45638. int width, int height,
  45639. int buttonDirection,
  45640. bool isScrollbarVertical,
  45641. bool isMouseOverButton,
  45642. bool isButtonDown);
  45643. virtual void drawScrollbar (Graphics& g,
  45644. ScrollBar& scrollbar,
  45645. int x, int y,
  45646. int width, int height,
  45647. bool isScrollbarVertical,
  45648. int thumbStartPosition,
  45649. int thumbSize,
  45650. bool isMouseOver,
  45651. bool isMouseDown);
  45652. virtual ImageEffectFilter* getScrollbarEffect();
  45653. virtual void drawTextEditorOutline (Graphics& g,
  45654. int width, int height,
  45655. TextEditor& textEditor);
  45656. /** Fills the background of a popup menu component. */
  45657. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  45658. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  45659. bool isMouseOverBar,
  45660. MenuBarComponent& menuBar);
  45661. virtual void drawComboBox (Graphics& g, int width, int height,
  45662. bool isButtonDown,
  45663. int buttonX, int buttonY,
  45664. int buttonW, int buttonH,
  45665. ComboBox& box);
  45666. virtual const Font getComboBoxFont (ComboBox& box);
  45667. virtual void drawLinearSlider (Graphics& g,
  45668. int x, int y,
  45669. int width, int height,
  45670. float sliderPos,
  45671. float minSliderPos,
  45672. float maxSliderPos,
  45673. const Slider::SliderStyle style,
  45674. Slider& slider);
  45675. virtual int getSliderThumbRadius (Slider& slider);
  45676. virtual Button* createSliderButton (bool isIncrement);
  45677. virtual ImageEffectFilter* getSliderEffect();
  45678. virtual void drawCornerResizer (Graphics& g,
  45679. int w, int h,
  45680. bool isMouseOver,
  45681. bool isMouseDragging);
  45682. virtual Button* createDocumentWindowButton (int buttonType);
  45683. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  45684. int titleBarX, int titleBarY,
  45685. int titleBarW, int titleBarH,
  45686. Button* minimiseButton,
  45687. Button* maximiseButton,
  45688. Button* closeButton,
  45689. bool positionTitleBarButtonsOnLeft);
  45690. private:
  45691. DropShadowEffect scrollbarShadow;
  45692. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OldSchoolLookAndFeel);
  45693. };
  45694. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  45695. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  45696. #endif
  45697. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  45698. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  45699. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  45700. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  45701. /**
  45702. A menu bar component.
  45703. @see MenuBarModel
  45704. */
  45705. class JUCE_API MenuBarComponent : public Component,
  45706. private MenuBarModel::Listener,
  45707. private Timer
  45708. {
  45709. public:
  45710. /** Creates a menu bar.
  45711. @param model the model object to use to control this bar. You can
  45712. pass 0 into this if you like, and set the model later
  45713. using the setModel() method
  45714. */
  45715. MenuBarComponent (MenuBarModel* model);
  45716. /** Destructor. */
  45717. ~MenuBarComponent();
  45718. /** Changes the model object to use to control the bar.
  45719. This can be 0, in which case the bar will be empty. Don't delete the object
  45720. that is passed-in while it's still being used by this MenuBar.
  45721. */
  45722. void setModel (MenuBarModel* newModel);
  45723. /** Returns the current menu bar model being used.
  45724. */
  45725. MenuBarModel* getModel() const throw();
  45726. /** Pops up one of the menu items.
  45727. This lets you manually open one of the menus - it could be triggered by a
  45728. key shortcut, for example.
  45729. */
  45730. void showMenu (int menuIndex);
  45731. /** @internal */
  45732. void paint (Graphics& g);
  45733. /** @internal */
  45734. void resized();
  45735. /** @internal */
  45736. void mouseEnter (const MouseEvent& e);
  45737. /** @internal */
  45738. void mouseExit (const MouseEvent& e);
  45739. /** @internal */
  45740. void mouseDown (const MouseEvent& e);
  45741. /** @internal */
  45742. void mouseDrag (const MouseEvent& e);
  45743. /** @internal */
  45744. void mouseUp (const MouseEvent& e);
  45745. /** @internal */
  45746. void mouseMove (const MouseEvent& e);
  45747. /** @internal */
  45748. void handleCommandMessage (int commandId);
  45749. /** @internal */
  45750. bool keyPressed (const KeyPress& key);
  45751. /** @internal */
  45752. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  45753. /** @internal */
  45754. void menuCommandInvoked (MenuBarModel* menuBarModel,
  45755. const ApplicationCommandTarget::InvocationInfo& info);
  45756. private:
  45757. MenuBarModel* model;
  45758. StringArray menuNames;
  45759. Array <int> xPositions;
  45760. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked;
  45761. int lastMouseX, lastMouseY;
  45762. int getItemAt (int x, int y);
  45763. void setItemUnderMouse (int index);
  45764. void setOpenItem (int index);
  45765. void updateItemUnderMouse (int x, int y);
  45766. void timerCallback();
  45767. void repaintMenuItem (int index);
  45768. void menuDismissed (int topLevelIndex, int itemId);
  45769. static void menuBarMenuDismissedCallback (int, MenuBarComponent*, int);
  45770. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarComponent);
  45771. };
  45772. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  45773. /*** End of inlined file: juce_MenuBarComponent.h ***/
  45774. #endif
  45775. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  45776. #endif
  45777. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  45778. #endif
  45779. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  45780. #endif
  45781. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  45782. #endif
  45783. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  45784. #endif
  45785. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  45786. #endif
  45787. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  45788. /*** Start of inlined file: juce_LassoComponent.h ***/
  45789. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  45790. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  45791. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  45792. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  45793. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  45794. /** Manages a list of selectable items.
  45795. Use one of these to keep a track of things that the user has highlighted, like
  45796. icons or things in a list.
  45797. The class is templated so that you can use it to hold either a set of pointers
  45798. to objects, or a set of ID numbers or handles, for cases where each item may
  45799. not always have a corresponding object.
  45800. To be informed when items are selected/deselected, register a ChangeListener with
  45801. this object.
  45802. @see SelectableObject
  45803. */
  45804. template <class SelectableItemType>
  45805. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  45806. {
  45807. public:
  45808. typedef SelectableItemType ItemType;
  45809. typedef PARAMETER_TYPE (SelectableItemType) ParameterType;
  45810. /** Creates an empty set. */
  45811. SelectedItemSet()
  45812. {
  45813. }
  45814. /** Creates a set based on an array of items. */
  45815. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  45816. : selectedItems (items)
  45817. {
  45818. }
  45819. /** Creates a copy of another set. */
  45820. SelectedItemSet (const SelectedItemSet& other)
  45821. : selectedItems (other.selectedItems)
  45822. {
  45823. }
  45824. /** Creates a copy of another set. */
  45825. SelectedItemSet& operator= (const SelectedItemSet& other)
  45826. {
  45827. if (selectedItems != other.selectedItems)
  45828. {
  45829. selectedItems = other.selectedItems;
  45830. changed();
  45831. }
  45832. return *this;
  45833. }
  45834. /** Clears any other currently selected items, and selects this item.
  45835. If this item is already the only thing selected, no change notification
  45836. will be sent out.
  45837. @see addToSelection, addToSelectionBasedOnModifiers
  45838. */
  45839. void selectOnly (ParameterType item)
  45840. {
  45841. if (isSelected (item))
  45842. {
  45843. for (int i = selectedItems.size(); --i >= 0;)
  45844. {
  45845. if (selectedItems.getUnchecked(i) != item)
  45846. {
  45847. deselect (selectedItems.getUnchecked(i));
  45848. i = jmin (i, selectedItems.size());
  45849. }
  45850. }
  45851. }
  45852. else
  45853. {
  45854. deselectAll();
  45855. changed();
  45856. selectedItems.add (item);
  45857. itemSelected (item);
  45858. }
  45859. }
  45860. /** Selects an item.
  45861. If the item is already selected, no change notification will be sent out.
  45862. @see selectOnly, addToSelectionBasedOnModifiers
  45863. */
  45864. void addToSelection (ParameterType item)
  45865. {
  45866. if (! isSelected (item))
  45867. {
  45868. changed();
  45869. selectedItems.add (item);
  45870. itemSelected (item);
  45871. }
  45872. }
  45873. /** Selects or deselects an item.
  45874. This will use the modifier keys to decide whether to deselect other items
  45875. first.
  45876. So if the shift key is held down, the item will be added without deselecting
  45877. anything (same as calling addToSelection() )
  45878. If no modifiers are down, the current selection will be cleared first (same
  45879. as calling selectOnly() )
  45880. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  45881. so it'll be added to the set unless it's already there, in which case it'll be
  45882. deselected.
  45883. If the items that you're selecting can also be dragged, you may need to use the
  45884. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  45885. subtleties of this kind of usage.
  45886. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  45887. */
  45888. void addToSelectionBasedOnModifiers (ParameterType item,
  45889. const ModifierKeys& modifiers)
  45890. {
  45891. if (modifiers.isShiftDown())
  45892. {
  45893. addToSelection (item);
  45894. }
  45895. else if (modifiers.isCommandDown())
  45896. {
  45897. if (isSelected (item))
  45898. deselect (item);
  45899. else
  45900. addToSelection (item);
  45901. }
  45902. else
  45903. {
  45904. selectOnly (item);
  45905. }
  45906. }
  45907. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  45908. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  45909. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  45910. makes it easy to handle multiple-selection of sets of objects that can also
  45911. be dragged.
  45912. For example, if you have several items already selected, and you click on
  45913. one of them (without dragging), then you'd expect this to deselect the other, and
  45914. just select the item you clicked on. But if you had clicked on this item and
  45915. dragged it, you'd have expected them all to stay selected.
  45916. When you call this method, you'll need to store the boolean result, because the
  45917. addToSelectionOnMouseUp() method will need to be know this value.
  45918. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  45919. */
  45920. bool addToSelectionOnMouseDown (ParameterType item,
  45921. const ModifierKeys& modifiers)
  45922. {
  45923. if (isSelected (item))
  45924. {
  45925. return ! modifiers.isPopupMenu();
  45926. }
  45927. else
  45928. {
  45929. addToSelectionBasedOnModifiers (item, modifiers);
  45930. return false;
  45931. }
  45932. }
  45933. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  45934. Call this during a mouseUp callback, when you have previously called the
  45935. addToSelectionOnMouseDown() method during your mouseDown event.
  45936. See addToSelectionOnMouseDown() for more info
  45937. @param item the item to select (or deselect)
  45938. @param modifiers the modifiers from the mouse-up event
  45939. @param wasItemDragged true if your item was dragged during the mouse click
  45940. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  45941. back from the addToSelectionOnMouseDown() call that you
  45942. should have made during the matching mouseDown event
  45943. */
  45944. void addToSelectionOnMouseUp (ParameterType item,
  45945. const ModifierKeys& modifiers,
  45946. const bool wasItemDragged,
  45947. const bool resultOfMouseDownSelectMethod)
  45948. {
  45949. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  45950. addToSelectionBasedOnModifiers (item, modifiers);
  45951. }
  45952. /** Deselects an item. */
  45953. void deselect (ParameterType item)
  45954. {
  45955. const int i = selectedItems.indexOf (item);
  45956. if (i >= 0)
  45957. {
  45958. changed();
  45959. itemDeselected (selectedItems.remove (i));
  45960. }
  45961. }
  45962. /** Deselects all items. */
  45963. void deselectAll()
  45964. {
  45965. if (selectedItems.size() > 0)
  45966. {
  45967. changed();
  45968. for (int i = selectedItems.size(); --i >= 0;)
  45969. {
  45970. itemDeselected (selectedItems.remove (i));
  45971. i = jmin (i, selectedItems.size());
  45972. }
  45973. }
  45974. }
  45975. /** Returns the number of currently selected items.
  45976. @see getSelectedItem
  45977. */
  45978. int getNumSelected() const throw()
  45979. {
  45980. return selectedItems.size();
  45981. }
  45982. /** Returns one of the currently selected items.
  45983. Returns 0 if the index is out-of-range.
  45984. @see getNumSelected
  45985. */
  45986. SelectableItemType getSelectedItem (const int index) const throw()
  45987. {
  45988. return selectedItems [index];
  45989. }
  45990. /** True if this item is currently selected. */
  45991. bool isSelected (ParameterType item) const throw()
  45992. {
  45993. return selectedItems.contains (item);
  45994. }
  45995. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  45996. /** Can be overridden to do special handling when an item is selected.
  45997. For example, if the item is an object, you might want to call it and tell
  45998. it that it's being selected.
  45999. */
  46000. virtual void itemSelected (SelectableItemType item) { (void) item; }
  46001. /** Can be overridden to do special handling when an item is deselected.
  46002. For example, if the item is an object, you might want to call it and tell
  46003. it that it's being deselected.
  46004. */
  46005. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  46006. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  46007. */
  46008. void changed (const bool synchronous = false)
  46009. {
  46010. if (synchronous)
  46011. sendSynchronousChangeMessage();
  46012. else
  46013. sendChangeMessage();
  46014. }
  46015. private:
  46016. Array <SelectableItemType> selectedItems;
  46017. JUCE_LEAK_DETECTOR (SelectedItemSet <SelectableItemType>);
  46018. };
  46019. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  46020. /*** End of inlined file: juce_SelectedItemSet.h ***/
  46021. /**
  46022. A class used by the LassoComponent to manage the things that it selects.
  46023. This allows the LassoComponent to find out which items are within the lasso,
  46024. and to change the list of selected items.
  46025. @see LassoComponent, SelectedItemSet
  46026. */
  46027. template <class SelectableItemType>
  46028. class LassoSource
  46029. {
  46030. public:
  46031. /** Destructor. */
  46032. virtual ~LassoSource() {}
  46033. /** Returns the set of items that lie within a given lassoable region.
  46034. Your implementation of this method must find all the relevent items that lie
  46035. within the given rectangle. and add them to the itemsFound array.
  46036. The co-ordinates are relative to the top-left of the lasso component's parent
  46037. component. (i.e. they are the same as the size and position of the lasso
  46038. component itself).
  46039. */
  46040. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  46041. const Rectangle<int>& area) = 0;
  46042. /** Returns the SelectedItemSet that the lasso should update.
  46043. This set will be continuously updated by the LassoComponent as it gets
  46044. dragged around, so make sure that you've got a ChangeListener attached to
  46045. the set so that your UI objects will know when the selection changes and
  46046. be able to update themselves appropriately.
  46047. */
  46048. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  46049. };
  46050. /**
  46051. A component that acts as a rectangular selection region, which you drag with
  46052. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  46053. To use one of these:
  46054. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  46055. component, and call its beginLasso() method, giving it a
  46056. suitable LassoSource object that it can use to find out which items are in
  46057. the active area.
  46058. - Each time your parent component gets a mouseDrag event, call dragLasso()
  46059. to update the lasso's position - it will use its LassoSource to calculate and
  46060. update the current selection.
  46061. - After the drag has finished and you get a mouseUp callback, you should call
  46062. endLasso() to clean up. This will make the lasso component invisible, and you
  46063. can remove it from the parent component, or delete it.
  46064. The class takes into account the modifier keys that are being held down while
  46065. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  46066. be added to the original selection; if ctrl or command is pressed, they will be
  46067. xor'ed with any previously selected items.
  46068. @see LassoSource, SelectedItemSet
  46069. */
  46070. template <class SelectableItemType>
  46071. class LassoComponent : public Component
  46072. {
  46073. public:
  46074. /** Creates a Lasso component.
  46075. The fill colour is used to fill the lasso'ed rectangle, and the outline
  46076. colour is used to draw a line around its edge.
  46077. */
  46078. explicit LassoComponent (const int outlineThickness_ = 1)
  46079. : source (0),
  46080. outlineThickness (outlineThickness_)
  46081. {
  46082. }
  46083. /** Destructor. */
  46084. ~LassoComponent()
  46085. {
  46086. }
  46087. /** Call this in your mouseDown event, to initialise a drag.
  46088. Pass in a suitable LassoSource object which the lasso will use to find
  46089. the items and change the selection.
  46090. After using this method to initialise the lasso, repeatedly call dragLasso()
  46091. in your component's mouseDrag callback.
  46092. @see dragLasso, endLasso, LassoSource
  46093. */
  46094. void beginLasso (const MouseEvent& e,
  46095. LassoSource <SelectableItemType>* const lassoSource)
  46096. {
  46097. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  46098. jassert (lassoSource != 0); // the source can't be null!
  46099. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  46100. source = lassoSource;
  46101. if (lassoSource != 0)
  46102. originalSelection = lassoSource->getLassoSelection().getItemArray();
  46103. setSize (0, 0);
  46104. dragStartPos = e.getMouseDownPosition();
  46105. }
  46106. /** Call this in your mouseDrag event, to update the lasso's position.
  46107. This must be repeatedly calling when the mouse is dragged, after you've
  46108. first initialised the lasso with beginLasso().
  46109. This method takes into account the modifier keys that are being held down, so
  46110. if shift is pressed, then the lassoed items will be added to any that were
  46111. previously selected; if ctrl or command is pressed, then they will be xor'ed
  46112. with previously selected items.
  46113. @see beginLasso, endLasso
  46114. */
  46115. void dragLasso (const MouseEvent& e)
  46116. {
  46117. if (source != 0)
  46118. {
  46119. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  46120. setVisible (true);
  46121. Array <SelectableItemType> itemsInLasso;
  46122. source->findLassoItemsInArea (itemsInLasso, getBounds());
  46123. if (e.mods.isShiftDown())
  46124. {
  46125. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  46126. itemsInLasso.addArray (originalSelection);
  46127. }
  46128. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  46129. {
  46130. Array <SelectableItemType> originalMinusNew (originalSelection);
  46131. originalMinusNew.removeValuesIn (itemsInLasso);
  46132. itemsInLasso.removeValuesIn (originalSelection);
  46133. itemsInLasso.addArray (originalMinusNew);
  46134. }
  46135. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  46136. }
  46137. }
  46138. /** Call this in your mouseUp event, after the lasso has been dragged.
  46139. @see beginLasso, dragLasso
  46140. */
  46141. void endLasso()
  46142. {
  46143. source = 0;
  46144. originalSelection.clear();
  46145. setVisible (false);
  46146. }
  46147. /** A set of colour IDs to use to change the colour of various aspects of the label.
  46148. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  46149. methods.
  46150. Note that you can also use the constants from TextEditor::ColourIds to change the
  46151. colour of the text editor that is opened when a label is editable.
  46152. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  46153. */
  46154. enum ColourIds
  46155. {
  46156. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  46157. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  46158. };
  46159. /** @internal */
  46160. void paint (Graphics& g)
  46161. {
  46162. g.fillAll (findColour (lassoFillColourId));
  46163. g.setColour (findColour (lassoOutlineColourId));
  46164. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  46165. // this suggests that you've left a lasso comp lying around after the
  46166. // mouse drag has finished.. Be careful to call endLasso() when you get a
  46167. // mouse-up event.
  46168. jassert (isMouseButtonDownAnywhere());
  46169. }
  46170. /** @internal */
  46171. bool hitTest (int, int) { return false; }
  46172. private:
  46173. Array <SelectableItemType> originalSelection;
  46174. LassoSource <SelectableItemType>* source;
  46175. int outlineThickness;
  46176. Point<int> dragStartPos;
  46177. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LassoComponent);
  46178. };
  46179. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  46180. /*** End of inlined file: juce_LassoComponent.h ***/
  46181. #endif
  46182. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  46183. #endif
  46184. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  46185. #endif
  46186. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46187. /*** Start of inlined file: juce_MouseInputSource.h ***/
  46188. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46189. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46190. class MouseInputSourceInternal;
  46191. /**
  46192. Represents a linear source of mouse events from a mouse device or individual finger
  46193. in a multi-touch environment.
  46194. Each MouseEvent object contains a reference to the MouseInputSource that generated
  46195. it. In an environment with a single mouse for input, all events will come from the
  46196. same source, but in a multi-touch system, there may be multiple MouseInputSource
  46197. obects active, each representing a stream of events coming from a particular finger.
  46198. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  46199. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  46200. the only events that can happen between a mouseDown and its corresponding mouseUp are
  46201. mouseDrags, etc.
  46202. When there are multiple touches arriving from multiple MouseInputSources, their
  46203. event streams may arrive in an interleaved order, so you should use the getIndex()
  46204. method to find out which finger each event came from.
  46205. @see MouseEvent
  46206. */
  46207. class JUCE_API MouseInputSource
  46208. {
  46209. public:
  46210. /** Creates a MouseInputSource.
  46211. You should never actually create a MouseInputSource in your own code - the
  46212. library takes care of managing these objects.
  46213. */
  46214. MouseInputSource (int index, bool isMouseDevice);
  46215. /** Destructor. */
  46216. ~MouseInputSource();
  46217. /** Returns true if this object represents a normal desk-based mouse device. */
  46218. bool isMouse() const;
  46219. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  46220. bool isTouch() const;
  46221. /** Returns true if this source has an on-screen pointer that can hover over
  46222. items without clicking them.
  46223. */
  46224. bool canHover() const;
  46225. /** Returns true if this source may have a scroll wheel. */
  46226. bool hasMouseWheel() const;
  46227. /** Returns this source's index in the global list of possible sources.
  46228. If the system only has a single mouse, there will only be a single MouseInputSource
  46229. with an index of 0.
  46230. If the system supports multi-touch input, then the index will represent a finger
  46231. number, starting from 0. When the first touch event begins, it will have finger
  46232. number 0, and then if a second touch happens while the first is still down, it
  46233. will have index 1, etc.
  46234. */
  46235. int getIndex() const;
  46236. /** Returns true if this device is currently being pressed. */
  46237. bool isDragging() const;
  46238. /** Returns the last-known screen position of this source. */
  46239. const Point<int> getScreenPosition() const;
  46240. /** Returns a set of modifiers that indicate which buttons are currently
  46241. held down on this device.
  46242. */
  46243. const ModifierKeys getCurrentModifiers() const;
  46244. /** Returns the component that was last known to be under this pointer. */
  46245. Component* getComponentUnderMouse() const;
  46246. /** Tells the device to dispatch a mouse-move or mouse-drag event.
  46247. This is asynchronous - the event will occur on the message thread.
  46248. */
  46249. void triggerFakeMove() const;
  46250. /** Returns the number of clicks that should be counted as belonging to the
  46251. current mouse event.
  46252. So the mouse is currently down and it's the second click of a double-click, this
  46253. will return 2.
  46254. */
  46255. int getNumberOfMultipleClicks() const throw();
  46256. /** Returns the time at which the last mouse-down occurred. */
  46257. const Time getLastMouseDownTime() const throw();
  46258. /** Returns the screen position at which the last mouse-down occurred. */
  46259. const Point<int> getLastMouseDownPosition() const throw();
  46260. /** Returns true if this mouse is currently down, and if it has been dragged more
  46261. than a couple of pixels from the place it was pressed.
  46262. */
  46263. bool hasMouseMovedSignificantlySincePressed() const throw();
  46264. /** Returns true if this input source uses a visible mouse cursor. */
  46265. bool hasMouseCursor() const throw();
  46266. /** Changes the mouse cursor, (if there is one). */
  46267. void showMouseCursor (const MouseCursor& cursor);
  46268. /** Hides the mouse cursor (if there is one). */
  46269. void hideCursor();
  46270. /** Un-hides the mouse cursor if it was hidden by hideCursor(). */
  46271. void revealCursor();
  46272. /** Forces an update of the mouse cursor for whatever component it's currently over. */
  46273. void forceMouseCursorUpdate();
  46274. /** Returns true if this mouse can be moved indefinitely in any direction without running out of space. */
  46275. bool canDoUnboundedMovement() const throw();
  46276. /** Allows the mouse to move beyond the edges of the screen.
  46277. Calling this method when the mouse button is currently pressed will remove the cursor
  46278. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  46279. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  46280. can be used for things like custom slider controls or dragging objects around, where
  46281. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  46282. The unbounded mode is automatically turned off when the mouse button is released, or
  46283. it can be turned off explicitly by calling this method again.
  46284. @param isEnabled whether to turn this mode on or off
  46285. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  46286. hidden; if true, it will only be hidden when it
  46287. is moved beyond the edge of the screen
  46288. */
  46289. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  46290. /** @internal */
  46291. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  46292. /** @internal */
  46293. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  46294. private:
  46295. friend class Desktop;
  46296. friend class ComponentPeer;
  46297. friend class MouseInputSourceInternal;
  46298. ScopedPointer<MouseInputSourceInternal> pimpl;
  46299. static const Point<int> getCurrentMousePosition();
  46300. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseInputSource);
  46301. };
  46302. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46303. /*** End of inlined file: juce_MouseInputSource.h ***/
  46304. #endif
  46305. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  46306. #endif
  46307. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  46308. #endif
  46309. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  46310. #endif
  46311. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  46312. #endif
  46313. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  46314. #endif
  46315. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46316. /*** Start of inlined file: juce_RelativeParallelogram.h ***/
  46317. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46318. #define __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46319. /**
  46320. A parallelogram defined by three RelativePoint positions.
  46321. @see RelativePoint, RelativeCoordinate
  46322. */
  46323. class JUCE_API RelativeParallelogram
  46324. {
  46325. public:
  46326. RelativeParallelogram();
  46327. RelativeParallelogram (const Rectangle<float>& simpleRectangle);
  46328. RelativeParallelogram (const RelativePoint& topLeft, const RelativePoint& topRight, const RelativePoint& bottomLeft);
  46329. RelativeParallelogram (const String& topLeft, const String& topRight, const String& bottomLeft);
  46330. ~RelativeParallelogram();
  46331. void resolveThreePoints (Point<float>* points, Expression::Scope* scope) const;
  46332. void resolveFourCorners (Point<float>* points, Expression::Scope* scope) const;
  46333. const Rectangle<float> getBounds (Expression::Scope* scope) const;
  46334. void getPath (Path& path, Expression::Scope* scope) const;
  46335. const AffineTransform resetToPerpendicular (Expression::Scope* scope);
  46336. bool isDynamic() const;
  46337. bool operator== (const RelativeParallelogram& other) const throw();
  46338. bool operator!= (const RelativeParallelogram& other) const throw();
  46339. static const Point<float> getInternalCoordForPoint (const Point<float>* parallelogramCorners, Point<float> point) throw();
  46340. static const Point<float> getPointForInternalCoord (const Point<float>* parallelogramCorners, const Point<float>& internalPoint) throw();
  46341. static const Rectangle<float> getBoundingBox (const Point<float>* parallelogramCorners) throw();
  46342. RelativePoint topLeft, topRight, bottomLeft;
  46343. };
  46344. #endif // __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46345. /*** End of inlined file: juce_RelativeParallelogram.h ***/
  46346. #endif
  46347. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  46348. #endif
  46349. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  46350. /*** Start of inlined file: juce_RelativePointPath.h ***/
  46351. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  46352. #define __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  46353. class DrawablePath;
  46354. /**
  46355. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  46356. One of these paths can be converted into a Path object for drawing and manipulation, but
  46357. unlike a Path, its points can be dynamic instead of just fixed.
  46358. @see RelativePoint, RelativeCoordinate
  46359. */
  46360. class JUCE_API RelativePointPath
  46361. {
  46362. public:
  46363. RelativePointPath();
  46364. RelativePointPath (const RelativePointPath& other);
  46365. explicit RelativePointPath (const Path& path);
  46366. ~RelativePointPath();
  46367. bool operator== (const RelativePointPath& other) const throw();
  46368. bool operator!= (const RelativePointPath& other) const throw();
  46369. /** Resolves this points in this path and adds them to a normal Path object. */
  46370. void createPath (Path& path, Expression::Scope* scope) const;
  46371. /** Returns true if the path contains any non-fixed points. */
  46372. bool containsAnyDynamicPoints() const;
  46373. /** Quickly swaps the contents of this path with another. */
  46374. void swapWith (RelativePointPath& other) throw();
  46375. /** The types of element that may be contained in this path.
  46376. @see RelativePointPath::ElementBase
  46377. */
  46378. enum ElementType
  46379. {
  46380. nullElement,
  46381. startSubPathElement,
  46382. closeSubPathElement,
  46383. lineToElement,
  46384. quadraticToElement,
  46385. cubicToElement
  46386. };
  46387. /** Base class for the elements that make up a RelativePointPath.
  46388. */
  46389. class JUCE_API ElementBase
  46390. {
  46391. public:
  46392. ElementBase (ElementType type);
  46393. virtual ~ElementBase() {}
  46394. virtual const ValueTree createTree() const = 0;
  46395. virtual void addToPath (Path& path, Expression::Scope*) const = 0;
  46396. virtual RelativePoint* getControlPoints (int& numPoints) = 0;
  46397. virtual ElementBase* clone() const = 0;
  46398. bool isDynamic();
  46399. const ElementType type;
  46400. private:
  46401. JUCE_DECLARE_NON_COPYABLE (ElementBase);
  46402. };
  46403. class JUCE_API StartSubPath : public ElementBase
  46404. {
  46405. public:
  46406. StartSubPath (const RelativePoint& pos);
  46407. const ValueTree createTree() const;
  46408. void addToPath (Path& path, Expression::Scope*) const;
  46409. RelativePoint* getControlPoints (int& numPoints);
  46410. ElementBase* clone() const;
  46411. RelativePoint startPos;
  46412. private:
  46413. JUCE_DECLARE_NON_COPYABLE (StartSubPath);
  46414. };
  46415. class JUCE_API CloseSubPath : public ElementBase
  46416. {
  46417. public:
  46418. CloseSubPath();
  46419. const ValueTree createTree() const;
  46420. void addToPath (Path& path, Expression::Scope*) const;
  46421. RelativePoint* getControlPoints (int& numPoints);
  46422. ElementBase* clone() const;
  46423. private:
  46424. JUCE_DECLARE_NON_COPYABLE (CloseSubPath);
  46425. };
  46426. class JUCE_API LineTo : public ElementBase
  46427. {
  46428. public:
  46429. LineTo (const RelativePoint& endPoint);
  46430. const ValueTree createTree() const;
  46431. void addToPath (Path& path, Expression::Scope*) const;
  46432. RelativePoint* getControlPoints (int& numPoints);
  46433. ElementBase* clone() const;
  46434. RelativePoint endPoint;
  46435. private:
  46436. JUCE_DECLARE_NON_COPYABLE (LineTo);
  46437. };
  46438. class JUCE_API QuadraticTo : public ElementBase
  46439. {
  46440. public:
  46441. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  46442. const ValueTree createTree() const;
  46443. void addToPath (Path& path, Expression::Scope*) const;
  46444. RelativePoint* getControlPoints (int& numPoints);
  46445. ElementBase* clone() const;
  46446. RelativePoint controlPoints[2];
  46447. private:
  46448. JUCE_DECLARE_NON_COPYABLE (QuadraticTo);
  46449. };
  46450. class JUCE_API CubicTo : public ElementBase
  46451. {
  46452. public:
  46453. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  46454. const ValueTree createTree() const;
  46455. void addToPath (Path& path, Expression::Scope*) const;
  46456. RelativePoint* getControlPoints (int& numPoints);
  46457. ElementBase* clone() const;
  46458. RelativePoint controlPoints[3];
  46459. private:
  46460. JUCE_DECLARE_NON_COPYABLE (CubicTo);
  46461. };
  46462. void addElement (ElementBase* newElement);
  46463. OwnedArray <ElementBase> elements;
  46464. bool usesNonZeroWinding;
  46465. private:
  46466. class Positioner;
  46467. friend class Positioner;
  46468. bool containsDynamicPoints;
  46469. void applyTo (DrawablePath& path) const;
  46470. RelativePointPath& operator= (const RelativePointPath&);
  46471. JUCE_LEAK_DETECTOR (RelativePointPath);
  46472. };
  46473. #endif // __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  46474. /*** End of inlined file: juce_RelativePointPath.h ***/
  46475. #endif
  46476. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  46477. /*** Start of inlined file: juce_RelativeRectangle.h ***/
  46478. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  46479. #define __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  46480. class Component;
  46481. /**
  46482. An rectangle stored as a set of RelativeCoordinate values.
  46483. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  46484. @see RelativeCoordinate, RelativePoint
  46485. */
  46486. class JUCE_API RelativeRectangle
  46487. {
  46488. public:
  46489. /** Creates a zero-size rectangle at the origin. */
  46490. RelativeRectangle();
  46491. /** Creates an absolute rectangle, relative to the origin. */
  46492. explicit RelativeRectangle (const Rectangle<float>& rect);
  46493. /** Creates a rectangle from four coordinates. */
  46494. RelativeRectangle (const RelativeCoordinate& left, const RelativeCoordinate& right,
  46495. const RelativeCoordinate& top, const RelativeCoordinate& bottom);
  46496. /** Creates a rectangle from a stringified representation.
  46497. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  46498. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  46499. RelativeCoordinate class.
  46500. @see toString
  46501. */
  46502. explicit RelativeRectangle (const String& stringVersion);
  46503. bool operator== (const RelativeRectangle& other) const throw();
  46504. bool operator!= (const RelativeRectangle& other) const throw();
  46505. /** Calculates the absolute position of this rectangle.
  46506. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  46507. be needed to calculate the result.
  46508. */
  46509. const Rectangle<float> resolve (const Expression::Scope* scope) const;
  46510. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  46511. Calling this will leave any anchor points unchanged, but will set any absolute
  46512. or relative positions to whatever values are necessary to make the resultant position
  46513. match the position that is provided.
  46514. */
  46515. void moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope);
  46516. /** Returns true if this rectangle depends on any external symbols for its position.
  46517. Coordinates that refer to symbols based on "this" are assumed not to be dynamic.
  46518. */
  46519. bool isDynamic() const;
  46520. /** Returns a string which represents this point.
  46521. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  46522. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  46523. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  46524. */
  46525. const String toString() const;
  46526. /** Renames a symbol if it is used by any of the coordinates.
  46527. This calls Expression::withRenamedSymbol() on the rectangle's coordinates.
  46528. */
  46529. void renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope);
  46530. /** Creates and sets an appropriate Component::Positioner object for the given component, which will
  46531. keep it positioned with this rectangle.
  46532. */
  46533. void applyToComponent (Component& component) const;
  46534. // The actual rectangle coords...
  46535. RelativeCoordinate left, right, top, bottom;
  46536. };
  46537. #endif // __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  46538. /*** End of inlined file: juce_RelativeRectangle.h ***/
  46539. #endif
  46540. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  46541. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  46542. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  46543. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  46544. /**
  46545. A PropertyComponent that contains an on/off toggle button.
  46546. This type of property component can be used if you have a boolean value to
  46547. toggle on/off.
  46548. @see PropertyComponent
  46549. */
  46550. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  46551. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  46552. {
  46553. protected:
  46554. /** Creates a button component.
  46555. If you use this constructor, you must override the getState() and setState()
  46556. methods.
  46557. @param propertyName the property name to be passed to the PropertyComponent
  46558. @param buttonTextWhenTrue the text shown in the button when the value is true
  46559. @param buttonTextWhenFalse the text shown in the button when the value is false
  46560. */
  46561. BooleanPropertyComponent (const String& propertyName,
  46562. const String& buttonTextWhenTrue,
  46563. const String& buttonTextWhenFalse);
  46564. public:
  46565. /** Creates a button component.
  46566. @param valueToControl a Value object that this property should refer to.
  46567. @param propertyName the property name to be passed to the PropertyComponent
  46568. @param buttonText the text shown in the ToggleButton component
  46569. */
  46570. BooleanPropertyComponent (const Value& valueToControl,
  46571. const String& propertyName,
  46572. const String& buttonText);
  46573. /** Destructor. */
  46574. ~BooleanPropertyComponent();
  46575. /** Called to change the state of the boolean value. */
  46576. virtual void setState (bool newState);
  46577. /** Must return the current value of the property. */
  46578. virtual bool getState() const;
  46579. /** @internal */
  46580. void paint (Graphics& g);
  46581. /** @internal */
  46582. void refresh();
  46583. /** @internal */
  46584. void buttonClicked (Button*);
  46585. private:
  46586. ToggleButton button;
  46587. String onText, offText;
  46588. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BooleanPropertyComponent);
  46589. };
  46590. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  46591. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  46592. #endif
  46593. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  46594. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  46595. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  46596. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  46597. /**
  46598. A PropertyComponent that contains a button.
  46599. This type of property component can be used if you need a button to trigger some
  46600. kind of action.
  46601. @see PropertyComponent
  46602. */
  46603. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  46604. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  46605. {
  46606. public:
  46607. /** Creates a button component.
  46608. @param propertyName the property name to be passed to the PropertyComponent
  46609. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  46610. */
  46611. ButtonPropertyComponent (const String& propertyName,
  46612. bool triggerOnMouseDown);
  46613. /** Destructor. */
  46614. ~ButtonPropertyComponent();
  46615. /** Called when the user clicks the button.
  46616. */
  46617. virtual void buttonClicked() = 0;
  46618. /** Returns the string that should be displayed in the button.
  46619. If you need to change this string, call refresh() to update the component.
  46620. */
  46621. virtual const String getButtonText() const = 0;
  46622. /** @internal */
  46623. void refresh();
  46624. /** @internal */
  46625. void buttonClicked (Button*);
  46626. private:
  46627. TextButton button;
  46628. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonPropertyComponent);
  46629. };
  46630. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  46631. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  46632. #endif
  46633. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  46634. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  46635. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  46636. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  46637. /**
  46638. A PropertyComponent that shows its value as a combo box.
  46639. This type of property component contains a list of options and has a
  46640. combo box to choose one.
  46641. Your subclass's constructor must add some strings to the choices StringArray
  46642. and these are shown in the list.
  46643. The getIndex() method will be called to find out which option is the currently
  46644. selected one. If you call refresh() it will call getIndex() to check whether
  46645. the value has changed, and will update the combo box if needed.
  46646. If the user selects a different item from the list, setIndex() will be
  46647. called to let your class process this.
  46648. @see PropertyComponent, PropertyPanel
  46649. */
  46650. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  46651. private ComboBoxListener // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  46652. {
  46653. protected:
  46654. /** Creates the component.
  46655. Your subclass's constructor must add a list of options to the choices
  46656. member variable.
  46657. */
  46658. ChoicePropertyComponent (const String& propertyName);
  46659. public:
  46660. /** Creates the component.
  46661. @param valueToControl the value that the combo box will read and control
  46662. @param propertyName the name of the property
  46663. @param choices the list of possible values that the drop-down list will contain
  46664. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  46665. These are the values that will be read and written to the
  46666. valueToControl value. This array must contain the same number of items
  46667. as the choices array
  46668. */
  46669. ChoicePropertyComponent (const Value& valueToControl,
  46670. const String& propertyName,
  46671. const StringArray& choices,
  46672. const Array <var>& correspondingValues);
  46673. /** Destructor. */
  46674. ~ChoicePropertyComponent();
  46675. /** Called when the user selects an item from the combo box.
  46676. Your subclass must use this callback to update the value that this component
  46677. represents. The index is the index of the chosen item in the choices
  46678. StringArray.
  46679. */
  46680. virtual void setIndex (int newIndex);
  46681. /** Returns the index of the item that should currently be shown.
  46682. This is the index of the item in the choices StringArray that will be
  46683. shown.
  46684. */
  46685. virtual int getIndex() const;
  46686. /** Returns the list of options. */
  46687. const StringArray& getChoices() const;
  46688. /** @internal */
  46689. void refresh();
  46690. /** @internal */
  46691. void comboBoxChanged (ComboBox*);
  46692. protected:
  46693. /** The list of options that will be shown in the combo box.
  46694. Your subclass must populate this array in its constructor. If any empty
  46695. strings are added, these will be replaced with horizontal separators (see
  46696. ComboBox::addSeparator() for more info).
  46697. */
  46698. StringArray choices;
  46699. private:
  46700. ComboBox comboBox;
  46701. bool isCustomClass;
  46702. class RemapperValueSource;
  46703. void createComboBox();
  46704. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChoicePropertyComponent);
  46705. };
  46706. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  46707. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  46708. #endif
  46709. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  46710. #endif
  46711. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  46712. #endif
  46713. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  46714. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  46715. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  46716. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  46717. /**
  46718. A PropertyComponent that shows its value as a slider.
  46719. @see PropertyComponent, Slider
  46720. */
  46721. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  46722. private SliderListener // (can't use Slider::Listener due to idiotic VC2005 bug)
  46723. {
  46724. protected:
  46725. /** Creates the property component.
  46726. The ranges, interval and skew factor are passed to the Slider component.
  46727. If you need to customise the slider in other ways, your constructor can
  46728. access the slider member variable and change it directly.
  46729. */
  46730. SliderPropertyComponent (const String& propertyName,
  46731. double rangeMin,
  46732. double rangeMax,
  46733. double interval,
  46734. double skewFactor = 1.0);
  46735. public:
  46736. /** Creates the property component.
  46737. The ranges, interval and skew factor are passed to the Slider component.
  46738. If you need to customise the slider in other ways, your constructor can
  46739. access the slider member variable and change it directly.
  46740. */
  46741. SliderPropertyComponent (const Value& valueToControl,
  46742. const String& propertyName,
  46743. double rangeMin,
  46744. double rangeMax,
  46745. double interval,
  46746. double skewFactor = 1.0);
  46747. /** Destructor. */
  46748. ~SliderPropertyComponent();
  46749. /** Called when the user moves the slider to change its value.
  46750. Your subclass must use this method to update whatever item this property
  46751. represents.
  46752. */
  46753. virtual void setValue (double newValue);
  46754. /** Returns the value that the slider should show. */
  46755. virtual double getValue() const;
  46756. /** @internal */
  46757. void refresh();
  46758. /** @internal */
  46759. void sliderValueChanged (Slider*);
  46760. protected:
  46761. /** The slider component being used in this component.
  46762. Your subclass has access to this in case it needs to customise it in some way.
  46763. */
  46764. Slider slider;
  46765. private:
  46766. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPropertyComponent);
  46767. };
  46768. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  46769. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  46770. #endif
  46771. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  46772. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  46773. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  46774. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  46775. /**
  46776. A PropertyComponent that shows its value as editable text.
  46777. @see PropertyComponent
  46778. */
  46779. class JUCE_API TextPropertyComponent : public PropertyComponent
  46780. {
  46781. protected:
  46782. /** Creates a text property component.
  46783. The maxNumChars is used to set the length of string allowable, and isMultiLine
  46784. sets whether the text editor allows carriage returns.
  46785. @see TextEditor
  46786. */
  46787. TextPropertyComponent (const String& propertyName,
  46788. int maxNumChars,
  46789. bool isMultiLine);
  46790. public:
  46791. /** Creates a text property component.
  46792. The maxNumChars is used to set the length of string allowable, and isMultiLine
  46793. sets whether the text editor allows carriage returns.
  46794. @see TextEditor
  46795. */
  46796. TextPropertyComponent (const Value& valueToControl,
  46797. const String& propertyName,
  46798. int maxNumChars,
  46799. bool isMultiLine);
  46800. /** Destructor. */
  46801. ~TextPropertyComponent();
  46802. /** Called when the user edits the text.
  46803. Your subclass must use this callback to change the value of whatever item
  46804. this property component represents.
  46805. */
  46806. virtual void setText (const String& newText);
  46807. /** Returns the text that should be shown in the text editor.
  46808. */
  46809. virtual const String getText() const;
  46810. /** @internal */
  46811. void refresh();
  46812. /** @internal */
  46813. void textWasEdited();
  46814. private:
  46815. ScopedPointer<Label> textEditor;
  46816. void createEditor (int maxNumChars, bool isMultiLine);
  46817. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextPropertyComponent);
  46818. };
  46819. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  46820. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  46821. #endif
  46822. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  46823. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  46824. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  46825. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  46826. #if JUCE_WINDOWS || DOXYGEN
  46827. /**
  46828. A Windows-specific class that can create and embed an ActiveX control inside
  46829. itself.
  46830. To use it, create one of these, put it in place and make sure it's visible in a
  46831. window, then use createControl() to instantiate an ActiveX control. The control
  46832. will then be moved and resized to follow the movements of this component.
  46833. Of course, since the control is a heavyweight window, it'll obliterate any
  46834. juce components that may overlap this component, but that's life.
  46835. */
  46836. class JUCE_API ActiveXControlComponent : public Component
  46837. {
  46838. public:
  46839. /** Create an initially-empty container. */
  46840. ActiveXControlComponent();
  46841. /** Destructor. */
  46842. ~ActiveXControlComponent();
  46843. /** Tries to create an ActiveX control and embed it in this peer.
  46844. The peer controlIID is a pointer to an IID structure - it's treated
  46845. as a void* because when including the Juce headers, you might not always
  46846. have included windows.h first, in which case IID wouldn't be defined.
  46847. e.g. @code
  46848. const IID myIID = __uuidof (QTControl);
  46849. myControlComp->createControl (&myIID);
  46850. @endcode
  46851. */
  46852. bool createControl (const void* controlIID);
  46853. /** Deletes the ActiveX control, if one has been created.
  46854. */
  46855. void deleteControl();
  46856. /** Returns true if a control is currently in use. */
  46857. bool isControlOpen() const throw() { return control != 0; }
  46858. /** Does a QueryInterface call on the embedded control object.
  46859. This allows you to cast the control to whatever type of COM object you need.
  46860. The iid parameter is a pointer to an IID structure - it's treated
  46861. as a void* because when including the Juce headers, you might not always
  46862. have included windows.h first, in which case IID wouldn't be defined, but
  46863. you should just pass a pointer to an IID.
  46864. e.g. @code
  46865. const IID iid = __uuidof (IOleWindow);
  46866. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  46867. if (oleWindow != 0)
  46868. {
  46869. HWND hwnd;
  46870. oleWindow->GetWindow (&hwnd);
  46871. ...
  46872. oleWindow->Release();
  46873. }
  46874. @endcode
  46875. */
  46876. void* queryInterface (const void* iid) const;
  46877. /** Set this to false to stop mouse events being allowed through to the control.
  46878. */
  46879. void setMouseEventsAllowed (bool eventsCanReachControl);
  46880. /** Returns true if mouse events are allowed to get through to the control.
  46881. */
  46882. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  46883. /** @internal */
  46884. void paint (Graphics& g);
  46885. /** @internal */
  46886. void* originalWndProc;
  46887. private:
  46888. class Pimpl;
  46889. friend class Pimpl;
  46890. friend class ScopedPointer <Pimpl>;
  46891. ScopedPointer <Pimpl> control;
  46892. bool mouseEventsAllowed;
  46893. void setControlBounds (const Rectangle<int>& bounds) const;
  46894. void setControlVisible (bool b) const;
  46895. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ActiveXControlComponent);
  46896. };
  46897. #endif
  46898. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  46899. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  46900. #endif
  46901. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  46902. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  46903. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  46904. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  46905. /**
  46906. A component containing controls to let the user change the audio settings of
  46907. an AudioDeviceManager object.
  46908. Very easy to use - just create one of these and show it to the user.
  46909. @see AudioDeviceManager
  46910. */
  46911. class JUCE_API AudioDeviceSelectorComponent : public Component,
  46912. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  46913. public ButtonListener,
  46914. public ChangeListener
  46915. {
  46916. public:
  46917. /** Creates the component.
  46918. If your app needs only output channels, you might ask for a maximum of 0 input
  46919. channels, and the component won't display any options for choosing the input
  46920. channels. And likewise if you're doing an input-only app.
  46921. @param deviceManager the device manager that this component should control
  46922. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  46923. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  46924. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  46925. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  46926. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  46927. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  46928. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  46929. treated as a set of separate mono channels.
  46930. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  46931. are shown, with an "advanced" button that shows the rest of them
  46932. */
  46933. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  46934. const int minAudioInputChannels,
  46935. const int maxAudioInputChannels,
  46936. const int minAudioOutputChannels,
  46937. const int maxAudioOutputChannels,
  46938. const bool showMidiInputOptions,
  46939. const bool showMidiOutputSelector,
  46940. const bool showChannelsAsStereoPairs,
  46941. const bool hideAdvancedOptionsWithButton);
  46942. /** Destructor */
  46943. ~AudioDeviceSelectorComponent();
  46944. /** @internal */
  46945. void resized();
  46946. /** @internal */
  46947. void comboBoxChanged (ComboBox*);
  46948. /** @internal */
  46949. void buttonClicked (Button*);
  46950. /** @internal */
  46951. void changeListenerCallback (ChangeBroadcaster*);
  46952. /** @internal */
  46953. void childBoundsChanged (Component*);
  46954. private:
  46955. AudioDeviceManager& deviceManager;
  46956. ScopedPointer<ComboBox> deviceTypeDropDown;
  46957. ScopedPointer<Label> deviceTypeDropDownLabel;
  46958. ScopedPointer<Component> audioDeviceSettingsComp;
  46959. String audioDeviceSettingsCompType;
  46960. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  46961. const bool showChannelsAsStereoPairs;
  46962. const bool hideAdvancedOptionsWithButton;
  46963. class MidiInputSelectorComponentListBox;
  46964. friend class ScopedPointer<MidiInputSelectorComponentListBox>;
  46965. ScopedPointer<MidiInputSelectorComponentListBox> midiInputsList;
  46966. ScopedPointer<ComboBox> midiOutputSelector;
  46967. ScopedPointer<Label> midiInputsLabel, midiOutputLabel;
  46968. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceSelectorComponent);
  46969. };
  46970. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  46971. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  46972. #endif
  46973. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  46974. /*** Start of inlined file: juce_BubbleComponent.h ***/
  46975. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  46976. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  46977. /**
  46978. A component for showing a message or other graphics inside a speech-bubble-shaped
  46979. outline, pointing at a location on the screen.
  46980. This is a base class that just draws and positions the bubble shape, but leaves
  46981. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  46982. that draws a text message.
  46983. To use it, create your subclass, then either add it to a parent component or
  46984. put it on the desktop with addToDesktop (0), use setPosition() to
  46985. resize and position it, then make it visible.
  46986. @see BubbleMessageComponent
  46987. */
  46988. class JUCE_API BubbleComponent : public Component
  46989. {
  46990. protected:
  46991. /** Creates a BubbleComponent.
  46992. Your subclass will need to implement the getContentSize() and paintContent()
  46993. methods to draw the bubble's contents.
  46994. */
  46995. BubbleComponent();
  46996. public:
  46997. /** Destructor. */
  46998. ~BubbleComponent();
  46999. /** A list of permitted placements for the bubble, relative to the co-ordinates
  47000. at which it should be pointing.
  47001. @see setAllowedPlacement
  47002. */
  47003. enum BubblePlacement
  47004. {
  47005. above = 1,
  47006. below = 2,
  47007. left = 4,
  47008. right = 8
  47009. };
  47010. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  47011. point at which it's pointing.
  47012. By default when setPosition() is called, the bubble will place itself either
  47013. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  47014. the values in BubblePlacement to restrict this choice.
  47015. E.g. if you only want your bubble to appear above or below the target area,
  47016. use setAllowedPlacement (above | below);
  47017. @see BubblePlacement
  47018. */
  47019. void setAllowedPlacement (int newPlacement);
  47020. /** Moves and resizes the bubble to point at a given component.
  47021. This will resize the bubble to fit its content, then find a position for it
  47022. so that it's next to, but doesn't overlap the given component.
  47023. It'll put itself either above, below, or to the side of the component depending
  47024. on where there's the most space, honouring any restrictions that were set
  47025. with setAllowedPlacement().
  47026. */
  47027. void setPosition (Component* componentToPointTo);
  47028. /** Moves and resizes the bubble to point at a given point.
  47029. This will resize the bubble to fit its content, then position it
  47030. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  47031. are relative to either the bubble component's parent component if it has one, or
  47032. they are screen co-ordinates if not.
  47033. It'll put itself either above, below, or to the side of this point, depending
  47034. on where there's the most space, honouring any restrictions that were set
  47035. with setAllowedPlacement().
  47036. */
  47037. void setPosition (int arrowTipX,
  47038. int arrowTipY);
  47039. /** Moves and resizes the bubble to point at a given rectangle.
  47040. This will resize the bubble to fit its content, then find a position for it
  47041. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  47042. co-ordinates are relative to either the bubble component's parent component
  47043. if it has one, or they are screen co-ordinates if not.
  47044. It'll put itself either above, below, or to the side of the component depending
  47045. on where there's the most space, honouring any restrictions that were set
  47046. with setAllowedPlacement().
  47047. */
  47048. void setPosition (const Rectangle<int>& rectangleToPointTo);
  47049. protected:
  47050. /** Subclasses should override this to return the size of the content they
  47051. want to draw inside the bubble.
  47052. */
  47053. virtual void getContentSize (int& width, int& height) = 0;
  47054. /** Subclasses should override this to draw their bubble's contents.
  47055. The graphics object's clip region and the dimensions passed in here are
  47056. set up to paint just the rectangle inside the bubble.
  47057. */
  47058. virtual void paintContent (Graphics& g, int width, int height) = 0;
  47059. public:
  47060. /** @internal */
  47061. void paint (Graphics& g);
  47062. private:
  47063. Rectangle<int> content;
  47064. int side, allowablePlacements;
  47065. float arrowTipX, arrowTipY;
  47066. DropShadowEffect shadow;
  47067. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleComponent);
  47068. };
  47069. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  47070. /*** End of inlined file: juce_BubbleComponent.h ***/
  47071. #endif
  47072. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47073. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  47074. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47075. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47076. /**
  47077. A speech-bubble component that displays a short message.
  47078. This can be used to show a message with the tail of the speech bubble
  47079. pointing to a particular component or location on the screen.
  47080. @see BubbleComponent
  47081. */
  47082. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  47083. private Timer
  47084. {
  47085. public:
  47086. /** Creates a bubble component.
  47087. After creating one a BubbleComponent, do the following:
  47088. - add it to an appropriate parent component, or put it on the
  47089. desktop with Component::addToDesktop (0).
  47090. - use the showAt() method to show a message.
  47091. - it will make itself invisible after it times-out (and can optionally
  47092. also delete itself), or you can reuse it somewhere else by calling
  47093. showAt() again.
  47094. */
  47095. BubbleMessageComponent (int fadeOutLengthMs = 150);
  47096. /** Destructor. */
  47097. ~BubbleMessageComponent();
  47098. /** Shows a message bubble at a particular position.
  47099. This shows the bubble with its stem pointing to the given location
  47100. (co-ordinates being relative to its parent component).
  47101. For details about exactly how it decides where to position itself, see
  47102. BubbleComponent::updatePosition().
  47103. @param x the x co-ordinate of end of the bubble's tail
  47104. @param y the y co-ordinate of end of the bubble's tail
  47105. @param message the text to display
  47106. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  47107. from its parent compnent. If this is 0 or less, it
  47108. will stay there until manually removed.
  47109. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  47110. mouse button is pressed (anywhere on the screen)
  47111. @param deleteSelfAfterUse if true, then the component will delete itself after
  47112. it becomes invisible
  47113. */
  47114. void showAt (int x, int y,
  47115. const String& message,
  47116. int numMillisecondsBeforeRemoving,
  47117. bool removeWhenMouseClicked = true,
  47118. bool deleteSelfAfterUse = false);
  47119. /** Shows a message bubble next to a particular component.
  47120. This shows the bubble with its stem pointing at the given component.
  47121. For details about exactly how it decides where to position itself, see
  47122. BubbleComponent::updatePosition().
  47123. @param component the component that you want to point at
  47124. @param message the text to display
  47125. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  47126. from its parent compnent. If this is 0 or less, it
  47127. will stay there until manually removed.
  47128. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  47129. mouse button is pressed (anywhere on the screen)
  47130. @param deleteSelfAfterUse if true, then the component will delete itself after
  47131. it becomes invisible
  47132. */
  47133. void showAt (Component* component,
  47134. const String& message,
  47135. int numMillisecondsBeforeRemoving,
  47136. bool removeWhenMouseClicked = true,
  47137. bool deleteSelfAfterUse = false);
  47138. /** @internal */
  47139. void getContentSize (int& w, int& h);
  47140. /** @internal */
  47141. void paintContent (Graphics& g, int w, int h);
  47142. /** @internal */
  47143. void timerCallback();
  47144. private:
  47145. int fadeOutLength, mouseClickCounter;
  47146. TextLayout textLayout;
  47147. int64 expiryTime;
  47148. bool deleteAfterUse;
  47149. void init (int numMillisecondsBeforeRemoving,
  47150. bool removeWhenMouseClicked,
  47151. bool deleteSelfAfterUse);
  47152. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleMessageComponent);
  47153. };
  47154. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47155. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  47156. #endif
  47157. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  47158. /*** Start of inlined file: juce_ColourSelector.h ***/
  47159. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  47160. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  47161. /**
  47162. A component that lets the user choose a colour.
  47163. This shows RGB sliders and a colourspace that the user can pick colours from.
  47164. This class is also a ChangeBroadcaster, so listeners can register to be told
  47165. when the colour changes.
  47166. */
  47167. class JUCE_API ColourSelector : public Component,
  47168. public ChangeBroadcaster,
  47169. protected SliderListener
  47170. {
  47171. public:
  47172. /** Options for the type of selector to show. These are passed into the constructor. */
  47173. enum ColourSelectorOptions
  47174. {
  47175. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  47176. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  47177. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  47178. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  47179. };
  47180. /** Creates a ColourSelector object.
  47181. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  47182. which of the selector's features should be visible.
  47183. The edgeGap value specifies the amount of space to leave around the edge.
  47184. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  47185. colourspace and hue selector components.
  47186. */
  47187. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  47188. int edgeGap = 4,
  47189. int gapAroundColourSpaceComponent = 7);
  47190. /** Destructor. */
  47191. ~ColourSelector();
  47192. /** Returns the colour that the user has currently selected.
  47193. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  47194. register to be told when the colour changes.
  47195. @see setCurrentColour
  47196. */
  47197. const Colour getCurrentColour() const;
  47198. /** Changes the colour that is currently being shown.
  47199. */
  47200. void setCurrentColour (const Colour& newColour);
  47201. /** Tells the selector how many preset colour swatches you want to have on the component.
  47202. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  47203. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  47204. their values.
  47205. */
  47206. virtual int getNumSwatches() const;
  47207. /** Called by the selector to find out the colour of one of the swatches.
  47208. Your subclass should return the colour of the swatch with the given index.
  47209. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  47210. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  47211. their values.
  47212. */
  47213. virtual const Colour getSwatchColour (int index) const;
  47214. /** Called by the selector when the user puts a new colour into one of the swatches.
  47215. Your subclass should change the colour of the swatch with the given index.
  47216. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  47217. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  47218. their values.
  47219. */
  47220. virtual void setSwatchColour (int index, const Colour& newColour) const;
  47221. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  47222. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  47223. methods.
  47224. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  47225. */
  47226. enum ColourIds
  47227. {
  47228. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  47229. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  47230. };
  47231. private:
  47232. class ColourSpaceView;
  47233. class HueSelectorComp;
  47234. class SwatchComponent;
  47235. friend class ColourSpaceView;
  47236. friend class ScopedPointer<ColourSpaceView>;
  47237. friend class HueSelectorComp;
  47238. friend class ScopedPointer<HueSelectorComp>;
  47239. Colour colour;
  47240. float h, s, v;
  47241. ScopedPointer<Slider> sliders[4];
  47242. ScopedPointer<ColourSpaceView> colourSpace;
  47243. ScopedPointer<HueSelectorComp> hueSelector;
  47244. OwnedArray <SwatchComponent> swatchComponents;
  47245. const int flags;
  47246. int edgeGap;
  47247. Rectangle<int> previewArea;
  47248. void setHue (float newH);
  47249. void setSV (float newS, float newV);
  47250. void updateHSV();
  47251. void update();
  47252. void sliderValueChanged (Slider*);
  47253. void paint (Graphics& g);
  47254. void resized();
  47255. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ColourSelector);
  47256. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  47257. // This constructor is here temporarily to prevent old code compiling, because the parameters
  47258. // have changed - if you get an error here, update your code to use the new constructor instead..
  47259. ColourSelector (bool);
  47260. #endif
  47261. };
  47262. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  47263. /*** End of inlined file: juce_ColourSelector.h ***/
  47264. #endif
  47265. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  47266. #endif
  47267. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  47268. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  47269. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  47270. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  47271. /**
  47272. A component that displays a piano keyboard, whose notes can be clicked on.
  47273. This component will mimic a physical midi keyboard, showing the current state of
  47274. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  47275. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  47276. Another feature is that the computer keyboard can also be used to play notes. By
  47277. default it maps the top two rows of a standard querty keyboard to the notes, but
  47278. these can be remapped if needed. It will only respond to keypresses when it has
  47279. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  47280. The component is also a ChangeBroadcaster, so if you want to be informed when the
  47281. keyboard is scrolled, you can register a ChangeListener for callbacks.
  47282. @see MidiKeyboardState
  47283. */
  47284. class JUCE_API MidiKeyboardComponent : public Component,
  47285. public MidiKeyboardStateListener,
  47286. public ChangeBroadcaster,
  47287. private Timer,
  47288. private AsyncUpdater
  47289. {
  47290. public:
  47291. /** The direction of the keyboard.
  47292. @see setOrientation
  47293. */
  47294. enum Orientation
  47295. {
  47296. horizontalKeyboard,
  47297. verticalKeyboardFacingLeft,
  47298. verticalKeyboardFacingRight,
  47299. };
  47300. /** Creates a MidiKeyboardComponent.
  47301. @param state the midi keyboard model that this component will represent
  47302. @param orientation whether the keyboard is horizonal or vertical
  47303. */
  47304. MidiKeyboardComponent (MidiKeyboardState& state,
  47305. Orientation orientation);
  47306. /** Destructor. */
  47307. ~MidiKeyboardComponent();
  47308. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  47309. on the component.
  47310. Values are 0 to 1.0, where 1.0 is the heaviest.
  47311. @see setMidiChannel
  47312. */
  47313. void setVelocity (float velocity, bool useMousePositionForVelocity);
  47314. /** Changes the midi channel number that will be used for events triggered by clicking
  47315. on the component.
  47316. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  47317. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  47318. Although this is the channel used for outgoing events, the component can display
  47319. incoming events from more than one channel - see setMidiChannelsToDisplay()
  47320. @see setVelocity
  47321. */
  47322. void setMidiChannel (int midiChannelNumber);
  47323. /** Returns the midi channel that the keyboard is using for midi messages.
  47324. @see setMidiChannel
  47325. */
  47326. int getMidiChannel() const throw() { return midiChannel; }
  47327. /** Sets a mask to indicate which incoming midi channels should be represented by
  47328. key movements.
  47329. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  47330. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  47331. in this mask, the on-screen keys will also go down.
  47332. By default, this mask is set to 0xffff (all channels displayed).
  47333. @see setMidiChannel
  47334. */
  47335. void setMidiChannelsToDisplay (int midiChannelMask);
  47336. /** Returns the current set of midi channels represented by the component.
  47337. This is the value that was set with setMidiChannelsToDisplay().
  47338. */
  47339. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  47340. /** Changes the width used to draw the white keys. */
  47341. void setKeyWidth (float widthInPixels);
  47342. /** Returns the width that was set by setKeyWidth(). */
  47343. float getKeyWidth() const throw() { return keyWidth; }
  47344. /** Changes the keyboard's current direction. */
  47345. void setOrientation (Orientation newOrientation);
  47346. /** Returns the keyboard's current direction. */
  47347. const Orientation getOrientation() const throw() { return orientation; }
  47348. /** Sets the range of midi notes that the keyboard will be limited to.
  47349. By default the range is 0 to 127 (inclusive), but you can limit this if you
  47350. only want a restricted set of the keys to be shown.
  47351. Note that the values here are inclusive and must be between 0 and 127.
  47352. */
  47353. void setAvailableRange (int lowestNote,
  47354. int highestNote);
  47355. /** Returns the first note in the available range.
  47356. @see setAvailableRange
  47357. */
  47358. int getRangeStart() const throw() { return rangeStart; }
  47359. /** Returns the last note in the available range.
  47360. @see setAvailableRange
  47361. */
  47362. int getRangeEnd() const throw() { return rangeEnd; }
  47363. /** If the keyboard extends beyond the size of the component, this will scroll
  47364. it to show the given key at the start.
  47365. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  47366. base class to send a callback to any ChangeListeners that have been registered.
  47367. */
  47368. void setLowestVisibleKey (int noteNumber);
  47369. /** Returns the number of the first key shown in the component.
  47370. @see setLowestVisibleKey
  47371. */
  47372. int getLowestVisibleKey() const throw() { return firstKey; }
  47373. /** Returns the length of the black notes.
  47374. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  47375. */
  47376. int getBlackNoteLength() const throw() { return blackNoteLength; }
  47377. /** If set to true, then scroll buttons will appear at either end of the keyboard
  47378. if there are too many notes to fit them all in the component at once.
  47379. */
  47380. void setScrollButtonsVisible (bool canScroll);
  47381. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  47382. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  47383. methods.
  47384. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  47385. */
  47386. enum ColourIds
  47387. {
  47388. whiteNoteColourId = 0x1005000,
  47389. blackNoteColourId = 0x1005001,
  47390. keySeparatorLineColourId = 0x1005002,
  47391. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  47392. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  47393. textLabelColourId = 0x1005005,
  47394. upDownButtonBackgroundColourId = 0x1005006,
  47395. upDownButtonArrowColourId = 0x1005007
  47396. };
  47397. /** Returns the position within the component of the left-hand edge of a key.
  47398. Depending on the keyboard's orientation, this may be a horizontal or vertical
  47399. distance, in either direction.
  47400. */
  47401. int getKeyStartPosition (const int midiNoteNumber) const;
  47402. /** Deletes all key-mappings.
  47403. @see setKeyPressForNote
  47404. */
  47405. void clearKeyMappings();
  47406. /** Maps a key-press to a given note.
  47407. @param key the key that should trigger the note
  47408. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  47409. be. The actual midi note that gets played will be
  47410. this value + (12 * the current base octave). To change
  47411. the base octave, see setKeyPressBaseOctave()
  47412. */
  47413. void setKeyPressForNote (const KeyPress& key,
  47414. int midiNoteOffsetFromC);
  47415. /** Removes any key-mappings for a given note.
  47416. For a description of what the note number means, see setKeyPressForNote().
  47417. */
  47418. void removeKeyPressForNote (int midiNoteOffsetFromC);
  47419. /** Changes the base note above which key-press-triggered notes are played.
  47420. The set of key-mappings that trigger notes can be moved up and down to cover
  47421. the entire scale using this method.
  47422. The value passed in is an octave number between 0 and 10 (inclusive), and
  47423. indicates which C is the base note to which the key-mapped notes are
  47424. relative.
  47425. */
  47426. void setKeyPressBaseOctave (int newOctaveNumber);
  47427. /** This sets the octave number which is shown as the octave number for middle C.
  47428. This affects only the default implementation of getWhiteNoteText(), which
  47429. passes this octave number to MidiMessage::getMidiNoteName() in order to
  47430. get the note text. See MidiMessage::getMidiNoteName() for more info about
  47431. the parameter.
  47432. By default this value is set to 3.
  47433. @see getOctaveForMiddleC
  47434. */
  47435. void setOctaveForMiddleC (int octaveNumForMiddleC);
  47436. /** This returns the value set by setOctaveForMiddleC().
  47437. @see setOctaveForMiddleC
  47438. */
  47439. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  47440. /** @internal */
  47441. void paint (Graphics& g);
  47442. /** @internal */
  47443. void resized();
  47444. /** @internal */
  47445. void mouseMove (const MouseEvent& e);
  47446. /** @internal */
  47447. void mouseDrag (const MouseEvent& e);
  47448. /** @internal */
  47449. void mouseDown (const MouseEvent& e);
  47450. /** @internal */
  47451. void mouseUp (const MouseEvent& e);
  47452. /** @internal */
  47453. void mouseEnter (const MouseEvent& e);
  47454. /** @internal */
  47455. void mouseExit (const MouseEvent& e);
  47456. /** @internal */
  47457. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  47458. /** @internal */
  47459. void timerCallback();
  47460. /** @internal */
  47461. bool keyStateChanged (bool isKeyDown);
  47462. /** @internal */
  47463. void focusLost (FocusChangeType cause);
  47464. /** @internal */
  47465. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  47466. /** @internal */
  47467. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  47468. /** @internal */
  47469. void handleAsyncUpdate();
  47470. /** @internal */
  47471. void colourChanged();
  47472. protected:
  47473. /** Draws a white note in the given rectangle.
  47474. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  47475. currently pressed down.
  47476. When doing this, be sure to note the keyboard's orientation.
  47477. */
  47478. virtual void drawWhiteNote (int midiNoteNumber,
  47479. Graphics& g,
  47480. int x, int y, int w, int h,
  47481. bool isDown, bool isOver,
  47482. const Colour& lineColour,
  47483. const Colour& textColour);
  47484. /** Draws a black note in the given rectangle.
  47485. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  47486. currently pressed down.
  47487. When doing this, be sure to note the keyboard's orientation.
  47488. */
  47489. virtual void drawBlackNote (int midiNoteNumber,
  47490. Graphics& g,
  47491. int x, int y, int w, int h,
  47492. bool isDown, bool isOver,
  47493. const Colour& noteFillColour);
  47494. /** Allows text to be drawn on the white notes.
  47495. By default this is used to label the C in each octave, but could be used for other things.
  47496. @see setOctaveForMiddleC
  47497. */
  47498. virtual const String getWhiteNoteText (const int midiNoteNumber);
  47499. /** Draws the up and down buttons that change the base note. */
  47500. virtual void drawUpDownButton (Graphics& g, int w, int h,
  47501. const bool isMouseOver,
  47502. const bool isButtonPressed,
  47503. const bool movesOctavesUp);
  47504. /** Callback when the mouse is clicked on a key.
  47505. You could use this to do things like handle right-clicks on keys, etc.
  47506. Return true if you want the click to trigger the note, or false if you
  47507. want to handle it yourself and not have the note played.
  47508. @see mouseDraggedToKey
  47509. */
  47510. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  47511. /** Callback when the mouse is dragged from one key onto another.
  47512. @see mouseDownOnKey
  47513. */
  47514. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  47515. /** Calculates the positon of a given midi-note.
  47516. This can be overridden to create layouts with custom key-widths.
  47517. @param midiNoteNumber the note to find
  47518. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  47519. @param x the x position of the left-hand edge of the key (this method
  47520. always works in terms of a horizontal keyboard)
  47521. @param w the width of the key
  47522. */
  47523. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  47524. int& x, int& w) const;
  47525. private:
  47526. friend class MidiKeyboardUpDownButton;
  47527. MidiKeyboardState& state;
  47528. int xOffset, blackNoteLength;
  47529. float keyWidth;
  47530. Orientation orientation;
  47531. int midiChannel, midiInChannelMask;
  47532. float velocity;
  47533. int noteUnderMouse, mouseDownNote;
  47534. BigInteger keysPressed, keysCurrentlyDrawnDown;
  47535. int rangeStart, rangeEnd, firstKey;
  47536. bool canScroll, mouseDragging, useMousePositionForVelocity;
  47537. ScopedPointer<Button> scrollDown, scrollUp;
  47538. Array <KeyPress> keyPresses;
  47539. Array <int> keyPressNotes;
  47540. int keyMappingOctave;
  47541. int octaveNumForMiddleC;
  47542. static const uint8 whiteNotes[];
  47543. static const uint8 blackNotes[];
  47544. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  47545. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  47546. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  47547. void resetAnyKeysInUse();
  47548. void updateNoteUnderMouse (const Point<int>& pos);
  47549. void repaintNote (const int midiNoteNumber);
  47550. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardComponent);
  47551. };
  47552. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  47553. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  47554. #endif
  47555. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  47556. /*** Start of inlined file: juce_NSViewComponent.h ***/
  47557. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  47558. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  47559. #if ! DOXYGEN
  47560. class NSViewComponentInternal;
  47561. #endif
  47562. #if JUCE_MAC || DOXYGEN
  47563. /**
  47564. A Mac-specific class that can create and embed an NSView inside itself.
  47565. To use it, create one of these, put it in place and make sure it's visible in a
  47566. window, then use setView() to assign an NSView to it. The view will then be
  47567. moved and resized to follow the movements of this component.
  47568. Of course, since the view is a native object, it'll obliterate any
  47569. juce components that may overlap this component, but that's life.
  47570. */
  47571. class JUCE_API NSViewComponent : public Component
  47572. {
  47573. public:
  47574. /** Create an initially-empty container. */
  47575. NSViewComponent();
  47576. /** Destructor. */
  47577. ~NSViewComponent();
  47578. /** Assigns an NSView to this peer.
  47579. The view will be retained and released by this component for as long as
  47580. it is needed. To remove the current view, just call setView (0).
  47581. Note: a void* is used here to avoid including the cocoa headers as
  47582. part of the juce.h, but the method expects an NSView*.
  47583. */
  47584. void setView (void* nsView);
  47585. /** Returns the current NSView.
  47586. Note: a void* is returned here to avoid including the cocoa headers as
  47587. a requirement of juce.h, so you should just cast the object to an NSView*.
  47588. */
  47589. void* getView() const;
  47590. /** Resizes this component to fit the view that it contains. */
  47591. void resizeToFitView();
  47592. /** @internal */
  47593. void paint (Graphics& g);
  47594. private:
  47595. friend class NSViewComponentInternal;
  47596. ScopedPointer <NSViewComponentInternal> info;
  47597. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponent);
  47598. };
  47599. #endif
  47600. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  47601. /*** End of inlined file: juce_NSViewComponent.h ***/
  47602. #endif
  47603. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  47604. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  47605. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  47606. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  47607. // this is used to disable OpenGL, and is defined in juce_Config.h
  47608. #if JUCE_OPENGL || DOXYGEN
  47609. /**
  47610. Represents the various properties of an OpenGL bitmap format.
  47611. @see OpenGLComponent::setPixelFormat
  47612. */
  47613. class JUCE_API OpenGLPixelFormat
  47614. {
  47615. public:
  47616. /** Creates an OpenGLPixelFormat.
  47617. The default constructor just initialises the object as a simple 8-bit
  47618. RGBA format.
  47619. */
  47620. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  47621. int alphaBits = 8,
  47622. int depthBufferBits = 16,
  47623. int stencilBufferBits = 0);
  47624. OpenGLPixelFormat (const OpenGLPixelFormat&);
  47625. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  47626. bool operator== (const OpenGLPixelFormat&) const;
  47627. int redBits; /**< The number of bits per pixel to use for the red channel. */
  47628. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  47629. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  47630. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  47631. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  47632. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  47633. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  47634. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  47635. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  47636. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  47637. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  47638. /** Returns a list of all the pixel formats that can be used in this system.
  47639. A reference component is needed in case there are multiple screens with different
  47640. capabilities - in which case, the one that the component is on will be used.
  47641. */
  47642. static void getAvailablePixelFormats (Component* component,
  47643. OwnedArray <OpenGLPixelFormat>& results);
  47644. private:
  47645. JUCE_LEAK_DETECTOR (OpenGLPixelFormat);
  47646. };
  47647. /**
  47648. A base class for types of OpenGL context.
  47649. An OpenGLComponent will supply its own context for drawing in its window.
  47650. */
  47651. class JUCE_API OpenGLContext
  47652. {
  47653. public:
  47654. /** Destructor. */
  47655. virtual ~OpenGLContext();
  47656. /** Makes this context the currently active one. */
  47657. virtual bool makeActive() const throw() = 0;
  47658. /** If this context is currently active, it is disactivated. */
  47659. virtual bool makeInactive() const throw() = 0;
  47660. /** Returns true if this context is currently active. */
  47661. virtual bool isActive() const throw() = 0;
  47662. /** Swaps the buffers (if the context can do this). */
  47663. virtual void swapBuffers() = 0;
  47664. /** Sets whether the context checks the vertical sync before swapping.
  47665. The value is the number of frames to allow between buffer-swapping. This is
  47666. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  47667. and greater numbers indicate that it should swap less often.
  47668. Returns true if it sets the value successfully.
  47669. */
  47670. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  47671. /** Returns the current swap-sync interval.
  47672. See setSwapInterval() for info about the value returned.
  47673. */
  47674. virtual int getSwapInterval() const = 0;
  47675. /** Returns the pixel format being used by this context. */
  47676. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  47677. /** For windowed contexts, this moves the context within the bounds of
  47678. its parent window.
  47679. */
  47680. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  47681. /** For windowed contexts, this triggers a repaint of the window.
  47682. (Not relevent on all platforms).
  47683. */
  47684. virtual void repaint() = 0;
  47685. /** Returns an OS-dependent handle to the raw GL context.
  47686. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  47687. a GLXContext.
  47688. */
  47689. virtual void* getRawContext() const throw() = 0;
  47690. /** Deletes the context.
  47691. This must only be called on the message thread, or will deadlock.
  47692. On background threads, call getCurrentContext()->deleteContext(), but be careful not
  47693. to call any other OpenGL function afterwards.
  47694. This doesn't touch other resources, such as window handles, etc.
  47695. You'll probably never have to call this method directly.
  47696. */
  47697. virtual void deleteContext() = 0;
  47698. /** Returns the context that's currently in active use by the calling thread.
  47699. Returns 0 if there isn't an active context.
  47700. */
  47701. static OpenGLContext* getCurrentContext();
  47702. protected:
  47703. OpenGLContext() throw();
  47704. private:
  47705. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLContext);
  47706. };
  47707. /**
  47708. A component that contains an OpenGL canvas.
  47709. Override this, add it to whatever component you want to, and use the renderOpenGL()
  47710. method to draw its contents.
  47711. */
  47712. class JUCE_API OpenGLComponent : public Component
  47713. {
  47714. public:
  47715. /** Used to select the type of openGL API to use, if more than one choice is available
  47716. on a particular platform.
  47717. */
  47718. enum OpenGLType
  47719. {
  47720. openGLDefault = 0,
  47721. #if JUCE_IOS
  47722. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  47723. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  47724. #endif
  47725. };
  47726. /** Creates an OpenGLComponent. */
  47727. OpenGLComponent (OpenGLType type = openGLDefault);
  47728. /** Destructor. */
  47729. ~OpenGLComponent();
  47730. /** Changes the pixel format used by this component.
  47731. @see OpenGLPixelFormat::getAvailablePixelFormats()
  47732. */
  47733. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  47734. /** Returns the pixel format that this component is currently using. */
  47735. const OpenGLPixelFormat getPixelFormat() const;
  47736. /** Specifies an OpenGL context which should be shared with the one that this
  47737. component is using.
  47738. This is an OpenGL feature that lets two contexts share their texture data.
  47739. Note that this pointer is stored by the component, and when the component
  47740. needs to recreate its internal context for some reason, the same context
  47741. will be used again to share lists. So if you pass a context in here,
  47742. don't delete the context while this component is still using it! You can
  47743. call shareWith (0) to stop this component from sharing with it.
  47744. */
  47745. void shareWith (OpenGLContext* contextToShareListsWith);
  47746. /** Returns the context that this component is sharing with.
  47747. @see shareWith
  47748. */
  47749. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  47750. /** Flips the openGL buffers over. */
  47751. void swapBuffers();
  47752. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  47753. When this is called, makeCurrentContextActive() will already have been called
  47754. for you, so you just need to draw.
  47755. */
  47756. virtual void renderOpenGL() = 0;
  47757. /** This method is called when the component creates a new OpenGL context.
  47758. A new context may be created when the component is first used, or when it
  47759. is moved to a different window, or when the window is hidden and re-shown,
  47760. etc.
  47761. You can use this callback as an opportunity to set up things like textures
  47762. that your context needs.
  47763. New contexts are created on-demand by the makeCurrentContextActive() method - so
  47764. if the context is deleted, e.g. by changing the pixel format or window, no context
  47765. will be created until the next call to makeCurrentContextActive(), which will
  47766. synchronously create one and call this method. This means that if you're using
  47767. a non-GUI thread for rendering, you can make sure this method is be called by
  47768. your renderer thread.
  47769. When this callback happens, the context will already have been made current
  47770. using the makeCurrentContextActive() method, so there's no need to call it
  47771. again in your code.
  47772. */
  47773. virtual void newOpenGLContextCreated() = 0;
  47774. /** Returns the context that will draw into this component.
  47775. This may return 0 if the component is currently invisible or hasn't currently
  47776. got a context. The context object can be deleted and a new one created during
  47777. the lifetime of this component, and there may be times when it doesn't have one.
  47778. @see newOpenGLContextCreated()
  47779. */
  47780. OpenGLContext* getCurrentContext() const throw() { return context; }
  47781. /** Makes this component the current openGL context.
  47782. You might want to use this in things like your resize() method, before calling
  47783. GL commands.
  47784. If this returns false, then the context isn't active, so you should avoid
  47785. making any calls.
  47786. This call may actually create a context if one isn't currently initialised. If
  47787. it does this, it will also synchronously call the newOpenGLContextCreated()
  47788. method to let you initialise it as necessary.
  47789. @see OpenGLContext::makeActive
  47790. */
  47791. bool makeCurrentContextActive();
  47792. /** Stops the current component being the active OpenGL context.
  47793. This is the opposite of makeCurrentContextActive()
  47794. @see OpenGLContext::makeInactive
  47795. */
  47796. void makeCurrentContextInactive();
  47797. /** Returns true if this component is the active openGL context for the
  47798. current thread.
  47799. @see OpenGLContext::isActive
  47800. */
  47801. bool isActiveContext() const throw();
  47802. /** Calls the rendering callback, and swaps the buffers afterwards.
  47803. This is called automatically by paint() when the component needs to be rendered.
  47804. It can be overridden if you need to decouple the rendering from the paint callback
  47805. and render with a custom thread.
  47806. Returns true if the operation succeeded.
  47807. */
  47808. virtual bool renderAndSwapBuffers();
  47809. /** This returns a critical section that can be used to lock the current context.
  47810. Because the context that is used by this component can change, e.g. when the
  47811. component is shown or hidden, then if you're rendering to it on a background
  47812. thread, this allows you to lock the context for the duration of your rendering
  47813. routine.
  47814. */
  47815. CriticalSection& getContextLock() throw() { return contextLock; }
  47816. /** Returns the native handle of an embedded heavyweight window, if there is one.
  47817. E.g. On windows, this will return the HWND of the sub-window containing
  47818. the opengl context, on the mac it'll be the NSOpenGLView.
  47819. */
  47820. void* getNativeWindowHandle() const;
  47821. /** Delete the context.
  47822. This can be called back on the same thread that created the context. */
  47823. void deleteContext();
  47824. /** @internal */
  47825. void paint (Graphics& g);
  47826. private:
  47827. const OpenGLType type;
  47828. class OpenGLComponentWatcher;
  47829. friend class OpenGLComponentWatcher;
  47830. friend class ScopedPointer <OpenGLComponentWatcher>;
  47831. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  47832. ScopedPointer <OpenGLContext> context;
  47833. OpenGLContext* contextToShareListsWith;
  47834. CriticalSection contextLock;
  47835. OpenGLPixelFormat preferredPixelFormat;
  47836. bool needToUpdateViewport;
  47837. OpenGLContext* createContext();
  47838. void updateContextPosition();
  47839. void internalRepaint (int x, int y, int w, int h);
  47840. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponent);
  47841. };
  47842. #endif
  47843. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  47844. /*** End of inlined file: juce_OpenGLComponent.h ***/
  47845. #endif
  47846. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  47847. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  47848. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  47849. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  47850. /**
  47851. A component with a set of buttons at the top for changing between pages of
  47852. preferences.
  47853. This is just a handy way of writing a Mac-style preferences panel where you
  47854. have a row of buttons along the top for the different preference categories,
  47855. each button having an icon above its name. Clicking these will show an
  47856. appropriate prefs page below it.
  47857. You can either put one of these inside your own component, or just use the
  47858. showInDialogBox() method to show it in a window and run it modally.
  47859. To use it, just add a set of named pages with the addSettingsPage() method,
  47860. and implement the createComponentForPage() method to create suitable components
  47861. for each of these pages.
  47862. */
  47863. class JUCE_API PreferencesPanel : public Component,
  47864. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  47865. {
  47866. public:
  47867. /** Creates an empty panel.
  47868. Use addSettingsPage() to add some pages to it in your constructor.
  47869. */
  47870. PreferencesPanel();
  47871. /** Destructor. */
  47872. ~PreferencesPanel();
  47873. /** Creates a page using a set of drawables to define the page's icon.
  47874. Note that the other version of this method is much easier if you're using
  47875. an image instead of a custom drawable.
  47876. @param pageTitle the name of this preferences page - you'll need to
  47877. make sure your createComponentForPage() method creates
  47878. a suitable component when it is passed this name
  47879. @param normalIcon the drawable to display in the page's button normally
  47880. @param overIcon the drawable to display in the page's button when the mouse is over
  47881. @param downIcon the drawable to display in the page's button when the button is down
  47882. @see DrawableButton
  47883. */
  47884. void addSettingsPage (const String& pageTitle,
  47885. const Drawable* normalIcon,
  47886. const Drawable* overIcon,
  47887. const Drawable* downIcon);
  47888. /** Creates a page using a set of drawables to define the page's icon.
  47889. The other version of this method gives you more control over the icon, but this
  47890. one is much easier if you're just loading it from a file.
  47891. @param pageTitle the name of this preferences page - you'll need to
  47892. make sure your createComponentForPage() method creates
  47893. a suitable component when it is passed this name
  47894. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  47895. For this to look good, you'll probably want to use a nice
  47896. transparent png file.
  47897. @param imageDataSize the size of the image data, in bytes
  47898. */
  47899. void addSettingsPage (const String& pageTitle,
  47900. const void* imageData,
  47901. int imageDataSize);
  47902. /** Utility method to display this panel in a DialogWindow.
  47903. Calling this will create a DialogWindow containing this panel with the
  47904. given size and title, and will run it modally, returning when the user
  47905. closes the dialog box.
  47906. */
  47907. void showInDialogBox (const String& dialogTitle,
  47908. int dialogWidth,
  47909. int dialogHeight,
  47910. const Colour& backgroundColour = Colours::white);
  47911. /** Subclasses must override this to return a component for each preferences page.
  47912. The subclass should return a pointer to a new component representing the named
  47913. page, which the panel will then display.
  47914. The panel will delete the component later when the user goes to another page
  47915. or deletes the panel.
  47916. */
  47917. virtual Component* createComponentForPage (const String& pageName) = 0;
  47918. /** Changes the current page being displayed. */
  47919. void setCurrentPage (const String& pageName);
  47920. /** @internal */
  47921. void resized();
  47922. /** @internal */
  47923. void paint (Graphics& g);
  47924. /** @internal */
  47925. void buttonClicked (Button* button);
  47926. private:
  47927. String currentPageName;
  47928. ScopedPointer <Component> currentPage;
  47929. OwnedArray<DrawableButton> buttons;
  47930. int buttonSize;
  47931. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PreferencesPanel);
  47932. };
  47933. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  47934. /*** End of inlined file: juce_PreferencesPanel.h ***/
  47935. #endif
  47936. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  47937. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  47938. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  47939. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  47940. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  47941. // amalgamated build)
  47942. #ifndef DOXYGEN
  47943. #if JUCE_WINDOWS
  47944. typedef ActiveXControlComponent QTCompBaseClass;
  47945. #elif JUCE_MAC
  47946. typedef NSViewComponent QTCompBaseClass;
  47947. #endif
  47948. #endif
  47949. // this is used to disable QuickTime, and is defined in juce_Config.h
  47950. #if JUCE_QUICKTIME || DOXYGEN
  47951. /**
  47952. A window that can play back a QuickTime movie.
  47953. */
  47954. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  47955. {
  47956. public:
  47957. /** Creates a QuickTimeMovieComponent, initially blank.
  47958. Use the loadMovie() method to load a movie once you've added the
  47959. component to a window, (or put it on the desktop as a heavyweight window).
  47960. Loading a movie when the component isn't visible can cause problems, as
  47961. QuickTime needs a window handle to initialise properly.
  47962. */
  47963. QuickTimeMovieComponent();
  47964. /** Destructor. */
  47965. ~QuickTimeMovieComponent();
  47966. /** Returns true if QT is installed and working on this machine.
  47967. */
  47968. static bool isQuickTimeAvailable() throw();
  47969. /** Tries to load a QuickTime movie from a file into the player.
  47970. It's best to call this function once you've added the component to a window,
  47971. (or put it on the desktop as a heavyweight window). Loading a movie when the
  47972. component isn't visible can cause problems, because QuickTime needs a window
  47973. handle to do its stuff.
  47974. @param movieFile the .mov file to open
  47975. @param isControllerVisible whether to show a controller bar at the bottom
  47976. @returns true if the movie opens successfully
  47977. */
  47978. bool loadMovie (const File& movieFile,
  47979. bool isControllerVisible);
  47980. /** Tries to load a QuickTime movie from a URL into the player.
  47981. It's best to call this function once you've added the component to a window,
  47982. (or put it on the desktop as a heavyweight window). Loading a movie when the
  47983. component isn't visible can cause problems, because QuickTime needs a window
  47984. handle to do its stuff.
  47985. @param movieURL the .mov file to open
  47986. @param isControllerVisible whether to show a controller bar at the bottom
  47987. @returns true if the movie opens successfully
  47988. */
  47989. bool loadMovie (const URL& movieURL,
  47990. bool isControllerVisible);
  47991. /** Tries to load a QuickTime movie from a stream into the player.
  47992. It's best to call this function once you've added the component to a window,
  47993. (or put it on the desktop as a heavyweight window). Loading a movie when the
  47994. component isn't visible can cause problems, because QuickTime needs a window
  47995. handle to do its stuff.
  47996. @param movieStream a stream containing a .mov file. The component may try
  47997. to read the whole stream before playing, rather than
  47998. streaming from it.
  47999. @param isControllerVisible whether to show a controller bar at the bottom
  48000. @returns true if the movie opens successfully
  48001. */
  48002. bool loadMovie (InputStream* movieStream,
  48003. bool isControllerVisible);
  48004. /** Closes the movie, if one is open. */
  48005. void closeMovie();
  48006. /** Returns the movie file that is currently open.
  48007. If there isn't one, this returns File::nonexistent
  48008. */
  48009. const File getCurrentMovieFile() const;
  48010. /** Returns true if there's currently a movie open. */
  48011. bool isMovieOpen() const;
  48012. /** Returns the length of the movie, in seconds. */
  48013. double getMovieDuration() const;
  48014. /** Returns the movie's natural size, in pixels.
  48015. You can use this to resize the component to show the movie at its preferred
  48016. scale.
  48017. If no movie is loaded, the size returned will be 0 x 0.
  48018. */
  48019. void getMovieNormalSize (int& width, int& height) const;
  48020. /** This will position the component within a given area, keeping its aspect
  48021. ratio correct according to the movie's normal size.
  48022. The component will be made as large as it can go within the space, and will
  48023. be aligned according to the justification value if this means there are gaps at
  48024. the top or sides.
  48025. */
  48026. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  48027. const RectanglePlacement& placement);
  48028. /** Starts the movie playing. */
  48029. void play();
  48030. /** Stops the movie playing. */
  48031. void stop();
  48032. /** Returns true if the movie is currently playing. */
  48033. bool isPlaying() const;
  48034. /** Moves the movie's position back to the start. */
  48035. void goToStart();
  48036. /** Sets the movie's position to a given time. */
  48037. void setPosition (double seconds);
  48038. /** Returns the current play position of the movie. */
  48039. double getPosition() const;
  48040. /** Changes the movie playback rate.
  48041. A value of 1 is normal speed, greater values play it proportionately faster,
  48042. smaller values play it slower.
  48043. */
  48044. void setSpeed (float newSpeed);
  48045. /** Changes the movie's playback volume.
  48046. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  48047. */
  48048. void setMovieVolume (float newVolume);
  48049. /** Returns the movie's playback volume.
  48050. @returns the volume in the range 0 (silent) to 1.0 (full)
  48051. */
  48052. float getMovieVolume() const;
  48053. /** Tells the movie whether it should loop. */
  48054. void setLooping (bool shouldLoop);
  48055. /** Returns true if the movie is currently looping.
  48056. @see setLooping
  48057. */
  48058. bool isLooping() const;
  48059. /** True if the native QuickTime controller bar is shown in the window.
  48060. @see loadMovie
  48061. */
  48062. bool isControllerVisible() const;
  48063. /** @internal */
  48064. void paint (Graphics& g);
  48065. private:
  48066. File movieFile;
  48067. bool movieLoaded, controllerVisible, looping;
  48068. #if JUCE_WINDOWS
  48069. void parentHierarchyChanged();
  48070. void visibilityChanged();
  48071. void createControlIfNeeded();
  48072. bool isControlCreated() const;
  48073. class Pimpl;
  48074. friend class ScopedPointer <Pimpl>;
  48075. ScopedPointer <Pimpl> pimpl;
  48076. #else
  48077. void* movie;
  48078. #endif
  48079. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QuickTimeMovieComponent);
  48080. };
  48081. #endif
  48082. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  48083. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  48084. #endif
  48085. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48086. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  48087. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48088. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48089. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  48090. /**
  48091. On Windows only, this component sits in the taskbar tray as a small icon.
  48092. To use it, just create one of these components, but don't attempt to make it
  48093. visible, add it to a parent, or put it on the desktop.
  48094. You can then call setIconImage() to create an icon for it in the taskbar.
  48095. To change the icon's tooltip, you can use setIconTooltip().
  48096. To respond to mouse-events, you can override the normal mouseDown(),
  48097. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  48098. position will not be valid, you can use this to respond to clicks. Traditionally
  48099. you'd use a left-click to show your application's window, and a right-click
  48100. to show a pop-up menu.
  48101. */
  48102. class JUCE_API SystemTrayIconComponent : public Component
  48103. {
  48104. public:
  48105. SystemTrayIconComponent();
  48106. /** Destructor. */
  48107. ~SystemTrayIconComponent();
  48108. /** Changes the image shown in the taskbar.
  48109. */
  48110. void setIconImage (const Image& newImage);
  48111. /** Changes the tooltip that Windows shows above the icon. */
  48112. void setIconTooltip (const String& tooltip);
  48113. #if JUCE_LINUX
  48114. /** @internal */
  48115. void paint (Graphics& g);
  48116. #endif
  48117. private:
  48118. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SystemTrayIconComponent);
  48119. };
  48120. #endif
  48121. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48122. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  48123. #endif
  48124. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48125. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  48126. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48127. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48128. #if JUCE_WEB_BROWSER || DOXYGEN
  48129. #if ! DOXYGEN
  48130. class WebBrowserComponentInternal;
  48131. #endif
  48132. /**
  48133. A component that displays an embedded web browser.
  48134. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  48135. Windows, probably IE.
  48136. */
  48137. class JUCE_API WebBrowserComponent : public Component
  48138. {
  48139. public:
  48140. /** Creates a WebBrowserComponent.
  48141. Once it's created and visible, send the browser to a URL using goToURL().
  48142. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  48143. component is taken offscreen, it'll clear the current page
  48144. and replace it with a blank page - this can be handy to stop
  48145. the browser using resources in the background when it's not
  48146. actually being used.
  48147. */
  48148. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  48149. /** Destructor. */
  48150. ~WebBrowserComponent();
  48151. /** Sends the browser to a particular URL.
  48152. @param url the URL to go to.
  48153. @param headers an optional set of parameters to put in the HTTP header. If
  48154. you supply this, it should be a set of string in the form
  48155. "HeaderKey: HeaderValue"
  48156. @param postData an optional block of data that will be attached to the HTTP
  48157. POST request
  48158. */
  48159. void goToURL (const String& url,
  48160. const StringArray* headers = 0,
  48161. const MemoryBlock* postData = 0);
  48162. /** Stops the current page loading.
  48163. */
  48164. void stop();
  48165. /** Sends the browser back one page.
  48166. */
  48167. void goBack();
  48168. /** Sends the browser forward one page.
  48169. */
  48170. void goForward();
  48171. /** Refreshes the browser.
  48172. */
  48173. void refresh();
  48174. /** This callback is called when the browser is about to navigate
  48175. to a new location.
  48176. You can override this method to perform some action when the user
  48177. tries to go to a particular URL. To allow the operation to carry on,
  48178. return true, or return false to stop the navigation happening.
  48179. */
  48180. virtual bool pageAboutToLoad (const String& newURL);
  48181. /** @internal */
  48182. void paint (Graphics& g);
  48183. /** @internal */
  48184. void resized();
  48185. /** @internal */
  48186. void parentHierarchyChanged();
  48187. /** @internal */
  48188. void visibilityChanged();
  48189. private:
  48190. WebBrowserComponentInternal* browser;
  48191. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  48192. String lastURL;
  48193. StringArray lastHeaders;
  48194. MemoryBlock lastPostData;
  48195. void reloadLastURL();
  48196. void checkWindowAssociation();
  48197. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponent);
  48198. };
  48199. #endif
  48200. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48201. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  48202. #endif
  48203. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  48204. #endif
  48205. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  48206. /*** Start of inlined file: juce_CallOutBox.h ***/
  48207. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  48208. #define __JUCE_CALLOUTBOX_JUCEHEADER__
  48209. /**
  48210. A box with a small arrow that can be used as a temporary pop-up window to show
  48211. extra controls when a button or other component is clicked.
  48212. Using one of these is similar to having a popup menu attached to a button or
  48213. other component - but it looks fancier, and has an arrow that can indicate the
  48214. object that it applies to.
  48215. Normally, you'd create one of these on the stack and run it modally, e.g.
  48216. @code
  48217. void mouseUp (const MouseEvent& e)
  48218. {
  48219. MyContentComponent content;
  48220. content.setSize (300, 300);
  48221. CallOutBox callOut (content, *this, 0);
  48222. callOut.runModalLoop();
  48223. }
  48224. @endcode
  48225. The call-out will resize and position itself when the content changes size.
  48226. */
  48227. class JUCE_API CallOutBox : public Component
  48228. {
  48229. public:
  48230. /** Creates a CallOutBox.
  48231. @param contentComponent the component to display inside the call-out. This should
  48232. already have a size set (although the call-out will also
  48233. update itself when the component's size is changed later).
  48234. Obviously this component must not be deleted until the
  48235. call-out box has been deleted.
  48236. @param componentToPointTo the component that the call-out's arrow should point towards
  48237. @param parentComponent if non-zero, this is the component to add the call-out to. If
  48238. this is zero, the call-out will be added to the desktop.
  48239. */
  48240. CallOutBox (Component& contentComponent,
  48241. Component& componentToPointTo,
  48242. Component* parentComponent);
  48243. /** Destructor. */
  48244. ~CallOutBox();
  48245. /** Changes the length of the arrow. */
  48246. void setArrowSize (float newSize);
  48247. /** Updates the position and size of the box.
  48248. You shouldn't normally need to call this, unless you need more precise control over the
  48249. layout.
  48250. @param newAreaToPointTo the rectangle to make the box's arrow point to
  48251. @param newAreaToFitIn the area within which the box's position should be constrained
  48252. */
  48253. void updatePosition (const Rectangle<int>& newAreaToPointTo,
  48254. const Rectangle<int>& newAreaToFitIn);
  48255. /** @internal */
  48256. void paint (Graphics& g);
  48257. /** @internal */
  48258. void resized();
  48259. /** @internal */
  48260. void moved();
  48261. /** @internal */
  48262. void childBoundsChanged (Component*);
  48263. /** @internal */
  48264. bool hitTest (int x, int y);
  48265. /** @internal */
  48266. void inputAttemptWhenModal();
  48267. /** @internal */
  48268. bool keyPressed (const KeyPress& key);
  48269. /** @internal */
  48270. void handleCommandMessage (int commandId);
  48271. private:
  48272. int borderSpace;
  48273. float arrowSize;
  48274. Component& content;
  48275. Path outline;
  48276. Point<float> targetPoint;
  48277. Rectangle<int> availableArea, targetArea;
  48278. Image background;
  48279. void refreshPath();
  48280. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallOutBox);
  48281. };
  48282. #endif // __JUCE_CALLOUTBOX_JUCEHEADER__
  48283. /*** End of inlined file: juce_CallOutBox.h ***/
  48284. #endif
  48285. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  48286. /*** Start of inlined file: juce_ComponentPeer.h ***/
  48287. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  48288. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  48289. class ComponentBoundsConstrainer;
  48290. /**
  48291. The Component class uses a ComponentPeer internally to create and manage a real
  48292. operating-system window.
  48293. This is an abstract base class - the platform specific code contains implementations of
  48294. it for the various platforms.
  48295. User-code should very rarely need to have any involvement with this class.
  48296. @see Component::createNewPeer
  48297. */
  48298. class JUCE_API ComponentPeer
  48299. {
  48300. public:
  48301. /** A combination of these flags is passed to the ComponentPeer constructor. */
  48302. enum StyleFlags
  48303. {
  48304. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  48305. entry on the taskbar (ignored on MacOSX) */
  48306. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  48307. tooltip, etc. */
  48308. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  48309. through it (may not be possible on some platforms). */
  48310. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  48311. title bar and frame\. if not specified, the window will be
  48312. borderless. */
  48313. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  48314. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  48315. minimise button on it. */
  48316. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  48317. maximise button on it. */
  48318. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  48319. close button on it. */
  48320. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  48321. not be possible on all platforms). */
  48322. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  48323. do its own repainting, but only to repaint when the
  48324. performAnyPendingRepaintsNow() method is called. */
  48325. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  48326. be used for things like plugin windows, to stop them interfering
  48327. with the host's shortcut keys */
  48328. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  48329. };
  48330. /** Creates a peer.
  48331. The component is the one that we intend to represent, and the style flags are
  48332. a combination of the values in the StyleFlags enum
  48333. */
  48334. ComponentPeer (Component* component, int styleFlags);
  48335. /** Destructor. */
  48336. virtual ~ComponentPeer();
  48337. /** Returns the component being represented by this peer. */
  48338. Component* getComponent() const throw() { return component; }
  48339. /** Returns the set of style flags that were set when the window was created.
  48340. @see Component::addToDesktop
  48341. */
  48342. int getStyleFlags() const throw() { return styleFlags; }
  48343. /** Returns the raw handle to whatever kind of window is being used.
  48344. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  48345. but rememeber there's no guarantees what you'll get back.
  48346. */
  48347. virtual void* getNativeHandle() const = 0;
  48348. /** Shows or hides the window. */
  48349. virtual void setVisible (bool shouldBeVisible) = 0;
  48350. /** Changes the title of the window. */
  48351. virtual void setTitle (const String& title) = 0;
  48352. /** Moves the window without changing its size.
  48353. If the native window is contained in another window, then the co-ordinates are
  48354. relative to the parent window's origin, not the screen origin.
  48355. This should result in a callback to handleMovedOrResized().
  48356. */
  48357. virtual void setPosition (int x, int y) = 0;
  48358. /** Resizes the window without changing its position.
  48359. This should result in a callback to handleMovedOrResized().
  48360. */
  48361. virtual void setSize (int w, int h) = 0;
  48362. /** Moves and resizes the window.
  48363. If the native window is contained in another window, then the co-ordinates are
  48364. relative to the parent window's origin, not the screen origin.
  48365. This should result in a callback to handleMovedOrResized().
  48366. */
  48367. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  48368. /** Returns the current position and size of the window.
  48369. If the native window is contained in another window, then the co-ordinates are
  48370. relative to the parent window's origin, not the screen origin.
  48371. */
  48372. virtual const Rectangle<int> getBounds() const = 0;
  48373. /** Returns the x-position of this window, relative to the screen's origin. */
  48374. virtual const Point<int> getScreenPosition() const = 0;
  48375. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  48376. virtual const Point<int> localToGlobal (const Point<int>& relativePosition) = 0;
  48377. /** Converts a rectangle relative to the top-left of this component to screen co-ordinates. */
  48378. virtual const Rectangle<int> localToGlobal (const Rectangle<int>& relativePosition);
  48379. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  48380. virtual const Point<int> globalToLocal (const Point<int>& screenPosition) = 0;
  48381. /** Converts a screen area to a position relative to the top-left of this component. */
  48382. virtual const Rectangle<int> globalToLocal (const Rectangle<int>& screenPosition);
  48383. /** Minimises the window. */
  48384. virtual void setMinimised (bool shouldBeMinimised) = 0;
  48385. /** True if the window is currently minimised. */
  48386. virtual bool isMinimised() const = 0;
  48387. /** Enable/disable fullscreen mode for the window. */
  48388. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  48389. /** True if the window is currently full-screen. */
  48390. virtual bool isFullScreen() const = 0;
  48391. /** Sets the size to restore to if fullscreen mode is turned off. */
  48392. void setNonFullScreenBounds (const Rectangle<int>& newBounds) throw();
  48393. /** Returns the size to restore to if fullscreen mode is turned off. */
  48394. const Rectangle<int>& getNonFullScreenBounds() const throw();
  48395. /** Attempts to change the icon associated with this window.
  48396. */
  48397. virtual void setIcon (const Image& newIcon) = 0;
  48398. /** Sets a constrainer to use if the peer can resize itself.
  48399. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  48400. */
  48401. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) throw();
  48402. /** Returns the current constrainer, if one has been set. */
  48403. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  48404. /** Checks if a point is in the window.
  48405. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  48406. is false, then this returns false if the point is actually inside a child of this
  48407. window.
  48408. */
  48409. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  48410. /** Returns the size of the window frame that's around this window.
  48411. Whether or not the window has a normal window frame depends on the flags
  48412. that were set when the window was created by Component::addToDesktop()
  48413. */
  48414. virtual const BorderSize<int> getFrameSize() const = 0;
  48415. /** This is called when the window's bounds change.
  48416. A peer implementation must call this when the window is moved and resized, so that
  48417. this method can pass the message on to the component.
  48418. */
  48419. void handleMovedOrResized();
  48420. /** This is called if the screen resolution changes.
  48421. A peer implementation must call this if the monitor arrangement changes or the available
  48422. screen size changes.
  48423. */
  48424. void handleScreenSizeChange();
  48425. /** This is called to repaint the component into the given context. */
  48426. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  48427. /** Sets this window to either be always-on-top or normal.
  48428. Some kinds of window might not be able to do this, so should return false.
  48429. */
  48430. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  48431. /** Brings the window to the top, optionally also giving it focus. */
  48432. virtual void toFront (bool makeActive) = 0;
  48433. /** Moves the window to be just behind another one. */
  48434. virtual void toBehind (ComponentPeer* other) = 0;
  48435. /** Called when the window is brought to the front, either by the OS or by a call
  48436. to toFront().
  48437. */
  48438. void handleBroughtToFront();
  48439. /** True if the window has the keyboard focus. */
  48440. virtual bool isFocused() const = 0;
  48441. /** Tries to give the window keyboard focus. */
  48442. virtual void grabFocus() = 0;
  48443. /** Tells the window that text input may be required at the given position.
  48444. This may cause things like a virtual on-screen keyboard to appear, depending
  48445. on the OS.
  48446. */
  48447. virtual void textInputRequired (const Point<int>& position) = 0;
  48448. /** Called when the window gains keyboard focus. */
  48449. void handleFocusGain();
  48450. /** Called when the window loses keyboard focus. */
  48451. void handleFocusLoss();
  48452. Component* getLastFocusedSubcomponent() const throw();
  48453. /** Called when a key is pressed.
  48454. For keycode info, see the KeyPress class.
  48455. Returns true if the keystroke was used.
  48456. */
  48457. bool handleKeyPress (int keyCode, juce_wchar textCharacter);
  48458. /** Called whenever a key is pressed or released.
  48459. Returns true if the keystroke was used.
  48460. */
  48461. bool handleKeyUpOrDown (bool isKeyDown);
  48462. /** Called whenever a modifier key is pressed or released. */
  48463. void handleModifierKeysChange();
  48464. /** Returns the currently focused TextInputTarget, or null if none is found. */
  48465. TextInputTarget* findCurrentTextInputTarget();
  48466. /** Invalidates a region of the window to be repainted asynchronously. */
  48467. virtual void repaint (const Rectangle<int>& area) = 0;
  48468. /** This can be called (from the message thread) to cause the immediate redrawing
  48469. of any areas of this window that need repainting.
  48470. You shouldn't ever really need to use this, it's mainly for special purposes
  48471. like supporting audio plugins where the host's event loop is out of our control.
  48472. */
  48473. virtual void performAnyPendingRepaintsNow() = 0;
  48474. /** Changes the window's transparency. */
  48475. virtual void setAlpha (float newAlpha) = 0;
  48476. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  48477. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  48478. void handleUserClosingWindow();
  48479. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  48480. void handleFileDragExit (const StringArray& files);
  48481. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  48482. /** Resets the masking region.
  48483. The subclass should call this every time it's about to call the handlePaint
  48484. method.
  48485. @see addMaskedRegion
  48486. */
  48487. void clearMaskedRegion();
  48488. /** Adds a rectangle to the set of areas not to paint over.
  48489. A component can call this on its peer during its paint() method, to signal
  48490. that the painting code should ignore a given region. The reason
  48491. for this is to stop embedded windows (such as OpenGL) getting painted over.
  48492. The masked region is cleared each time before a paint happens, so a component
  48493. will have to make sure it calls this every time it's painted.
  48494. */
  48495. void addMaskedRegion (int x, int y, int w, int h);
  48496. /** Returns the number of currently-active peers.
  48497. @see getPeer
  48498. */
  48499. static int getNumPeers() throw();
  48500. /** Returns one of the currently-active peers.
  48501. @see getNumPeers
  48502. */
  48503. static ComponentPeer* getPeer (int index) throw();
  48504. /** Checks if this peer object is valid.
  48505. @see getNumPeers
  48506. */
  48507. static bool isValidPeer (const ComponentPeer* peer) throw();
  48508. virtual const StringArray getAvailableRenderingEngines();
  48509. virtual int getCurrentRenderingEngine() const;
  48510. virtual void setCurrentRenderingEngine (int index);
  48511. protected:
  48512. Component* const component;
  48513. const int styleFlags;
  48514. RectangleList maskedRegion;
  48515. Rectangle<int> lastNonFullscreenBounds;
  48516. uint32 lastPaintTime;
  48517. ComponentBoundsConstrainer* constrainer;
  48518. static void updateCurrentModifiers() throw();
  48519. private:
  48520. WeakReference<Component> lastFocusedComponent, dragAndDropTargetComponent;
  48521. Component* lastDragAndDropCompUnderMouse;
  48522. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  48523. friend class Component;
  48524. friend class Desktop;
  48525. static ComponentPeer* getPeerFor (const Component* component) throw();
  48526. void setLastDragDropTarget (Component* comp);
  48527. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentPeer);
  48528. };
  48529. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  48530. /*** End of inlined file: juce_ComponentPeer.h ***/
  48531. #endif
  48532. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  48533. /*** Start of inlined file: juce_DialogWindow.h ***/
  48534. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  48535. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  48536. /**
  48537. A dialog-box style window.
  48538. This class is a convenient way of creating a DocumentWindow with a close button
  48539. that can be triggered by pressing the escape key.
  48540. Any of the methods available to a DocumentWindow or ResizableWindow are also
  48541. available to this, so it can be made resizable, have a menu bar, etc.
  48542. To add items to the box, see the ResizableWindow::setContentOwned() or
  48543. ResizableWindow::setContentNonOwned() methods. Don't add components directly to this
  48544. class - always put them in a content component!
  48545. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  48546. the user clicking the close button - for more info, see the DocumentWindow
  48547. help.
  48548. @see DocumentWindow, ResizableWindow
  48549. */
  48550. class JUCE_API DialogWindow : public DocumentWindow
  48551. {
  48552. public:
  48553. /** Creates a DialogWindow.
  48554. @param name the name to give the component - this is also
  48555. the title shown at the top of the window. To change
  48556. this later, use setName()
  48557. @param backgroundColour the colour to use for filling the window's background.
  48558. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  48559. close button to be triggered
  48560. @param addToDesktop if true, the window will be automatically added to the
  48561. desktop; if false, you can use it as a child component
  48562. */
  48563. DialogWindow (const String& name,
  48564. const Colour& backgroundColour,
  48565. bool escapeKeyTriggersCloseButton,
  48566. bool addToDesktop = true);
  48567. /** Destructor.
  48568. If a content component has been set with setContentOwned(), it will be deleted.
  48569. */
  48570. ~DialogWindow();
  48571. /** Easy way of quickly showing a dialog box containing a given component.
  48572. This will open and display a DialogWindow containing a given component, making it
  48573. modal, but returning immediately to allow the dialog to finish in its own time. If
  48574. you want to block and run a modal loop until the dialog is dismissed, use showModalDialog()
  48575. instead.
  48576. To close the dialog programatically, you should call exitModalState (returnValue) on
  48577. the DialogWindow that is created. To find a pointer to this window from your
  48578. contentComponent, you can do something like this:
  48579. @code
  48580. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  48581. if (dw != 0)
  48582. dw->exitModalState (1234);
  48583. @endcode
  48584. @param dialogTitle the dialog box's title
  48585. @param contentComponent the content component for the dialog box. Make sure
  48586. that this has been set to the size you want it to
  48587. be before calling this method. The component won't
  48588. be deleted by this call, so you can re-use it or delete
  48589. it afterwards
  48590. @param componentToCentreAround if this is non-zero, it indicates a component that
  48591. you'd like to show this dialog box in front of. See the
  48592. DocumentWindow::centreAroundComponent() method for more
  48593. info on this parameter
  48594. @param backgroundColour a colour to use for the dialog box's background colour
  48595. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  48596. close button to be triggered
  48597. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  48598. a corner resizer
  48599. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  48600. to use a border or corner resizer component. See ResizableWindow::setResizable()
  48601. */
  48602. static void showDialog (const String& dialogTitle,
  48603. Component* contentComponent,
  48604. Component* componentToCentreAround,
  48605. const Colour& backgroundColour,
  48606. bool escapeKeyTriggersCloseButton,
  48607. bool shouldBeResizable = false,
  48608. bool useBottomRightCornerResizer = false);
  48609. /** Easy way of quickly showing a dialog box containing a given component.
  48610. This will open and display a DialogWindow containing a given component, returning
  48611. when the user clicks its close button.
  48612. It returns the value that was returned by the dialog box's runModalLoop() call.
  48613. To close the dialog programatically, you should call exitModalState (returnValue) on
  48614. the DialogWindow that is created. To find a pointer to this window from your
  48615. contentComponent, you can do something like this:
  48616. @code
  48617. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  48618. if (dw != 0)
  48619. dw->exitModalState (1234);
  48620. @endcode
  48621. @param dialogTitle the dialog box's title
  48622. @param contentComponent the content component for the dialog box. Make sure
  48623. that this has been set to the size you want it to
  48624. be before calling this method. The component won't
  48625. be deleted by this call, so you can re-use it or delete
  48626. it afterwards
  48627. @param componentToCentreAround if this is non-zero, it indicates a component that
  48628. you'd like to show this dialog box in front of. See the
  48629. DocumentWindow::centreAroundComponent() method for more
  48630. info on this parameter
  48631. @param backgroundColour a colour to use for the dialog box's background colour
  48632. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  48633. close button to be triggered
  48634. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  48635. a corner resizer
  48636. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  48637. to use a border or corner resizer component. See ResizableWindow::setResizable()
  48638. */
  48639. #if JUCE_MODAL_LOOPS_PERMITTED
  48640. static int showModalDialog (const String& dialogTitle,
  48641. Component* contentComponent,
  48642. Component* componentToCentreAround,
  48643. const Colour& backgroundColour,
  48644. bool escapeKeyTriggersCloseButton,
  48645. bool shouldBeResizable = false,
  48646. bool useBottomRightCornerResizer = false);
  48647. #endif
  48648. protected:
  48649. /** @internal */
  48650. void resized();
  48651. private:
  48652. bool escapeKeyTriggersCloseButton;
  48653. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DialogWindow);
  48654. };
  48655. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  48656. /*** End of inlined file: juce_DialogWindow.h ***/
  48657. #endif
  48658. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  48659. #endif
  48660. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  48661. #endif
  48662. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  48663. /*** Start of inlined file: juce_SplashScreen.h ***/
  48664. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  48665. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  48666. /** A component for showing a splash screen while your app starts up.
  48667. This will automatically position itself, and delete itself when the app has
  48668. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  48669. this).
  48670. To use it, just create one of these in your JUCEApplication::initialise() method,
  48671. call its show() method and let the object delete itself later.
  48672. E.g. @code
  48673. void MyApp::initialise (const String& commandLine)
  48674. {
  48675. SplashScreen* splash = new SplashScreen();
  48676. splash->show ("welcome to my app",
  48677. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  48678. 4000, false);
  48679. .. no need to delete the splash screen - it'll do that itself.
  48680. }
  48681. @endcode
  48682. */
  48683. class JUCE_API SplashScreen : public Component,
  48684. public Timer,
  48685. private DeletedAtShutdown
  48686. {
  48687. public:
  48688. /** Creates a SplashScreen object.
  48689. After creating one of these (or your subclass of it), call one of the show()
  48690. methods to display it.
  48691. */
  48692. SplashScreen();
  48693. /** Destructor. */
  48694. ~SplashScreen();
  48695. /** Creates a SplashScreen object that will display an image.
  48696. As soon as this is called, the SplashScreen will be displayed in the centre of the
  48697. screen. This method will also dispatch any pending messages to make sure that when
  48698. it returns, the splash screen has been completely drawn, and your initialisation
  48699. code can carry on.
  48700. @param title the name to give the component
  48701. @param backgroundImage an image to draw on the component. The component's size
  48702. will be set to the size of this image, and if the image is
  48703. semi-transparent, the component will be made semi-transparent
  48704. too. This image will be deleted (or released from the ImageCache
  48705. if that's how it was created) by the splash screen object when
  48706. it is itself deleted.
  48707. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  48708. should stay visible for. If the initialisation takes longer than
  48709. this time, the splash screen will wait for it to finish before
  48710. disappearing, but if initialisation is very quick, this lets
  48711. you make sure that people get a good look at your splash.
  48712. @param useDropShadow if true, the window will have a drop shadow
  48713. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  48714. the mouse (anywhere)
  48715. */
  48716. void show (const String& title,
  48717. const Image& backgroundImage,
  48718. int minimumTimeToDisplayFor,
  48719. bool useDropShadow,
  48720. bool removeOnMouseClick = true);
  48721. /** Creates a SplashScreen object with a specified size.
  48722. For a custom splash screen, you can use this method to display it at a certain size
  48723. and then override the paint() method yourself to do whatever's necessary.
  48724. As soon as this is called, the SplashScreen will be displayed in the centre of the
  48725. screen. This method will also dispatch any pending messages to make sure that when
  48726. it returns, the splash screen has been completely drawn, and your initialisation
  48727. code can carry on.
  48728. @param title the name to give the component
  48729. @param width the width to use
  48730. @param height the height to use
  48731. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  48732. should stay visible for. If the initialisation takes longer than
  48733. this time, the splash screen will wait for it to finish before
  48734. disappearing, but if initialisation is very quick, this lets
  48735. you make sure that people get a good look at your splash.
  48736. @param useDropShadow if true, the window will have a drop shadow
  48737. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  48738. the mouse (anywhere)
  48739. */
  48740. void show (const String& title,
  48741. int width,
  48742. int height,
  48743. int minimumTimeToDisplayFor,
  48744. bool useDropShadow,
  48745. bool removeOnMouseClick = true);
  48746. /** @internal */
  48747. void paint (Graphics& g);
  48748. /** @internal */
  48749. void timerCallback();
  48750. private:
  48751. Image backgroundImage;
  48752. Time earliestTimeToDelete;
  48753. int originalClickCounter;
  48754. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SplashScreen);
  48755. };
  48756. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  48757. /*** End of inlined file: juce_SplashScreen.h ***/
  48758. #endif
  48759. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  48760. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  48761. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  48762. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  48763. /**
  48764. A thread that automatically pops up a modal dialog box with a progress bar
  48765. and cancel button while it's busy running.
  48766. These are handy for performing some sort of task while giving the user feedback
  48767. about how long there is to go, etc.
  48768. E.g. @code
  48769. class MyTask : public ThreadWithProgressWindow
  48770. {
  48771. public:
  48772. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  48773. {
  48774. }
  48775. ~MyTask()
  48776. {
  48777. }
  48778. void run()
  48779. {
  48780. for (int i = 0; i < thingsToDo; ++i)
  48781. {
  48782. // must check this as often as possible, because this is
  48783. // how we know if the user's pressed 'cancel'
  48784. if (threadShouldExit())
  48785. break;
  48786. // this will update the progress bar on the dialog box
  48787. setProgress (i / (double) thingsToDo);
  48788. // ... do the business here...
  48789. }
  48790. }
  48791. };
  48792. void doTheTask()
  48793. {
  48794. MyTask m;
  48795. if (m.runThread())
  48796. {
  48797. // thread finished normally..
  48798. }
  48799. else
  48800. {
  48801. // user pressed the cancel button..
  48802. }
  48803. }
  48804. @endcode
  48805. @see Thread, AlertWindow
  48806. */
  48807. class JUCE_API ThreadWithProgressWindow : public Thread,
  48808. private Timer
  48809. {
  48810. public:
  48811. /** Creates the thread.
  48812. Initially, the dialog box won't be visible, it'll only appear when the
  48813. runThread() method is called.
  48814. @param windowTitle the title to go at the top of the dialog box
  48815. @param hasProgressBar whether the dialog box should have a progress bar (see
  48816. setProgress() )
  48817. @param hasCancelButton whether the dialog box should have a cancel button
  48818. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  48819. the thread to stop before killing it forcibly (see
  48820. Thread::stopThread() )
  48821. @param cancelButtonText the text that should be shown in the cancel button
  48822. (if it has one)
  48823. */
  48824. ThreadWithProgressWindow (const String& windowTitle,
  48825. bool hasProgressBar,
  48826. bool hasCancelButton,
  48827. int timeOutMsWhenCancelling = 10000,
  48828. const String& cancelButtonText = "Cancel");
  48829. /** Destructor. */
  48830. ~ThreadWithProgressWindow();
  48831. /** Starts the thread and waits for it to finish.
  48832. This will start the thread, make the dialog box appear, and wait until either
  48833. the thread finishes normally, or until the cancel button is pressed.
  48834. Before returning, the dialog box will be hidden.
  48835. @param threadPriority the priority to use when starting the thread - see
  48836. Thread::startThread() for values
  48837. @returns true if the thread finished normally; false if the user pressed cancel
  48838. */
  48839. bool runThread (int threadPriority = 5);
  48840. /** The thread should call this periodically to update the position of the progress bar.
  48841. @param newProgress the progress, from 0.0 to 1.0
  48842. @see setStatusMessage
  48843. */
  48844. void setProgress (double newProgress);
  48845. /** The thread can call this to change the message that's displayed in the dialog box.
  48846. */
  48847. void setStatusMessage (const String& newStatusMessage);
  48848. /** Returns the AlertWindow that is being used.
  48849. */
  48850. AlertWindow* getAlertWindow() const throw() { return alertWindow; }
  48851. private:
  48852. void timerCallback();
  48853. double progress;
  48854. ScopedPointer <AlertWindow> alertWindow;
  48855. String message;
  48856. CriticalSection messageLock;
  48857. const int timeOutMsWhenCancelling;
  48858. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadWithProgressWindow);
  48859. };
  48860. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  48861. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  48862. #endif
  48863. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  48864. #endif
  48865. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  48866. #endif
  48867. #ifndef __JUCE_COLOUR_JUCEHEADER__
  48868. #endif
  48869. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  48870. #endif
  48871. #ifndef __JUCE_COLOURS_JUCEHEADER__
  48872. #endif
  48873. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  48874. #endif
  48875. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  48876. /*** Start of inlined file: juce_EdgeTable.h ***/
  48877. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  48878. #define __JUCE_EDGETABLE_JUCEHEADER__
  48879. class Path;
  48880. class Image;
  48881. /**
  48882. A table of horizontal scan-line segments - used for rasterising Paths.
  48883. @see Path, Graphics
  48884. */
  48885. class JUCE_API EdgeTable
  48886. {
  48887. public:
  48888. /** Creates an edge table containing a path.
  48889. A table is created with a fixed vertical range, and only sections of the path
  48890. which lie within this range will be added to the table.
  48891. @param clipLimits only the region of the path that lies within this area will be added
  48892. @param pathToAdd the path to add to the table
  48893. @param transform a transform to apply to the path being added
  48894. */
  48895. EdgeTable (const Rectangle<int>& clipLimits,
  48896. const Path& pathToAdd,
  48897. const AffineTransform& transform);
  48898. /** Creates an edge table containing a rectangle. */
  48899. EdgeTable (const Rectangle<int>& rectangleToAdd);
  48900. /** Creates an edge table containing a rectangle list. */
  48901. EdgeTable (const RectangleList& rectanglesToAdd);
  48902. /** Creates an edge table containing a rectangle. */
  48903. EdgeTable (const Rectangle<float>& rectangleToAdd);
  48904. /** Creates a copy of another edge table. */
  48905. EdgeTable (const EdgeTable& other);
  48906. /** Copies from another edge table. */
  48907. EdgeTable& operator= (const EdgeTable& other);
  48908. /** Destructor. */
  48909. ~EdgeTable();
  48910. void clipToRectangle (const Rectangle<int>& r);
  48911. void excludeRectangle (const Rectangle<int>& r);
  48912. void clipToEdgeTable (const EdgeTable& other);
  48913. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels);
  48914. bool isEmpty() throw();
  48915. const Rectangle<int>& getMaximumBounds() const throw() { return bounds; }
  48916. void translate (float dx, int dy) throw();
  48917. /** Reduces the amount of space the table has allocated.
  48918. This will shrink the table down to use as little memory as possible - useful for
  48919. read-only tables that get stored and re-used for rendering.
  48920. */
  48921. void optimiseTable();
  48922. /** Iterates the lines in the table, for rendering.
  48923. This function will iterate each line in the table, and call a user-defined class
  48924. to render each pixel or continuous line of pixels that the table contains.
  48925. @param iterationCallback this templated class must contain the following methods:
  48926. @code
  48927. inline void setEdgeTableYPos (int y);
  48928. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  48929. inline void handleEdgeTablePixelFull (int x) const;
  48930. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  48931. inline void handleEdgeTableLineFull (int x, int width) const;
  48932. @endcode
  48933. (these don't necessarily have to be 'const', but it might help it go faster)
  48934. */
  48935. template <class EdgeTableIterationCallback>
  48936. void iterate (EdgeTableIterationCallback& iterationCallback) const throw()
  48937. {
  48938. const int* lineStart = table;
  48939. for (int y = 0; y < bounds.getHeight(); ++y)
  48940. {
  48941. const int* line = lineStart;
  48942. lineStart += lineStrideElements;
  48943. int numPoints = line[0];
  48944. if (--numPoints > 0)
  48945. {
  48946. int x = *++line;
  48947. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  48948. int levelAccumulator = 0;
  48949. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  48950. while (--numPoints >= 0)
  48951. {
  48952. const int level = *++line;
  48953. jassert (isPositiveAndBelow (level, (int) 256));
  48954. const int endX = *++line;
  48955. jassert (endX >= x);
  48956. const int endOfRun = (endX >> 8);
  48957. if (endOfRun == (x >> 8))
  48958. {
  48959. // small segment within the same pixel, so just save it for the next
  48960. // time round..
  48961. levelAccumulator += (endX - x) * level;
  48962. }
  48963. else
  48964. {
  48965. // plot the fist pixel of this segment, including any accumulated
  48966. // levels from smaller segments that haven't been drawn yet
  48967. levelAccumulator += (0x100 - (x & 0xff)) * level;
  48968. levelAccumulator >>= 8;
  48969. x >>= 8;
  48970. if (levelAccumulator > 0)
  48971. {
  48972. if (levelAccumulator >= 255)
  48973. iterationCallback.handleEdgeTablePixelFull (x);
  48974. else
  48975. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  48976. }
  48977. // if there's a run of similar pixels, do it all in one go..
  48978. if (level > 0)
  48979. {
  48980. jassert (endOfRun <= bounds.getRight());
  48981. const int numPix = endOfRun - ++x;
  48982. if (numPix > 0)
  48983. iterationCallback.handleEdgeTableLine (x, numPix, level);
  48984. }
  48985. // save the bit at the end to be drawn next time round the loop.
  48986. levelAccumulator = (endX & 0xff) * level;
  48987. }
  48988. x = endX;
  48989. }
  48990. levelAccumulator >>= 8;
  48991. if (levelAccumulator > 0)
  48992. {
  48993. x >>= 8;
  48994. jassert (x >= bounds.getX() && x < bounds.getRight());
  48995. if (levelAccumulator >= 255)
  48996. iterationCallback.handleEdgeTablePixelFull (x);
  48997. else
  48998. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  48999. }
  49000. }
  49001. }
  49002. }
  49003. private:
  49004. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  49005. HeapBlock<int> table;
  49006. Rectangle<int> bounds;
  49007. int maxEdgesPerLine, lineStrideElements;
  49008. bool needToCheckEmptinesss;
  49009. void addEdgePoint (int x, int y, int winding);
  49010. void remapTableForNumEdges (int newNumEdgesPerLine);
  49011. void intersectWithEdgeTableLine (int y, const int* otherLine);
  49012. void clipEdgeTableLineToRange (int* line, int x1, int x2) throw();
  49013. void sanitiseLevels (bool useNonZeroWinding) throw();
  49014. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) throw();
  49015. JUCE_LEAK_DETECTOR (EdgeTable);
  49016. };
  49017. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  49018. /*** End of inlined file: juce_EdgeTable.h ***/
  49019. #endif
  49020. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  49021. /*** Start of inlined file: juce_FillType.h ***/
  49022. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  49023. #define __JUCE_FILLTYPE_JUCEHEADER__
  49024. /**
  49025. Represents a colour or fill pattern to use for rendering paths.
  49026. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  49027. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  49028. @see Graphics::setFillType, DrawablePath::setFill
  49029. */
  49030. class JUCE_API FillType
  49031. {
  49032. public:
  49033. /** Creates a default fill type, of solid black. */
  49034. FillType() throw();
  49035. /** Creates a fill type of a solid colour.
  49036. @see setColour
  49037. */
  49038. FillType (const Colour& colour) throw();
  49039. /** Creates a gradient fill type.
  49040. @see setGradient
  49041. */
  49042. FillType (const ColourGradient& gradient);
  49043. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  49044. and rotation of the pattern.
  49045. @see setTiledImage
  49046. */
  49047. FillType (const Image& image, const AffineTransform& transform) throw();
  49048. /** Creates a copy of another FillType. */
  49049. FillType (const FillType& other);
  49050. /** Makes a copy of another FillType. */
  49051. FillType& operator= (const FillType& other);
  49052. /** Destructor. */
  49053. ~FillType() throw();
  49054. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  49055. bool isColour() const throw() { return gradient == 0 && image.isNull(); }
  49056. /** Returns true if this is a gradient fill. */
  49057. bool isGradient() const throw() { return gradient != 0; }
  49058. /** Returns true if this is a tiled image pattern fill. */
  49059. bool isTiledImage() const throw() { return image.isValid(); }
  49060. /** Turns this object into a solid colour fill.
  49061. If the object was an image or gradient, those fields will no longer be valid. */
  49062. void setColour (const Colour& newColour) throw();
  49063. /** Turns this object into a gradient fill. */
  49064. void setGradient (const ColourGradient& newGradient);
  49065. /** Turns this object into a tiled image fill type. The transform allows you to set
  49066. the scaling, offset and rotation of the pattern.
  49067. */
  49068. void setTiledImage (const Image& image, const AffineTransform& transform) throw();
  49069. /** Changes the opacity that should be used.
  49070. If the fill is a solid colour, this just changes the opacity of that colour. For
  49071. gradients and image tiles, it changes the opacity that will be used for them.
  49072. */
  49073. void setOpacity (float newOpacity) throw();
  49074. /** Returns the current opacity to be applied to the colour, gradient, or image.
  49075. @see setOpacity
  49076. */
  49077. float getOpacity() const throw() { return colour.getFloatAlpha(); }
  49078. /** Returns true if this fill type is completely transparent. */
  49079. bool isInvisible() const throw();
  49080. /** The solid colour being used.
  49081. If the fill type is not a solid colour, the alpha channel of this colour indicates
  49082. the opacity that should be used for the fill, and the RGB channels are ignored.
  49083. */
  49084. Colour colour;
  49085. /** Returns the gradient that should be used for filling.
  49086. This will be zero if the object is some other type of fill.
  49087. If a gradient is active, the overall opacity with which it should be applied
  49088. is indicated by the alpha channel of the colour variable.
  49089. */
  49090. ScopedPointer <ColourGradient> gradient;
  49091. /** The image that should be used for tiling.
  49092. If an image fill is active, the overall opacity with which it should be applied
  49093. is indicated by the alpha channel of the colour variable.
  49094. */
  49095. Image image;
  49096. /** The transform that should be applied to the image or gradient that's being drawn. */
  49097. AffineTransform transform;
  49098. bool operator== (const FillType& other) const;
  49099. bool operator!= (const FillType& other) const;
  49100. private:
  49101. JUCE_LEAK_DETECTOR (FillType);
  49102. };
  49103. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  49104. /*** End of inlined file: juce_FillType.h ***/
  49105. #endif
  49106. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  49107. #endif
  49108. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  49109. #endif
  49110. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49111. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  49112. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49113. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49114. /**
  49115. Interface class for graphics context objects, used internally by the Graphics class.
  49116. Users are not supposed to create instances of this class directly - do your drawing
  49117. via the Graphics object instead.
  49118. It's a base class for different types of graphics context, that may perform software-based
  49119. or OS-accelerated rendering.
  49120. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  49121. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  49122. context.
  49123. */
  49124. class JUCE_API LowLevelGraphicsContext
  49125. {
  49126. protected:
  49127. LowLevelGraphicsContext();
  49128. public:
  49129. virtual ~LowLevelGraphicsContext();
  49130. /** Returns true if this device is vector-based, e.g. a printer. */
  49131. virtual bool isVectorDevice() const = 0;
  49132. /** Moves the origin to a new position.
  49133. The co-ords are relative to the current origin, and indicate the new position
  49134. of (0, 0).
  49135. */
  49136. virtual void setOrigin (int x, int y) = 0;
  49137. virtual void addTransform (const AffineTransform& transform) = 0;
  49138. virtual float getScaleFactor() = 0;
  49139. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  49140. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  49141. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  49142. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  49143. virtual void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform) = 0;
  49144. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  49145. virtual const Rectangle<int> getClipBounds() const = 0;
  49146. virtual bool isClipEmpty() const = 0;
  49147. virtual void saveState() = 0;
  49148. virtual void restoreState() = 0;
  49149. virtual void beginTransparencyLayer (float opacity) = 0;
  49150. virtual void endTransparencyLayer() = 0;
  49151. virtual void setFill (const FillType& fillType) = 0;
  49152. virtual void setOpacity (float newOpacity) = 0;
  49153. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  49154. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  49155. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  49156. virtual void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  49157. virtual void drawLine (const Line <float>& line) = 0;
  49158. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  49159. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  49160. virtual void setFont (const Font& newFont) = 0;
  49161. virtual const Font getFont() = 0;
  49162. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  49163. };
  49164. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49165. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  49166. #endif
  49167. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  49168. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  49169. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  49170. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  49171. /**
  49172. An implementation of LowLevelGraphicsContext that turns the drawing operations
  49173. into a PostScript document.
  49174. */
  49175. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  49176. {
  49177. public:
  49178. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  49179. const String& documentTitle,
  49180. int totalWidth,
  49181. int totalHeight);
  49182. ~LowLevelGraphicsPostScriptRenderer();
  49183. bool isVectorDevice() const;
  49184. void setOrigin (int x, int y);
  49185. void addTransform (const AffineTransform& transform);
  49186. float getScaleFactor();
  49187. bool clipToRectangle (const Rectangle<int>& r);
  49188. bool clipToRectangleList (const RectangleList& clipRegion);
  49189. void excludeClipRectangle (const Rectangle<int>& r);
  49190. void clipToPath (const Path& path, const AffineTransform& transform);
  49191. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  49192. void saveState();
  49193. void restoreState();
  49194. void beginTransparencyLayer (float opacity);
  49195. void endTransparencyLayer();
  49196. bool clipRegionIntersects (const Rectangle<int>& r);
  49197. const Rectangle<int> getClipBounds() const;
  49198. bool isClipEmpty() const;
  49199. void setFill (const FillType& fillType);
  49200. void setOpacity (float opacity);
  49201. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  49202. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  49203. void fillPath (const Path& path, const AffineTransform& transform);
  49204. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  49205. void drawLine (const Line <float>& line);
  49206. void drawVerticalLine (int x, float top, float bottom);
  49207. void drawHorizontalLine (int x, float top, float bottom);
  49208. const Font getFont();
  49209. void setFont (const Font& newFont);
  49210. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  49211. protected:
  49212. OutputStream& out;
  49213. int totalWidth, totalHeight;
  49214. bool needToClip;
  49215. Colour lastColour;
  49216. struct SavedState
  49217. {
  49218. SavedState();
  49219. ~SavedState();
  49220. RectangleList clip;
  49221. int xOffset, yOffset;
  49222. FillType fillType;
  49223. Font font;
  49224. private:
  49225. SavedState& operator= (const SavedState&);
  49226. };
  49227. OwnedArray <SavedState> stateStack;
  49228. void writeClip();
  49229. void writeColour (const Colour& colour);
  49230. void writePath (const Path& path) const;
  49231. void writeXY (float x, float y) const;
  49232. void writeTransform (const AffineTransform& trans) const;
  49233. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  49234. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsPostScriptRenderer);
  49235. };
  49236. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  49237. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  49238. #endif
  49239. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  49240. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  49241. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  49242. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  49243. /**
  49244. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  49245. its rendering in memory.
  49246. User code is not supposed to create instances of this class directly - do all your
  49247. rendering via the Graphics class instead.
  49248. */
  49249. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  49250. {
  49251. public:
  49252. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn);
  49253. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  49254. ~LowLevelGraphicsSoftwareRenderer();
  49255. bool isVectorDevice() const;
  49256. void setOrigin (int x, int y);
  49257. void addTransform (const AffineTransform& transform);
  49258. float getScaleFactor();
  49259. bool clipToRectangle (const Rectangle<int>& r);
  49260. bool clipToRectangleList (const RectangleList& clipRegion);
  49261. void excludeClipRectangle (const Rectangle<int>& r);
  49262. void clipToPath (const Path& path, const AffineTransform& transform);
  49263. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  49264. bool clipRegionIntersects (const Rectangle<int>& r);
  49265. const Rectangle<int> getClipBounds() const;
  49266. bool isClipEmpty() const;
  49267. void saveState();
  49268. void restoreState();
  49269. void beginTransparencyLayer (float opacity);
  49270. void endTransparencyLayer();
  49271. void setFill (const FillType& fillType);
  49272. void setOpacity (float opacity);
  49273. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  49274. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  49275. void fillPath (const Path& path, const AffineTransform& transform);
  49276. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  49277. void drawLine (const Line <float>& line);
  49278. void drawVerticalLine (int x, float top, float bottom);
  49279. void drawHorizontalLine (int x, float top, float bottom);
  49280. void setFont (const Font& newFont);
  49281. const Font getFont();
  49282. void drawGlyph (int glyphNumber, float x, float y);
  49283. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  49284. protected:
  49285. Image image;
  49286. class GlyphCache;
  49287. class CachedGlyph;
  49288. class SavedState;
  49289. friend class ScopedPointer <SavedState>;
  49290. friend class OwnedArray <SavedState>;
  49291. friend class OwnedArray <CachedGlyph>;
  49292. ScopedPointer <SavedState> currentState;
  49293. OwnedArray <SavedState> stateStack;
  49294. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsSoftwareRenderer);
  49295. };
  49296. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  49297. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  49298. #endif
  49299. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  49300. #endif
  49301. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  49302. #endif
  49303. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  49304. /*** Start of inlined file: juce_DrawableComposite.h ***/
  49305. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  49306. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  49307. /**
  49308. A drawable object which acts as a container for a set of other Drawables.
  49309. @see Drawable
  49310. */
  49311. class JUCE_API DrawableComposite : public Drawable
  49312. {
  49313. public:
  49314. /** Creates a composite Drawable. */
  49315. DrawableComposite();
  49316. /** Creates a copy of a DrawableComposite. */
  49317. DrawableComposite (const DrawableComposite& other);
  49318. /** Destructor. */
  49319. ~DrawableComposite();
  49320. /** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  49321. @see setContentArea
  49322. */
  49323. void setBoundingBox (const RelativeParallelogram& newBoundingBox);
  49324. /** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  49325. @see setBoundingBox
  49326. */
  49327. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  49328. /** Changes the bounding box transform to match the content area, so that any sub-items will
  49329. be drawn at their untransformed positions.
  49330. */
  49331. void resetBoundingBoxToContentArea();
  49332. /** Returns the main content rectangle.
  49333. The content area is actually defined by the markers named "left", "right", "top" and
  49334. "bottom", but this method is a shortcut that returns them all at once.
  49335. @see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  49336. */
  49337. const RelativeRectangle getContentArea() const;
  49338. /** Changes the main content area.
  49339. The content area is actually defined by the markers named "left", "right", "top" and
  49340. "bottom", but this method is a shortcut that sets them all at once.
  49341. @see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  49342. */
  49343. void setContentArea (const RelativeRectangle& newArea);
  49344. /** Resets the content area and the bounding transform to fit around the area occupied
  49345. by the child components (ignoring any markers).
  49346. */
  49347. void resetContentAreaAndBoundingBoxToFitChildren();
  49348. /** The name of the marker that defines the left edge of the content area. */
  49349. static const char* const contentLeftMarkerName;
  49350. /** The name of the marker that defines the right edge of the content area. */
  49351. static const char* const contentRightMarkerName;
  49352. /** The name of the marker that defines the top edge of the content area. */
  49353. static const char* const contentTopMarkerName;
  49354. /** The name of the marker that defines the bottom edge of the content area. */
  49355. static const char* const contentBottomMarkerName;
  49356. /** @internal */
  49357. Drawable* createCopy() const;
  49358. /** @internal */
  49359. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  49360. /** @internal */
  49361. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  49362. /** @internal */
  49363. static const Identifier valueTreeType;
  49364. /** @internal */
  49365. const Rectangle<float> getDrawableBounds() const;
  49366. /** @internal */
  49367. void childBoundsChanged (Component*);
  49368. /** @internal */
  49369. void childrenChanged();
  49370. /** @internal */
  49371. void parentHierarchyChanged();
  49372. /** @internal */
  49373. MarkerList* getMarkers (bool xAxis);
  49374. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  49375. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  49376. {
  49377. public:
  49378. ValueTreeWrapper (const ValueTree& state);
  49379. ValueTree getChildList() const;
  49380. ValueTree getChildListCreating (UndoManager* undoManager);
  49381. const RelativeParallelogram getBoundingBox() const;
  49382. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  49383. void resetBoundingBoxToContentArea (UndoManager* undoManager);
  49384. const RelativeRectangle getContentArea() const;
  49385. void setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager);
  49386. MarkerList::ValueTreeWrapper getMarkerList (bool xAxis) const;
  49387. MarkerList::ValueTreeWrapper getMarkerListCreating (bool xAxis, UndoManager* undoManager);
  49388. static const Identifier topLeft, topRight, bottomLeft;
  49389. private:
  49390. static const Identifier childGroupTag, markerGroupTagX, markerGroupTagY;
  49391. };
  49392. private:
  49393. RelativeParallelogram bounds;
  49394. MarkerList markersX, markersY;
  49395. bool updateBoundsReentrant;
  49396. friend class Drawable::Positioner<DrawableComposite>;
  49397. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  49398. void recalculateCoordinates (Expression::Scope*);
  49399. void updateBoundsToFitChildren();
  49400. DrawableComposite& operator= (const DrawableComposite&);
  49401. JUCE_LEAK_DETECTOR (DrawableComposite);
  49402. };
  49403. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  49404. /*** End of inlined file: juce_DrawableComposite.h ***/
  49405. #endif
  49406. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  49407. /*** Start of inlined file: juce_DrawableImage.h ***/
  49408. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  49409. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  49410. /**
  49411. A drawable object which is a bitmap image.
  49412. @see Drawable
  49413. */
  49414. class JUCE_API DrawableImage : public Drawable
  49415. {
  49416. public:
  49417. DrawableImage();
  49418. DrawableImage (const DrawableImage& other);
  49419. /** Destructor. */
  49420. ~DrawableImage();
  49421. /** Sets the image that this drawable will render. */
  49422. void setImage (const Image& imageToUse);
  49423. /** Returns the current image. */
  49424. const Image getImage() const { return image; }
  49425. /** Sets the opacity to use when drawing the image. */
  49426. void setOpacity (float newOpacity);
  49427. /** Returns the image's opacity. */
  49428. float getOpacity() const throw() { return opacity; }
  49429. /** Sets a colour to draw over the image's alpha channel.
  49430. By default this is transparent so isn't drawn, but if you set a non-transparent
  49431. colour here, then it will be overlaid on the image, using the image's alpha
  49432. channel as a mask.
  49433. This is handy for doing things like darkening or lightening an image by overlaying
  49434. it with semi-transparent black or white.
  49435. */
  49436. void setOverlayColour (const Colour& newOverlayColour);
  49437. /** Returns the overlay colour. */
  49438. const Colour& getOverlayColour() const throw() { return overlayColour; }
  49439. /** Sets the bounding box within which the image should be displayed. */
  49440. void setBoundingBox (const RelativeParallelogram& newBounds);
  49441. /** Returns the position to which the image's top-left corner should be remapped in the target
  49442. coordinate space when rendering this object.
  49443. @see setTransform
  49444. */
  49445. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  49446. /** @internal */
  49447. void paint (Graphics& g);
  49448. /** @internal */
  49449. bool hitTest (int x, int y);
  49450. /** @internal */
  49451. Drawable* createCopy() const;
  49452. /** @internal */
  49453. const Rectangle<float> getDrawableBounds() const;
  49454. /** @internal */
  49455. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  49456. /** @internal */
  49457. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  49458. /** @internal */
  49459. static const Identifier valueTreeType;
  49460. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  49461. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  49462. {
  49463. public:
  49464. ValueTreeWrapper (const ValueTree& state);
  49465. const var getImageIdentifier() const;
  49466. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  49467. Value getImageIdentifierValue (UndoManager* undoManager);
  49468. float getOpacity() const;
  49469. void setOpacity (float newOpacity, UndoManager* undoManager);
  49470. Value getOpacityValue (UndoManager* undoManager);
  49471. const Colour getOverlayColour() const;
  49472. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  49473. Value getOverlayColourValue (UndoManager* undoManager);
  49474. const RelativeParallelogram getBoundingBox() const;
  49475. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  49476. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  49477. };
  49478. private:
  49479. Image image;
  49480. float opacity;
  49481. Colour overlayColour;
  49482. RelativeParallelogram bounds;
  49483. friend class Drawable::Positioner<DrawableImage>;
  49484. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  49485. void recalculateCoordinates (Expression::Scope*);
  49486. DrawableImage& operator= (const DrawableImage&);
  49487. JUCE_LEAK_DETECTOR (DrawableImage);
  49488. };
  49489. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  49490. /*** End of inlined file: juce_DrawableImage.h ***/
  49491. #endif
  49492. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  49493. /*** Start of inlined file: juce_DrawablePath.h ***/
  49494. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  49495. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  49496. /*** Start of inlined file: juce_DrawableShape.h ***/
  49497. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  49498. #define __JUCE_DRAWABLESHAPE_JUCEHEADER__
  49499. /**
  49500. A base class implementing common functionality for Drawable classes which
  49501. consist of some kind of filled and stroked outline.
  49502. @see DrawablePath, DrawableRectangle
  49503. */
  49504. class JUCE_API DrawableShape : public Drawable
  49505. {
  49506. protected:
  49507. DrawableShape();
  49508. DrawableShape (const DrawableShape&);
  49509. public:
  49510. /** Destructor. */
  49511. ~DrawableShape();
  49512. /** A FillType wrapper that allows the gradient coordinates to be implemented using RelativePoint.
  49513. */
  49514. class RelativeFillType
  49515. {
  49516. public:
  49517. RelativeFillType();
  49518. RelativeFillType (const FillType& fill);
  49519. RelativeFillType (const RelativeFillType&);
  49520. RelativeFillType& operator= (const RelativeFillType&);
  49521. bool operator== (const RelativeFillType&) const;
  49522. bool operator!= (const RelativeFillType&) const;
  49523. bool isDynamic() const;
  49524. bool recalculateCoords (Expression::Scope* scope);
  49525. void writeTo (ValueTree& v, ComponentBuilder::ImageProvider*, UndoManager*) const;
  49526. bool readFrom (const ValueTree& v, ComponentBuilder::ImageProvider*);
  49527. FillType fill;
  49528. RelativePoint gradientPoint1, gradientPoint2, gradientPoint3;
  49529. };
  49530. /** Sets a fill type for the path.
  49531. This colour is used to fill the path - if you don't want the path to be
  49532. filled (e.g. if you're just drawing an outline), set this to a transparent
  49533. colour.
  49534. @see setPath, setStrokeFill
  49535. */
  49536. void setFill (const FillType& newFill);
  49537. /** Sets a fill type for the path.
  49538. This colour is used to fill the path - if you don't want the path to be
  49539. filled (e.g. if you're just drawing an outline), set this to a transparent
  49540. colour.
  49541. @see setPath, setStrokeFill
  49542. */
  49543. void setFill (const RelativeFillType& newFill);
  49544. /** Returns the current fill type.
  49545. @see setFill
  49546. */
  49547. const RelativeFillType& getFill() const throw() { return mainFill; }
  49548. /** Sets the fill type with which the outline will be drawn.
  49549. @see setFill
  49550. */
  49551. void setStrokeFill (const FillType& newStrokeFill);
  49552. /** Sets the fill type with which the outline will be drawn.
  49553. @see setFill
  49554. */
  49555. void setStrokeFill (const RelativeFillType& newStrokeFill);
  49556. /** Returns the current stroke fill.
  49557. @see setStrokeFill
  49558. */
  49559. const RelativeFillType& getStrokeFill() const throw() { return strokeFill; }
  49560. /** Changes the properties of the outline that will be drawn around the path.
  49561. If the stroke has 0 thickness, no stroke will be drawn.
  49562. @see setStrokeThickness, setStrokeColour
  49563. */
  49564. void setStrokeType (const PathStrokeType& newStrokeType);
  49565. /** Changes the stroke thickness.
  49566. This is a shortcut for calling setStrokeType.
  49567. */
  49568. void setStrokeThickness (float newThickness);
  49569. /** Returns the current outline style. */
  49570. const PathStrokeType& getStrokeType() const throw() { return strokeType; }
  49571. /** @internal */
  49572. class FillAndStrokeState : public Drawable::ValueTreeWrapperBase
  49573. {
  49574. public:
  49575. FillAndStrokeState (const ValueTree& state);
  49576. ValueTree getFillState (const Identifier& fillOrStrokeType);
  49577. const RelativeFillType getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider*) const;
  49578. void setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  49579. ComponentBuilder::ImageProvider*, UndoManager*);
  49580. const PathStrokeType getStrokeType() const;
  49581. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager*);
  49582. static const Identifier type, colour, colours, fill, stroke, path, jointStyle, capStyle, strokeWidth,
  49583. gradientPoint1, gradientPoint2, gradientPoint3, radial, imageId, imageOpacity;
  49584. };
  49585. /** @internal */
  49586. const Rectangle<float> getDrawableBounds() const;
  49587. /** @internal */
  49588. void paint (Graphics& g);
  49589. /** @internal */
  49590. bool hitTest (int x, int y);
  49591. protected:
  49592. /** Called when the cached path should be updated. */
  49593. void pathChanged();
  49594. /** Called when the cached stroke should be updated. */
  49595. void strokeChanged();
  49596. /** True if there's a stroke with a non-zero thickness and non-transparent colour. */
  49597. bool isStrokeVisible() const throw();
  49598. /** Updates the details from a FillAndStrokeState object, returning true if something changed. */
  49599. void refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider*);
  49600. /** Writes the stroke and fill details to a FillAndStrokeState object. */
  49601. void writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider*, UndoManager*) const;
  49602. PathStrokeType strokeType;
  49603. Path path, strokePath;
  49604. private:
  49605. class RelativePositioner;
  49606. RelativeFillType mainFill, strokeFill;
  49607. ScopedPointer<RelativeCoordinatePositionerBase> mainFillPositioner, strokeFillPositioner;
  49608. void setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  49609. ScopedPointer<RelativeCoordinatePositionerBase>& positioner);
  49610. DrawableShape& operator= (const DrawableShape&);
  49611. };
  49612. #endif // __JUCE_DRAWABLESHAPE_JUCEHEADER__
  49613. /*** End of inlined file: juce_DrawableShape.h ***/
  49614. /**
  49615. A drawable object which renders a filled or outlined shape.
  49616. For details on how to change the fill and stroke, see the DrawableShape class.
  49617. @see Drawable, DrawableShape
  49618. */
  49619. class JUCE_API DrawablePath : public DrawableShape
  49620. {
  49621. public:
  49622. /** Creates a DrawablePath. */
  49623. DrawablePath();
  49624. DrawablePath (const DrawablePath& other);
  49625. /** Destructor. */
  49626. ~DrawablePath();
  49627. /** Changes the path that will be drawn.
  49628. @see setFillColour, setStrokeType
  49629. */
  49630. void setPath (const Path& newPath);
  49631. /** Sets the path using a RelativePointPath.
  49632. Calling this will set up a Component::Positioner to automatically update the path
  49633. if any of the points in the source path are dynamic.
  49634. */
  49635. void setPath (const RelativePointPath& newPath);
  49636. /** Returns the current path. */
  49637. const Path& getPath() const;
  49638. /** Returns the current path for the outline. */
  49639. const Path& getStrokePath() const;
  49640. /** @internal */
  49641. Drawable* createCopy() const;
  49642. /** @internal */
  49643. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  49644. /** @internal */
  49645. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  49646. /** @internal */
  49647. static const Identifier valueTreeType;
  49648. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  49649. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  49650. {
  49651. public:
  49652. ValueTreeWrapper (const ValueTree& state);
  49653. bool usesNonZeroWinding() const;
  49654. void setUsesNonZeroWinding (bool b, UndoManager* undoManager);
  49655. class Element
  49656. {
  49657. public:
  49658. explicit Element (const ValueTree& state);
  49659. ~Element();
  49660. const Identifier getType() const throw() { return state.getType(); }
  49661. int getNumControlPoints() const throw();
  49662. const RelativePoint getControlPoint (int index) const;
  49663. Value getControlPointValue (int index, UndoManager*) const;
  49664. const RelativePoint getStartPoint() const;
  49665. const RelativePoint getEndPoint() const;
  49666. void setControlPoint (int index, const RelativePoint& point, UndoManager*);
  49667. float getLength (Expression::Scope*) const;
  49668. ValueTreeWrapper getParent() const;
  49669. Element getPreviousElement() const;
  49670. const String getModeOfEndPoint() const;
  49671. void setModeOfEndPoint (const String& newMode, UndoManager*);
  49672. void convertToLine (UndoManager*);
  49673. void convertToCubic (Expression::Scope*, UndoManager*);
  49674. void convertToPathBreak (UndoManager* undoManager);
  49675. ValueTree insertPoint (const Point<float>& targetPoint, Expression::Scope*, UndoManager*);
  49676. void removePoint (UndoManager* undoManager);
  49677. float findProportionAlongLine (const Point<float>& targetPoint, Expression::Scope*) const;
  49678. static const Identifier mode, startSubPathElement, closeSubPathElement,
  49679. lineToElement, quadraticToElement, cubicToElement;
  49680. static const char* cornerMode;
  49681. static const char* roundedMode;
  49682. static const char* symmetricMode;
  49683. ValueTree state;
  49684. };
  49685. ValueTree getPathState();
  49686. void readFrom (const RelativePointPath& path, UndoManager* undoManager);
  49687. void writeTo (RelativePointPath& path) const;
  49688. static const Identifier nonZeroWinding, point1, point2, point3;
  49689. };
  49690. private:
  49691. ScopedPointer<RelativePointPath> relativePath;
  49692. class RelativePositioner;
  49693. friend class RelativePositioner;
  49694. void applyRelativePath (const RelativePointPath&, Expression::Scope*);
  49695. DrawablePath& operator= (const DrawablePath&);
  49696. JUCE_LEAK_DETECTOR (DrawablePath);
  49697. };
  49698. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  49699. /*** End of inlined file: juce_DrawablePath.h ***/
  49700. #endif
  49701. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  49702. /*** Start of inlined file: juce_DrawableRectangle.h ***/
  49703. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  49704. #define __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  49705. /**
  49706. A Drawable object which draws a rectangle.
  49707. For details on how to change the fill and stroke, see the DrawableShape class.
  49708. @see Drawable, DrawableShape
  49709. */
  49710. class JUCE_API DrawableRectangle : public DrawableShape
  49711. {
  49712. public:
  49713. DrawableRectangle();
  49714. DrawableRectangle (const DrawableRectangle& other);
  49715. /** Destructor. */
  49716. ~DrawableRectangle();
  49717. /** Sets the rectangle's bounds. */
  49718. void setRectangle (const RelativeParallelogram& newBounds);
  49719. /** Returns the rectangle's bounds. */
  49720. const RelativeParallelogram& getRectangle() const throw() { return bounds; }
  49721. /** Returns the corner size to be used. */
  49722. const RelativePoint getCornerSize() const { return cornerSize; }
  49723. /** Sets a new corner size for the rectangle */
  49724. void setCornerSize (const RelativePoint& newSize);
  49725. /** @internal */
  49726. Drawable* createCopy() const;
  49727. /** @internal */
  49728. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  49729. /** @internal */
  49730. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  49731. /** @internal */
  49732. static const Identifier valueTreeType;
  49733. /** Internally-used class for wrapping a DrawableRectangle's state into a ValueTree. */
  49734. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  49735. {
  49736. public:
  49737. ValueTreeWrapper (const ValueTree& state);
  49738. const RelativeParallelogram getRectangle() const;
  49739. void setRectangle (const RelativeParallelogram& newBounds, UndoManager*);
  49740. void setCornerSize (const RelativePoint& cornerSize, UndoManager*);
  49741. const RelativePoint getCornerSize() const;
  49742. Value getCornerSizeValue (UndoManager*) const;
  49743. static const Identifier topLeft, topRight, bottomLeft, cornerSize;
  49744. };
  49745. private:
  49746. friend class Drawable::Positioner<DrawableRectangle>;
  49747. RelativeParallelogram bounds;
  49748. RelativePoint cornerSize;
  49749. void rebuildPath();
  49750. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  49751. void recalculateCoordinates (Expression::Scope*);
  49752. DrawableRectangle& operator= (const DrawableRectangle&);
  49753. JUCE_LEAK_DETECTOR (DrawableRectangle);
  49754. };
  49755. #endif // __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  49756. /*** End of inlined file: juce_DrawableRectangle.h ***/
  49757. #endif
  49758. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  49759. #endif
  49760. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  49761. /*** Start of inlined file: juce_DrawableText.h ***/
  49762. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  49763. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  49764. /**
  49765. A drawable object which renders a line of text.
  49766. @see Drawable
  49767. */
  49768. class JUCE_API DrawableText : public Drawable
  49769. {
  49770. public:
  49771. /** Creates a DrawableText object. */
  49772. DrawableText();
  49773. DrawableText (const DrawableText& other);
  49774. /** Destructor. */
  49775. ~DrawableText();
  49776. /** Sets the text to display.*/
  49777. void setText (const String& newText);
  49778. /** Sets the colour of the text. */
  49779. void setColour (const Colour& newColour);
  49780. /** Returns the current text colour. */
  49781. const Colour& getColour() const throw() { return colour; }
  49782. /** Sets the font to use.
  49783. Note that the font height and horizontal scale are actually based upon the position
  49784. of the fontSizeAndScaleAnchor parameter to setBounds(). If applySizeAndScale is true, then
  49785. the height and scale control point will be moved to match the dimensions of the font supplied;
  49786. if it is false, then the new font's height and scale are ignored.
  49787. */
  49788. void setFont (const Font& newFont, bool applySizeAndScale);
  49789. /** Changes the justification of the text within the bounding box. */
  49790. void setJustification (const Justification& newJustification);
  49791. /** Returns the parallelogram that defines the text bounding box. */
  49792. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  49793. /** Sets the bounding box that contains the text. */
  49794. void setBoundingBox (const RelativeParallelogram& newBounds);
  49795. /** Returns the point within the bounds that defines the font's size and scale. */
  49796. const RelativePoint& getFontSizeControlPoint() const throw() { return fontSizeControlPoint; }
  49797. /** Sets the control point that defines the font's height and horizontal scale.
  49798. This position is a point within the bounding box parallelogram, whose Y position (relative
  49799. to the parallelogram's origin and possibly distorted shape) specifies the font's height,
  49800. and its X defines the font's horizontal scale.
  49801. */
  49802. void setFontSizeControlPoint (const RelativePoint& newPoint);
  49803. /** @internal */
  49804. void paint (Graphics& g);
  49805. /** @internal */
  49806. Drawable* createCopy() const;
  49807. /** @internal */
  49808. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  49809. /** @internal */
  49810. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  49811. /** @internal */
  49812. static const Identifier valueTreeType;
  49813. /** @internal */
  49814. const Rectangle<float> getDrawableBounds() const;
  49815. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  49816. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  49817. {
  49818. public:
  49819. ValueTreeWrapper (const ValueTree& state);
  49820. const String getText() const;
  49821. void setText (const String& newText, UndoManager* undoManager);
  49822. Value getTextValue (UndoManager* undoManager);
  49823. const Colour getColour() const;
  49824. void setColour (const Colour& newColour, UndoManager* undoManager);
  49825. const Justification getJustification() const;
  49826. void setJustification (const Justification& newJustification, UndoManager* undoManager);
  49827. const Font getFont() const;
  49828. void setFont (const Font& newFont, UndoManager* undoManager);
  49829. Value getFontValue (UndoManager* undoManager);
  49830. const RelativeParallelogram getBoundingBox() const;
  49831. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  49832. const RelativePoint getFontSizeControlPoint() const;
  49833. void setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager);
  49834. static const Identifier text, colour, font, justification, topLeft, topRight, bottomLeft, fontSizeAnchor;
  49835. };
  49836. private:
  49837. RelativeParallelogram bounds;
  49838. RelativePoint fontSizeControlPoint;
  49839. Point<float> resolvedPoints[3];
  49840. Font font, scaledFont;
  49841. String text;
  49842. Colour colour;
  49843. Justification justification;
  49844. friend class Drawable::Positioner<DrawableText>;
  49845. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  49846. void recalculateCoordinates (Expression::Scope*);
  49847. void refreshBounds();
  49848. const AffineTransform getArrangementAndTransform (GlyphArrangement& glyphs) const;
  49849. DrawableText& operator= (const DrawableText&);
  49850. JUCE_LEAK_DETECTOR (DrawableText);
  49851. };
  49852. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  49853. /*** End of inlined file: juce_DrawableText.h ***/
  49854. #endif
  49855. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  49856. #endif
  49857. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  49858. /*** Start of inlined file: juce_GlowEffect.h ***/
  49859. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  49860. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  49861. /**
  49862. A component effect that adds a coloured blur around the component's contents.
  49863. (This will only work on non-opaque components).
  49864. @see Component::setComponentEffect, DropShadowEffect
  49865. */
  49866. class JUCE_API GlowEffect : public ImageEffectFilter
  49867. {
  49868. public:
  49869. /** Creates a default 'glow' effect.
  49870. To customise its appearance, use the setGlowProperties() method.
  49871. */
  49872. GlowEffect();
  49873. /** Destructor. */
  49874. ~GlowEffect();
  49875. /** Sets the glow's radius and colour.
  49876. The radius is how large the blur should be, and the colour is
  49877. used to render it (for a less intense glow, lower the colour's
  49878. opacity).
  49879. */
  49880. void setGlowProperties (float newRadius,
  49881. const Colour& newColour);
  49882. /** @internal */
  49883. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  49884. private:
  49885. float radius;
  49886. Colour colour;
  49887. JUCE_LEAK_DETECTOR (GlowEffect);
  49888. };
  49889. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  49890. /*** End of inlined file: juce_GlowEffect.h ***/
  49891. #endif
  49892. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  49893. #endif
  49894. #ifndef __JUCE_FONT_JUCEHEADER__
  49895. #endif
  49896. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  49897. #endif
  49898. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  49899. #endif
  49900. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  49901. #endif
  49902. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  49903. #endif
  49904. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  49905. #endif
  49906. #ifndef __JUCE_LINE_JUCEHEADER__
  49907. #endif
  49908. #ifndef __JUCE_PATH_JUCEHEADER__
  49909. #endif
  49910. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  49911. /*** Start of inlined file: juce_PathIterator.h ***/
  49912. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  49913. #define __JUCE_PATHITERATOR_JUCEHEADER__
  49914. /**
  49915. Flattens a Path object into a series of straight-line sections.
  49916. Use one of these to iterate through a Path object, and it will convert
  49917. all the curves into line sections so it's easy to render or perform
  49918. geometric operations on.
  49919. @see Path
  49920. */
  49921. class JUCE_API PathFlatteningIterator
  49922. {
  49923. public:
  49924. /** Creates a PathFlatteningIterator.
  49925. After creation, use the next() method to initialise the fields in the
  49926. object with the first line's position.
  49927. @param path the path to iterate along
  49928. @param transform a transform to apply to each point in the path being iterated
  49929. @param tolerance the amount by which the curves are allowed to deviate from the lines
  49930. into which they are being broken down - a higher tolerance contains
  49931. less lines, so can be generated faster, but will be less smooth.
  49932. */
  49933. PathFlatteningIterator (const Path& path,
  49934. const AffineTransform& transform = AffineTransform::identity,
  49935. float tolerance = defaultTolerance);
  49936. /** Destructor. */
  49937. ~PathFlatteningIterator();
  49938. /** Fetches the next line segment from the path.
  49939. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  49940. so that they describe the new line segment.
  49941. @returns false when there are no more lines to fetch.
  49942. */
  49943. bool next();
  49944. float x1; /**< The x position of the start of the current line segment. */
  49945. float y1; /**< The y position of the start of the current line segment. */
  49946. float x2; /**< The x position of the end of the current line segment. */
  49947. float y2; /**< The y position of the end of the current line segment. */
  49948. /** Indicates whether the current line segment is closing a sub-path.
  49949. If the current line is the one that connects the end of a sub-path
  49950. back to the start again, this will be true.
  49951. */
  49952. bool closesSubPath;
  49953. /** The index of the current line within the current sub-path.
  49954. E.g. you can use this to see whether the line is the first one in the
  49955. subpath by seeing if it's 0.
  49956. */
  49957. int subPathIndex;
  49958. /** Returns true if the current segment is the last in the current sub-path. */
  49959. bool isLastInSubpath() const throw();
  49960. /** This is the default value that should be used for the tolerance value (see the constructor parameters). */
  49961. static const float defaultTolerance;
  49962. private:
  49963. const Path& path;
  49964. const AffineTransform transform;
  49965. float* points;
  49966. const float toleranceSquared;
  49967. float subPathCloseX, subPathCloseY;
  49968. const bool isIdentityTransform;
  49969. HeapBlock <float> stackBase;
  49970. float* stackPos;
  49971. size_t index, stackSize;
  49972. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PathFlatteningIterator);
  49973. };
  49974. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  49975. /*** End of inlined file: juce_PathIterator.h ***/
  49976. #endif
  49977. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  49978. #endif
  49979. #ifndef __JUCE_POINT_JUCEHEADER__
  49980. #endif
  49981. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  49982. #endif
  49983. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  49984. #endif
  49985. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  49986. /*** Start of inlined file: juce_CameraDevice.h ***/
  49987. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  49988. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  49989. #if JUCE_USE_CAMERA || DOXYGEN
  49990. /**
  49991. Controls any video capture devices that might be available.
  49992. Use getAvailableDevices() to list the devices that are attached to the
  49993. system, then call openDevice to open one for use. Once you have a CameraDevice
  49994. object, you can get a viewer component from it, and use its methods to
  49995. stream to a file or capture still-frames.
  49996. */
  49997. class JUCE_API CameraDevice
  49998. {
  49999. public:
  50000. /** Destructor. */
  50001. virtual ~CameraDevice();
  50002. /** Returns a list of the available cameras on this machine.
  50003. You can open one of these devices by calling openDevice().
  50004. */
  50005. static const StringArray getAvailableDevices();
  50006. /** Opens a camera device.
  50007. The index parameter indicates which of the items returned by getAvailableDevices()
  50008. to open.
  50009. The size constraints allow the method to choose between different resolutions if
  50010. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  50011. then these will be ignored.
  50012. */
  50013. static CameraDevice* openDevice (int deviceIndex,
  50014. int minWidth = 128, int minHeight = 64,
  50015. int maxWidth = 1024, int maxHeight = 768);
  50016. /** Returns the name of this device */
  50017. const String getName() const { return name; }
  50018. /** Creates a component that can be used to display a preview of the
  50019. video from this camera.
  50020. */
  50021. Component* createViewerComponent();
  50022. /** Starts recording video to the specified file.
  50023. You should use getFileExtension() to find out the correct extension to
  50024. use for your filename.
  50025. If the file exists, it will be deleted before the recording starts.
  50026. This method may not start recording instantly, so if you need to know the
  50027. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  50028. after the recording has finished.
  50029. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  50030. or may not be used, depending on the driver.
  50031. */
  50032. void startRecordingToFile (const File& file, int quality = 2);
  50033. /** Stops recording, after a call to startRecordingToFile().
  50034. */
  50035. void stopRecording();
  50036. /** Returns the file extension that should be used for the files
  50037. that you pass to startRecordingToFile().
  50038. This may be platform-specific, e.g. ".mov" or ".avi".
  50039. */
  50040. static const String getFileExtension();
  50041. /** After calling stopRecording(), this method can be called to return the timestamp
  50042. of the first frame that was written to the file.
  50043. */
  50044. const Time getTimeOfFirstRecordedFrame() const;
  50045. /**
  50046. Receives callbacks with images from a CameraDevice.
  50047. @see CameraDevice::addListener
  50048. */
  50049. class JUCE_API Listener
  50050. {
  50051. public:
  50052. Listener() {}
  50053. virtual ~Listener() {}
  50054. /** This method is called when a new image arrives.
  50055. This may be called by any thread, so be careful about thread-safety,
  50056. and make sure that you process the data as quickly as possible to
  50057. avoid glitching!
  50058. */
  50059. virtual void imageReceived (const Image& image) = 0;
  50060. };
  50061. /** Adds a listener to receive images from the camera.
  50062. Be very careful not to delete the listener without first removing it by calling
  50063. removeListener().
  50064. */
  50065. void addListener (Listener* listenerToAdd);
  50066. /** Removes a listener that was previously added with addListener().
  50067. */
  50068. void removeListener (Listener* listenerToRemove);
  50069. protected:
  50070. /** @internal */
  50071. CameraDevice (const String& name, int index);
  50072. private:
  50073. void* internal;
  50074. bool isRecording;
  50075. String name;
  50076. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CameraDevice);
  50077. };
  50078. /** This typedef is just for compatibility with old code - newer code should use the CameraDevice::Listener class directly. */
  50079. typedef CameraDevice::Listener CameraImageListener;
  50080. #endif
  50081. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  50082. /*** End of inlined file: juce_CameraDevice.h ***/
  50083. #endif
  50084. #ifndef __JUCE_IMAGE_JUCEHEADER__
  50085. #endif
  50086. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  50087. /*** Start of inlined file: juce_ImageCache.h ***/
  50088. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  50089. #define __JUCE_IMAGECACHE_JUCEHEADER__
  50090. /**
  50091. A global cache of images that have been loaded from files or memory.
  50092. If you're loading an image and may need to use the image in more than one
  50093. place, this is used to allow the same image to be shared rather than loading
  50094. multiple copies into memory.
  50095. Another advantage is that after images are released, they will be kept in
  50096. memory for a few seconds before it is actually deleted, so if you're repeatedly
  50097. loading/deleting the same image, it'll reduce the chances of having to reload it
  50098. each time.
  50099. @see Image, ImageFileFormat
  50100. */
  50101. class JUCE_API ImageCache
  50102. {
  50103. public:
  50104. /** Loads an image from a file, (or just returns the image if it's already cached).
  50105. If the cache already contains an image that was loaded from this file,
  50106. that image will be returned. Otherwise, this method will try to load the
  50107. file, add it to the cache, and return it.
  50108. Remember that the image returned is shared, so drawing into it might
  50109. affect other things that are using it! If you want to draw on it, first
  50110. call Image::duplicateIfShared()
  50111. @param file the file to try to load
  50112. @returns the image, or null if it there was an error loading it
  50113. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  50114. */
  50115. static const Image getFromFile (const File& file);
  50116. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  50117. If the cache already contains an image that was loaded from this block of memory,
  50118. that image will be returned. Otherwise, this method will try to load the
  50119. file, add it to the cache, and return it.
  50120. Remember that the image returned is shared, so drawing into it might
  50121. affect other things that are using it! If you want to draw on it, first
  50122. call Image::duplicateIfShared()
  50123. @param imageData the block of memory containing the image data
  50124. @param dataSize the data size in bytes
  50125. @returns the image, or an invalid image if it there was an error loading it
  50126. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  50127. */
  50128. static const Image getFromMemory (const void* imageData, int dataSize);
  50129. /** Checks the cache for an image with a particular hashcode.
  50130. If there's an image in the cache with this hashcode, it will be returned,
  50131. otherwise it will return an invalid image.
  50132. @param hashCode the hash code that was associated with the image by addImageToCache()
  50133. @see addImageToCache
  50134. */
  50135. static const Image getFromHashCode (int64 hashCode);
  50136. /** Adds an image to the cache with a user-defined hash-code.
  50137. The image passed-in will be referenced (not copied) by the cache, so it's probably
  50138. a good idea not to draw into it after adding it, otherwise this will affect all
  50139. instances of it that may be in use.
  50140. @param image the image to add
  50141. @param hashCode the hash-code to associate with it
  50142. @see getFromHashCode
  50143. */
  50144. static void addImageToCache (const Image& image, int64 hashCode);
  50145. /** Changes the amount of time before an unused image will be removed from the cache.
  50146. By default this is about 5 seconds.
  50147. */
  50148. static void setCacheTimeout (int millisecs);
  50149. private:
  50150. class Pimpl;
  50151. friend class Pimpl;
  50152. ImageCache();
  50153. ~ImageCache();
  50154. JUCE_DECLARE_NON_COPYABLE (ImageCache);
  50155. };
  50156. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  50157. /*** End of inlined file: juce_ImageCache.h ***/
  50158. #endif
  50159. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50160. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  50161. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50162. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50163. /**
  50164. Represents a filter kernel to use in convoluting an image.
  50165. @see Image::applyConvolution
  50166. */
  50167. class JUCE_API ImageConvolutionKernel
  50168. {
  50169. public:
  50170. /** Creates an empty convulution kernel.
  50171. @param size the length of each dimension of the kernel, so e.g. if the size
  50172. is 5, it will create a 5x5 kernel
  50173. */
  50174. ImageConvolutionKernel (int size);
  50175. /** Destructor. */
  50176. ~ImageConvolutionKernel();
  50177. /** Resets all values in the kernel to zero. */
  50178. void clear();
  50179. /** Returns one of the kernel values. */
  50180. float getKernelValue (int x, int y) const throw();
  50181. /** Sets the value of a specific cell in the kernel.
  50182. The x and y parameters must be in the range 0 < x < getKernelSize().
  50183. @see setOverallSum
  50184. */
  50185. void setKernelValue (int x, int y, float value) throw();
  50186. /** Rescales all values in the kernel to make the total add up to a fixed value.
  50187. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  50188. */
  50189. void setOverallSum (float desiredTotalSum);
  50190. /** Multiplies all values in the kernel by a value. */
  50191. void rescaleAllValues (float multiplier);
  50192. /** Intialises the kernel for a gaussian blur.
  50193. @param blurRadius this may be larger or smaller than the kernel's actual
  50194. size but this will obviously be wasteful or clip at the
  50195. edges. Ideally the kernel should be just larger than
  50196. (blurRadius * 2).
  50197. */
  50198. void createGaussianBlur (float blurRadius);
  50199. /** Returns the size of the kernel.
  50200. E.g. if it's a 3x3 kernel, this returns 3.
  50201. */
  50202. int getKernelSize() const { return size; }
  50203. /** Applies the kernel to an image.
  50204. @param destImage the image that will receive the resultant convoluted pixels.
  50205. @param sourceImage the source image to read from - this can be the same image as
  50206. the destination, but if different, it must be exactly the same
  50207. size and format.
  50208. @param destinationArea the region of the image to apply the filter to
  50209. */
  50210. void applyToImage (Image& destImage,
  50211. const Image& sourceImage,
  50212. const Rectangle<int>& destinationArea) const;
  50213. private:
  50214. HeapBlock <float> values;
  50215. const int size;
  50216. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageConvolutionKernel);
  50217. };
  50218. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50219. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  50220. #endif
  50221. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  50222. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  50223. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  50224. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  50225. /**
  50226. Base-class for codecs that can read and write image file formats such
  50227. as PNG, JPEG, etc.
  50228. This class also contains static methods to make it easy to load images
  50229. from files, streams or from memory.
  50230. @see Image, ImageCache
  50231. */
  50232. class JUCE_API ImageFileFormat
  50233. {
  50234. protected:
  50235. /** Creates an ImageFormat. */
  50236. ImageFileFormat() {}
  50237. public:
  50238. /** Destructor. */
  50239. virtual ~ImageFileFormat() {}
  50240. /** Returns a description of this file format.
  50241. E.g. "JPEG", "PNG"
  50242. */
  50243. virtual const String getFormatName() = 0;
  50244. /** Returns true if the given stream seems to contain data that this format
  50245. understands.
  50246. The format class should only read the first few bytes of the stream and sniff
  50247. for header bytes that it understands.
  50248. @see decodeImage
  50249. */
  50250. virtual bool canUnderstand (InputStream& input) = 0;
  50251. /** Tries to decode and return an image from the given stream.
  50252. This will be called for an image format after calling its canUnderStand() method
  50253. to see if it can handle the stream.
  50254. @param input the stream to read the data from. The stream will be positioned
  50255. at the start of the image data (but this may not necessarily
  50256. be position 0)
  50257. @returns the image that was decoded, or an invalid image if it fails.
  50258. @see loadFrom
  50259. */
  50260. virtual const Image decodeImage (InputStream& input) = 0;
  50261. /** Attempts to write an image to a stream.
  50262. To specify extra information like encoding quality, there will be appropriate parameters
  50263. in the subclasses of the specific file types.
  50264. @returns true if it nothing went wrong.
  50265. */
  50266. virtual bool writeImageToStream (const Image& sourceImage,
  50267. OutputStream& destStream) = 0;
  50268. /** Tries the built-in decoders to see if it can find one to read this stream.
  50269. There are currently built-in decoders for PNG, JPEG and GIF formats.
  50270. The object that is returned should not be deleted by the caller.
  50271. @see canUnderstand, decodeImage, loadFrom
  50272. */
  50273. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  50274. /** Tries to load an image from a stream.
  50275. This will use the findImageFormatForStream() method to locate a suitable
  50276. codec, and use that to load the image.
  50277. @returns the image that was decoded, or an invalid image if it fails.
  50278. */
  50279. static const Image loadFrom (InputStream& input);
  50280. /** Tries to load an image from a file.
  50281. This will use the findImageFormatForStream() method to locate a suitable
  50282. codec, and use that to load the image.
  50283. @returns the image that was decoded, or an invalid image if it fails.
  50284. */
  50285. static const Image loadFrom (const File& file);
  50286. /** Tries to load an image from a block of raw image data.
  50287. This will use the findImageFormatForStream() method to locate a suitable
  50288. codec, and use that to load the image.
  50289. @returns the image that was decoded, or an invalid image if it fails.
  50290. */
  50291. static const Image loadFrom (const void* rawData,
  50292. const int numBytesOfData);
  50293. };
  50294. /**
  50295. A subclass of ImageFileFormat for reading and writing PNG files.
  50296. @see ImageFileFormat, JPEGImageFormat
  50297. */
  50298. class JUCE_API PNGImageFormat : public ImageFileFormat
  50299. {
  50300. public:
  50301. PNGImageFormat();
  50302. ~PNGImageFormat();
  50303. const String getFormatName();
  50304. bool canUnderstand (InputStream& input);
  50305. const Image decodeImage (InputStream& input);
  50306. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  50307. };
  50308. /**
  50309. A subclass of ImageFileFormat for reading and writing JPEG files.
  50310. @see ImageFileFormat, PNGImageFormat
  50311. */
  50312. class JUCE_API JPEGImageFormat : public ImageFileFormat
  50313. {
  50314. public:
  50315. JPEGImageFormat();
  50316. ~JPEGImageFormat();
  50317. /** Specifies the quality to be used when writing a JPEG file.
  50318. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  50319. any negative value is "default" quality
  50320. */
  50321. void setQuality (float newQuality);
  50322. const String getFormatName();
  50323. bool canUnderstand (InputStream& input);
  50324. const Image decodeImage (InputStream& input);
  50325. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  50326. private:
  50327. float quality;
  50328. };
  50329. /**
  50330. A subclass of ImageFileFormat for reading GIF files.
  50331. @see ImageFileFormat, PNGImageFormat, JPEGImageFormat
  50332. */
  50333. class JUCE_API GIFImageFormat : public ImageFileFormat
  50334. {
  50335. public:
  50336. GIFImageFormat();
  50337. ~GIFImageFormat();
  50338. const String getFormatName();
  50339. bool canUnderstand (InputStream& input);
  50340. const Image decodeImage (InputStream& input);
  50341. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  50342. };
  50343. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  50344. /*** End of inlined file: juce_ImageFileFormat.h ***/
  50345. #endif
  50346. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  50347. #endif
  50348. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  50349. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  50350. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  50351. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  50352. /**
  50353. A class to take care of the logic involved with the loading/saving of some kind
  50354. of document.
  50355. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  50356. functions you need for documents that get saved to a file, so this class attempts
  50357. to abstract most of the boring stuff.
  50358. Your subclass should just implement all the pure virtual methods, and you can
  50359. then use the higher-level public methods to do the load/save dialogs, to warn the user
  50360. about overwriting files, etc.
  50361. The document object keeps track of whether it has changed since it was last saved or
  50362. loaded, so when you change something, call its changed() method. This will set a
  50363. flag so it knows it needs saving, and will also broadcast a change message using the
  50364. ChangeBroadcaster base class.
  50365. @see ChangeBroadcaster
  50366. */
  50367. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  50368. {
  50369. public:
  50370. /** Creates a FileBasedDocument.
  50371. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  50372. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  50373. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  50374. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  50375. */
  50376. FileBasedDocument (const String& fileExtension,
  50377. const String& fileWildCard,
  50378. const String& openFileDialogTitle,
  50379. const String& saveFileDialogTitle);
  50380. /** Destructor. */
  50381. virtual ~FileBasedDocument();
  50382. /** Returns true if the changed() method has been called since the file was
  50383. last saved or loaded.
  50384. @see resetChangedFlag, changed
  50385. */
  50386. bool hasChangedSinceSaved() const { return changedSinceSave; }
  50387. /** Called to indicate that the document has changed and needs saving.
  50388. This method will also trigger a change message to be sent out using the
  50389. ChangeBroadcaster base class.
  50390. After calling the method, the hasChangedSinceSaved() method will return true, until
  50391. it is reset either by saving to a file or using the resetChangedFlag() method.
  50392. @see hasChangedSinceSaved, resetChangedFlag
  50393. */
  50394. virtual void changed();
  50395. /** Sets the state of the 'changed' flag.
  50396. The 'changed' flag is set to true when the changed() method is called - use this method
  50397. to reset it or to set it without also broadcasting a change message.
  50398. @see changed, hasChangedSinceSaved
  50399. */
  50400. void setChangedFlag (bool hasChanged);
  50401. /** Tries to open a file.
  50402. If the file opens correctly, the document's file (see the getFile() method) is set
  50403. to this new one; if it fails, the document's file is left unchanged, and optionally
  50404. a message box is shown telling the user there was an error.
  50405. @returns true if the new file loaded successfully
  50406. @see loadDocument, loadFromUserSpecifiedFile
  50407. */
  50408. bool loadFrom (const File& fileToLoadFrom,
  50409. bool showMessageOnFailure);
  50410. /** Asks the user for a file and tries to load it.
  50411. This will pop up a dialog box using the title, file extension and
  50412. wildcard specified in the document's constructor, and asks the user
  50413. for a file. If they pick one, the loadFrom() method is used to
  50414. try to load it, optionally showing a message if it fails.
  50415. @returns true if a file was loaded; false if the user cancelled or if they
  50416. picked a file which failed to load correctly
  50417. @see loadFrom
  50418. */
  50419. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  50420. /** A set of possible outcomes of one of the save() methods
  50421. */
  50422. enum SaveResult
  50423. {
  50424. savedOk = 0, /**< indicates that a file was saved successfully. */
  50425. userCancelledSave, /**< indicates that the user aborted the save operation. */
  50426. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  50427. };
  50428. /** Tries to save the document to the last file it was saved or loaded from.
  50429. This will always try to write to the file, even if the document isn't flagged as
  50430. having changed.
  50431. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  50432. true, it will prompt the user to pick a file, as if
  50433. saveAsInteractive() was called.
  50434. @param showMessageOnFailure if true it will show a warning message when if the
  50435. save operation fails
  50436. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  50437. */
  50438. SaveResult save (bool askUserForFileIfNotSpecified,
  50439. bool showMessageOnFailure);
  50440. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  50441. it if they say yes.
  50442. If you've got a document open and want to close it (e.g. to quit the app), this is the
  50443. method to call.
  50444. If the document doesn't need saving it'll return the value savedOk so
  50445. you can go ahead and delete the document.
  50446. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  50447. return savedOk, so again, you can safely delete the document.
  50448. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  50449. close-document operation.
  50450. And if they click "save changes", it'll try to save and either return savedOk, or
  50451. failedToWriteToFile if there was a problem.
  50452. @see save, saveAs, saveAsInteractive
  50453. */
  50454. SaveResult saveIfNeededAndUserAgrees();
  50455. /** Tries to save the document to a specified file.
  50456. If this succeeds, it'll also change the document's internal file (as returned by
  50457. the getFile() method). If it fails, the file will be left unchanged.
  50458. @param newFile the file to try to write to
  50459. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  50460. the user first if they want to overwrite it
  50461. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  50462. use the saveAsInteractive() method to ask the user for a
  50463. filename
  50464. @param showMessageOnFailure if true and the write operation fails, it'll show
  50465. a message box to warn the user
  50466. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  50467. */
  50468. SaveResult saveAs (const File& newFile,
  50469. bool warnAboutOverwritingExistingFiles,
  50470. bool askUserForFileIfNotSpecified,
  50471. bool showMessageOnFailure);
  50472. /** Prompts the user for a filename and tries to save to it.
  50473. This will pop up a dialog box using the title, file extension and
  50474. wildcard specified in the document's constructor, and asks the user
  50475. for a file. If they pick one, the saveAs() method is used to try to save
  50476. to this file.
  50477. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  50478. the user first if they want to overwrite it
  50479. @see saveIfNeededAndUserAgrees, save, saveAs
  50480. */
  50481. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  50482. /** Returns the file that this document was last successfully saved or loaded from.
  50483. When the document object is created, this will be set to File::nonexistent.
  50484. It is changed when one of the load or save methods is used, or when setFile()
  50485. is used to explicitly set it.
  50486. */
  50487. const File getFile() const { return documentFile; }
  50488. /** Sets the file that this document thinks it was loaded from.
  50489. This won't actually load anything - it just changes the file stored internally.
  50490. @see getFile
  50491. */
  50492. void setFile (const File& newFile);
  50493. protected:
  50494. /** Overload this to return the title of the document.
  50495. This is used in message boxes, filenames and file choosers, so it should be
  50496. something sensible.
  50497. */
  50498. virtual const String getDocumentTitle() = 0;
  50499. /** This method should try to load your document from the given file.
  50500. If it fails, it should return an error message. If it succeeds, it should return
  50501. an empty string.
  50502. */
  50503. virtual const String loadDocument (const File& file) = 0;
  50504. /** This method should try to write your document to the given file.
  50505. If it fails, it should return an error message. If it succeeds, it should return
  50506. an empty string.
  50507. */
  50508. virtual const String saveDocument (const File& file) = 0;
  50509. /** This is used for dialog boxes to make them open at the last folder you
  50510. were using.
  50511. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  50512. the last document that was used - you might want to store this value
  50513. in a static variable, or even in your application's properties. It should
  50514. be a global setting rather than a property of this object.
  50515. This method works very well in conjunction with a RecentlyOpenedFilesList
  50516. object to manage your recent-files list.
  50517. As a default value, it's ok to return File::nonexistent, and the document
  50518. object will use a sensible one instead.
  50519. @see RecentlyOpenedFilesList
  50520. */
  50521. virtual const File getLastDocumentOpened() = 0;
  50522. /** This is used for dialog boxes to make them open at the last folder you
  50523. were using.
  50524. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  50525. the last document that was used - you might want to store this value
  50526. in a static variable, or even in your application's properties. It should
  50527. be a global setting rather than a property of this object.
  50528. This method works very well in conjunction with a RecentlyOpenedFilesList
  50529. object to manage your recent-files list.
  50530. @see RecentlyOpenedFilesList
  50531. */
  50532. virtual void setLastDocumentOpened (const File& file) = 0;
  50533. private:
  50534. File documentFile;
  50535. bool changedSinceSave;
  50536. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  50537. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBasedDocument);
  50538. };
  50539. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  50540. /*** End of inlined file: juce_FileBasedDocument.h ***/
  50541. #endif
  50542. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  50543. #endif
  50544. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  50545. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  50546. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  50547. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  50548. /**
  50549. Manages a set of files for use as a list of recently-opened documents.
  50550. This is a handy class for holding your list of recently-opened documents, with
  50551. helpful methods for things like purging any non-existent files, automatically
  50552. adding them to a menu, and making persistence easy.
  50553. @see File, FileBasedDocument
  50554. */
  50555. class JUCE_API RecentlyOpenedFilesList
  50556. {
  50557. public:
  50558. /** Creates an empty list.
  50559. */
  50560. RecentlyOpenedFilesList();
  50561. /** Destructor. */
  50562. ~RecentlyOpenedFilesList();
  50563. /** Sets a limit for the number of files that will be stored in the list.
  50564. When addFile() is called, then if there is no more space in the list, the
  50565. least-recently added file will be dropped.
  50566. @see getMaxNumberOfItems
  50567. */
  50568. void setMaxNumberOfItems (int newMaxNumber);
  50569. /** Returns the number of items that this list will store.
  50570. @see setMaxNumberOfItems
  50571. */
  50572. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  50573. /** Returns the number of files in the list.
  50574. The most recently added file is always at index 0.
  50575. */
  50576. int getNumFiles() const;
  50577. /** Returns one of the files in the list.
  50578. The most recently added file is always at index 0.
  50579. */
  50580. const File getFile (int index) const;
  50581. /** Returns an array of all the absolute pathnames in the list.
  50582. */
  50583. const StringArray& getAllFilenames() const throw() { return files; }
  50584. /** Clears all the files from the list. */
  50585. void clear();
  50586. /** Adds a file to the list.
  50587. The file will be added at index 0. If this file is already in the list, it will
  50588. be moved up to index 0, but a file can only appear once in the list.
  50589. If the list already contains the maximum number of items that is permitted, the
  50590. least-recently added file will be dropped from the end.
  50591. */
  50592. void addFile (const File& file);
  50593. /** Checks each of the files in the list, removing any that don't exist.
  50594. You might want to call this after reloading a list of files, or before putting them
  50595. on a menu.
  50596. */
  50597. void removeNonExistentFiles();
  50598. /** Adds entries to a menu, representing each of the files in the list.
  50599. This is handy for creating an "open recent file..." menu in your app. The
  50600. menu items are numbered consecutively starting with the baseItemId value,
  50601. and can either be added as complete pathnames, or just the last part of the
  50602. filename.
  50603. If dontAddNonExistentFiles is true, then each file will be checked and only those
  50604. that exist will be added.
  50605. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  50606. pointers to file objects. Any files that appear in this list will not be added to the
  50607. menu - the reason for this is that you might have a number of files already open, so
  50608. might not want these to be shown in the menu.
  50609. It returns the number of items that were added.
  50610. */
  50611. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  50612. int baseItemId,
  50613. bool showFullPaths,
  50614. bool dontAddNonExistentFiles,
  50615. const File** filesToAvoid = 0);
  50616. /** Returns a string that encapsulates all the files in the list.
  50617. The string that is returned can later be passed into restoreFromString() in
  50618. order to recreate the list. This is handy for persisting your list, e.g. in
  50619. a PropertiesFile object.
  50620. @see restoreFromString
  50621. */
  50622. const String toString() const;
  50623. /** Restores the list from a previously stringified version of the list.
  50624. Pass in a stringified version created with toString() in order to persist/restore
  50625. your list.
  50626. @see toString
  50627. */
  50628. void restoreFromString (const String& stringifiedVersion);
  50629. private:
  50630. StringArray files;
  50631. int maxNumberOfItems;
  50632. JUCE_LEAK_DETECTOR (RecentlyOpenedFilesList);
  50633. };
  50634. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  50635. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  50636. #endif
  50637. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  50638. #endif
  50639. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  50640. /*** Start of inlined file: juce_SystemClipboard.h ***/
  50641. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  50642. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  50643. /**
  50644. Handles reading/writing to the system's clipboard.
  50645. */
  50646. class JUCE_API SystemClipboard
  50647. {
  50648. public:
  50649. /** Copies a string of text onto the clipboard */
  50650. static void copyTextToClipboard (const String& text);
  50651. /** Gets the current clipboard's contents.
  50652. Obviously this might have come from another app, so could contain
  50653. anything..
  50654. */
  50655. static const String getTextFromClipboard();
  50656. };
  50657. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  50658. /*** End of inlined file: juce_SystemClipboard.h ***/
  50659. #endif
  50660. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  50661. #endif
  50662. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  50663. #endif
  50664. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  50665. /*** Start of inlined file: juce_UnitTest.h ***/
  50666. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  50667. #define __JUCE_UNITTEST_JUCEHEADER__
  50668. class UnitTestRunner;
  50669. /**
  50670. This is a base class for classes that perform a unit test.
  50671. To write a test using this class, your code should look something like this:
  50672. @code
  50673. class MyTest : public UnitTest
  50674. {
  50675. public:
  50676. MyTest() : UnitTest ("Foobar testing") {}
  50677. void runTest()
  50678. {
  50679. beginTest ("Part 1");
  50680. expect (myFoobar.doesSomething());
  50681. expect (myFoobar.doesSomethingElse());
  50682. beginTest ("Part 2");
  50683. expect (myOtherFoobar.doesSomething());
  50684. expect (myOtherFoobar.doesSomethingElse());
  50685. ...etc..
  50686. }
  50687. };
  50688. // Creating a static instance will automatically add the instance to the array
  50689. // returned by UnitTest::getAllTests(), so the test will be included when you call
  50690. // UnitTestRunner::runAllTests()
  50691. static MyTest test;
  50692. @endcode
  50693. To run a test, use the UnitTestRunner class.
  50694. @see UnitTestRunner
  50695. */
  50696. class JUCE_API UnitTest
  50697. {
  50698. public:
  50699. /** Creates a test with the given name. */
  50700. explicit UnitTest (const String& name);
  50701. /** Destructor. */
  50702. virtual ~UnitTest();
  50703. /** Returns the name of the test. */
  50704. const String getName() const throw() { return name; }
  50705. /** Runs the test, using the specified UnitTestRunner.
  50706. You shouldn't need to call this method directly - use
  50707. UnitTestRunner::runTests() instead.
  50708. */
  50709. void performTest (UnitTestRunner* runner);
  50710. /** Returns the set of all UnitTest objects that currently exist. */
  50711. static Array<UnitTest*>& getAllTests();
  50712. /** You can optionally implement this method to set up your test.
  50713. This method will be called before runTest().
  50714. */
  50715. virtual void initialise();
  50716. /** You can optionally implement this method to clear up after your test has been run.
  50717. This method will be called after runTest() has returned.
  50718. */
  50719. virtual void shutdown();
  50720. /** Implement this method in your subclass to actually run your tests.
  50721. The content of your implementation should call beginTest() and expect()
  50722. to perform the tests.
  50723. */
  50724. virtual void runTest() = 0;
  50725. /** Tells the system that a new subsection of tests is beginning.
  50726. This should be called from your runTest() method, and may be called
  50727. as many times as you like, to demarcate different sets of tests.
  50728. */
  50729. void beginTest (const String& testName);
  50730. /** Checks that the result of a test is true, and logs this result.
  50731. In your runTest() method, you should call this method for each condition that
  50732. you want to check, e.g.
  50733. @code
  50734. void runTest()
  50735. {
  50736. beginTest ("basic tests");
  50737. expect (x + y == 2);
  50738. expect (getThing() == someThing);
  50739. ...etc...
  50740. }
  50741. @endcode
  50742. If testResult is true, a pass is logged; if it's false, a failure is logged.
  50743. If the failure message is specified, it will be written to the log if the test fails.
  50744. */
  50745. void expect (bool testResult, const String& failureMessage = String::empty);
  50746. /** Compares two values, and if they don't match, prints out a message containing the
  50747. expected and actual result values.
  50748. */
  50749. template <class ValueType>
  50750. void expectEquals (ValueType actual, ValueType expected, String failureMessage = String::empty)
  50751. {
  50752. const bool result = (actual == expected);
  50753. if (! result)
  50754. {
  50755. if (failureMessage.isNotEmpty())
  50756. failureMessage << " -- ";
  50757. failureMessage << "Expected value: " << expected << ", Actual value: " << actual;
  50758. }
  50759. expect (result, failureMessage);
  50760. }
  50761. /** Writes a message to the test log.
  50762. This can only be called from within your runTest() method.
  50763. */
  50764. void logMessage (const String& message);
  50765. private:
  50766. const String name;
  50767. UnitTestRunner* runner;
  50768. JUCE_DECLARE_NON_COPYABLE (UnitTest);
  50769. };
  50770. /**
  50771. Runs a set of unit tests.
  50772. You can instantiate one of these objects and use it to invoke tests on a set of
  50773. UnitTest objects.
  50774. By using a subclass of UnitTestRunner, you can intercept logging messages and
  50775. perform custom behaviour when each test completes.
  50776. @see UnitTest
  50777. */
  50778. class JUCE_API UnitTestRunner
  50779. {
  50780. public:
  50781. /** */
  50782. UnitTestRunner();
  50783. /** Destructor. */
  50784. virtual ~UnitTestRunner();
  50785. /** Runs a set of tests.
  50786. The tests are performed in order, and the results are logged. To run all the
  50787. registered UnitTest objects that exist, use runAllTests().
  50788. */
  50789. void runTests (const Array<UnitTest*>& tests, bool assertOnFailure);
  50790. /** Runs all the UnitTest objects that currently exist.
  50791. This calls runTests() for all the objects listed in UnitTest::getAllTests().
  50792. */
  50793. void runAllTests (bool assertOnFailure);
  50794. /** Contains the results of a test.
  50795. One of these objects is instantiated each time UnitTest::beginTest() is called, and
  50796. it contains details of the number of subsequent UnitTest::expect() calls that are
  50797. made.
  50798. */
  50799. struct TestResult
  50800. {
  50801. /** The main name of this test (i.e. the name of the UnitTest object being run). */
  50802. String unitTestName;
  50803. /** The name of the current subcategory (i.e. the name that was set when UnitTest::beginTest() was called). */
  50804. String subcategoryName;
  50805. /** The number of UnitTest::expect() calls that succeeded. */
  50806. int passes;
  50807. /** The number of UnitTest::expect() calls that failed. */
  50808. int failures;
  50809. /** A list of messages describing the failed tests. */
  50810. StringArray messages;
  50811. };
  50812. /** Returns the number of TestResult objects that have been performed.
  50813. @see getResult
  50814. */
  50815. int getNumResults() const throw();
  50816. /** Returns one of the TestResult objects that describes a test that has been run.
  50817. @see getNumResults
  50818. */
  50819. const TestResult* getResult (int index) const throw();
  50820. protected:
  50821. /** Called when the list of results changes.
  50822. You can override this to perform some sort of behaviour when results are added.
  50823. */
  50824. virtual void resultsUpdated();
  50825. /** Logs a message about the current test progress.
  50826. By default this just writes the message to the Logger class, but you could override
  50827. this to do something else with the data.
  50828. */
  50829. virtual void logMessage (const String& message);
  50830. private:
  50831. friend class UnitTest;
  50832. UnitTest* currentTest;
  50833. String currentSubCategory;
  50834. OwnedArray <TestResult, CriticalSection> results;
  50835. bool assertOnFailure;
  50836. void beginNewTest (UnitTest* test, const String& subCategory);
  50837. void endTest();
  50838. void addPass();
  50839. void addFail (const String& failureMessage);
  50840. JUCE_DECLARE_NON_COPYABLE (UnitTestRunner);
  50841. };
  50842. #endif // __JUCE_UNITTEST_JUCEHEADER__
  50843. /*** End of inlined file: juce_UnitTest.h ***/
  50844. #endif
  50845. #endif
  50846. /*** End of inlined file: juce_app_includes.h ***/
  50847. #endif
  50848. #if JUCE_MSVC
  50849. #pragma warning (pop)
  50850. #pragma pack (pop)
  50851. #endif
  50852. END_JUCE_NAMESPACE
  50853. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  50854. #ifdef JUCE_NAMESPACE
  50855. // this will obviously save a lot of typing, but can be disabled by
  50856. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  50857. using namespace JUCE_NAMESPACE;
  50858. /* On the Mac, these symbols are defined in the Mac libraries, so
  50859. these macros make it easier to reference them without writing out
  50860. the namespace every time.
  50861. If you run into difficulties where these macros interfere with the contents
  50862. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  50863. the comments in that file for more information.
  50864. */
  50865. #if (JUCE_MAC || JUCE_IOS) && ! JUCE_DONT_DEFINE_MACROS
  50866. #define Component JUCE_NAMESPACE::Component
  50867. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  50868. #define Point JUCE_NAMESPACE::Point
  50869. #define Button JUCE_NAMESPACE::Button
  50870. #endif
  50871. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  50872. it easier to use the juce version explicitly.
  50873. If you run into difficulties where this macro interferes with other 3rd party header
  50874. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  50875. file for more information.
  50876. */
  50877. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  50878. #define Rectangle JUCE_NAMESPACE::Rectangle
  50879. #endif
  50880. #endif
  50881. #endif
  50882. /* Easy autolinking to the right JUCE libraries under win32.
  50883. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  50884. including this header file.
  50885. */
  50886. #if JUCE_MSVC
  50887. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  50888. /** If you want your application to link to Juce as a DLL instead of
  50889. a static library (on win32), just define the JUCE_DLL macro before
  50890. including juce.h
  50891. */
  50892. #ifdef JUCE_DLL
  50893. #if JUCE_DEBUG
  50894. #define AUTOLINKEDLIB "JUCE_debug.lib"
  50895. #else
  50896. #define AUTOLINKEDLIB "JUCE.lib"
  50897. #endif
  50898. #else
  50899. #if JUCE_DEBUG
  50900. #ifdef _WIN64
  50901. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  50902. #else
  50903. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  50904. #endif
  50905. #else
  50906. #ifdef _WIN64
  50907. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  50908. #else
  50909. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  50910. #endif
  50911. #endif
  50912. #endif
  50913. #pragma comment(lib, AUTOLINKEDLIB)
  50914. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  50915. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  50916. #endif
  50917. // Auto-link the other win32 libs that are needed by library calls..
  50918. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  50919. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  50920. // Auto-links to various win32 libs that are needed by library calls..
  50921. #pragma comment(lib, "kernel32.lib")
  50922. #pragma comment(lib, "user32.lib")
  50923. #pragma comment(lib, "shell32.lib")
  50924. #pragma comment(lib, "gdi32.lib")
  50925. #pragma comment(lib, "vfw32.lib")
  50926. #pragma comment(lib, "comdlg32.lib")
  50927. #pragma comment(lib, "winmm.lib")
  50928. #pragma comment(lib, "wininet.lib")
  50929. #pragma comment(lib, "ole32.lib")
  50930. #pragma comment(lib, "oleaut32.lib")
  50931. #pragma comment(lib, "advapi32.lib")
  50932. #pragma comment(lib, "ws2_32.lib")
  50933. #pragma comment(lib, "version.lib")
  50934. #pragma comment(lib, "shlwapi.lib")
  50935. #ifdef _NATIVE_WCHAR_T_DEFINED
  50936. #ifdef _DEBUG
  50937. #pragma comment(lib, "comsuppwd.lib")
  50938. #else
  50939. #pragma comment(lib, "comsuppw.lib")
  50940. #endif
  50941. #else
  50942. #ifdef _DEBUG
  50943. #pragma comment(lib, "comsuppd.lib")
  50944. #else
  50945. #pragma comment(lib, "comsupp.lib")
  50946. #endif
  50947. #endif
  50948. #if JUCE_OPENGL
  50949. #pragma comment(lib, "OpenGL32.Lib")
  50950. #pragma comment(lib, "GlU32.Lib")
  50951. #endif
  50952. #if JUCE_QUICKTIME
  50953. #pragma comment (lib, "QTMLClient.lib")
  50954. #endif
  50955. #if JUCE_USE_CAMERA
  50956. #pragma comment (lib, "Strmiids.lib")
  50957. #pragma comment (lib, "wmvcore.lib")
  50958. #endif
  50959. #if JUCE_DIRECT2D
  50960. #pragma comment (lib, "Dwrite.lib")
  50961. #pragma comment (lib, "D2d1.lib")
  50962. #endif
  50963. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  50964. #endif
  50965. #endif
  50966. #endif
  50967. #endif // __JUCE_JUCEHEADER__
  50968. /*** End of inlined file: juce.h ***/
  50969. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__