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.

67136 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 48
  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. private:
  1682. static double mulexp10 (const double value, int exponent) throw();
  1683. };
  1684. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1685. /*** End of inlined file: juce_CharacterFunctions.h ***/
  1686. #ifndef JUCE_STRING_UTF_TYPE
  1687. #define JUCE_STRING_UTF_TYPE 8
  1688. #endif
  1689. #if JUCE_MSVC
  1690. #pragma warning (push)
  1691. #pragma warning (disable: 4514 4996)
  1692. #endif
  1693. /*** Start of inlined file: juce_Atomic.h ***/
  1694. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1695. #define __JUCE_ATOMIC_JUCEHEADER__
  1696. /**
  1697. Simple class to hold a primitive value and perform atomic operations on it.
  1698. The type used must be a 32 or 64 bit primitive, like an int, pointer, etc.
  1699. There are methods to perform most of the basic atomic operations.
  1700. */
  1701. template <typename Type>
  1702. class Atomic
  1703. {
  1704. public:
  1705. /** Creates a new value, initialised to zero. */
  1706. inline Atomic() throw()
  1707. : value (0)
  1708. {
  1709. }
  1710. /** Creates a new value, with a given initial value. */
  1711. inline Atomic (const Type initialValue) throw()
  1712. : value (initialValue)
  1713. {
  1714. }
  1715. /** Copies another value (atomically). */
  1716. inline Atomic (const Atomic& other) throw()
  1717. : value (other.get())
  1718. {
  1719. }
  1720. /** Destructor. */
  1721. inline ~Atomic() throw()
  1722. {
  1723. // This class can only be used for types which are 32 or 64 bits in size.
  1724. static_jassert (sizeof (Type) == 4 || sizeof (Type) == 8);
  1725. }
  1726. /** Atomically reads and returns the current value. */
  1727. Type get() const throw();
  1728. /** Copies another value onto this one (atomically). */
  1729. inline Atomic& operator= (const Atomic& other) throw() { exchange (other.get()); return *this; }
  1730. /** Copies another value onto this one (atomically). */
  1731. inline Atomic& operator= (const Type newValue) throw() { exchange (newValue); return *this; }
  1732. /** Atomically sets the current value. */
  1733. void set (Type newValue) throw() { exchange (newValue); }
  1734. /** Atomically sets the current value, returning the value that was replaced. */
  1735. Type exchange (Type value) throw();
  1736. /** Atomically adds a number to this value, returning the new value. */
  1737. Type operator+= (Type amountToAdd) throw();
  1738. /** Atomically subtracts a number from this value, returning the new value. */
  1739. Type operator-= (Type amountToSubtract) throw();
  1740. /** Atomically increments this value, returning the new value. */
  1741. Type operator++() throw();
  1742. /** Atomically decrements this value, returning the new value. */
  1743. Type operator--() throw();
  1744. /** Atomically compares this value with a target value, and if it is equal, sets
  1745. this to be equal to a new value.
  1746. This operation is the atomic equivalent of doing this:
  1747. @code
  1748. bool compareAndSetBool (Type newValue, Type valueToCompare)
  1749. {
  1750. if (get() == valueToCompare)
  1751. {
  1752. set (newValue);
  1753. return true;
  1754. }
  1755. return false;
  1756. }
  1757. @endcode
  1758. @returns true if the comparison was true and the value was replaced; false if
  1759. the comparison failed and the value was left unchanged.
  1760. @see compareAndSetValue
  1761. */
  1762. bool compareAndSetBool (Type newValue, Type valueToCompare) throw();
  1763. /** Atomically compares this value with a target value, and if it is equal, sets
  1764. this to be equal to a new value.
  1765. This operation is the atomic equivalent of doing this:
  1766. @code
  1767. Type compareAndSetValue (Type newValue, Type valueToCompare)
  1768. {
  1769. Type oldValue = get();
  1770. if (oldValue == valueToCompare)
  1771. set (newValue);
  1772. return oldValue;
  1773. }
  1774. @endcode
  1775. @returns the old value before it was changed.
  1776. @see compareAndSetBool
  1777. */
  1778. Type compareAndSetValue (Type newValue, Type valueToCompare) throw();
  1779. /** Implements a memory read/write barrier. */
  1780. static void memoryBarrier() throw();
  1781. JUCE_ALIGN(8)
  1782. /** The raw value that this class operates on.
  1783. This is exposed publically in case you need to manipulate it directly
  1784. for performance reasons.
  1785. */
  1786. volatile Type value;
  1787. private:
  1788. static inline Type castFrom32Bit (int32 value) throw() { return *(Type*) &value; }
  1789. static inline Type castFrom64Bit (int64 value) throw() { return *(Type*) &value; }
  1790. static inline int32 castTo32Bit (Type value) throw() { return *(int32*) &value; }
  1791. static inline int64 castTo64Bit (Type value) throw() { return *(int64*) &value; }
  1792. Type operator++ (int); // better to just use pre-increment with atomics..
  1793. Type operator-- (int);
  1794. };
  1795. /*
  1796. The following code is in the header so that the atomics can be inlined where possible...
  1797. */
  1798. #if (JUCE_IOS && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  1799. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  1800. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  1801. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1802. #define JUCE_MAC_ATOMICS_VOLATILE
  1803. #else
  1804. #define JUCE_MAC_ATOMICS_VOLATILE volatile
  1805. #endif
  1806. #if JUCE_PPC || JUCE_IOS
  1807. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  1808. template <typename Type> static Type OSAtomicAdd64Barrier (Type b, JUCE_MAC_ATOMICS_VOLATILE Type* a) throw() { jassertfalse; return *a += b; }
  1809. template <typename Type> static Type OSAtomicIncrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) throw() { jassertfalse; return ++*a; }
  1810. template <typename Type> static Type OSAtomicDecrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) throw() { jassertfalse; return --*a; }
  1811. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, JUCE_MAC_ATOMICS_VOLATILE Type* value) throw()
  1812. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  1813. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1814. #endif
  1815. #elif JUCE_ANDROID
  1816. #define JUCE_ATOMICS_ANDROID 1 // Android atomic functions
  1817. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1818. #elif JUCE_GCC
  1819. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  1820. #if JUCE_IOS
  1821. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1 // (on the iphone, the 64-bit ops will compile but not link)
  1822. #endif
  1823. #else
  1824. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  1825. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  1826. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  1827. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  1828. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  1829. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  1830. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  1831. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  1832. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  1833. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  1834. #define juce_MemoryBarrier _ReadWriteBarrier
  1835. #else
  1836. // (these are defined in juce_win32_Threads.cpp)
  1837. long juce_InterlockedExchange (volatile long* a, long b) throw();
  1838. long juce_InterlockedIncrement (volatile long* a) throw();
  1839. long juce_InterlockedDecrement (volatile long* a) throw();
  1840. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw();
  1841. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw();
  1842. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) throw();
  1843. inline void juce_MemoryBarrier() throw() { long x = 0; juce_InterlockedIncrement (&x); }
  1844. #endif
  1845. #if JUCE_64BIT
  1846. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  1847. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  1848. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  1849. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  1850. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  1851. #else
  1852. // None of these atomics are available in a 32-bit Windows build!!
  1853. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a += b; return old; }
  1854. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a = b; return old; }
  1855. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) throw() { jassertfalse; return ++*a; }
  1856. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) throw() { jassertfalse; return --*a; }
  1857. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1858. #endif
  1859. #endif
  1860. #if JUCE_MSVC
  1861. #pragma warning (push)
  1862. #pragma warning (disable: 4311) // (truncation warning)
  1863. #endif
  1864. template <typename Type>
  1865. inline Type Atomic<Type>::get() const throw()
  1866. {
  1867. #if JUCE_ATOMICS_MAC
  1868. return sizeof (Type) == 4 ? castFrom32Bit ((int32) OSAtomicAdd32Barrier ((int32_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value))
  1869. : castFrom64Bit ((int64) OSAtomicAdd64Barrier ((int64_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value));
  1870. #elif JUCE_ATOMICS_WINDOWS
  1871. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchangeAdd ((volatile long*) &value, (long) 0))
  1872. : castFrom64Bit ((int64) juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0));
  1873. #elif JUCE_ATOMICS_ANDROID
  1874. return value;
  1875. #elif JUCE_ATOMICS_GCC
  1876. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_add_and_fetch ((volatile int32*) &value, 0))
  1877. : castFrom64Bit ((int64) __sync_add_and_fetch ((volatile int64*) &value, 0));
  1878. #endif
  1879. }
  1880. template <typename Type>
  1881. inline Type Atomic<Type>::exchange (const Type newValue) throw()
  1882. {
  1883. #if JUCE_ATOMICS_ANDROID
  1884. return castFrom32Bit (__atomic_swap (castTo32Bit (newValue), (volatile int*) &value));
  1885. #elif JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  1886. Type currentVal = value;
  1887. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  1888. return currentVal;
  1889. #elif JUCE_ATOMICS_WINDOWS
  1890. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue)))
  1891. : castFrom64Bit ((int64) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue)));
  1892. #endif
  1893. }
  1894. template <typename Type>
  1895. inline Type Atomic<Type>::operator+= (const Type amountToAdd) throw()
  1896. {
  1897. #if JUCE_ATOMICS_MAC
  1898. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32Barrier ((int32_t) castTo32Bit (amountToAdd), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1899. : (Type) OSAtomicAdd64Barrier ((int64_t) amountToAdd, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1900. #elif JUCE_ATOMICS_WINDOWS
  1901. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  1902. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  1903. #elif JUCE_ATOMICS_ANDROID
  1904. for (;;)
  1905. {
  1906. const Type oldValue (value);
  1907. const Type newValue (castFrom32Bit (castTo32Bit (oldValue) + castTo32Bit (amountToAdd)));
  1908. if (compareAndSetBool (newValue, oldValue))
  1909. return newValue;
  1910. }
  1911. #elif JUCE_ATOMICS_GCC
  1912. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  1913. #endif
  1914. }
  1915. template <typename Type>
  1916. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) throw()
  1917. {
  1918. return operator+= (juce_negate (amountToSubtract));
  1919. }
  1920. template <typename Type>
  1921. inline Type Atomic<Type>::operator++() throw()
  1922. {
  1923. #if JUCE_ATOMICS_MAC
  1924. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1925. : (Type) OSAtomicIncrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1926. #elif JUCE_ATOMICS_WINDOWS
  1927. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  1928. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  1929. #elif JUCE_ATOMICS_ANDROID
  1930. return (Type) (__atomic_inc ((volatile int*) &value) + 1);
  1931. #elif JUCE_ATOMICS_GCC
  1932. return (Type) __sync_add_and_fetch (&value, 1);
  1933. #endif
  1934. }
  1935. template <typename Type>
  1936. inline Type Atomic<Type>::operator--() throw()
  1937. {
  1938. #if JUCE_ATOMICS_MAC
  1939. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1940. : (Type) OSAtomicDecrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1941. #elif JUCE_ATOMICS_WINDOWS
  1942. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  1943. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  1944. #elif JUCE_ATOMICS_ANDROID
  1945. return (Type) (__atomic_dec ((volatile int*) &value) - 1);
  1946. #elif JUCE_ATOMICS_GCC
  1947. return (Type) __sync_add_and_fetch (&value, -1);
  1948. #endif
  1949. }
  1950. template <typename Type>
  1951. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) throw()
  1952. {
  1953. #if JUCE_ATOMICS_MAC
  1954. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) castTo32Bit (valueToCompare), (int32_t) castTo32Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1955. : OSAtomicCompareAndSwap64Barrier ((int64_t) castTo64Bit (valueToCompare), (int64_t) castTo64Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1956. #elif JUCE_ATOMICS_WINDOWS
  1957. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  1958. #elif JUCE_ATOMICS_ANDROID
  1959. return __atomic_cmpxchg (castTo32Bit (valueToCompare), castTo32Bit (newValue), (volatile int*) &value) == 0;
  1960. #elif JUCE_ATOMICS_GCC
  1961. return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))
  1962. : __sync_bool_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue));
  1963. #endif
  1964. }
  1965. template <typename Type>
  1966. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) throw()
  1967. {
  1968. #if JUCE_ATOMICS_MAC || JUCE_ATOMICS_ANDROID
  1969. for (;;) // Annoying workaround for only having a bool CAS operation..
  1970. {
  1971. if (compareAndSetBool (newValue, valueToCompare))
  1972. return valueToCompare;
  1973. const Type result = value;
  1974. if (result != valueToCompare)
  1975. return result;
  1976. }
  1977. #elif JUCE_ATOMICS_WINDOWS
  1978. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare)))
  1979. : castFrom64Bit ((int64) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare)));
  1980. #elif JUCE_ATOMICS_GCC
  1981. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_val_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)))
  1982. : castFrom64Bit ((int64) __sync_val_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)));
  1983. #endif
  1984. }
  1985. template <typename Type>
  1986. inline void Atomic<Type>::memoryBarrier() throw()
  1987. {
  1988. #if JUCE_ATOMICS_MAC
  1989. OSMemoryBarrier();
  1990. #elif JUCE_ATOMICS_GCC
  1991. __sync_synchronize();
  1992. #elif JUCE_ATOMICS_WINDOWS
  1993. juce_MemoryBarrier();
  1994. #endif
  1995. }
  1996. #if JUCE_MSVC
  1997. #pragma warning (pop)
  1998. #endif
  1999. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2000. /*** End of inlined file: juce_Atomic.h ***/
  2001. /*** Start of inlined file: juce_CharPointer_UTF8.h ***/
  2002. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2003. #define __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2004. /**
  2005. Wraps a pointer to a null-terminated UTF-8 character string, and provides
  2006. various methods to operate on the data.
  2007. @see CharPointer_UTF16, CharPointer_UTF32
  2008. */
  2009. class CharPointer_UTF8
  2010. {
  2011. public:
  2012. typedef char CharType;
  2013. inline explicit CharPointer_UTF8 (const CharType* const rawPointer) throw()
  2014. : data (const_cast <CharType*> (rawPointer))
  2015. {
  2016. }
  2017. inline CharPointer_UTF8 (const CharPointer_UTF8& other) throw()
  2018. : data (other.data)
  2019. {
  2020. }
  2021. inline CharPointer_UTF8& operator= (const CharPointer_UTF8& other) throw()
  2022. {
  2023. data = other.data;
  2024. return *this;
  2025. }
  2026. inline CharPointer_UTF8& operator= (const CharType* text) throw()
  2027. {
  2028. data = const_cast <CharType*> (text);
  2029. return *this;
  2030. }
  2031. /** This is a pointer comparison, it doesn't compare the actual text. */
  2032. inline bool operator== (const CharPointer_UTF8& other) const throw() { return data == other.data; }
  2033. inline bool operator!= (const CharPointer_UTF8& other) const throw() { return data != other.data; }
  2034. inline bool operator<= (const CharPointer_UTF8& other) const throw() { return data <= other.data; }
  2035. inline bool operator< (const CharPointer_UTF8& other) const throw() { return data < other.data; }
  2036. inline bool operator>= (const CharPointer_UTF8& other) const throw() { return data >= other.data; }
  2037. inline bool operator> (const CharPointer_UTF8& other) const throw() { return data > other.data; }
  2038. /** Returns the address that this pointer is pointing to. */
  2039. inline CharType* getAddress() const throw() { return data; }
  2040. /** Returns the address that this pointer is pointing to. */
  2041. inline operator const CharType*() const throw() { return data; }
  2042. /** Returns true if this pointer is pointing to a null character. */
  2043. inline bool isEmpty() const throw() { return *data == 0; }
  2044. /** Returns the unicode character that this pointer is pointing to. */
  2045. juce_wchar operator*() const throw()
  2046. {
  2047. const signed char byte = (signed char) *data;
  2048. if (byte >= 0)
  2049. return byte;
  2050. uint32 n = (uint32) (uint8) byte;
  2051. uint32 mask = 0x7f;
  2052. uint32 bit = 0x40;
  2053. size_t numExtraValues = 0;
  2054. while ((n & bit) != 0 && bit > 0x10)
  2055. {
  2056. mask >>= 1;
  2057. ++numExtraValues;
  2058. bit >>= 1;
  2059. }
  2060. n &= mask;
  2061. for (size_t i = 1; i <= numExtraValues; ++i)
  2062. {
  2063. const juce_wchar nextByte = data [i];
  2064. if ((nextByte & 0xc0) != 0x80)
  2065. break;
  2066. n <<= 6;
  2067. n |= (nextByte & 0x3f);
  2068. }
  2069. return (juce_wchar) n;
  2070. }
  2071. /** Moves this pointer along to the next character in the string. */
  2072. CharPointer_UTF8& operator++() throw()
  2073. {
  2074. const signed char n = (signed char) *data++;
  2075. if (n < 0)
  2076. {
  2077. juce_wchar bit = 0x40;
  2078. while ((n & bit) != 0 && bit > 0x8)
  2079. {
  2080. ++data;
  2081. bit >>= 1;
  2082. }
  2083. }
  2084. return *this;
  2085. }
  2086. /** Moves this pointer back to the previous character in the string. */
  2087. CharPointer_UTF8& operator--() throw()
  2088. {
  2089. const char n = *--data;
  2090. if ((n & 0xc0) == 0xc0)
  2091. {
  2092. int count = 3;
  2093. do
  2094. {
  2095. --data;
  2096. }
  2097. while ((*data & 0xc0) == 0xc0 && --count >= 0);
  2098. }
  2099. return *this;
  2100. }
  2101. /** Returns the character that this pointer is currently pointing to, and then
  2102. advances the pointer to point to the next character. */
  2103. juce_wchar getAndAdvance() throw()
  2104. {
  2105. const signed char byte = (signed char) *data++;
  2106. if (byte >= 0)
  2107. return byte;
  2108. uint32 n = (uint32) (uint8) byte;
  2109. uint32 mask = 0x7f;
  2110. uint32 bit = 0x40;
  2111. int numExtraValues = 0;
  2112. while ((n & bit) != 0 && bit > 0x8)
  2113. {
  2114. mask >>= 1;
  2115. ++numExtraValues;
  2116. bit >>= 1;
  2117. }
  2118. n &= mask;
  2119. while (--numExtraValues >= 0)
  2120. {
  2121. const uint32 nextByte = (uint32) (uint8) *data++;
  2122. if ((nextByte & 0xc0) != 0x80)
  2123. break;
  2124. n <<= 6;
  2125. n |= (nextByte & 0x3f);
  2126. }
  2127. return (juce_wchar) n;
  2128. }
  2129. /** Moves this pointer along to the next character in the string. */
  2130. CharPointer_UTF8 operator++ (int) throw()
  2131. {
  2132. CharPointer_UTF8 temp (*this);
  2133. ++*this;
  2134. return temp;
  2135. }
  2136. /** Moves this pointer forwards by the specified number of characters. */
  2137. void operator+= (int numToSkip) throw()
  2138. {
  2139. if (numToSkip < 0)
  2140. {
  2141. while (++numToSkip <= 0)
  2142. --*this;
  2143. }
  2144. else
  2145. {
  2146. while (--numToSkip >= 0)
  2147. ++*this;
  2148. }
  2149. }
  2150. /** Moves this pointer backwards by the specified number of characters. */
  2151. void operator-= (int numToSkip) throw()
  2152. {
  2153. operator+= (-numToSkip);
  2154. }
  2155. /** Returns the character at a given character index from the start of the string. */
  2156. juce_wchar operator[] (int characterIndex) const throw()
  2157. {
  2158. CharPointer_UTF8 p (*this);
  2159. p += characterIndex;
  2160. return *p;
  2161. }
  2162. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2163. CharPointer_UTF8 operator+ (int numToSkip) const throw()
  2164. {
  2165. CharPointer_UTF8 p (*this);
  2166. p += numToSkip;
  2167. return p;
  2168. }
  2169. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2170. CharPointer_UTF8 operator- (int numToSkip) const throw()
  2171. {
  2172. CharPointer_UTF8 p (*this);
  2173. p += -numToSkip;
  2174. return p;
  2175. }
  2176. /** Returns the number of characters in this string. */
  2177. size_t length() const throw()
  2178. {
  2179. const CharType* d = data;
  2180. size_t count = 0;
  2181. for (;;)
  2182. {
  2183. const uint32 n = (uint32) (uint8) *d++;
  2184. if ((n & 0x80) != 0)
  2185. {
  2186. uint32 bit = 0x40;
  2187. while ((n & bit) != 0)
  2188. {
  2189. ++d;
  2190. bit >>= 1;
  2191. if (bit == 0)
  2192. break; // illegal utf-8 sequence
  2193. }
  2194. }
  2195. else if (n == 0)
  2196. break;
  2197. ++count;
  2198. }
  2199. return count;
  2200. }
  2201. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2202. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  2203. {
  2204. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2205. }
  2206. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2207. size_t lengthUpTo (const CharPointer_UTF8& end) const throw()
  2208. {
  2209. return CharacterFunctions::lengthUpTo (*this, end);
  2210. }
  2211. /** Returns the number of bytes that are used to represent this string.
  2212. This includes the terminating null character.
  2213. */
  2214. size_t sizeInBytes() const throw()
  2215. {
  2216. return strlen (data) + 1;
  2217. }
  2218. /** Returns the number of bytes that would be needed to represent the given
  2219. unicode character in this encoding format.
  2220. */
  2221. static size_t getBytesRequiredFor (const juce_wchar charToWrite) throw()
  2222. {
  2223. size_t num = 1;
  2224. const uint32 c = (uint32) charToWrite;
  2225. if (c >= 0x80)
  2226. {
  2227. ++num;
  2228. if (c >= 0x800)
  2229. {
  2230. ++num;
  2231. if (c >= 0x10000)
  2232. ++num;
  2233. }
  2234. }
  2235. return num;
  2236. }
  2237. /** Returns the number of bytes that would be needed to represent the given
  2238. string in this encoding format.
  2239. The value returned does NOT include the terminating null character.
  2240. */
  2241. template <class CharPointer>
  2242. static size_t getBytesRequiredFor (CharPointer text) throw()
  2243. {
  2244. size_t count = 0;
  2245. juce_wchar n;
  2246. while ((n = text.getAndAdvance()) != 0)
  2247. count += getBytesRequiredFor (n);
  2248. return count;
  2249. }
  2250. /** Returns a pointer to the null character that terminates this string. */
  2251. CharPointer_UTF8 findTerminatingNull() const throw()
  2252. {
  2253. return CharPointer_UTF8 (data + strlen (data));
  2254. }
  2255. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2256. void write (const juce_wchar charToWrite) throw()
  2257. {
  2258. const uint32 c = (uint32) charToWrite;
  2259. if (c >= 0x80)
  2260. {
  2261. int numExtraBytes = 1;
  2262. if (c >= 0x800)
  2263. {
  2264. ++numExtraBytes;
  2265. if (c >= 0x10000)
  2266. ++numExtraBytes;
  2267. }
  2268. *data++ = (CharType) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  2269. while (--numExtraBytes >= 0)
  2270. *data++ = (CharType) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  2271. }
  2272. else
  2273. {
  2274. *data++ = (CharType) c;
  2275. }
  2276. }
  2277. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2278. inline void writeNull() const throw()
  2279. {
  2280. *data = 0;
  2281. }
  2282. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2283. template <typename CharPointer>
  2284. void writeAll (const CharPointer& src) throw()
  2285. {
  2286. CharacterFunctions::copyAll (*this, src);
  2287. }
  2288. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2289. void writeAll (const CharPointer_UTF8& src) throw()
  2290. {
  2291. const CharType* s = src.data;
  2292. while ((*data = *s) != 0)
  2293. {
  2294. ++data;
  2295. ++s;
  2296. }
  2297. }
  2298. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2299. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2300. to the destination buffer before stopping.
  2301. */
  2302. template <typename CharPointer>
  2303. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  2304. {
  2305. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2306. }
  2307. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2308. The maxChars parameter specifies the maximum number of characters that can be
  2309. written to the destination buffer before stopping (including the terminating null).
  2310. */
  2311. template <typename CharPointer>
  2312. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  2313. {
  2314. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2315. }
  2316. /** Compares this string with another one. */
  2317. template <typename CharPointer>
  2318. int compare (const CharPointer& other) const throw()
  2319. {
  2320. return CharacterFunctions::compare (*this, other);
  2321. }
  2322. /** Compares this string with another one, up to a specified number of characters. */
  2323. template <typename CharPointer>
  2324. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  2325. {
  2326. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2327. }
  2328. /** Compares this string with another one. */
  2329. template <typename CharPointer>
  2330. int compareIgnoreCase (const CharPointer& other) const throw()
  2331. {
  2332. return CharacterFunctions::compareIgnoreCase (*this, other);
  2333. }
  2334. /** Compares this string with another one. */
  2335. int compareIgnoreCase (const CharPointer_UTF8& other) const throw()
  2336. {
  2337. #if JUCE_WINDOWS
  2338. return stricmp (data, other.data);
  2339. #else
  2340. return strcasecmp (data, other.data);
  2341. #endif
  2342. }
  2343. /** Compares this string with another one, up to a specified number of characters. */
  2344. template <typename CharPointer>
  2345. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  2346. {
  2347. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2348. }
  2349. /** Compares this string with another one, up to a specified number of characters. */
  2350. int compareIgnoreCaseUpTo (const CharPointer_UTF8& other, const int maxChars) const throw()
  2351. {
  2352. #if JUCE_WINDOWS
  2353. return strnicmp (data, other.data, maxChars);
  2354. #else
  2355. return strncasecmp (data, other.data, maxChars);
  2356. #endif
  2357. }
  2358. /** Returns the character index of a substring, or -1 if it isn't found. */
  2359. template <typename CharPointer>
  2360. int indexOf (const CharPointer& stringToFind) const throw()
  2361. {
  2362. return CharacterFunctions::indexOf (*this, stringToFind);
  2363. }
  2364. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2365. int indexOf (const juce_wchar charToFind) const throw()
  2366. {
  2367. return CharacterFunctions::indexOfChar (*this, charToFind);
  2368. }
  2369. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2370. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  2371. {
  2372. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2373. : CharacterFunctions::indexOfChar (*this, charToFind);
  2374. }
  2375. /** Returns true if the first character of this string is whitespace. */
  2376. bool isWhitespace() const throw() { return *data == ' ' || (*data <= 13 && *data >= 9); }
  2377. /** Returns true if the first character of this string is a digit. */
  2378. bool isDigit() const throw() { return *data >= '0' && *data <= '9'; }
  2379. /** Returns true if the first character of this string is a letter. */
  2380. bool isLetter() const throw() { return CharacterFunctions::isLetter (operator*()) != 0; }
  2381. /** Returns true if the first character of this string is a letter or digit. */
  2382. bool isLetterOrDigit() const throw() { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2383. /** Returns true if the first character of this string is upper-case. */
  2384. bool isUpperCase() const throw() { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2385. /** Returns true if the first character of this string is lower-case. */
  2386. bool isLowerCase() const throw() { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2387. /** Returns an upper-case version of the first character of this string. */
  2388. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (operator*()); }
  2389. /** Returns a lower-case version of the first character of this string. */
  2390. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (operator*()); }
  2391. /** Parses this string as a 32-bit integer. */
  2392. int getIntValue32() const throw() { return atoi (data); }
  2393. /** Parses this string as a 64-bit integer. */
  2394. int64 getIntValue64() const throw()
  2395. {
  2396. #if JUCE_LINUX || JUCE_ANDROID
  2397. return atoll (data);
  2398. #elif JUCE_WINDOWS
  2399. return _atoi64 (data);
  2400. #else
  2401. return CharacterFunctions::getIntValue <int64, CharPointer_UTF8> (*this);
  2402. #endif
  2403. }
  2404. /** Parses this string as a floating point double. */
  2405. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  2406. /** Returns the first non-whitespace character in the string. */
  2407. CharPointer_UTF8 findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  2408. /** Returns true if the given unicode character can be represented in this encoding. */
  2409. static bool canRepresent (juce_wchar character) throw()
  2410. {
  2411. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  2412. }
  2413. /** Returns true if this data contains a valid string in this encoding. */
  2414. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2415. {
  2416. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2417. {
  2418. const signed char byte = (signed char) *dataToTest;
  2419. if (byte < 0)
  2420. {
  2421. uint32 n = (uint32) (uint8) byte;
  2422. uint32 mask = 0x7f;
  2423. uint32 bit = 0x40;
  2424. int numExtraValues = 0;
  2425. while ((n & bit) != 0)
  2426. {
  2427. if (bit <= 0x10)
  2428. return false;
  2429. mask >>= 1;
  2430. ++numExtraValues;
  2431. bit >>= 1;
  2432. }
  2433. n &= mask;
  2434. while (--numExtraValues >= 0)
  2435. {
  2436. const uint32 nextByte = (uint32) (uint8) *dataToTest++;
  2437. if ((nextByte & 0xc0) != 0x80)
  2438. return false;
  2439. }
  2440. }
  2441. }
  2442. return true;
  2443. }
  2444. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2445. CharPointer_UTF8 atomicSwap (const CharPointer_UTF8& newValue)
  2446. {
  2447. return CharPointer_UTF8 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2448. }
  2449. /** These values are the byte-order-mark (BOM) values for a UTF-8 stream. */
  2450. enum
  2451. {
  2452. byteOrderMark1 = 0xef,
  2453. byteOrderMark2 = 0xbb,
  2454. byteOrderMark3 = 0xbf
  2455. };
  2456. private:
  2457. CharType* data;
  2458. };
  2459. #endif // __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2460. /*** End of inlined file: juce_CharPointer_UTF8.h ***/
  2461. /*** Start of inlined file: juce_CharPointer_UTF16.h ***/
  2462. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2463. #define __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2464. /**
  2465. Wraps a pointer to a null-terminated UTF-16 character string, and provides
  2466. various methods to operate on the data.
  2467. @see CharPointer_UTF8, CharPointer_UTF32
  2468. */
  2469. class CharPointer_UTF16
  2470. {
  2471. public:
  2472. #if JUCE_NATIVE_WCHAR_IS_UTF16
  2473. typedef wchar_t CharType;
  2474. #else
  2475. typedef int16 CharType;
  2476. #endif
  2477. inline explicit CharPointer_UTF16 (const CharType* const rawPointer) throw()
  2478. : data (const_cast <CharType*> (rawPointer))
  2479. {
  2480. }
  2481. inline CharPointer_UTF16 (const CharPointer_UTF16& other) throw()
  2482. : data (other.data)
  2483. {
  2484. }
  2485. inline CharPointer_UTF16& operator= (const CharPointer_UTF16& other) throw()
  2486. {
  2487. data = other.data;
  2488. return *this;
  2489. }
  2490. inline CharPointer_UTF16& operator= (const CharType* text) throw()
  2491. {
  2492. data = const_cast <CharType*> (text);
  2493. return *this;
  2494. }
  2495. /** This is a pointer comparison, it doesn't compare the actual text. */
  2496. inline bool operator== (const CharPointer_UTF16& other) const throw() { return data == other.data; }
  2497. inline bool operator!= (const CharPointer_UTF16& other) const throw() { return data != other.data; }
  2498. inline bool operator<= (const CharPointer_UTF16& other) const throw() { return data <= other.data; }
  2499. inline bool operator< (const CharPointer_UTF16& other) const throw() { return data < other.data; }
  2500. inline bool operator>= (const CharPointer_UTF16& other) const throw() { return data >= other.data; }
  2501. inline bool operator> (const CharPointer_UTF16& other) const throw() { return data > other.data; }
  2502. /** Returns the address that this pointer is pointing to. */
  2503. inline CharType* getAddress() const throw() { return data; }
  2504. /** Returns the address that this pointer is pointing to. */
  2505. inline operator const CharType*() const throw() { return data; }
  2506. /** Returns true if this pointer is pointing to a null character. */
  2507. inline bool isEmpty() const throw() { return *data == 0; }
  2508. /** Returns the unicode character that this pointer is pointing to. */
  2509. juce_wchar operator*() const throw()
  2510. {
  2511. uint32 n = (uint32) (uint16) *data;
  2512. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) data[1]) >= 0xdc00)
  2513. n = 0x10000 + (((n - 0xd800) << 10) | (((uint32) (uint16) data[1]) - 0xdc00));
  2514. return (juce_wchar) n;
  2515. }
  2516. /** Moves this pointer along to the next character in the string. */
  2517. CharPointer_UTF16& operator++() throw()
  2518. {
  2519. const juce_wchar n = *data++;
  2520. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2521. ++data;
  2522. return *this;
  2523. }
  2524. /** Moves this pointer back to the previous character in the string. */
  2525. CharPointer_UTF16& operator--() throw()
  2526. {
  2527. const juce_wchar n = *--data;
  2528. if (n >= 0xdc00 && n <= 0xdfff)
  2529. --data;
  2530. return *this;
  2531. }
  2532. /** Returns the character that this pointer is currently pointing to, and then
  2533. advances the pointer to point to the next character. */
  2534. juce_wchar getAndAdvance() throw()
  2535. {
  2536. uint32 n = (uint32) (uint16) *data++;
  2537. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2538. n = 0x10000 + ((((n - 0xd800) << 10) | (((uint32) (uint16) *data++) - 0xdc00)));
  2539. return (juce_wchar) n;
  2540. }
  2541. /** Moves this pointer along to the next character in the string. */
  2542. CharPointer_UTF16 operator++ (int) throw()
  2543. {
  2544. CharPointer_UTF16 temp (*this);
  2545. ++*this;
  2546. return temp;
  2547. }
  2548. /** Moves this pointer forwards by the specified number of characters. */
  2549. void operator+= (int numToSkip) throw()
  2550. {
  2551. if (numToSkip < 0)
  2552. {
  2553. while (++numToSkip <= 0)
  2554. --*this;
  2555. }
  2556. else
  2557. {
  2558. while (--numToSkip >= 0)
  2559. ++*this;
  2560. }
  2561. }
  2562. /** Moves this pointer backwards by the specified number of characters. */
  2563. void operator-= (int numToSkip) throw()
  2564. {
  2565. operator+= (-numToSkip);
  2566. }
  2567. /** Returns the character at a given character index from the start of the string. */
  2568. juce_wchar operator[] (const int characterIndex) const throw()
  2569. {
  2570. CharPointer_UTF16 p (*this);
  2571. p += characterIndex;
  2572. return *p;
  2573. }
  2574. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2575. CharPointer_UTF16 operator+ (const int numToSkip) const throw()
  2576. {
  2577. CharPointer_UTF16 p (*this);
  2578. p += numToSkip;
  2579. return p;
  2580. }
  2581. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2582. CharPointer_UTF16 operator- (const int numToSkip) const throw()
  2583. {
  2584. CharPointer_UTF16 p (*this);
  2585. p += -numToSkip;
  2586. return p;
  2587. }
  2588. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2589. void write (juce_wchar charToWrite) throw()
  2590. {
  2591. if (charToWrite >= 0x10000)
  2592. {
  2593. charToWrite -= 0x10000;
  2594. *data++ = (CharType) (0xd800 + (charToWrite >> 10));
  2595. *data++ = (CharType) (0xdc00 + (charToWrite & 0x3ff));
  2596. }
  2597. else
  2598. {
  2599. *data++ = (CharType) charToWrite;
  2600. }
  2601. }
  2602. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2603. inline void writeNull() const throw()
  2604. {
  2605. *data = 0;
  2606. }
  2607. /** Returns the number of characters in this string. */
  2608. size_t length() const throw()
  2609. {
  2610. const CharType* d = data;
  2611. size_t count = 0;
  2612. for (;;)
  2613. {
  2614. const int n = *d++;
  2615. if (n >= 0xd800 && n <= 0xdfff)
  2616. {
  2617. if (*d++ == 0)
  2618. break;
  2619. }
  2620. else if (n == 0)
  2621. break;
  2622. ++count;
  2623. }
  2624. return count;
  2625. }
  2626. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2627. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  2628. {
  2629. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2630. }
  2631. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2632. size_t lengthUpTo (const CharPointer_UTF16& end) const throw()
  2633. {
  2634. return CharacterFunctions::lengthUpTo (*this, end);
  2635. }
  2636. /** Returns the number of bytes that are used to represent this string.
  2637. This includes the terminating null character.
  2638. */
  2639. size_t sizeInBytes() const throw()
  2640. {
  2641. return sizeof (CharType) * (findNullIndex (data) + 1);
  2642. }
  2643. /** Returns the number of bytes that would be needed to represent the given
  2644. unicode character in this encoding format.
  2645. */
  2646. static size_t getBytesRequiredFor (const juce_wchar charToWrite) throw()
  2647. {
  2648. return (charToWrite >= 0x10000) ? (sizeof (CharType) * 2) : sizeof (CharType);
  2649. }
  2650. /** Returns the number of bytes that would be needed to represent the given
  2651. string in this encoding format.
  2652. The value returned does NOT include the terminating null character.
  2653. */
  2654. template <class CharPointer>
  2655. static size_t getBytesRequiredFor (CharPointer text) throw()
  2656. {
  2657. size_t count = 0;
  2658. juce_wchar n;
  2659. while ((n = text.getAndAdvance()) != 0)
  2660. count += getBytesRequiredFor (n);
  2661. return count;
  2662. }
  2663. /** Returns a pointer to the null character that terminates this string. */
  2664. CharPointer_UTF16 findTerminatingNull() const throw()
  2665. {
  2666. const CharType* t = data;
  2667. while (*t != 0)
  2668. ++t;
  2669. return CharPointer_UTF16 (t);
  2670. }
  2671. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2672. template <typename CharPointer>
  2673. void writeAll (const CharPointer& src) throw()
  2674. {
  2675. CharacterFunctions::copyAll (*this, src);
  2676. }
  2677. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2678. void writeAll (const CharPointer_UTF16& src) throw()
  2679. {
  2680. const CharType* s = src.data;
  2681. while ((*data = *s) != 0)
  2682. {
  2683. ++data;
  2684. ++s;
  2685. }
  2686. }
  2687. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2688. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2689. to the destination buffer before stopping.
  2690. */
  2691. template <typename CharPointer>
  2692. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  2693. {
  2694. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2695. }
  2696. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2697. The maxChars parameter specifies the maximum number of characters that can be
  2698. written to the destination buffer before stopping (including the terminating null).
  2699. */
  2700. template <typename CharPointer>
  2701. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  2702. {
  2703. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2704. }
  2705. /** Compares this string with another one. */
  2706. template <typename CharPointer>
  2707. int compare (const CharPointer& other) const throw()
  2708. {
  2709. return CharacterFunctions::compare (*this, other);
  2710. }
  2711. /** Compares this string with another one, up to a specified number of characters. */
  2712. template <typename CharPointer>
  2713. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  2714. {
  2715. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2716. }
  2717. /** Compares this string with another one. */
  2718. template <typename CharPointer>
  2719. int compareIgnoreCase (const CharPointer& other) const throw()
  2720. {
  2721. return CharacterFunctions::compareIgnoreCase (*this, other);
  2722. }
  2723. /** Compares this string with another one, up to a specified number of characters. */
  2724. template <typename CharPointer>
  2725. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  2726. {
  2727. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2728. }
  2729. #if JUCE_WINDOWS && ! DOXYGEN
  2730. int compareIgnoreCase (const CharPointer_UTF16& other) const throw()
  2731. {
  2732. return _wcsicmp (data, other.data);
  2733. }
  2734. int compareIgnoreCaseUpTo (const CharPointer_UTF16& other, int maxChars) const throw()
  2735. {
  2736. return _wcsnicmp (data, other.data, maxChars);
  2737. }
  2738. int indexOf (const CharPointer_UTF16& stringToFind) const throw()
  2739. {
  2740. const CharType* const t = wcsstr (data, stringToFind.getAddress());
  2741. return t == 0 ? -1 : (int) (t - data);
  2742. }
  2743. #endif
  2744. /** Returns the character index of a substring, or -1 if it isn't found. */
  2745. template <typename CharPointer>
  2746. int indexOf (const CharPointer& stringToFind) const throw()
  2747. {
  2748. return CharacterFunctions::indexOf (*this, stringToFind);
  2749. }
  2750. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2751. int indexOf (const juce_wchar charToFind) const throw()
  2752. {
  2753. return CharacterFunctions::indexOfChar (*this, charToFind);
  2754. }
  2755. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2756. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  2757. {
  2758. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2759. : CharacterFunctions::indexOfChar (*this, charToFind);
  2760. }
  2761. /** Returns true if the first character of this string is whitespace. */
  2762. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (operator*()) != 0; }
  2763. /** Returns true if the first character of this string is a digit. */
  2764. bool isDigit() const throw() { return CharacterFunctions::isDigit (operator*()) != 0; }
  2765. /** Returns true if the first character of this string is a letter. */
  2766. bool isLetter() const throw() { return CharacterFunctions::isLetter (operator*()) != 0; }
  2767. /** Returns true if the first character of this string is a letter or digit. */
  2768. bool isLetterOrDigit() const throw() { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2769. /** Returns true if the first character of this string is upper-case. */
  2770. bool isUpperCase() const throw() { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2771. /** Returns true if the first character of this string is lower-case. */
  2772. bool isLowerCase() const throw() { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2773. /** Returns an upper-case version of the first character of this string. */
  2774. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (operator*()); }
  2775. /** Returns a lower-case version of the first character of this string. */
  2776. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (operator*()); }
  2777. /** Parses this string as a 32-bit integer. */
  2778. int getIntValue32() const throw()
  2779. {
  2780. #if JUCE_WINDOWS
  2781. return _wtoi (data);
  2782. #else
  2783. return CharacterFunctions::getIntValue <int, CharPointer_UTF16> (*this);
  2784. #endif
  2785. }
  2786. /** Parses this string as a 64-bit integer. */
  2787. int64 getIntValue64() const throw()
  2788. {
  2789. #if JUCE_WINDOWS
  2790. return _wtoi64 (data);
  2791. #else
  2792. return CharacterFunctions::getIntValue <int64, CharPointer_UTF16> (*this);
  2793. #endif
  2794. }
  2795. /** Parses this string as a floating point double. */
  2796. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  2797. /** Returns the first non-whitespace character in the string. */
  2798. CharPointer_UTF16 findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  2799. /** Returns true if the given unicode character can be represented in this encoding. */
  2800. static bool canRepresent (juce_wchar character) throw()
  2801. {
  2802. return ((unsigned int) character) < (unsigned int) 0x10ffff
  2803. && (((unsigned int) character) < 0xd800 || ((unsigned int) character) > 0xdfff);
  2804. }
  2805. /** Returns true if this data contains a valid string in this encoding. */
  2806. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2807. {
  2808. maxBytesToRead /= sizeof (CharType);
  2809. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2810. {
  2811. const uint32 n = (uint32) (uint16) *dataToTest++;
  2812. if (n >= 0xd800)
  2813. {
  2814. if (n > 0x10ffff)
  2815. return false;
  2816. if (n <= 0xdfff)
  2817. {
  2818. if (n > 0xdc00)
  2819. return false;
  2820. const uint32 nextChar = (uint32) (uint16) *dataToTest++;
  2821. if (nextChar < 0xdc00 || nextChar > 0xdfff)
  2822. return false;
  2823. }
  2824. }
  2825. }
  2826. return true;
  2827. }
  2828. /** Atomically swaps this pointer for a new value, returning the previous value. */
  2829. CharPointer_UTF16 atomicSwap (const CharPointer_UTF16& newValue)
  2830. {
  2831. return CharPointer_UTF16 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  2832. }
  2833. /** These values are the byte-order-mark (BOM) values for a UTF-16 stream. */
  2834. enum
  2835. {
  2836. byteOrderMarkBE1 = 0xfe,
  2837. byteOrderMarkBE2 = 0xff,
  2838. byteOrderMarkLE1 = 0xff,
  2839. byteOrderMarkLE2 = 0xfe
  2840. };
  2841. private:
  2842. CharType* data;
  2843. static int findNullIndex (const CharType* const t) throw()
  2844. {
  2845. int n = 0;
  2846. while (t[n] != 0)
  2847. ++n;
  2848. return n;
  2849. }
  2850. };
  2851. #endif // __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2852. /*** End of inlined file: juce_CharPointer_UTF16.h ***/
  2853. /*** Start of inlined file: juce_CharPointer_UTF32.h ***/
  2854. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2855. #define __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2856. /**
  2857. Wraps a pointer to a null-terminated UTF-32 character string, and provides
  2858. various methods to operate on the data.
  2859. @see CharPointer_UTF8, CharPointer_UTF16
  2860. */
  2861. class CharPointer_UTF32
  2862. {
  2863. public:
  2864. typedef juce_wchar CharType;
  2865. inline explicit CharPointer_UTF32 (const CharType* const rawPointer) throw()
  2866. : data (const_cast <CharType*> (rawPointer))
  2867. {
  2868. }
  2869. inline CharPointer_UTF32 (const CharPointer_UTF32& other) throw()
  2870. : data (other.data)
  2871. {
  2872. }
  2873. inline CharPointer_UTF32& operator= (const CharPointer_UTF32& other) throw()
  2874. {
  2875. data = other.data;
  2876. return *this;
  2877. }
  2878. inline CharPointer_UTF32& operator= (const CharType* text) throw()
  2879. {
  2880. data = const_cast <CharType*> (text);
  2881. return *this;
  2882. }
  2883. /** This is a pointer comparison, it doesn't compare the actual text. */
  2884. inline bool operator== (const CharPointer_UTF32& other) const throw() { return data == other.data; }
  2885. inline bool operator!= (const CharPointer_UTF32& other) const throw() { return data != other.data; }
  2886. inline bool operator<= (const CharPointer_UTF32& other) const throw() { return data <= other.data; }
  2887. inline bool operator< (const CharPointer_UTF32& other) const throw() { return data < other.data; }
  2888. inline bool operator>= (const CharPointer_UTF32& other) const throw() { return data >= other.data; }
  2889. inline bool operator> (const CharPointer_UTF32& other) const throw() { return data > other.data; }
  2890. /** Returns the address that this pointer is pointing to. */
  2891. inline CharType* getAddress() const throw() { return data; }
  2892. /** Returns the address that this pointer is pointing to. */
  2893. inline operator const CharType*() const throw() { return data; }
  2894. /** Returns true if this pointer is pointing to a null character. */
  2895. inline bool isEmpty() const throw() { return *data == 0; }
  2896. /** Returns the unicode character that this pointer is pointing to. */
  2897. inline juce_wchar operator*() const throw() { return *data; }
  2898. /** Moves this pointer along to the next character in the string. */
  2899. inline CharPointer_UTF32& operator++() throw()
  2900. {
  2901. ++data;
  2902. return *this;
  2903. }
  2904. /** Moves this pointer to the previous character in the string. */
  2905. inline CharPointer_UTF32& operator--() throw()
  2906. {
  2907. --data;
  2908. return *this;
  2909. }
  2910. /** Returns the character that this pointer is currently pointing to, and then
  2911. advances the pointer to point to the next character. */
  2912. inline juce_wchar getAndAdvance() throw() { return *data++; }
  2913. /** Moves this pointer along to the next character in the string. */
  2914. CharPointer_UTF32 operator++ (int) throw()
  2915. {
  2916. CharPointer_UTF32 temp (*this);
  2917. ++data;
  2918. return temp;
  2919. }
  2920. /** Moves this pointer forwards by the specified number of characters. */
  2921. inline void operator+= (const int numToSkip) throw()
  2922. {
  2923. data += numToSkip;
  2924. }
  2925. inline void operator-= (const int numToSkip) throw()
  2926. {
  2927. data -= numToSkip;
  2928. }
  2929. /** Returns the character at a given character index from the start of the string. */
  2930. inline juce_wchar& operator[] (const int characterIndex) const throw()
  2931. {
  2932. return data [characterIndex];
  2933. }
  2934. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2935. CharPointer_UTF32 operator+ (const int numToSkip) const throw()
  2936. {
  2937. return CharPointer_UTF32 (data + numToSkip);
  2938. }
  2939. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2940. CharPointer_UTF32 operator- (const int numToSkip) const throw()
  2941. {
  2942. return CharPointer_UTF32 (data - numToSkip);
  2943. }
  2944. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2945. inline void write (const juce_wchar charToWrite) throw()
  2946. {
  2947. *data++ = charToWrite;
  2948. }
  2949. inline void replaceChar (const juce_wchar newChar) throw()
  2950. {
  2951. *data = newChar;
  2952. }
  2953. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2954. inline void writeNull() const throw()
  2955. {
  2956. *data = 0;
  2957. }
  2958. /** Returns the number of characters in this string. */
  2959. size_t length() const throw()
  2960. {
  2961. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  2962. return wcslen (data);
  2963. #else
  2964. size_t n = 0;
  2965. while (data[n] != 0)
  2966. ++n;
  2967. return n;
  2968. #endif
  2969. }
  2970. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2971. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  2972. {
  2973. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2974. }
  2975. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  2976. size_t lengthUpTo (const CharPointer_UTF32& end) const throw()
  2977. {
  2978. return CharacterFunctions::lengthUpTo (*this, end);
  2979. }
  2980. /** Returns the number of bytes that are used to represent this string.
  2981. This includes the terminating null character.
  2982. */
  2983. size_t sizeInBytes() const throw()
  2984. {
  2985. return sizeof (CharType) * (length() + 1);
  2986. }
  2987. /** Returns the number of bytes that would be needed to represent the given
  2988. unicode character in this encoding format.
  2989. */
  2990. static inline size_t getBytesRequiredFor (const juce_wchar) throw()
  2991. {
  2992. return sizeof (CharType);
  2993. }
  2994. /** Returns the number of bytes that would be needed to represent the given
  2995. string in this encoding format.
  2996. The value returned does NOT include the terminating null character.
  2997. */
  2998. template <class CharPointer>
  2999. static size_t getBytesRequiredFor (const CharPointer& text) throw()
  3000. {
  3001. return sizeof (CharType) * text.length();
  3002. }
  3003. /** Returns a pointer to the null character that terminates this string. */
  3004. CharPointer_UTF32 findTerminatingNull() const throw()
  3005. {
  3006. return CharPointer_UTF32 (data + length());
  3007. }
  3008. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3009. template <typename CharPointer>
  3010. void writeAll (const CharPointer& src) throw()
  3011. {
  3012. CharacterFunctions::copyAll (*this, src);
  3013. }
  3014. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3015. void writeAll (const CharPointer_UTF32& src) throw()
  3016. {
  3017. const CharType* s = src.data;
  3018. while ((*data = *s) != 0)
  3019. {
  3020. ++data;
  3021. ++s;
  3022. }
  3023. }
  3024. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3025. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3026. to the destination buffer before stopping.
  3027. */
  3028. template <typename CharPointer>
  3029. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  3030. {
  3031. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3032. }
  3033. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3034. The maxChars parameter specifies the maximum number of characters that can be
  3035. written to the destination buffer before stopping (including the terminating null).
  3036. */
  3037. template <typename CharPointer>
  3038. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  3039. {
  3040. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3041. }
  3042. /** Compares this string with another one. */
  3043. template <typename CharPointer>
  3044. int compare (const CharPointer& other) const throw()
  3045. {
  3046. return CharacterFunctions::compare (*this, other);
  3047. }
  3048. #if JUCE_NATIVE_WCHAR_IS_UTF32 && ! JUCE_ANDROID
  3049. /** Compares this string with another one. */
  3050. int compare (const CharPointer_UTF32& other) const throw()
  3051. {
  3052. return wcscmp (data, other.data);
  3053. }
  3054. #endif
  3055. /** Compares this string with another one, up to a specified number of characters. */
  3056. template <typename CharPointer>
  3057. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  3058. {
  3059. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3060. }
  3061. /** Compares this string with another one. */
  3062. template <typename CharPointer>
  3063. int compareIgnoreCase (const CharPointer& other) const
  3064. {
  3065. return CharacterFunctions::compareIgnoreCase (*this, other);
  3066. }
  3067. /** Compares this string with another one, up to a specified number of characters. */
  3068. template <typename CharPointer>
  3069. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  3070. {
  3071. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3072. }
  3073. /** Returns the character index of a substring, or -1 if it isn't found. */
  3074. template <typename CharPointer>
  3075. int indexOf (const CharPointer& stringToFind) const throw()
  3076. {
  3077. return CharacterFunctions::indexOf (*this, stringToFind);
  3078. }
  3079. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3080. int indexOf (const juce_wchar charToFind) const throw()
  3081. {
  3082. int i = 0;
  3083. while (data[i] != 0)
  3084. {
  3085. if (data[i] == charToFind)
  3086. return i;
  3087. ++i;
  3088. }
  3089. return -1;
  3090. }
  3091. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3092. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  3093. {
  3094. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3095. : CharacterFunctions::indexOfChar (*this, charToFind);
  3096. }
  3097. /** Returns true if the first character of this string is whitespace. */
  3098. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3099. /** Returns true if the first character of this string is a digit. */
  3100. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3101. /** Returns true if the first character of this string is a letter. */
  3102. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3103. /** Returns true if the first character of this string is a letter or digit. */
  3104. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3105. /** Returns true if the first character of this string is upper-case. */
  3106. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3107. /** Returns true if the first character of this string is lower-case. */
  3108. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3109. /** Returns an upper-case version of the first character of this string. */
  3110. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (*data); }
  3111. /** Returns a lower-case version of the first character of this string. */
  3112. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (*data); }
  3113. /** Parses this string as a 32-bit integer. */
  3114. int getIntValue32() const throw() { return CharacterFunctions::getIntValue <int, CharPointer_UTF32> (*this); }
  3115. /** Parses this string as a 64-bit integer. */
  3116. int64 getIntValue64() const throw() { return CharacterFunctions::getIntValue <int64, CharPointer_UTF32> (*this); }
  3117. /** Parses this string as a floating point double. */
  3118. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  3119. /** Returns the first non-whitespace character in the string. */
  3120. CharPointer_UTF32 findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  3121. /** Returns true if the given unicode character can be represented in this encoding. */
  3122. static bool canRepresent (juce_wchar character) throw()
  3123. {
  3124. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  3125. }
  3126. /** Returns true if this data contains a valid string in this encoding. */
  3127. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3128. {
  3129. maxBytesToRead /= sizeof (CharType);
  3130. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  3131. if (! canRepresent (*dataToTest++))
  3132. return false;
  3133. return true;
  3134. }
  3135. /** Atomically swaps this pointer for a new value, returning the previous value. */
  3136. CharPointer_UTF32 atomicSwap (const CharPointer_UTF32& newValue)
  3137. {
  3138. return CharPointer_UTF32 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  3139. }
  3140. private:
  3141. CharType* data;
  3142. };
  3143. #endif // __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  3144. /*** End of inlined file: juce_CharPointer_UTF32.h ***/
  3145. /*** Start of inlined file: juce_CharPointer_ASCII.h ***/
  3146. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3147. #define __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3148. /**
  3149. Wraps a pointer to a null-terminated ASCII character string, and provides
  3150. various methods to operate on the data.
  3151. A valid ASCII string is assumed to not contain any characters above 127.
  3152. @see CharPointer_UTF8, CharPointer_UTF16, CharPointer_UTF32
  3153. */
  3154. class CharPointer_ASCII
  3155. {
  3156. public:
  3157. typedef char CharType;
  3158. inline explicit CharPointer_ASCII (const CharType* const rawPointer) throw()
  3159. : data (const_cast <CharType*> (rawPointer))
  3160. {
  3161. }
  3162. inline CharPointer_ASCII (const CharPointer_ASCII& other) throw()
  3163. : data (other.data)
  3164. {
  3165. }
  3166. inline CharPointer_ASCII& operator= (const CharPointer_ASCII& other) throw()
  3167. {
  3168. data = other.data;
  3169. return *this;
  3170. }
  3171. inline CharPointer_ASCII& operator= (const CharType* text) throw()
  3172. {
  3173. data = const_cast <CharType*> (text);
  3174. return *this;
  3175. }
  3176. /** This is a pointer comparison, it doesn't compare the actual text. */
  3177. inline bool operator== (const CharPointer_ASCII& other) const throw() { return data == other.data; }
  3178. inline bool operator!= (const CharPointer_ASCII& other) const throw() { return data != other.data; }
  3179. inline bool operator<= (const CharPointer_ASCII& other) const throw() { return data <= other.data; }
  3180. inline bool operator< (const CharPointer_ASCII& other) const throw() { return data < other.data; }
  3181. inline bool operator>= (const CharPointer_ASCII& other) const throw() { return data >= other.data; }
  3182. inline bool operator> (const CharPointer_ASCII& other) const throw() { return data > other.data; }
  3183. /** Returns the address that this pointer is pointing to. */
  3184. inline CharType* getAddress() const throw() { return data; }
  3185. /** Returns the address that this pointer is pointing to. */
  3186. inline operator const CharType*() const throw() { return data; }
  3187. /** Returns true if this pointer is pointing to a null character. */
  3188. inline bool isEmpty() const throw() { return *data == 0; }
  3189. /** Returns the unicode character that this pointer is pointing to. */
  3190. inline juce_wchar operator*() const throw() { return *data; }
  3191. /** Moves this pointer along to the next character in the string. */
  3192. inline CharPointer_ASCII& operator++() throw()
  3193. {
  3194. ++data;
  3195. return *this;
  3196. }
  3197. /** Moves this pointer to the previous character in the string. */
  3198. inline CharPointer_ASCII& operator--() throw()
  3199. {
  3200. --data;
  3201. return *this;
  3202. }
  3203. /** Returns the character that this pointer is currently pointing to, and then
  3204. advances the pointer to point to the next character. */
  3205. inline juce_wchar getAndAdvance() throw() { return *data++; }
  3206. /** Moves this pointer along to the next character in the string. */
  3207. CharPointer_ASCII operator++ (int) throw()
  3208. {
  3209. CharPointer_ASCII temp (*this);
  3210. ++data;
  3211. return temp;
  3212. }
  3213. /** Moves this pointer forwards by the specified number of characters. */
  3214. inline void operator+= (const int numToSkip) throw()
  3215. {
  3216. data += numToSkip;
  3217. }
  3218. inline void operator-= (const int numToSkip) throw()
  3219. {
  3220. data -= numToSkip;
  3221. }
  3222. /** Returns the character at a given character index from the start of the string. */
  3223. inline juce_wchar operator[] (const int characterIndex) const throw()
  3224. {
  3225. return (juce_wchar) (unsigned char) data [characterIndex];
  3226. }
  3227. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  3228. CharPointer_ASCII operator+ (const int numToSkip) const throw()
  3229. {
  3230. return CharPointer_ASCII (data + numToSkip);
  3231. }
  3232. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  3233. CharPointer_ASCII operator- (const int numToSkip) const throw()
  3234. {
  3235. return CharPointer_ASCII (data - numToSkip);
  3236. }
  3237. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  3238. inline void write (const juce_wchar charToWrite) throw()
  3239. {
  3240. *data++ = (char) charToWrite;
  3241. }
  3242. inline void replaceChar (const juce_wchar newChar) throw()
  3243. {
  3244. *data = (char) newChar;
  3245. }
  3246. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  3247. inline void writeNull() const throw()
  3248. {
  3249. *data = 0;
  3250. }
  3251. /** Returns the number of characters in this string. */
  3252. size_t length() const throw()
  3253. {
  3254. return (size_t) strlen (data);
  3255. }
  3256. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  3257. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  3258. {
  3259. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  3260. }
  3261. /** Returns the number of characters in this string, or up to the given end pointer, whichever is lower. */
  3262. size_t lengthUpTo (const CharPointer_ASCII& end) const throw()
  3263. {
  3264. return CharacterFunctions::lengthUpTo (*this, end);
  3265. }
  3266. /** Returns the number of bytes that are used to represent this string.
  3267. This includes the terminating null character.
  3268. */
  3269. size_t sizeInBytes() const throw()
  3270. {
  3271. return length() + 1;
  3272. }
  3273. /** Returns the number of bytes that would be needed to represent the given
  3274. unicode character in this encoding format.
  3275. */
  3276. static inline size_t getBytesRequiredFor (const juce_wchar) throw()
  3277. {
  3278. return 1;
  3279. }
  3280. /** Returns the number of bytes that would be needed to represent the given
  3281. string in this encoding format.
  3282. The value returned does NOT include the terminating null character.
  3283. */
  3284. template <class CharPointer>
  3285. static size_t getBytesRequiredFor (const CharPointer& text) throw()
  3286. {
  3287. return text.length();
  3288. }
  3289. /** Returns a pointer to the null character that terminates this string. */
  3290. CharPointer_ASCII findTerminatingNull() const throw()
  3291. {
  3292. return CharPointer_ASCII (data + length());
  3293. }
  3294. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3295. template <typename CharPointer>
  3296. void writeAll (const CharPointer& src) throw()
  3297. {
  3298. CharacterFunctions::copyAll (*this, src);
  3299. }
  3300. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3301. void writeAll (const CharPointer_ASCII& src) throw()
  3302. {
  3303. strcpy (data, src.data);
  3304. }
  3305. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3306. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3307. to the destination buffer before stopping.
  3308. */
  3309. template <typename CharPointer>
  3310. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  3311. {
  3312. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3313. }
  3314. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3315. The maxChars parameter specifies the maximum number of characters that can be
  3316. written to the destination buffer before stopping (including the terminating null).
  3317. */
  3318. template <typename CharPointer>
  3319. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  3320. {
  3321. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3322. }
  3323. /** Compares this string with another one. */
  3324. template <typename CharPointer>
  3325. int compare (const CharPointer& other) const throw()
  3326. {
  3327. return CharacterFunctions::compare (*this, other);
  3328. }
  3329. /** Compares this string with another one. */
  3330. int compare (const CharPointer_ASCII& other) const throw()
  3331. {
  3332. return strcmp (data, other.data);
  3333. }
  3334. /** Compares this string with another one, up to a specified number of characters. */
  3335. template <typename CharPointer>
  3336. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  3337. {
  3338. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3339. }
  3340. /** Compares this string with another one, up to a specified number of characters. */
  3341. int compareUpTo (const CharPointer_ASCII& other, const int maxChars) const throw()
  3342. {
  3343. return strncmp (data, other.data, (size_t) maxChars);
  3344. }
  3345. /** Compares this string with another one. */
  3346. template <typename CharPointer>
  3347. int compareIgnoreCase (const CharPointer& other) const
  3348. {
  3349. return CharacterFunctions::compareIgnoreCase (*this, other);
  3350. }
  3351. int compareIgnoreCase (const CharPointer_ASCII& other) const
  3352. {
  3353. #if JUCE_WINDOWS
  3354. return stricmp (data, other.data);
  3355. #else
  3356. return strcasecmp (data, other.data);
  3357. #endif
  3358. }
  3359. /** Compares this string with another one, up to a specified number of characters. */
  3360. template <typename CharPointer>
  3361. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  3362. {
  3363. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3364. }
  3365. /** Returns the character index of a substring, or -1 if it isn't found. */
  3366. template <typename CharPointer>
  3367. int indexOf (const CharPointer& stringToFind) const throw()
  3368. {
  3369. return CharacterFunctions::indexOf (*this, stringToFind);
  3370. }
  3371. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3372. int indexOf (const juce_wchar charToFind) const throw()
  3373. {
  3374. int i = 0;
  3375. while (data[i] != 0)
  3376. {
  3377. if (data[i] == (char) charToFind)
  3378. return i;
  3379. ++i;
  3380. }
  3381. return -1;
  3382. }
  3383. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3384. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  3385. {
  3386. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3387. : CharacterFunctions::indexOfChar (*this, charToFind);
  3388. }
  3389. /** Returns true if the first character of this string is whitespace. */
  3390. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3391. /** Returns true if the first character of this string is a digit. */
  3392. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3393. /** Returns true if the first character of this string is a letter. */
  3394. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3395. /** Returns true if the first character of this string is a letter or digit. */
  3396. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3397. /** Returns true if the first character of this string is upper-case. */
  3398. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3399. /** Returns true if the first character of this string is lower-case. */
  3400. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3401. /** Returns an upper-case version of the first character of this string. */
  3402. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (*data); }
  3403. /** Returns a lower-case version of the first character of this string. */
  3404. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (*data); }
  3405. /** Parses this string as a 32-bit integer. */
  3406. int getIntValue32() const throw() { return atoi (data); }
  3407. /** Parses this string as a 64-bit integer. */
  3408. int64 getIntValue64() const throw()
  3409. {
  3410. #if JUCE_LINUX || JUCE_ANDROID
  3411. return atoll (data);
  3412. #elif JUCE_WINDOWS
  3413. return _atoi64 (data);
  3414. #else
  3415. return CharacterFunctions::getIntValue <int64, CharPointer_ASCII> (*this);
  3416. #endif
  3417. }
  3418. /** Parses this string as a floating point double. */
  3419. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  3420. /** Returns the first non-whitespace character in the string. */
  3421. CharPointer_ASCII findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  3422. /** Returns true if the given unicode character can be represented in this encoding. */
  3423. static bool canRepresent (juce_wchar character) throw()
  3424. {
  3425. return ((unsigned int) character) < (unsigned int) 128;
  3426. }
  3427. /** Returns true if this data contains a valid string in this encoding. */
  3428. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3429. {
  3430. while (--maxBytesToRead >= 0)
  3431. {
  3432. if (((signed char) *dataToTest) <= 0)
  3433. return *dataToTest == 0;
  3434. ++dataToTest;
  3435. }
  3436. return true;
  3437. }
  3438. private:
  3439. CharType* data;
  3440. };
  3441. #endif // __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3442. /*** End of inlined file: juce_CharPointer_ASCII.h ***/
  3443. #if JUCE_MSVC
  3444. #pragma warning (pop)
  3445. #endif
  3446. class OutputStream;
  3447. /**
  3448. The JUCE String class!
  3449. Using a reference-counted internal representation, these strings are fast
  3450. and efficient, and there are methods to do just about any operation you'll ever
  3451. dream of.
  3452. @see StringArray, StringPairArray
  3453. */
  3454. class JUCE_API String
  3455. {
  3456. public:
  3457. /** Creates an empty string.
  3458. @see empty
  3459. */
  3460. String() throw();
  3461. /** Creates a copy of another string. */
  3462. String (const String& other) throw();
  3463. /** Creates a string from a zero-terminated ascii text string.
  3464. The string passed-in must not contain any characters with a value above 127, because
  3465. these can't be converted to unicode without knowing the original encoding that was
  3466. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3467. assertion.
  3468. To create strings with extended characters from UTF-8, you should explicitly call
  3469. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3470. use UTF-8 with escape characters in your source code to represent extended characters,
  3471. because there's no other way to represent unicode strings in a way that isn't dependent
  3472. on the compiler, source code editor and platform.
  3473. */
  3474. String (const char* text);
  3475. /** Creates a string from a string of 8-bit ascii characters.
  3476. The string passed-in must not contain any characters with a value above 127, because
  3477. these can't be converted to unicode without knowing the original encoding that was
  3478. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3479. assertion.
  3480. To create strings with extended characters from UTF-8, you should explicitly call
  3481. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3482. use UTF-8 with escape characters in your source code to represent extended characters,
  3483. because there's no other way to represent unicode strings in a way that isn't dependent
  3484. on the compiler, source code editor and platform.
  3485. This will use up the the first maxChars characters of the string (or less if the string
  3486. is actually shorter).
  3487. */
  3488. String (const char* text, size_t maxChars);
  3489. /** Creates a string from a whcar_t character string.
  3490. Depending on the platform, this may be treated as either UTF-32 or UTF-16.
  3491. */
  3492. String (const wchar_t* text);
  3493. /** Creates a string from a whcar_t character string.
  3494. Depending on the platform, this may be treated as either UTF-32 or UTF-16.
  3495. */
  3496. String (const wchar_t* text, size_t maxChars);
  3497. /** Creates a string from a UTF-8 character string */
  3498. String (const CharPointer_UTF8& text);
  3499. /** Creates a string from a UTF-8 character string */
  3500. String (const CharPointer_UTF8& text, size_t maxChars);
  3501. /** Creates a string from a UTF-8 character string */
  3502. String (const CharPointer_UTF8& start, const CharPointer_UTF8& end);
  3503. /** Creates a string from a UTF-16 character string */
  3504. String (const CharPointer_UTF16& text);
  3505. /** Creates a string from a UTF-16 character string */
  3506. String (const CharPointer_UTF16& text, size_t maxChars);
  3507. /** Creates a string from a UTF-16 character string */
  3508. String (const CharPointer_UTF16& start, const CharPointer_UTF16& end);
  3509. /** Creates a string from a UTF-32 character string */
  3510. String (const CharPointer_UTF32& text);
  3511. /** Creates a string from a UTF-32 character string */
  3512. String (const CharPointer_UTF32& text, size_t maxChars);
  3513. /** Creates a string from a UTF-32 character string */
  3514. String (const CharPointer_UTF32& start, const CharPointer_UTF32& end);
  3515. /** Creates a string from an ASCII character string */
  3516. String (const CharPointer_ASCII& text);
  3517. /** Creates a string from a single character. */
  3518. static const String charToString (juce_wchar character);
  3519. /** Destructor. */
  3520. ~String() throw();
  3521. /** This is an empty string that can be used whenever one is needed.
  3522. It's better to use this than String() because it explains what's going on
  3523. and is more efficient.
  3524. */
  3525. static const String empty;
  3526. /** This is the character encoding type used internally to store the string.
  3527. By setting the value of JUCE_STRING_UTF_TYPE to 8, 16, or 32, you can change the
  3528. internal storage format of the String class. UTF-8 uses the least space (if your strings
  3529. contain few extended characters), but call operator[] involves iterating the string to find
  3530. the required index. UTF-32 provides instant random access to its characters, but uses 4 bytes
  3531. per character to store them. UTF-16 uses more space than UTF-8 and is also slow to index,
  3532. but is the native wchar_t format used in Windows.
  3533. It doesn't matter too much which format you pick, because the toUTF8(), toUTF16() and
  3534. toUTF32() methods let you access the string's content in any of the other formats.
  3535. */
  3536. #if (JUCE_STRING_UTF_TYPE == 32)
  3537. typedef CharPointer_UTF32 CharPointerType;
  3538. #elif (JUCE_STRING_UTF_TYPE == 16)
  3539. typedef CharPointer_UTF16 CharPointerType;
  3540. #elif (JUCE_STRING_UTF_TYPE == 8)
  3541. typedef CharPointer_UTF8 CharPointerType;
  3542. #else
  3543. #error "You must set the value of JUCE_STRING_UTF_TYPE to be either 8, 16, or 32!"
  3544. #endif
  3545. /** Generates a probably-unique 32-bit hashcode from this string. */
  3546. int hashCode() const throw();
  3547. /** Generates a probably-unique 64-bit hashcode from this string. */
  3548. int64 hashCode64() const throw();
  3549. /** Returns the number of characters in the string. */
  3550. int length() const throw();
  3551. // Assignment and concatenation operators..
  3552. /** Replaces this string's contents with another string. */
  3553. String& operator= (const String& other) throw();
  3554. /** Appends another string at the end of this one. */
  3555. String& operator+= (const String& stringToAppend);
  3556. /** Appends another string at the end of this one. */
  3557. String& operator+= (const char* textToAppend);
  3558. /** Appends another string at the end of this one. */
  3559. String& operator+= (const wchar_t* textToAppend);
  3560. /** Appends a decimal number at the end of this string. */
  3561. String& operator+= (int numberToAppend);
  3562. /** Appends a character at the end of this string. */
  3563. String& operator+= (char characterToAppend);
  3564. /** Appends a character at the end of this string. */
  3565. String& operator+= (wchar_t characterToAppend);
  3566. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  3567. /** Appends a character at the end of this string. */
  3568. String& operator+= (juce_wchar characterToAppend);
  3569. #endif
  3570. /** Appends a string to the end of this one.
  3571. @param textToAppend the string to add
  3572. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3573. */
  3574. void append (const String& textToAppend, size_t maxCharsToTake);
  3575. /** Appends a string to the end of this one.
  3576. @param textToAppend the string to add
  3577. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3578. */
  3579. template <class CharPointer>
  3580. void appendCharPointer (const CharPointer& textToAppend, size_t maxCharsToTake)
  3581. {
  3582. if (textToAppend.getAddress() != 0)
  3583. {
  3584. size_t extraBytesNeeded = 0;
  3585. size_t numChars = 0;
  3586. for (CharPointer t (textToAppend); numChars < maxCharsToTake && ! t.isEmpty();)
  3587. {
  3588. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3589. ++numChars;
  3590. }
  3591. if (numChars > 0)
  3592. {
  3593. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3594. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3595. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeWithCharLimit (textToAppend, (int) (numChars + 1));
  3596. }
  3597. }
  3598. }
  3599. /** Appends a string to the end of this one.
  3600. @param textToAppend the string to add
  3601. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3602. */
  3603. template <class CharPointer>
  3604. void appendCharPointer (const CharPointer& textToAppend)
  3605. {
  3606. if (textToAppend.getAddress() != 0)
  3607. {
  3608. size_t extraBytesNeeded = 0;
  3609. for (CharPointer t (textToAppend); ! t.isEmpty();)
  3610. extraBytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  3611. if (extraBytesNeeded > 0)
  3612. {
  3613. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  3614. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  3615. CharPointerType (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull)).writeAll (textToAppend);
  3616. }
  3617. }
  3618. }
  3619. // Comparison methods..
  3620. /** Returns true if the string contains no characters.
  3621. Note that there's also an isNotEmpty() method to help write readable code.
  3622. @see containsNonWhitespaceChars()
  3623. */
  3624. inline bool isEmpty() const throw() { return text[0] == 0; }
  3625. /** Returns true if the string contains at least one character.
  3626. Note that there's also an isEmpty() method to help write readable code.
  3627. @see containsNonWhitespaceChars()
  3628. */
  3629. inline bool isNotEmpty() const throw() { return text[0] != 0; }
  3630. /** Case-insensitive comparison with another string. */
  3631. bool equalsIgnoreCase (const String& other) const throw();
  3632. /** Case-insensitive comparison with another string. */
  3633. bool equalsIgnoreCase (const wchar_t* other) const throw();
  3634. /** Case-insensitive comparison with another string. */
  3635. bool equalsIgnoreCase (const char* other) const throw();
  3636. /** Case-sensitive comparison with another string.
  3637. @returns 0 if the two strings are identical; negative if this string comes before
  3638. the other one alphabetically, or positive if it comes after it.
  3639. */
  3640. int compare (const String& other) const throw();
  3641. /** Case-sensitive comparison with another string.
  3642. @returns 0 if the two strings are identical; negative if this string comes before
  3643. the other one alphabetically, or positive if it comes after it.
  3644. */
  3645. int compare (const char* other) const throw();
  3646. /** Case-sensitive comparison with another string.
  3647. @returns 0 if the two strings are identical; negative if this string comes before
  3648. the other one alphabetically, or positive if it comes after it.
  3649. */
  3650. int compare (const wchar_t* other) const throw();
  3651. /** Case-insensitive comparison with another string.
  3652. @returns 0 if the two strings are identical; negative if this string comes before
  3653. the other one alphabetically, or positive if it comes after it.
  3654. */
  3655. int compareIgnoreCase (const String& other) const throw();
  3656. /** Lexicographic comparison with another string.
  3657. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  3658. characters, making it good for sorting human-readable strings.
  3659. @returns 0 if the two strings are identical; negative if this string comes before
  3660. the other one alphabetically, or positive if it comes after it.
  3661. */
  3662. int compareLexicographically (const String& other) const throw();
  3663. /** Tests whether the string begins with another string.
  3664. If the parameter is an empty string, this will always return true.
  3665. Uses a case-sensitive comparison.
  3666. */
  3667. bool startsWith (const String& text) const throw();
  3668. /** Tests whether the string begins with a particular character.
  3669. If the character is 0, this will always return false.
  3670. Uses a case-sensitive comparison.
  3671. */
  3672. bool startsWithChar (juce_wchar character) const throw();
  3673. /** Tests whether the string begins with another string.
  3674. If the parameter is an empty string, this will always return true.
  3675. Uses a case-insensitive comparison.
  3676. */
  3677. bool startsWithIgnoreCase (const String& text) const throw();
  3678. /** Tests whether the string ends with another string.
  3679. If the parameter is an empty string, this will always return true.
  3680. Uses a case-sensitive comparison.
  3681. */
  3682. bool endsWith (const String& text) const throw();
  3683. /** Tests whether the string ends with a particular character.
  3684. If the character is 0, this will always return false.
  3685. Uses a case-sensitive comparison.
  3686. */
  3687. bool endsWithChar (juce_wchar character) const throw();
  3688. /** Tests whether the string ends with another string.
  3689. If the parameter is an empty string, this will always return true.
  3690. Uses a case-insensitive comparison.
  3691. */
  3692. bool endsWithIgnoreCase (const String& text) const throw();
  3693. /** Tests whether the string contains another substring.
  3694. If the parameter is an empty string, this will always return true.
  3695. Uses a case-sensitive comparison.
  3696. */
  3697. bool contains (const String& text) const throw();
  3698. /** Tests whether the string contains a particular character.
  3699. Uses a case-sensitive comparison.
  3700. */
  3701. bool containsChar (juce_wchar character) const throw();
  3702. /** Tests whether the string contains another substring.
  3703. Uses a case-insensitive comparison.
  3704. */
  3705. bool containsIgnoreCase (const String& text) const throw();
  3706. /** Tests whether the string contains another substring as a distict word.
  3707. @returns true if the string contains this word, surrounded by
  3708. non-alphanumeric characters
  3709. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3710. */
  3711. bool containsWholeWord (const String& wordToLookFor) const throw();
  3712. /** Tests whether the string contains another substring as a distict word.
  3713. @returns true if the string contains this word, surrounded by
  3714. non-alphanumeric characters
  3715. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3716. */
  3717. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  3718. /** Finds an instance of another substring if it exists as a distict word.
  3719. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3720. then this will return the index of the start of the substring. If it isn't
  3721. found, then it will return -1
  3722. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3723. */
  3724. int indexOfWholeWord (const String& wordToLookFor) const throw();
  3725. /** Finds an instance of another substring if it exists as a distict word.
  3726. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3727. then this will return the index of the start of the substring. If it isn't
  3728. found, then it will return -1
  3729. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3730. */
  3731. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  3732. /** Looks for any of a set of characters in the string.
  3733. Uses a case-sensitive comparison.
  3734. @returns true if the string contains any of the characters from
  3735. the string that is passed in.
  3736. */
  3737. bool containsAnyOf (const String& charactersItMightContain) const throw();
  3738. /** Looks for a set of characters in the string.
  3739. Uses a case-sensitive comparison.
  3740. @returns Returns false if any of the characters in this string do not occur in
  3741. the parameter string. If this string is empty, the return value will
  3742. always be true.
  3743. */
  3744. bool containsOnly (const String& charactersItMightContain) const throw();
  3745. /** Returns true if this string contains any non-whitespace characters.
  3746. This will return false if the string contains only whitespace characters, or
  3747. if it's empty.
  3748. It is equivalent to calling "myString.trim().isNotEmpty()".
  3749. */
  3750. bool containsNonWhitespaceChars() const throw();
  3751. /** Returns true if the string matches this simple wildcard expression.
  3752. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  3753. This isn't a full-blown regex though! The only wildcard characters supported
  3754. are "*" and "?". It's mainly intended for filename pattern matching.
  3755. */
  3756. bool matchesWildcard (const String& wildcard, bool ignoreCase) const throw();
  3757. // Substring location methods..
  3758. /** Searches for a character inside this string.
  3759. Uses a case-sensitive comparison.
  3760. @returns the index of the first occurrence of the character in this
  3761. string, or -1 if it's not found.
  3762. */
  3763. int indexOfChar (juce_wchar characterToLookFor) const throw();
  3764. /** Searches for a character inside this string.
  3765. Uses a case-sensitive comparison.
  3766. @param startIndex the index from which the search should proceed
  3767. @param characterToLookFor the character to look for
  3768. @returns the index of the first occurrence of the character in this
  3769. string, or -1 if it's not found.
  3770. */
  3771. int indexOfChar (int startIndex, juce_wchar characterToLookFor) const throw();
  3772. /** Returns the index of the first character that matches one of the characters
  3773. passed-in to this method.
  3774. This scans the string, beginning from the startIndex supplied, and if it finds
  3775. a character that appears in the string charactersToLookFor, it returns its index.
  3776. If none of these characters are found, it returns -1.
  3777. If ignoreCase is true, the comparison will be case-insensitive.
  3778. @see indexOfChar, lastIndexOfAnyOf
  3779. */
  3780. int indexOfAnyOf (const String& charactersToLookFor,
  3781. int startIndex = 0,
  3782. bool ignoreCase = false) const throw();
  3783. /** Searches for a substring within this string.
  3784. Uses a case-sensitive comparison.
  3785. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3786. If textToLookFor is an empty string, this will always return 0.
  3787. */
  3788. int indexOf (const String& textToLookFor) const throw();
  3789. /** Searches for a substring within this string.
  3790. Uses a case-sensitive comparison.
  3791. @param startIndex the index from which the search should proceed
  3792. @param textToLookFor the string to search for
  3793. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3794. If textToLookFor is an empty string, this will always return -1.
  3795. */
  3796. int indexOf (int startIndex, const String& textToLookFor) const throw();
  3797. /** Searches for a substring within this string.
  3798. Uses a case-insensitive comparison.
  3799. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3800. If textToLookFor is an empty string, this will always return 0.
  3801. */
  3802. int indexOfIgnoreCase (const String& textToLookFor) const throw();
  3803. /** Searches for a substring within this string.
  3804. Uses a case-insensitive comparison.
  3805. @param startIndex the index from which the search should proceed
  3806. @param textToLookFor the string to search for
  3807. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3808. If textToLookFor is an empty string, this will always return -1.
  3809. */
  3810. int indexOfIgnoreCase (int startIndex, const String& textToLookFor) const throw();
  3811. /** Searches for a character inside this string (working backwards from the end of the string).
  3812. Uses a case-sensitive comparison.
  3813. @returns the index of the last occurrence of the character in this string, or -1 if it's not found.
  3814. */
  3815. int lastIndexOfChar (juce_wchar character) const throw();
  3816. /** Searches for a substring inside this string (working backwards from the end of the string).
  3817. Uses a case-sensitive comparison.
  3818. @returns the index of the start of the last occurrence of the substring within this string,
  3819. or -1 if it's not found. If textToLookFor is an empty string, this will always return -1.
  3820. */
  3821. int lastIndexOf (const String& textToLookFor) const throw();
  3822. /** Searches for a substring inside this string (working backwards from the end of the string).
  3823. Uses a case-insensitive comparison.
  3824. @returns the index of the start of the last occurrence of the substring within this string, or -1
  3825. if it's not found. If textToLookFor is an empty string, this will always return -1.
  3826. */
  3827. int lastIndexOfIgnoreCase (const String& textToLookFor) const throw();
  3828. /** Returns the index of the last character in this string that matches one of the
  3829. characters passed-in to this method.
  3830. This scans the string backwards, starting from its end, and if it finds
  3831. a character that appears in the string charactersToLookFor, it returns its index.
  3832. If none of these characters are found, it returns -1.
  3833. If ignoreCase is true, the comparison will be case-insensitive.
  3834. @see lastIndexOf, indexOfAnyOf
  3835. */
  3836. int lastIndexOfAnyOf (const String& charactersToLookFor,
  3837. bool ignoreCase = false) const throw();
  3838. // Substring extraction and manipulation methods..
  3839. /** Returns the character at this index in the string.
  3840. In a release build, no checks are made to see if the index is within a valid range, so be
  3841. careful! In a debug build, the index is checked and an assertion fires if it's out-of-range.
  3842. Also beware that depending on the encoding format that the string is using internally, this
  3843. method may execute in either O(1) or O(n) time, so be careful when using it in your algorithms.
  3844. If you're scanning through a string to inspect its characters, you should never use this operator
  3845. for random access, it's far more efficient to call getCharPointer() to return a pointer, and
  3846. then to use that to iterate the string.
  3847. @see getCharPointer
  3848. */
  3849. const juce_wchar operator[] (int index) const throw();
  3850. /** Returns the final character of the string.
  3851. If the string is empty this will return 0.
  3852. */
  3853. juce_wchar getLastCharacter() const throw();
  3854. /** Returns a subsection of the string.
  3855. If the range specified is beyond the limits of the string, as much as
  3856. possible is returned.
  3857. @param startIndex the index of the start of the substring needed
  3858. @param endIndex all characters from startIndex up to (but not including)
  3859. this index are returned
  3860. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  3861. */
  3862. const String substring (int startIndex, int endIndex) const;
  3863. /** Returns a section of the string, starting from a given position.
  3864. @param startIndex the first character to include. If this is beyond the end
  3865. of the string, an empty string is returned. If it is zero or
  3866. less, the whole string is returned.
  3867. @returns the substring from startIndex up to the end of the string
  3868. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  3869. */
  3870. const String substring (int startIndex) const;
  3871. /** Returns a version of this string with a number of characters removed
  3872. from the end.
  3873. @param numberToDrop the number of characters to drop from the end of the
  3874. string. If this is greater than the length of the string,
  3875. an empty string will be returned. If zero or less, the
  3876. original string will be returned.
  3877. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  3878. */
  3879. const String dropLastCharacters (int numberToDrop) const;
  3880. /** Returns a number of characters from the end of the string.
  3881. This returns the last numCharacters characters from the end of the string. If the
  3882. string is shorter than numCharacters, the whole string is returned.
  3883. @see substring, dropLastCharacters, getLastCharacter
  3884. */
  3885. const String getLastCharacters (int numCharacters) const;
  3886. /** Returns a section of the string starting from a given substring.
  3887. This will search for the first occurrence of the given substring, and
  3888. return the section of the string starting from the point where this is
  3889. found (optionally not including the substring itself).
  3890. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  3891. fromFirstOccurrenceOf ("34", false) would return "56".
  3892. If the substring isn't found, the method will return an empty string.
  3893. If ignoreCase is true, the comparison will be case-insensitive.
  3894. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  3895. */
  3896. const String fromFirstOccurrenceOf (const String& substringToStartFrom,
  3897. bool includeSubStringInResult,
  3898. bool ignoreCase) const;
  3899. /** Returns a section of the string starting from the last occurrence of a given substring.
  3900. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  3901. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  3902. return the whole of the original string.
  3903. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  3904. */
  3905. const String fromLastOccurrenceOf (const String& substringToFind,
  3906. bool includeSubStringInResult,
  3907. bool ignoreCase) const;
  3908. /** Returns the start of this string, up to the first occurrence of a substring.
  3909. This will search for the first occurrence of a given substring, and then
  3910. return a copy of the string, up to the position of this substring,
  3911. optionally including or excluding the substring itself in the result.
  3912. e.g. for the string "123456", upTo ("34", false) would return "12", and
  3913. upTo ("34", true) would return "1234".
  3914. If the substring isn't found, this will return the whole of the original string.
  3915. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  3916. */
  3917. const String upToFirstOccurrenceOf (const String& substringToEndWith,
  3918. bool includeSubStringInResult,
  3919. bool ignoreCase) const;
  3920. /** Returns the start of this string, up to the last occurrence of a substring.
  3921. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  3922. If the substring isn't found, this will return the whole of the original string.
  3923. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  3924. */
  3925. const String upToLastOccurrenceOf (const String& substringToFind,
  3926. bool includeSubStringInResult,
  3927. bool ignoreCase) const;
  3928. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  3929. const String trim() const;
  3930. /** Returns a copy of this string with any whitespace characters removed from the start. */
  3931. const String trimStart() const;
  3932. /** Returns a copy of this string with any whitespace characters removed from the end. */
  3933. const String trimEnd() const;
  3934. /** Returns a copy of this string, having removed a specified set of characters from its start.
  3935. Characters are removed from the start of the string until it finds one that is not in the
  3936. specified set, and then it stops.
  3937. @param charactersToTrim the set of characters to remove.
  3938. @see trim, trimStart, trimCharactersAtEnd
  3939. */
  3940. const String trimCharactersAtStart (const String& charactersToTrim) const;
  3941. /** Returns a copy of this string, having removed a specified set of characters from its end.
  3942. Characters are removed from the end of the string until it finds one that is not in the
  3943. specified set, and then it stops.
  3944. @param charactersToTrim the set of characters to remove.
  3945. @see trim, trimEnd, trimCharactersAtStart
  3946. */
  3947. const String trimCharactersAtEnd (const String& charactersToTrim) const;
  3948. /** Returns an upper-case version of this string. */
  3949. const String toUpperCase() const;
  3950. /** Returns an lower-case version of this string. */
  3951. const String toLowerCase() const;
  3952. /** Replaces a sub-section of the string with another string.
  3953. This will return a copy of this string, with a set of characters
  3954. from startIndex to startIndex + numCharsToReplace removed, and with
  3955. a new string inserted in their place.
  3956. Note that this is a const method, and won't alter the string itself.
  3957. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  3958. it will be constrained to a valid range.
  3959. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  3960. characters will be taken out.
  3961. @param stringToInsert the new string to insert at startIndex after the characters have been
  3962. removed.
  3963. */
  3964. const String replaceSection (int startIndex,
  3965. int numCharactersToReplace,
  3966. const String& stringToInsert) const;
  3967. /** Replaces all occurrences of a substring with another string.
  3968. Returns a copy of this string, with any occurrences of stringToReplace
  3969. swapped for stringToInsertInstead.
  3970. Note that this is a const method, and won't alter the string itself.
  3971. */
  3972. const String replace (const String& stringToReplace,
  3973. const String& stringToInsertInstead,
  3974. bool ignoreCase = false) const;
  3975. /** Returns a string with all occurrences of a character replaced with a different one. */
  3976. const String replaceCharacter (juce_wchar characterToReplace,
  3977. juce_wchar characterToInsertInstead) const;
  3978. /** Replaces a set of characters with another set.
  3979. Returns a string in which each character from charactersToReplace has been replaced
  3980. by the character at the equivalent position in newCharacters (so the two strings
  3981. passed in must be the same length).
  3982. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  3983. Note that this is a const method, and won't affect the string itself.
  3984. */
  3985. const String replaceCharacters (const String& charactersToReplace,
  3986. const String& charactersToInsertInstead) const;
  3987. /** Returns a version of this string that only retains a fixed set of characters.
  3988. This will return a copy of this string, omitting any characters which are not
  3989. found in the string passed-in.
  3990. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  3991. Note that this is a const method, and won't alter the string itself.
  3992. */
  3993. const String retainCharacters (const String& charactersToRetain) const;
  3994. /** Returns a version of this string with a set of characters removed.
  3995. This will return a copy of this string, omitting any characters which are
  3996. found in the string passed-in.
  3997. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  3998. Note that this is a const method, and won't alter the string itself.
  3999. */
  4000. const String removeCharacters (const String& charactersToRemove) const;
  4001. /** Returns a section from the start of the string that only contains a certain set of characters.
  4002. This returns the leftmost section of the string, up to (and not including) the
  4003. first character that doesn't appear in the string passed in.
  4004. */
  4005. const String initialSectionContainingOnly (const String& permittedCharacters) const;
  4006. /** Returns a section from the start of the string that only contains a certain set of characters.
  4007. This returns the leftmost section of the string, up to (and not including) the
  4008. first character that occurs in the string passed in. (If none of the specified
  4009. characters are found in the string, the return value will just be the original string).
  4010. */
  4011. const String initialSectionNotContaining (const String& charactersToStopAt) const;
  4012. /** Checks whether the string might be in quotation marks.
  4013. @returns true if the string begins with a quote character (either a double or single quote).
  4014. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  4015. @see unquoted, quoted
  4016. */
  4017. bool isQuotedString() const;
  4018. /** Removes quotation marks from around the string, (if there are any).
  4019. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  4020. at the ends of the string are not affected. If there aren't any quotes, the original string
  4021. is returned.
  4022. Note that this is a const method, and won't alter the string itself.
  4023. @see isQuotedString, quoted
  4024. */
  4025. const String unquoted() const;
  4026. /** Adds quotation marks around a string.
  4027. This will return a copy of the string with a quote at the start and end, (but won't
  4028. add the quote if there's already one there, so it's safe to call this on strings that
  4029. may already have quotes around them).
  4030. Note that this is a const method, and won't alter the string itself.
  4031. @param quoteCharacter the character to add at the start and end
  4032. @see isQuotedString, unquoted
  4033. */
  4034. const String quoted (juce_wchar quoteCharacter = '"') const;
  4035. /** Creates a string which is a version of a string repeated and joined together.
  4036. @param stringToRepeat the string to repeat
  4037. @param numberOfTimesToRepeat how many times to repeat it
  4038. */
  4039. static const String repeatedString (const String& stringToRepeat,
  4040. int numberOfTimesToRepeat);
  4041. /** Returns a copy of this string with the specified character repeatedly added to its
  4042. beginning until the total length is at least the minimum length specified.
  4043. */
  4044. const String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  4045. /** Returns a copy of this string with the specified character repeatedly added to its
  4046. end until the total length is at least the minimum length specified.
  4047. */
  4048. const String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  4049. /** Creates a string from data in an unknown format.
  4050. This looks at some binary data and tries to guess whether it's Unicode
  4051. or 8-bit characters, then returns a string that represents it correctly.
  4052. Should be able to handle Unicode endianness correctly, by looking at
  4053. the first two bytes.
  4054. */
  4055. static const String createStringFromData (const void* data, int size);
  4056. /** Creates a String from a printf-style parameter list.
  4057. I don't like this method. I don't use it myself, and I recommend avoiding it and
  4058. using the operator<< methods or pretty much anything else instead. It's only provided
  4059. here because of the popular unrest that was stirred-up when I tried to remove it...
  4060. If you're really determined to use it, at least make sure that you never, ever,
  4061. pass any String objects to it as parameters. And bear in mind that internally, depending
  4062. on the platform, it may be using wchar_t or char character types, so that even string
  4063. literals can't be safely used as parameters if you're writing portable code.
  4064. */
  4065. static const String formatted (const String formatString, ... );
  4066. // Numeric conversions..
  4067. /** Creates a string containing this signed 32-bit integer as a decimal number.
  4068. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4069. */
  4070. explicit String (int decimalInteger);
  4071. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  4072. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4073. */
  4074. explicit String (unsigned int decimalInteger);
  4075. /** Creates a string containing this signed 16-bit integer as a decimal number.
  4076. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4077. */
  4078. explicit String (short decimalInteger);
  4079. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  4080. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  4081. */
  4082. explicit String (unsigned short decimalInteger);
  4083. /** Creates a string containing this signed 64-bit integer as a decimal number.
  4084. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4085. */
  4086. explicit String (int64 largeIntegerValue);
  4087. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  4088. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  4089. */
  4090. explicit String (uint64 largeIntegerValue);
  4091. /** Creates a string representing this floating-point number.
  4092. @param floatValue the value to convert to a string
  4093. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4094. decimal places, and will not use exponent notation. If 0 or
  4095. less, it will use exponent notation if necessary.
  4096. @see getDoubleValue, getIntValue
  4097. */
  4098. explicit String (float floatValue,
  4099. int numberOfDecimalPlaces = 0);
  4100. /** Creates a string representing this floating-point number.
  4101. @param doubleValue the value to convert to a string
  4102. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  4103. decimal places, and will not use exponent notation. If 0 or
  4104. less, it will use exponent notation if necessary.
  4105. @see getFloatValue, getIntValue
  4106. */
  4107. explicit String (double doubleValue,
  4108. int numberOfDecimalPlaces = 0);
  4109. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  4110. @returns the value of the string as a 32 bit signed base-10 integer.
  4111. @see getTrailingIntValue, getHexValue32, getHexValue64
  4112. */
  4113. int getIntValue() const throw();
  4114. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  4115. @returns the value of the string as a 64 bit signed base-10 integer.
  4116. */
  4117. int64 getLargeIntValue() const throw();
  4118. /** Parses a decimal number from the end of the string.
  4119. This will look for a value at the end of the string.
  4120. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  4121. Negative numbers are not handled, so "xyz-5" returns 5.
  4122. @see getIntValue
  4123. */
  4124. int getTrailingIntValue() const throw();
  4125. /** Parses this string as a floating point number.
  4126. @returns the value of the string as a 32-bit floating point value.
  4127. @see getDoubleValue
  4128. */
  4129. float getFloatValue() const throw();
  4130. /** Parses this string as a floating point number.
  4131. @returns the value of the string as a 64-bit floating point value.
  4132. @see getFloatValue
  4133. */
  4134. double getDoubleValue() const throw();
  4135. /** Parses the string as a hexadecimal number.
  4136. Non-hexadecimal characters in the string are ignored.
  4137. If the string contains too many characters, then the lowest significant
  4138. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  4139. @returns a 32-bit number which is the value of the string in hex.
  4140. */
  4141. int getHexValue32() const throw();
  4142. /** Parses the string as a hexadecimal number.
  4143. Non-hexadecimal characters in the string are ignored.
  4144. If the string contains too many characters, then the lowest significant
  4145. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  4146. @returns a 64-bit number which is the value of the string in hex.
  4147. */
  4148. int64 getHexValue64() const throw();
  4149. /** Creates a string representing this 32-bit value in hexadecimal. */
  4150. static const String toHexString (int number);
  4151. /** Creates a string representing this 64-bit value in hexadecimal. */
  4152. static const String toHexString (int64 number);
  4153. /** Creates a string representing this 16-bit value in hexadecimal. */
  4154. static const String toHexString (short number);
  4155. /** Creates a string containing a hex dump of a block of binary data.
  4156. @param data the binary data to use as input
  4157. @param size how many bytes of data to use
  4158. @param groupSize how many bytes are grouped together before inserting a
  4159. space into the output. e.g. group size 0 has no spaces,
  4160. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  4161. like "bea1 c2ff".
  4162. */
  4163. static const String toHexString (const unsigned char* data,
  4164. int size,
  4165. int groupSize = 1);
  4166. /** Returns the character pointer currently being used to store this string.
  4167. Because it returns a reference to the string's internal data, the pointer
  4168. that is returned must not be stored anywhere, as it can be deleted whenever the
  4169. string changes.
  4170. */
  4171. inline const CharPointerType& getCharPointer() const throw() { return text; }
  4172. /** Returns a pointer to a UTF-8 version of this string.
  4173. Because it returns a reference to the string's internal data, the pointer
  4174. that is returned must not be stored anywhere, as it can be deleted whenever the
  4175. string changes.
  4176. To find out how many bytes you need to store this string as UTF-8, you can call
  4177. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4178. @see getCharPointer, toUTF16, toUTF32
  4179. */
  4180. const CharPointer_UTF8 toUTF8() const;
  4181. /** Returns a pointer to a UTF-32 version of this string.
  4182. Because it returns a reference to the string's internal data, the pointer
  4183. that is returned must not be stored anywhere, as it can be deleted whenever the
  4184. string changes.
  4185. To find out how many bytes you need to store this string as UTF-16, you can call
  4186. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4187. @see getCharPointer, toUTF8, toUTF32
  4188. */
  4189. CharPointer_UTF16 toUTF16() const;
  4190. /** Returns a pointer to a UTF-32 version of this string.
  4191. Because it returns a reference to the string's internal data, the pointer
  4192. that is returned must not be stored anywhere, as it can be deleted whenever the
  4193. string changes.
  4194. @see getCharPointer, toUTF8, toUTF16
  4195. */
  4196. CharPointer_UTF32 toUTF32() const;
  4197. /** Returns a pointer to a wchar_t version of this string.
  4198. Because it returns a reference to the string's internal data, the pointer
  4199. that is returned must not be stored anywhere, as it can be deleted whenever the
  4200. string changes.
  4201. Bear in mind that the wchar_t type is different on different platforms, so on
  4202. Windows, this will be equivalent to calling toUTF16(), on unix it'll be the same
  4203. as calling toUTF32(), etc.
  4204. @see getCharPointer, toUTF8, toUTF16, toUTF32
  4205. */
  4206. const wchar_t* toWideCharPointer() const;
  4207. /** Creates a String from a UTF-8 encoded buffer.
  4208. If the size is < 0, it'll keep reading until it hits a zero.
  4209. */
  4210. static const String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  4211. /** Returns the number of bytes required to represent this string as UTF8.
  4212. The number returned does NOT include the trailing zero.
  4213. @see toUTF8, copyToUTF8
  4214. */
  4215. int getNumBytesAsUTF8() const throw();
  4216. /** Copies the string to a buffer as UTF-8 characters.
  4217. Returns the number of bytes copied to the buffer, including the terminating null
  4218. character.
  4219. To find out how many bytes you need to store this string as UTF-8, you can call
  4220. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4221. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4222. returns the number of bytes required (including the terminating null character).
  4223. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4224. put in as many as it can while still allowing for a terminating null char at the
  4225. end, and will return the number of bytes that were actually used.
  4226. @see CharPointer_UTF8::writeWithDestByteLimit
  4227. */
  4228. int copyToUTF8 (CharPointer_UTF8::CharType* destBuffer, int maxBufferSizeBytes) const throw();
  4229. /** Copies the string to a buffer as UTF-16 characters.
  4230. Returns the number of bytes copied to the buffer, including the terminating null
  4231. character.
  4232. To find out how many bytes you need to store this string as UTF-16, you can call
  4233. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4234. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4235. returns the number of bytes required (including the terminating null character).
  4236. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4237. put in as many as it can while still allowing for a terminating null char at the
  4238. end, and will return the number of bytes that were actually used.
  4239. @see CharPointer_UTF16::writeWithDestByteLimit
  4240. */
  4241. int copyToUTF16 (CharPointer_UTF16::CharType* destBuffer, int maxBufferSizeBytes) const throw();
  4242. /** Copies the string to a buffer as UTF-16 characters.
  4243. Returns the number of bytes copied to the buffer, including the terminating null
  4244. character.
  4245. To find out how many bytes you need to store this string as UTF-32, you can call
  4246. CharPointer_UTF32::getBytesRequiredFor (myString.getCharPointer())
  4247. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4248. returns the number of bytes required (including the terminating null character).
  4249. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4250. put in as many as it can while still allowing for a terminating null char at the
  4251. end, and will return the number of bytes that were actually used.
  4252. @see CharPointer_UTF32::writeWithDestByteLimit
  4253. */
  4254. int copyToUTF32 (CharPointer_UTF32::CharType* destBuffer, int maxBufferSizeBytes) const throw();
  4255. /** Increases the string's internally allocated storage.
  4256. Although the string's contents won't be affected by this call, it will
  4257. increase the amount of memory allocated internally for the string to grow into.
  4258. If you're about to make a large number of calls to methods such
  4259. as += or <<, it's more efficient to preallocate enough extra space
  4260. beforehand, so that these methods won't have to keep resizing the string
  4261. to append the extra characters.
  4262. @param numBytesNeeded the number of bytes to allocate storage for. If this
  4263. value is less than the currently allocated size, it will
  4264. have no effect.
  4265. */
  4266. void preallocateBytes (size_t numBytesNeeded);
  4267. /** Swaps the contents of this string with another one.
  4268. This is a very fast operation, as no allocation or copying needs to be done.
  4269. */
  4270. void swapWith (String& other) throw();
  4271. /** A helper class to improve performance when concatenating many large strings
  4272. together.
  4273. Because appending one string to another involves measuring the length of
  4274. both strings, repeatedly doing this for many long strings will become
  4275. an exponentially slow operation. This class uses some internal state to
  4276. avoid that, so that each append operation only needs to measure the length
  4277. of the appended string.
  4278. */
  4279. class JUCE_API Concatenator
  4280. {
  4281. public:
  4282. Concatenator (String& stringToAppendTo);
  4283. ~Concatenator();
  4284. void append (const String& s);
  4285. private:
  4286. String& result;
  4287. int nextIndex;
  4288. JUCE_DECLARE_NON_COPYABLE (Concatenator);
  4289. };
  4290. private:
  4291. CharPointerType text;
  4292. struct PreallocationBytes
  4293. {
  4294. explicit PreallocationBytes (size_t);
  4295. size_t numBytes;
  4296. };
  4297. explicit String (const PreallocationBytes&); // This constructor preallocates a certain amount of memory
  4298. void appendFixedLength (const char* text, int numExtraChars);
  4299. size_t getByteOffsetOfEnd() const throw();
  4300. JUCE_DEPRECATED (String (const String& stringToCopy, size_t charsToAllocate));
  4301. // This private cast operator should prevent strings being accidentally cast
  4302. // to bools (this is possible because the compiler can add an implicit cast
  4303. // via a const char*)
  4304. operator bool() const throw() { return false; }
  4305. };
  4306. /** Concatenates two strings. */
  4307. JUCE_API const String JUCE_CALLTYPE operator+ (const char* string1, const String& string2);
  4308. /** Concatenates two strings. */
  4309. JUCE_API const String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2);
  4310. /** Concatenates two strings. */
  4311. JUCE_API const String JUCE_CALLTYPE operator+ (char string1, const String& string2);
  4312. /** Concatenates two strings. */
  4313. JUCE_API const String JUCE_CALLTYPE operator+ (wchar_t string1, const String& string2);
  4314. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4315. /** Concatenates two strings. */
  4316. JUCE_API const String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2);
  4317. #endif
  4318. /** Concatenates two strings. */
  4319. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2);
  4320. /** Concatenates two strings. */
  4321. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* string2);
  4322. /** Concatenates two strings. */
  4323. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2);
  4324. /** Concatenates two strings. */
  4325. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, char characterToAppend);
  4326. /** Concatenates two strings. */
  4327. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, wchar_t characterToAppend);
  4328. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4329. /** Concatenates two strings. */
  4330. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend);
  4331. #endif
  4332. /** Appends a character at the end of a string. */
  4333. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend);
  4334. /** Appends a character at the end of a string. */
  4335. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, wchar_t characterToAppend);
  4336. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  4337. /** Appends a character at the end of a string. */
  4338. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend);
  4339. #endif
  4340. /** Appends a string to the end of the first one. */
  4341. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* string2);
  4342. /** Appends a string to the end of the first one. */
  4343. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const wchar_t* string2);
  4344. /** Appends a string to the end of the first one. */
  4345. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2);
  4346. /** Appends a decimal number at the end of a string. */
  4347. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, short number);
  4348. /** Appends a decimal number at the end of a string. */
  4349. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, int number);
  4350. /** Appends a decimal number at the end of a string. */
  4351. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, long number);
  4352. /** Appends a decimal number at the end of a string. */
  4353. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, float number);
  4354. /** Appends a decimal number at the end of a string. */
  4355. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, double number);
  4356. /** Case-sensitive comparison of two strings. */
  4357. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw();
  4358. /** Case-sensitive comparison of two strings. */
  4359. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw();
  4360. /** Case-sensitive comparison of two strings. */
  4361. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const wchar_t* string2) throw();
  4362. /** Case-sensitive comparison of two strings. */
  4363. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF8& string2) throw();
  4364. /** Case-sensitive comparison of two strings. */
  4365. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF16& string2) throw();
  4366. /** Case-sensitive comparison of two strings. */
  4367. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF32& string2) throw();
  4368. /** Case-sensitive comparison of two strings. */
  4369. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw();
  4370. /** Case-sensitive comparison of two strings. */
  4371. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw();
  4372. /** Case-sensitive comparison of two strings. */
  4373. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const wchar_t* string2) throw();
  4374. /** Case-sensitive comparison of two strings. */
  4375. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8& string2) throw();
  4376. /** Case-sensitive comparison of two strings. */
  4377. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16& string2) throw();
  4378. /** Case-sensitive comparison of two strings. */
  4379. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32& string2) throw();
  4380. /** Case-sensitive comparison of two strings. */
  4381. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw();
  4382. /** Case-sensitive comparison of two strings. */
  4383. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw();
  4384. /** Case-sensitive comparison of two strings. */
  4385. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw();
  4386. /** Case-sensitive comparison of two strings. */
  4387. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw();
  4388. /** This streaming override allows you to pass a juce String directly into std output streams.
  4389. This is very handy for writing strings to std::cout, std::cerr, etc.
  4390. */
  4391. template <class charT, class traits>
  4392. std::basic_ostream <charT, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <charT, traits>& stream, const String& stringToWrite)
  4393. {
  4394. return stream << stringToWrite.toUTF8().getAddress();
  4395. }
  4396. /** Writes a string to an OutputStream as UTF8. */
  4397. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text);
  4398. #endif // __JUCE_STRING_JUCEHEADER__
  4399. /*** End of inlined file: juce_String.h ***/
  4400. /**
  4401. Acts as an application-wide logging class.
  4402. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  4403. method and this will then be used by all calls to writeToLog.
  4404. The logger class also contains methods for writing messages to the debugger's
  4405. output stream.
  4406. @see FileLogger
  4407. */
  4408. class JUCE_API Logger
  4409. {
  4410. public:
  4411. /** Destructor. */
  4412. virtual ~Logger();
  4413. /** Sets the current logging class to use.
  4414. Note that the object passed in won't be deleted when no longer needed.
  4415. A null pointer can be passed-in to disable any logging.
  4416. If deleteOldLogger is set to true, the existing logger will be
  4417. deleted (if there is one).
  4418. */
  4419. static void JUCE_CALLTYPE setCurrentLogger (Logger* newLogger,
  4420. bool deleteOldLogger = false);
  4421. /** Writes a string to the current logger.
  4422. This will pass the string to the logger's logMessage() method if a logger
  4423. has been set.
  4424. @see logMessage
  4425. */
  4426. static void JUCE_CALLTYPE writeToLog (const String& message);
  4427. /** Writes a message to the standard error stream.
  4428. This can be called directly, or by using the DBG() macro in
  4429. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  4430. */
  4431. static void JUCE_CALLTYPE outputDebugString (const String& text);
  4432. protected:
  4433. Logger();
  4434. /** This is overloaded by subclasses to implement custom logging behaviour.
  4435. @see setCurrentLogger
  4436. */
  4437. virtual void logMessage (const String& message) = 0;
  4438. private:
  4439. static Logger* currentLogger;
  4440. };
  4441. #endif // __JUCE_LOGGER_JUCEHEADER__
  4442. /*** End of inlined file: juce_Logger.h ***/
  4443. /*** Start of inlined file: juce_LeakedObjectDetector.h ***/
  4444. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4445. #define __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4446. /**
  4447. Embedding an instance of this class inside another class can be used as a low-overhead
  4448. way of detecting leaked instances.
  4449. This class keeps an internal static count of the number of instances that are
  4450. active, so that when the app is shutdown and the static destructors are called,
  4451. it can check whether there are any left-over instances that may have been leaked.
  4452. To use it, use the JUCE_LEAK_DETECTOR macro as a simple way to put one in your
  4453. class declaration. Have a look through the juce codebase for examples, it's used
  4454. in most of the classes.
  4455. */
  4456. template <class OwnerClass>
  4457. class LeakedObjectDetector
  4458. {
  4459. public:
  4460. LeakedObjectDetector() throw() { ++(getCounter().numObjects); }
  4461. LeakedObjectDetector (const LeakedObjectDetector&) throw() { ++(getCounter().numObjects); }
  4462. ~LeakedObjectDetector()
  4463. {
  4464. if (--(getCounter().numObjects) < 0)
  4465. {
  4466. DBG ("*** Dangling pointer deletion! Class: " << getLeakedObjectClassName());
  4467. /** If you hit this, then you've managed to delete more instances of this class than you've
  4468. created.. That indicates that you're deleting some dangling pointers.
  4469. Note that although this assertion will have been triggered during a destructor, it might
  4470. not be this particular deletion that's at fault - the incorrect one may have happened
  4471. at an earlier point in the program, and simply not been detected until now.
  4472. Most errors like this are caused by using old-fashioned, non-RAII techniques for
  4473. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4474. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4475. */
  4476. jassertfalse;
  4477. }
  4478. }
  4479. private:
  4480. class LeakCounter
  4481. {
  4482. public:
  4483. LeakCounter() throw() {}
  4484. ~LeakCounter()
  4485. {
  4486. if (numObjects.value > 0)
  4487. {
  4488. DBG ("*** Leaked objects detected: " << numObjects.value << " instance(s) of class " << getLeakedObjectClassName());
  4489. /** If you hit this, then you've leaked one or more objects of the type specified by
  4490. the 'OwnerClass' template parameter - the name should have been printed by the line above.
  4491. If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for
  4492. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4493. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4494. */
  4495. jassertfalse;
  4496. }
  4497. }
  4498. Atomic<int> numObjects;
  4499. };
  4500. static const char* getLeakedObjectClassName()
  4501. {
  4502. return OwnerClass::getLeakedObjectClassName();
  4503. }
  4504. static LeakCounter& getCounter() throw()
  4505. {
  4506. static LeakCounter counter;
  4507. return counter;
  4508. }
  4509. };
  4510. #if DOXYGEN || ! defined (JUCE_LEAK_DETECTOR)
  4511. #if (DOXYGEN || JUCE_CHECK_MEMORY_LEAKS)
  4512. /** This macro lets you embed a leak-detecting object inside a class.
  4513. To use it, simply declare a JUCE_LEAK_DETECTOR(YourClassName) inside a private section
  4514. of the class declaration. E.g.
  4515. @code
  4516. class MyClass
  4517. {
  4518. public:
  4519. MyClass();
  4520. void blahBlah();
  4521. private:
  4522. JUCE_LEAK_DETECTOR (MyClass);
  4523. };@endcode
  4524. @see JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR, LeakedObjectDetector
  4525. */
  4526. #define JUCE_LEAK_DETECTOR(OwnerClass) \
  4527. friend class JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass>; \
  4528. static const char* getLeakedObjectClassName() throw() { return #OwnerClass; } \
  4529. JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass> JUCE_JOIN_MACRO (leakDetector, __LINE__);
  4530. #else
  4531. #define JUCE_LEAK_DETECTOR(OwnerClass)
  4532. #endif
  4533. #endif
  4534. #endif // __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4535. /*** End of inlined file: juce_LeakedObjectDetector.h ***/
  4536. END_JUCE_NAMESPACE
  4537. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  4538. /*** End of inlined file: juce_StandardHeader.h ***/
  4539. BEGIN_JUCE_NAMESPACE
  4540. #if JUCE_MSVC
  4541. // this is set explicitly in case the app is using a different packing size.
  4542. #pragma pack (push, 8)
  4543. #pragma warning (push)
  4544. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  4545. #ifdef __INTEL_COMPILER
  4546. #pragma warning (disable: 1125)
  4547. #endif
  4548. #endif
  4549. // this is where all the class header files get brought in..
  4550. /*** Start of inlined file: juce_core_includes.h ***/
  4551. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4552. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4553. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4554. /*** Start of inlined file: juce_AbstractFifo.h ***/
  4555. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4556. #define __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4557. /**
  4558. Encapsulates the logic required to implement a lock-free FIFO.
  4559. This class handles the logic needed when building a single-reader, single-writer FIFO.
  4560. It doesn't actually hold any data itself, but your FIFO class can use one of these to manage
  4561. its position and status when reading or writing to it.
  4562. To use it, you can call prepareToWrite() to determine the position within your own buffer that
  4563. an incoming block of data should be stored, and prepareToRead() to find out when the next
  4564. outgoing block should be read from.
  4565. e.g.
  4566. @code
  4567. class MyFifo
  4568. {
  4569. public:
  4570. MyFifo() : abstractFifo (1024)
  4571. {
  4572. }
  4573. void addToFifo (const int* someData, int numItems)
  4574. {
  4575. int start1, size1, start2, size2;
  4576. prepareToWrite (numItems, start1, size1, start2, size2);
  4577. if (size1 > 0)
  4578. copySomeData (myBuffer + start1, someData, size1);
  4579. if (size2 > 0)
  4580. copySomeData (myBuffer + start2, someData + size1, size2);
  4581. finishedWrite (size1 + size2);
  4582. }
  4583. void readFromFifo (int* someData, int numItems)
  4584. {
  4585. int start1, size1, start2, size2;
  4586. prepareToRead (numSamples, start1, size1, start2, size2);
  4587. if (size1 > 0)
  4588. copySomeData (someData, myBuffer + start1, size1);
  4589. if (size2 > 0)
  4590. copySomeData (someData + size1, myBuffer + start2, size2);
  4591. finishedRead (size1 + size2);
  4592. }
  4593. private:
  4594. AbstractFifo abstractFifo;
  4595. int myBuffer [1024];
  4596. };
  4597. @endcode
  4598. */
  4599. class JUCE_API AbstractFifo
  4600. {
  4601. public:
  4602. /** Creates a FIFO to manage a buffer with the specified capacity. */
  4603. AbstractFifo (int capacity) throw();
  4604. /** Destructor */
  4605. ~AbstractFifo();
  4606. /** Returns the total size of the buffer being managed. */
  4607. int getTotalSize() const throw();
  4608. /** Returns the number of items that can currently be added to the buffer without it overflowing. */
  4609. int getFreeSpace() const throw();
  4610. /** Returns the number of items that can currently be read from the buffer. */
  4611. int getNumReady() const throw();
  4612. /** Clears the buffer positions, so that it appears empty. */
  4613. void reset() throw();
  4614. /** Changes the buffer's total size.
  4615. Note that this isn't thread-safe, so don't call it if there's any danger that it
  4616. might overlap with a call to any other method in this class!
  4617. */
  4618. void setTotalSize (int newSize) throw();
  4619. /** Returns the location within the buffer at which an incoming block of data should be written.
  4620. Because the section of data that you want to add to the buffer may overlap the end
  4621. and wrap around to the start, two blocks within your buffer are returned, and you
  4622. should copy your data into the first one, with any remaining data spilling over into
  4623. the second.
  4624. If the number of items you ask for is too large to fit within the buffer's free space, then
  4625. blockSize1 + blockSize2 may add up to a lower value than numToWrite. If this happens, you
  4626. may decide to keep waiting and re-trying the method until there's enough space available.
  4627. After calling this method, if you choose to write your data into the blocks returned, you
  4628. must call finishedWrite() to tell the FIFO how much data you actually added.
  4629. e.g.
  4630. @code
  4631. void addToFifo (const int* someData, int numItems)
  4632. {
  4633. int start1, size1, start2, size2;
  4634. prepareToWrite (numItems, start1, size1, start2, size2);
  4635. if (size1 > 0)
  4636. copySomeData (myBuffer + start1, someData, size1);
  4637. if (size2 > 0)
  4638. copySomeData (myBuffer + start2, someData + size1, size2);
  4639. finishedWrite (size1 + size2);
  4640. }
  4641. @endcode
  4642. @param numToWrite indicates how many items you'd like to add to the buffer
  4643. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4644. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4645. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4646. the first block should be written
  4647. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4648. @see finishedWrite
  4649. */
  4650. void prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw();
  4651. /** Called after reading from the FIFO, to indicate that this many items have been added.
  4652. @see prepareToWrite
  4653. */
  4654. void finishedWrite (int numWritten) throw();
  4655. /** Returns the location within the buffer from which the next block of data should be read.
  4656. Because the section of data that you want to read from the buffer may overlap the end
  4657. and wrap around to the start, two blocks within your buffer are returned, and you
  4658. should read from both of them.
  4659. If the number of items you ask for is greater than the amount of data available, then
  4660. blockSize1 + blockSize2 may add up to a lower value than numWanted. If this happens, you
  4661. may decide to keep waiting and re-trying the method until there's enough data available.
  4662. After calling this method, if you choose to read the data, you must call finishedRead() to
  4663. tell the FIFO how much data you have consumed.
  4664. e.g.
  4665. @code
  4666. void readFromFifo (int* someData, int numItems)
  4667. {
  4668. int start1, size1, start2, size2;
  4669. prepareToRead (numSamples, start1, size1, start2, size2);
  4670. if (size1 > 0)
  4671. copySomeData (someData, myBuffer + start1, size1);
  4672. if (size2 > 0)
  4673. copySomeData (someData + size1, myBuffer + start2, size2);
  4674. finishedRead (size1 + size2);
  4675. }
  4676. @endcode
  4677. @param numWanted indicates how many items you'd like to add to the buffer
  4678. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4679. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4680. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4681. the first block should be written
  4682. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4683. @see finishedRead
  4684. */
  4685. void prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw();
  4686. /** Called after reading from the FIFO, to indicate that this many items have now been consumed.
  4687. @see prepareToRead
  4688. */
  4689. void finishedRead (int numRead) throw();
  4690. private:
  4691. int bufferSize;
  4692. Atomic <int> validStart, validEnd;
  4693. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AbstractFifo);
  4694. };
  4695. #endif // __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4696. /*** End of inlined file: juce_AbstractFifo.h ***/
  4697. #endif
  4698. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4699. /*** Start of inlined file: juce_Array.h ***/
  4700. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4701. #define __JUCE_ARRAY_JUCEHEADER__
  4702. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  4703. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4704. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4705. /*** Start of inlined file: juce_HeapBlock.h ***/
  4706. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  4707. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  4708. /**
  4709. Very simple container class to hold a pointer to some data on the heap.
  4710. When you need to allocate some heap storage for something, always try to use
  4711. this class instead of allocating the memory directly using malloc/free.
  4712. A HeapBlock<char> object can be treated in pretty much exactly the same way
  4713. as an char*, but as long as you allocate it on the stack or as a class member,
  4714. it's almost impossible for it to leak memory.
  4715. It also makes your code much more concise and readable than doing the same thing
  4716. using direct allocations,
  4717. E.g. instead of this:
  4718. @code
  4719. int* temp = (int*) malloc (1024 * sizeof (int));
  4720. memcpy (temp, xyz, 1024 * sizeof (int));
  4721. free (temp);
  4722. temp = (int*) calloc (2048 * sizeof (int));
  4723. temp[0] = 1234;
  4724. memcpy (foobar, temp, 2048 * sizeof (int));
  4725. free (temp);
  4726. @endcode
  4727. ..you could just write this:
  4728. @code
  4729. HeapBlock <int> temp (1024);
  4730. memcpy (temp, xyz, 1024 * sizeof (int));
  4731. temp.calloc (2048);
  4732. temp[0] = 1234;
  4733. memcpy (foobar, temp, 2048 * sizeof (int));
  4734. @endcode
  4735. The class is extremely lightweight, containing only a pointer to the
  4736. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  4737. as their less object-oriented counterparts. Despite adding safety, you probably
  4738. won't sacrifice any performance by using this in place of normal pointers.
  4739. @see Array, OwnedArray, MemoryBlock
  4740. */
  4741. template <class ElementType>
  4742. class HeapBlock
  4743. {
  4744. public:
  4745. /** Creates a HeapBlock which is initially just a null pointer.
  4746. After creation, you can resize the array using the malloc(), calloc(),
  4747. or realloc() methods.
  4748. */
  4749. HeapBlock() throw() : data (0)
  4750. {
  4751. }
  4752. /** Creates a HeapBlock containing a number of elements.
  4753. The contents of the block are undefined, as it will have been created by a
  4754. malloc call.
  4755. If you want an array of zero values, you can use the calloc() method instead.
  4756. */
  4757. explicit HeapBlock (const size_t numElements)
  4758. : data (static_cast <ElementType*> (::malloc (numElements * sizeof (ElementType))))
  4759. {
  4760. }
  4761. /** Destructor.
  4762. This will free the data, if any has been allocated.
  4763. */
  4764. ~HeapBlock()
  4765. {
  4766. ::free (data);
  4767. }
  4768. /** Returns a raw pointer to the allocated data.
  4769. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4770. freed by calling the free() method.
  4771. */
  4772. inline operator ElementType*() const throw() { return data; }
  4773. /** Returns a raw pointer to the allocated data.
  4774. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4775. freed by calling the free() method.
  4776. */
  4777. inline ElementType* getData() const throw() { return data; }
  4778. /** Returns a void pointer to the allocated data.
  4779. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4780. freed by calling the free() method.
  4781. */
  4782. inline operator void*() const throw() { return static_cast <void*> (data); }
  4783. /** Returns a void pointer to the allocated data.
  4784. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4785. freed by calling the free() method.
  4786. */
  4787. inline operator const void*() const throw() { return static_cast <const void*> (data); }
  4788. /** Lets you use indirect calls to the first element in the array.
  4789. Obviously this will cause problems if the array hasn't been initialised, because it'll
  4790. be referencing a null pointer.
  4791. */
  4792. inline ElementType* operator->() const throw() { return data; }
  4793. /** Returns a reference to one of the data elements.
  4794. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  4795. has no idea of the size it currently has allocated.
  4796. */
  4797. template <typename IndexType>
  4798. inline ElementType& operator[] (IndexType index) const throw() { return data [index]; }
  4799. /** Returns a pointer to a data element at an offset from the start of the array.
  4800. This is the same as doing pointer arithmetic on the raw pointer itself.
  4801. */
  4802. template <typename IndexType>
  4803. inline ElementType* operator+ (IndexType index) const throw() { return data + index; }
  4804. /** Compares the pointer with another pointer.
  4805. This can be handy for checking whether this is a null pointer.
  4806. */
  4807. inline bool operator== (const ElementType* const otherPointer) const throw() { return otherPointer == data; }
  4808. /** Compares the pointer with another pointer.
  4809. This can be handy for checking whether this is a null pointer.
  4810. */
  4811. inline bool operator!= (const ElementType* const otherPointer) const throw() { return otherPointer != data; }
  4812. /** Allocates a specified amount of memory.
  4813. This uses the normal malloc to allocate an amount of memory for this object.
  4814. Any previously allocated memory will be freed by this method.
  4815. The number of bytes allocated will be (newNumElements * elementSize). Normally
  4816. you wouldn't need to specify the second parameter, but it can be handy if you need
  4817. to allocate a size in bytes rather than in terms of the number of elements.
  4818. The data that is allocated will be freed when this object is deleted, or when you
  4819. call free() or any of the allocation methods.
  4820. */
  4821. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4822. {
  4823. ::free (data);
  4824. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4825. }
  4826. /** Allocates a specified amount of memory and clears it.
  4827. This does the same job as the malloc() method, but clears the memory that it allocates.
  4828. */
  4829. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4830. {
  4831. ::free (data);
  4832. data = static_cast <ElementType*> (::calloc (newNumElements, elementSize));
  4833. }
  4834. /** Allocates a specified amount of memory and optionally clears it.
  4835. This does the same job as either malloc() or calloc(), depending on the
  4836. initialiseToZero parameter.
  4837. */
  4838. void allocate (const size_t newNumElements, const bool initialiseToZero)
  4839. {
  4840. ::free (data);
  4841. if (initialiseToZero)
  4842. data = static_cast <ElementType*> (::calloc (newNumElements, sizeof (ElementType)));
  4843. else
  4844. data = static_cast <ElementType*> (::malloc (newNumElements * sizeof (ElementType)));
  4845. }
  4846. /** Re-allocates a specified amount of memory.
  4847. The semantics of this method are the same as malloc() and calloc(), but it
  4848. uses realloc() to keep as much of the existing data as possible.
  4849. */
  4850. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4851. {
  4852. if (data == 0)
  4853. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4854. else
  4855. data = static_cast <ElementType*> (::realloc (data, newNumElements * elementSize));
  4856. }
  4857. /** Frees any currently-allocated data.
  4858. This will free the data and reset this object to be a null pointer.
  4859. */
  4860. void free()
  4861. {
  4862. ::free (data);
  4863. data = 0;
  4864. }
  4865. /** Swaps this object's data with the data of another HeapBlock.
  4866. The two objects simply exchange their data pointers.
  4867. */
  4868. void swapWith (HeapBlock <ElementType>& other) throw()
  4869. {
  4870. swapVariables (data, other.data);
  4871. }
  4872. /** This fills the block with zeros, up to the number of elements specified.
  4873. Since the block has no way of knowing its own size, you must make sure that the number of
  4874. elements you specify doesn't exceed the allocated size.
  4875. */
  4876. void clear (size_t numElements) throw()
  4877. {
  4878. zeromem (data, sizeof (ElementType) * numElements);
  4879. }
  4880. private:
  4881. ElementType* data;
  4882. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HeapBlock);
  4883. };
  4884. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  4885. /*** End of inlined file: juce_HeapBlock.h ***/
  4886. /**
  4887. Implements some basic array storage allocation functions.
  4888. This class isn't really for public use - it's used by the other
  4889. array classes, but might come in handy for some purposes.
  4890. It inherits from a critical section class to allow the arrays to use
  4891. the "empty base class optimisation" pattern to reduce their footprint.
  4892. @see Array, OwnedArray, ReferenceCountedArray
  4893. */
  4894. template <class ElementType, class TypeOfCriticalSectionToUse>
  4895. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  4896. {
  4897. public:
  4898. /** Creates an empty array. */
  4899. ArrayAllocationBase() throw()
  4900. : numAllocated (0)
  4901. {
  4902. }
  4903. /** Destructor. */
  4904. ~ArrayAllocationBase()
  4905. {
  4906. }
  4907. /** Changes the amount of storage allocated.
  4908. This will retain any data currently held in the array, and either add or
  4909. remove extra space at the end.
  4910. @param numElements the number of elements that are needed
  4911. */
  4912. void setAllocatedSize (const int numElements)
  4913. {
  4914. if (numAllocated != numElements)
  4915. {
  4916. if (numElements > 0)
  4917. elements.realloc (numElements);
  4918. else
  4919. elements.free();
  4920. numAllocated = numElements;
  4921. }
  4922. }
  4923. /** Increases the amount of storage allocated if it is less than a given amount.
  4924. This will retain any data currently held in the array, but will add
  4925. extra space at the end to make sure there it's at least as big as the size
  4926. passed in. If it's already bigger, no action is taken.
  4927. @param minNumElements the minimum number of elements that are needed
  4928. */
  4929. void ensureAllocatedSize (const int minNumElements)
  4930. {
  4931. if (minNumElements > numAllocated)
  4932. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  4933. }
  4934. /** Minimises the amount of storage allocated so that it's no more than
  4935. the given number of elements.
  4936. */
  4937. void shrinkToNoMoreThan (const int maxNumElements)
  4938. {
  4939. if (maxNumElements < numAllocated)
  4940. setAllocatedSize (maxNumElements);
  4941. }
  4942. /** Swap the contents of two objects. */
  4943. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  4944. {
  4945. elements.swapWith (other.elements);
  4946. swapVariables (numAllocated, other.numAllocated);
  4947. }
  4948. HeapBlock <ElementType> elements;
  4949. int numAllocated;
  4950. private:
  4951. JUCE_DECLARE_NON_COPYABLE (ArrayAllocationBase);
  4952. };
  4953. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4954. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  4955. /*** Start of inlined file: juce_ElementComparator.h ***/
  4956. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4957. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4958. /**
  4959. Sorts a range of elements in an array.
  4960. The comparator object that is passed-in must define a public method with the following
  4961. signature:
  4962. @code
  4963. int compareElements (ElementType first, ElementType second);
  4964. @endcode
  4965. ..and this method must return:
  4966. - a value of < 0 if the first comes before the second
  4967. - a value of 0 if the two objects are equivalent
  4968. - a value of > 0 if the second comes before the first
  4969. To improve performance, the compareElements() method can be declared as static or const.
  4970. @param comparator an object which defines a compareElements() method
  4971. @param array the array to sort
  4972. @param firstElement the index of the first element of the range to be sorted
  4973. @param lastElement the index of the last element in the range that needs
  4974. sorting (this is inclusive)
  4975. @param retainOrderOfEquivalentItems if true, the order of items that the
  4976. comparator deems the same will be maintained - this will be
  4977. a slower algorithm than if they are allowed to be moved around.
  4978. @see sortArrayRetainingOrder
  4979. */
  4980. template <class ElementType, class ElementComparator>
  4981. static void sortArray (ElementComparator& comparator,
  4982. ElementType* const array,
  4983. int firstElement,
  4984. int lastElement,
  4985. const bool retainOrderOfEquivalentItems)
  4986. {
  4987. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4988. // avoids getting warning messages about the parameter being unused
  4989. if (lastElement > firstElement)
  4990. {
  4991. if (retainOrderOfEquivalentItems)
  4992. {
  4993. for (int i = firstElement; i < lastElement; ++i)
  4994. {
  4995. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  4996. {
  4997. swapVariables (array[i], array[i + 1]);
  4998. if (i > firstElement)
  4999. i -= 2;
  5000. }
  5001. }
  5002. }
  5003. else
  5004. {
  5005. int fromStack[30], toStack[30];
  5006. int stackIndex = 0;
  5007. for (;;)
  5008. {
  5009. const int size = (lastElement - firstElement) + 1;
  5010. if (size <= 8)
  5011. {
  5012. int j = lastElement;
  5013. int maxIndex;
  5014. while (j > firstElement)
  5015. {
  5016. maxIndex = firstElement;
  5017. for (int k = firstElement + 1; k <= j; ++k)
  5018. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  5019. maxIndex = k;
  5020. swapVariables (array[j], array[maxIndex]);
  5021. --j;
  5022. }
  5023. }
  5024. else
  5025. {
  5026. const int mid = firstElement + (size >> 1);
  5027. swapVariables (array[mid], array[firstElement]);
  5028. int i = firstElement;
  5029. int j = lastElement + 1;
  5030. for (;;)
  5031. {
  5032. while (++i <= lastElement
  5033. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  5034. {}
  5035. while (--j > firstElement
  5036. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  5037. {}
  5038. if (j < i)
  5039. break;
  5040. swapVariables (array[i], array[j]);
  5041. }
  5042. swapVariables (array[j], array[firstElement]);
  5043. if (j - 1 - firstElement >= lastElement - i)
  5044. {
  5045. if (firstElement + 1 < j)
  5046. {
  5047. fromStack [stackIndex] = firstElement;
  5048. toStack [stackIndex] = j - 1;
  5049. ++stackIndex;
  5050. }
  5051. if (i < lastElement)
  5052. {
  5053. firstElement = i;
  5054. continue;
  5055. }
  5056. }
  5057. else
  5058. {
  5059. if (i < lastElement)
  5060. {
  5061. fromStack [stackIndex] = i;
  5062. toStack [stackIndex] = lastElement;
  5063. ++stackIndex;
  5064. }
  5065. if (firstElement + 1 < j)
  5066. {
  5067. lastElement = j - 1;
  5068. continue;
  5069. }
  5070. }
  5071. }
  5072. if (--stackIndex < 0)
  5073. break;
  5074. jassert (stackIndex < numElementsInArray (fromStack));
  5075. firstElement = fromStack [stackIndex];
  5076. lastElement = toStack [stackIndex];
  5077. }
  5078. }
  5079. }
  5080. }
  5081. /**
  5082. Searches a sorted array of elements, looking for the index at which a specified value
  5083. should be inserted for it to be in the correct order.
  5084. The comparator object that is passed-in must define a public method with the following
  5085. signature:
  5086. @code
  5087. int compareElements (ElementType first, ElementType second);
  5088. @endcode
  5089. ..and this method must return:
  5090. - a value of < 0 if the first comes before the second
  5091. - a value of 0 if the two objects are equivalent
  5092. - a value of > 0 if the second comes before the first
  5093. To improve performance, the compareElements() method can be declared as static or const.
  5094. @param comparator an object which defines a compareElements() method
  5095. @param array the array to search
  5096. @param newElement the value that is going to be inserted
  5097. @param firstElement the index of the first element to search
  5098. @param lastElement the index of the last element in the range (this is non-inclusive)
  5099. */
  5100. template <class ElementType, class ElementComparator>
  5101. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  5102. ElementType* const array,
  5103. const ElementType newElement,
  5104. int firstElement,
  5105. int lastElement)
  5106. {
  5107. jassert (firstElement <= lastElement);
  5108. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5109. // avoids getting warning messages about the parameter being unused
  5110. while (firstElement < lastElement)
  5111. {
  5112. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  5113. {
  5114. ++firstElement;
  5115. break;
  5116. }
  5117. else
  5118. {
  5119. const int halfway = (firstElement + lastElement) >> 1;
  5120. if (halfway == firstElement)
  5121. {
  5122. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5123. ++firstElement;
  5124. break;
  5125. }
  5126. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  5127. {
  5128. firstElement = halfway;
  5129. }
  5130. else
  5131. {
  5132. lastElement = halfway;
  5133. }
  5134. }
  5135. }
  5136. return firstElement;
  5137. }
  5138. /**
  5139. A simple ElementComparator class that can be used to sort an array of
  5140. objects that support the '<' operator.
  5141. This will work for primitive types and objects that implement operator<().
  5142. Example: @code
  5143. Array <int> myArray;
  5144. DefaultElementComparator<int> sorter;
  5145. myArray.sort (sorter);
  5146. @endcode
  5147. @see ElementComparator
  5148. */
  5149. template <class ElementType>
  5150. class DefaultElementComparator
  5151. {
  5152. private:
  5153. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5154. public:
  5155. static int compareElements (ParameterType first, ParameterType second)
  5156. {
  5157. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  5158. }
  5159. };
  5160. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5161. /*** End of inlined file: juce_ElementComparator.h ***/
  5162. /*** Start of inlined file: juce_CriticalSection.h ***/
  5163. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  5164. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  5165. #ifndef DOXYGEN
  5166. class ScopedLock;
  5167. class ScopedUnlock;
  5168. #endif
  5169. /**
  5170. Prevents multiple threads from accessing shared objects at the same time.
  5171. @see ScopedLock, Thread, InterProcessLock
  5172. */
  5173. class JUCE_API CriticalSection
  5174. {
  5175. public:
  5176. /**
  5177. Creates a CriticalSection object
  5178. */
  5179. CriticalSection() throw();
  5180. /** Destroys a CriticalSection object.
  5181. If the critical section is deleted whilst locked, its subsequent behaviour
  5182. is unpredictable.
  5183. */
  5184. ~CriticalSection() throw();
  5185. /** Locks this critical section.
  5186. If the lock is currently held by another thread, this will wait until it
  5187. becomes free.
  5188. If the lock is already held by the caller thread, the method returns immediately.
  5189. @see exit, ScopedLock
  5190. */
  5191. void enter() const throw();
  5192. /** Attempts to lock this critical section without blocking.
  5193. This method behaves identically to CriticalSection::enter, except that the caller thread
  5194. does not wait if the lock is currently held by another thread but returns false immediately.
  5195. @returns false if the lock is currently held by another thread, true otherwise.
  5196. @see enter
  5197. */
  5198. bool tryEnter() const throw();
  5199. /** Releases the lock.
  5200. If the caller thread hasn't got the lock, this can have unpredictable results.
  5201. If the enter() method has been called multiple times by the thread, each
  5202. call must be matched by a call to exit() before other threads will be allowed
  5203. to take over the lock.
  5204. @see enter, ScopedLock
  5205. */
  5206. void exit() const throw();
  5207. /** Provides the type of scoped lock to use with this type of critical section object. */
  5208. typedef ScopedLock ScopedLockType;
  5209. /** Provides the type of scoped unlocker to use with this type of critical section object. */
  5210. typedef ScopedUnlock ScopedUnlockType;
  5211. private:
  5212. #if JUCE_WINDOWS
  5213. #if JUCE_64BIT
  5214. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  5215. // block of memory here that's big enough to be used internally as a windows critical
  5216. // section object.
  5217. uint8 internal [44];
  5218. #else
  5219. uint8 internal [24];
  5220. #endif
  5221. #else
  5222. mutable pthread_mutex_t internal;
  5223. #endif
  5224. JUCE_DECLARE_NON_COPYABLE (CriticalSection);
  5225. };
  5226. /**
  5227. A class that can be used in place of a real CriticalSection object.
  5228. This is currently used by some templated classes, and should get
  5229. optimised out by the compiler.
  5230. @see Array, OwnedArray, ReferenceCountedArray
  5231. */
  5232. class JUCE_API DummyCriticalSection
  5233. {
  5234. public:
  5235. inline DummyCriticalSection() throw() {}
  5236. inline ~DummyCriticalSection() throw() {}
  5237. inline void enter() const throw() {}
  5238. inline void exit() const throw() {}
  5239. /** A dummy scoped-lock type to use with a dummy critical section. */
  5240. struct ScopedLockType
  5241. {
  5242. ScopedLockType (const DummyCriticalSection&) throw() {}
  5243. };
  5244. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  5245. typedef ScopedLockType ScopedUnlockType;
  5246. private:
  5247. JUCE_DECLARE_NON_COPYABLE (DummyCriticalSection);
  5248. };
  5249. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  5250. /*** End of inlined file: juce_CriticalSection.h ***/
  5251. /**
  5252. Holds a resizable array of primitive or copy-by-value objects.
  5253. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  5254. The Array class can be used to hold simple, non-polymorphic objects as well as primitive types - to
  5255. do so, the class must fulfil these requirements:
  5256. - it must have a copy constructor and assignment operator
  5257. - it must be able to be relocated in memory by a memcpy without this causing any problems - so
  5258. objects whose functionality relies on external pointers or references to themselves can be used.
  5259. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  5260. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  5261. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  5262. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  5263. specialised class StringArray, which provides more useful functions.
  5264. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  5265. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  5266. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  5267. */
  5268. template <typename ElementType,
  5269. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  5270. class Array
  5271. {
  5272. private:
  5273. #if JUCE_VC8_OR_EARLIER
  5274. typedef const ElementType& ParameterType;
  5275. #else
  5276. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5277. #endif
  5278. public:
  5279. /** Creates an empty array. */
  5280. Array() throw()
  5281. : numUsed (0)
  5282. {
  5283. }
  5284. /** Creates a copy of another array.
  5285. @param other the array to copy
  5286. */
  5287. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  5288. {
  5289. const ScopedLockType lock (other.getLock());
  5290. numUsed = other.numUsed;
  5291. data.setAllocatedSize (other.numUsed);
  5292. for (int i = 0; i < numUsed; ++i)
  5293. new (data.elements + i) ElementType (other.data.elements[i]);
  5294. }
  5295. /** Initalises from a null-terminated C array of values.
  5296. @param values the array to copy from
  5297. */
  5298. template <typename TypeToCreateFrom>
  5299. explicit Array (const TypeToCreateFrom* values)
  5300. : numUsed (0)
  5301. {
  5302. while (*values != TypeToCreateFrom())
  5303. add (*values++);
  5304. }
  5305. /** Initalises from a C array of values.
  5306. @param values the array to copy from
  5307. @param numValues the number of values in the array
  5308. */
  5309. template <typename TypeToCreateFrom>
  5310. Array (const TypeToCreateFrom* values, int numValues)
  5311. : numUsed (numValues)
  5312. {
  5313. data.setAllocatedSize (numValues);
  5314. for (int i = 0; i < numValues; ++i)
  5315. new (data.elements + i) ElementType (values[i]);
  5316. }
  5317. /** Destructor. */
  5318. ~Array()
  5319. {
  5320. for (int i = 0; i < numUsed; ++i)
  5321. data.elements[i].~ElementType();
  5322. }
  5323. /** Copies another array.
  5324. @param other the array to copy
  5325. */
  5326. Array& operator= (const Array& other)
  5327. {
  5328. if (this != &other)
  5329. {
  5330. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  5331. swapWithArray (otherCopy);
  5332. }
  5333. return *this;
  5334. }
  5335. /** Compares this array to another one.
  5336. Two arrays are considered equal if they both contain the same set of
  5337. elements, in the same order.
  5338. @param other the other array to compare with
  5339. */
  5340. template <class OtherArrayType>
  5341. bool operator== (const OtherArrayType& other) const
  5342. {
  5343. const ScopedLockType lock (getLock());
  5344. if (numUsed != other.numUsed)
  5345. return false;
  5346. for (int i = numUsed; --i >= 0;)
  5347. if (! (data.elements [i] == other.data.elements [i]))
  5348. return false;
  5349. return true;
  5350. }
  5351. /** Compares this array to another one.
  5352. Two arrays are considered equal if they both contain the same set of
  5353. elements, in the same order.
  5354. @param other the other array to compare with
  5355. */
  5356. template <class OtherArrayType>
  5357. bool operator!= (const OtherArrayType& other) const
  5358. {
  5359. return ! operator== (other);
  5360. }
  5361. /** Removes all elements from the array.
  5362. This will remove all the elements, and free any storage that the array is
  5363. using. To clear the array without freeing the storage, use the clearQuick()
  5364. method instead.
  5365. @see clearQuick
  5366. */
  5367. void clear()
  5368. {
  5369. const ScopedLockType lock (getLock());
  5370. for (int i = 0; i < numUsed; ++i)
  5371. data.elements[i].~ElementType();
  5372. data.setAllocatedSize (0);
  5373. numUsed = 0;
  5374. }
  5375. /** Removes all elements from the array without freeing the array's allocated storage.
  5376. @see clear
  5377. */
  5378. void clearQuick()
  5379. {
  5380. const ScopedLockType lock (getLock());
  5381. for (int i = 0; i < numUsed; ++i)
  5382. data.elements[i].~ElementType();
  5383. numUsed = 0;
  5384. }
  5385. /** Returns the current number of elements in the array.
  5386. */
  5387. inline int size() const throw()
  5388. {
  5389. return numUsed;
  5390. }
  5391. /** Returns one of the elements in the array.
  5392. If the index passed in is beyond the range of valid elements, this
  5393. will return zero.
  5394. If you're certain that the index will always be a valid element, you
  5395. can call getUnchecked() instead, which is faster.
  5396. @param index the index of the element being requested (0 is the first element in the array)
  5397. @see getUnchecked, getFirst, getLast
  5398. */
  5399. inline ElementType operator[] (const int index) const
  5400. {
  5401. const ScopedLockType lock (getLock());
  5402. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  5403. : ElementType();
  5404. }
  5405. /** Returns one of the elements in the array, without checking the index passed in.
  5406. Unlike the operator[] method, this will try to return an element without
  5407. checking that the index is within the bounds of the array, so should only
  5408. be used when you're confident that it will always be a valid index.
  5409. @param index the index of the element being requested (0 is the first element in the array)
  5410. @see operator[], getFirst, getLast
  5411. */
  5412. inline const ElementType getUnchecked (const int index) const
  5413. {
  5414. const ScopedLockType lock (getLock());
  5415. jassert (isPositiveAndBelow (index, numUsed));
  5416. return data.elements [index];
  5417. }
  5418. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  5419. This is like getUnchecked, but returns a direct reference to the element, so that
  5420. you can alter it directly. Obviously this can be dangerous, so only use it when
  5421. absolutely necessary.
  5422. @param index the index of the element being requested (0 is the first element in the array)
  5423. @see operator[], getFirst, getLast
  5424. */
  5425. inline ElementType& getReference (const int index) const throw()
  5426. {
  5427. const ScopedLockType lock (getLock());
  5428. jassert (isPositiveAndBelow (index, numUsed));
  5429. return data.elements [index];
  5430. }
  5431. /** Returns the first element in the array, or 0 if the array is empty.
  5432. @see operator[], getUnchecked, getLast
  5433. */
  5434. inline ElementType getFirst() const
  5435. {
  5436. const ScopedLockType lock (getLock());
  5437. return (numUsed > 0) ? data.elements [0]
  5438. : ElementType();
  5439. }
  5440. /** Returns the last element in the array, or 0 if the array is empty.
  5441. @see operator[], getUnchecked, getFirst
  5442. */
  5443. inline ElementType getLast() const
  5444. {
  5445. const ScopedLockType lock (getLock());
  5446. return (numUsed > 0) ? data.elements [numUsed - 1]
  5447. : ElementType();
  5448. }
  5449. /** Returns a pointer to the actual array data.
  5450. This pointer will only be valid until the next time a non-const method
  5451. is called on the array.
  5452. */
  5453. inline ElementType* getRawDataPointer() throw()
  5454. {
  5455. return data.elements;
  5456. }
  5457. /** Finds the index of the first element which matches the value passed in.
  5458. This will search the array for the given object, and return the index
  5459. of its first occurrence. If the object isn't found, the method will return -1.
  5460. @param elementToLookFor the value or object to look for
  5461. @returns the index of the object, or -1 if it's not found
  5462. */
  5463. int indexOf (ParameterType elementToLookFor) const
  5464. {
  5465. const ScopedLockType lock (getLock());
  5466. const ElementType* e = data.elements.getData();
  5467. const ElementType* const end = e + numUsed;
  5468. for (; e != end; ++e)
  5469. if (elementToLookFor == *e)
  5470. return static_cast <int> (e - data.elements.getData());
  5471. return -1;
  5472. }
  5473. /** Returns true if the array contains at least one occurrence of an object.
  5474. @param elementToLookFor the value or object to look for
  5475. @returns true if the item is found
  5476. */
  5477. bool contains (ParameterType elementToLookFor) const
  5478. {
  5479. const ScopedLockType lock (getLock());
  5480. const ElementType* e = data.elements.getData();
  5481. const ElementType* const end = e + numUsed;
  5482. for (; e != end; ++e)
  5483. if (elementToLookFor == *e)
  5484. return true;
  5485. return false;
  5486. }
  5487. /** Appends a new element at the end of the array.
  5488. @param newElement the new object to add to the array
  5489. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  5490. */
  5491. void add (ParameterType newElement)
  5492. {
  5493. const ScopedLockType lock (getLock());
  5494. data.ensureAllocatedSize (numUsed + 1);
  5495. new (data.elements + numUsed++) ElementType (newElement);
  5496. }
  5497. /** Inserts a new element into the array at a given position.
  5498. If the index is less than 0 or greater than the size of the array, the
  5499. element will be added to the end of the array.
  5500. Otherwise, it will be inserted into the array, moving all the later elements
  5501. along to make room.
  5502. @param indexToInsertAt the index at which the new element should be
  5503. inserted (pass in -1 to add it to the end)
  5504. @param newElement the new object to add to the array
  5505. @see add, addSorted, addUsingDefaultSort, set
  5506. */
  5507. void insert (int indexToInsertAt, ParameterType newElement)
  5508. {
  5509. const ScopedLockType lock (getLock());
  5510. data.ensureAllocatedSize (numUsed + 1);
  5511. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5512. {
  5513. ElementType* const insertPos = data.elements + indexToInsertAt;
  5514. const int numberToMove = numUsed - indexToInsertAt;
  5515. if (numberToMove > 0)
  5516. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  5517. new (insertPos) ElementType (newElement);
  5518. ++numUsed;
  5519. }
  5520. else
  5521. {
  5522. new (data.elements + numUsed++) ElementType (newElement);
  5523. }
  5524. }
  5525. /** Inserts multiple copies of an element into the array at a given position.
  5526. If the index is less than 0 or greater than the size of the array, the
  5527. element will be added to the end of the array.
  5528. Otherwise, it will be inserted into the array, moving all the later elements
  5529. along to make room.
  5530. @param indexToInsertAt the index at which the new element should be inserted
  5531. @param newElement the new object to add to the array
  5532. @param numberOfTimesToInsertIt how many copies of the value to insert
  5533. @see insert, add, addSorted, set
  5534. */
  5535. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  5536. int numberOfTimesToInsertIt)
  5537. {
  5538. if (numberOfTimesToInsertIt > 0)
  5539. {
  5540. const ScopedLockType lock (getLock());
  5541. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  5542. ElementType* insertPos;
  5543. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5544. {
  5545. insertPos = data.elements + indexToInsertAt;
  5546. const int numberToMove = numUsed - indexToInsertAt;
  5547. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  5548. }
  5549. else
  5550. {
  5551. insertPos = data.elements + numUsed;
  5552. }
  5553. numUsed += numberOfTimesToInsertIt;
  5554. while (--numberOfTimesToInsertIt >= 0)
  5555. new (insertPos++) ElementType (newElement);
  5556. }
  5557. }
  5558. /** Inserts an array of values into this array at a given position.
  5559. If the index is less than 0 or greater than the size of the array, the
  5560. new elements will be added to the end of the array.
  5561. Otherwise, they will be inserted into the array, moving all the later elements
  5562. along to make room.
  5563. @param indexToInsertAt the index at which the first new element should be inserted
  5564. @param newElements the new values to add to the array
  5565. @param numberOfElements how many items are in the array
  5566. @see insert, add, addSorted, set
  5567. */
  5568. void insertArray (int indexToInsertAt,
  5569. const ElementType* newElements,
  5570. int numberOfElements)
  5571. {
  5572. if (numberOfElements > 0)
  5573. {
  5574. const ScopedLockType lock (getLock());
  5575. data.ensureAllocatedSize (numUsed + numberOfElements);
  5576. ElementType* insertPos;
  5577. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5578. {
  5579. insertPos = data.elements + indexToInsertAt;
  5580. const int numberToMove = numUsed - indexToInsertAt;
  5581. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  5582. }
  5583. else
  5584. {
  5585. insertPos = data.elements + numUsed;
  5586. }
  5587. numUsed += numberOfElements;
  5588. while (--numberOfElements >= 0)
  5589. new (insertPos++) ElementType (*newElements++);
  5590. }
  5591. }
  5592. /** Appends a new element at the end of the array as long as the array doesn't
  5593. already contain it.
  5594. If the array already contains an element that matches the one passed in, nothing
  5595. will be done.
  5596. @param newElement the new object to add to the array
  5597. */
  5598. void addIfNotAlreadyThere (ParameterType newElement)
  5599. {
  5600. const ScopedLockType lock (getLock());
  5601. if (! contains (newElement))
  5602. add (newElement);
  5603. }
  5604. /** Replaces an element with a new value.
  5605. If the index is less than zero, this method does nothing.
  5606. If the index is beyond the end of the array, the item is added to the end of the array.
  5607. @param indexToChange the index whose value you want to change
  5608. @param newValue the new value to set for this index.
  5609. @see add, insert
  5610. */
  5611. void set (const int indexToChange, ParameterType newValue)
  5612. {
  5613. jassert (indexToChange >= 0);
  5614. const ScopedLockType lock (getLock());
  5615. if (isPositiveAndBelow (indexToChange, numUsed))
  5616. {
  5617. data.elements [indexToChange] = newValue;
  5618. }
  5619. else if (indexToChange >= 0)
  5620. {
  5621. data.ensureAllocatedSize (numUsed + 1);
  5622. new (data.elements + numUsed++) ElementType (newValue);
  5623. }
  5624. }
  5625. /** Replaces an element with a new value without doing any bounds-checking.
  5626. This just sets a value directly in the array's internal storage, so you'd
  5627. better make sure it's in range!
  5628. @param indexToChange the index whose value you want to change
  5629. @param newValue the new value to set for this index.
  5630. @see set, getUnchecked
  5631. */
  5632. void setUnchecked (const int indexToChange, ParameterType newValue)
  5633. {
  5634. const ScopedLockType lock (getLock());
  5635. jassert (isPositiveAndBelow (indexToChange, numUsed));
  5636. data.elements [indexToChange] = newValue;
  5637. }
  5638. /** Adds elements from an array to the end of this array.
  5639. @param elementsToAdd the array of elements to add
  5640. @param numElementsToAdd how many elements are in this other array
  5641. @see add
  5642. */
  5643. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  5644. {
  5645. const ScopedLockType lock (getLock());
  5646. if (numElementsToAdd > 0)
  5647. {
  5648. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5649. while (--numElementsToAdd >= 0)
  5650. {
  5651. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  5652. ++numUsed;
  5653. }
  5654. }
  5655. }
  5656. /** This swaps the contents of this array with those of another array.
  5657. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5658. because it just swaps their internal pointers.
  5659. */
  5660. void swapWithArray (Array& otherArray) throw()
  5661. {
  5662. const ScopedLockType lock1 (getLock());
  5663. const ScopedLockType lock2 (otherArray.getLock());
  5664. data.swapWith (otherArray.data);
  5665. swapVariables (numUsed, otherArray.numUsed);
  5666. }
  5667. /** Adds elements from another array to the end of this array.
  5668. @param arrayToAddFrom the array from which to copy the elements
  5669. @param startIndex the first element of the other array to start copying from
  5670. @param numElementsToAdd how many elements to add from the other array. If this
  5671. value is negative or greater than the number of available elements,
  5672. all available elements will be copied.
  5673. @see add
  5674. */
  5675. template <class OtherArrayType>
  5676. void addArray (const OtherArrayType& arrayToAddFrom,
  5677. int startIndex = 0,
  5678. int numElementsToAdd = -1)
  5679. {
  5680. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5681. {
  5682. const ScopedLockType lock2 (getLock());
  5683. if (startIndex < 0)
  5684. {
  5685. jassertfalse;
  5686. startIndex = 0;
  5687. }
  5688. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5689. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5690. while (--numElementsToAdd >= 0)
  5691. add (arrayToAddFrom.getUnchecked (startIndex++));
  5692. }
  5693. }
  5694. /** Inserts a new element into the array, assuming that the array is sorted.
  5695. This will use a comparator to find the position at which the new element
  5696. should go. If the array isn't sorted, the behaviour of this
  5697. method will be unpredictable.
  5698. @param comparator the comparator to use to compare the elements - see the sort()
  5699. method for details about the form this object should take
  5700. @param newElement the new element to insert to the array
  5701. @see addUsingDefaultSort, add, sort
  5702. */
  5703. template <class ElementComparator>
  5704. void addSorted (ElementComparator& comparator, ParameterType newElement)
  5705. {
  5706. const ScopedLockType lock (getLock());
  5707. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed), newElement);
  5708. }
  5709. /** Inserts a new element into the array, assuming that the array is sorted.
  5710. This will use the DefaultElementComparator class for sorting, so your ElementType
  5711. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  5712. method will be unpredictable.
  5713. @param newElement the new element to insert to the array
  5714. @see addSorted, sort
  5715. */
  5716. void addUsingDefaultSort (ParameterType newElement)
  5717. {
  5718. DefaultElementComparator <ElementType> comparator;
  5719. addSorted (comparator, newElement);
  5720. }
  5721. /** Finds the index of an element in the array, assuming that the array is sorted.
  5722. This will use a comparator to do a binary-chop to find the index of the given
  5723. element, if it exists. If the array isn't sorted, the behaviour of this
  5724. method will be unpredictable.
  5725. @param comparator the comparator to use to compare the elements - see the sort()
  5726. method for details about the form this object should take
  5727. @param elementToLookFor the element to search for
  5728. @returns the index of the element, or -1 if it's not found
  5729. @see addSorted, sort
  5730. */
  5731. template <class ElementComparator>
  5732. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  5733. {
  5734. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5735. // avoids getting warning messages about the parameter being unused
  5736. const ScopedLockType lock (getLock());
  5737. int start = 0;
  5738. int end = numUsed;
  5739. for (;;)
  5740. {
  5741. if (start >= end)
  5742. {
  5743. return -1;
  5744. }
  5745. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  5746. {
  5747. return start;
  5748. }
  5749. else
  5750. {
  5751. const int halfway = (start + end) >> 1;
  5752. if (halfway == start)
  5753. return -1;
  5754. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  5755. start = halfway;
  5756. else
  5757. end = halfway;
  5758. }
  5759. }
  5760. }
  5761. /** Removes an element from the array.
  5762. This will remove the element at a given index, and move back
  5763. all the subsequent elements to close the gap.
  5764. If the index passed in is out-of-range, nothing will happen.
  5765. @param indexToRemove the index of the element to remove
  5766. @returns the element that has been removed
  5767. @see removeValue, removeRange
  5768. */
  5769. ElementType remove (const int indexToRemove)
  5770. {
  5771. const ScopedLockType lock (getLock());
  5772. if (isPositiveAndBelow (indexToRemove, numUsed))
  5773. {
  5774. --numUsed;
  5775. ElementType* const e = data.elements + indexToRemove;
  5776. ElementType removed (*e);
  5777. e->~ElementType();
  5778. const int numberToShift = numUsed - indexToRemove;
  5779. if (numberToShift > 0)
  5780. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  5781. if ((numUsed << 1) < data.numAllocated)
  5782. minimiseStorageOverheads();
  5783. return removed;
  5784. }
  5785. else
  5786. {
  5787. return ElementType();
  5788. }
  5789. }
  5790. /** Removes an item from the array.
  5791. This will remove the first occurrence of the given element from the array.
  5792. If the item isn't found, no action is taken.
  5793. @param valueToRemove the object to try to remove
  5794. @see remove, removeRange
  5795. */
  5796. void removeValue (ParameterType valueToRemove)
  5797. {
  5798. const ScopedLockType lock (getLock());
  5799. ElementType* const e = data.elements;
  5800. for (int i = 0; i < numUsed; ++i)
  5801. {
  5802. if (valueToRemove == e[i])
  5803. {
  5804. remove (i);
  5805. break;
  5806. }
  5807. }
  5808. }
  5809. /** Removes a range of elements from the array.
  5810. This will remove a set of elements, starting from the given index,
  5811. and move subsequent elements down to close the gap.
  5812. If the range extends beyond the bounds of the array, it will
  5813. be safely clipped to the size of the array.
  5814. @param startIndex the index of the first element to remove
  5815. @param numberToRemove how many elements should be removed
  5816. @see remove, removeValue
  5817. */
  5818. void removeRange (int startIndex, int numberToRemove)
  5819. {
  5820. const ScopedLockType lock (getLock());
  5821. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  5822. startIndex = jlimit (0, numUsed, startIndex);
  5823. if (endIndex > startIndex)
  5824. {
  5825. ElementType* const e = data.elements + startIndex;
  5826. numberToRemove = endIndex - startIndex;
  5827. for (int i = 0; i < numberToRemove; ++i)
  5828. e[i].~ElementType();
  5829. const int numToShift = numUsed - endIndex;
  5830. if (numToShift > 0)
  5831. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  5832. numUsed -= numberToRemove;
  5833. if ((numUsed << 1) < data.numAllocated)
  5834. minimiseStorageOverheads();
  5835. }
  5836. }
  5837. /** Removes the last n elements from the array.
  5838. @param howManyToRemove how many elements to remove from the end of the array
  5839. @see remove, removeValue, removeRange
  5840. */
  5841. void removeLast (int howManyToRemove = 1)
  5842. {
  5843. const ScopedLockType lock (getLock());
  5844. if (howManyToRemove > numUsed)
  5845. howManyToRemove = numUsed;
  5846. for (int i = 1; i <= howManyToRemove; ++i)
  5847. data.elements [numUsed - i].~ElementType();
  5848. numUsed -= howManyToRemove;
  5849. if ((numUsed << 1) < data.numAllocated)
  5850. minimiseStorageOverheads();
  5851. }
  5852. /** Removes any elements which are also in another array.
  5853. @param otherArray the other array in which to look for elements to remove
  5854. @see removeValuesNotIn, remove, removeValue, removeRange
  5855. */
  5856. template <class OtherArrayType>
  5857. void removeValuesIn (const OtherArrayType& otherArray)
  5858. {
  5859. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  5860. const ScopedLockType lock2 (getLock());
  5861. if (this == &otherArray)
  5862. {
  5863. clear();
  5864. }
  5865. else
  5866. {
  5867. if (otherArray.size() > 0)
  5868. {
  5869. for (int i = numUsed; --i >= 0;)
  5870. if (otherArray.contains (data.elements [i]))
  5871. remove (i);
  5872. }
  5873. }
  5874. }
  5875. /** Removes any elements which are not found in another array.
  5876. Only elements which occur in this other array will be retained.
  5877. @param otherArray the array in which to look for elements NOT to remove
  5878. @see removeValuesIn, remove, removeValue, removeRange
  5879. */
  5880. template <class OtherArrayType>
  5881. void removeValuesNotIn (const OtherArrayType& otherArray)
  5882. {
  5883. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  5884. const ScopedLockType lock2 (getLock());
  5885. if (this != &otherArray)
  5886. {
  5887. if (otherArray.size() <= 0)
  5888. {
  5889. clear();
  5890. }
  5891. else
  5892. {
  5893. for (int i = numUsed; --i >= 0;)
  5894. if (! otherArray.contains (data.elements [i]))
  5895. remove (i);
  5896. }
  5897. }
  5898. }
  5899. /** Swaps over two elements in the array.
  5900. This swaps over the elements found at the two indexes passed in.
  5901. If either index is out-of-range, this method will do nothing.
  5902. @param index1 index of one of the elements to swap
  5903. @param index2 index of the other element to swap
  5904. */
  5905. void swap (const int index1,
  5906. const int index2)
  5907. {
  5908. const ScopedLockType lock (getLock());
  5909. if (isPositiveAndBelow (index1, numUsed)
  5910. && isPositiveAndBelow (index2, numUsed))
  5911. {
  5912. swapVariables (data.elements [index1],
  5913. data.elements [index2]);
  5914. }
  5915. }
  5916. /** Moves one of the values to a different position.
  5917. This will move the value to a specified index, shuffling along
  5918. any intervening elements as required.
  5919. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5920. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5921. @param currentIndex the index of the value to be moved. If this isn't a
  5922. valid index, then nothing will be done
  5923. @param newIndex the index at which you'd like this value to end up. If this
  5924. is less than zero, the value will be moved to the end
  5925. of the array
  5926. */
  5927. void move (const int currentIndex, int newIndex) throw()
  5928. {
  5929. if (currentIndex != newIndex)
  5930. {
  5931. const ScopedLockType lock (getLock());
  5932. if (isPositiveAndBelow (currentIndex, numUsed))
  5933. {
  5934. if (! isPositiveAndBelow (newIndex, numUsed))
  5935. newIndex = numUsed - 1;
  5936. char tempCopy [sizeof (ElementType)];
  5937. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  5938. if (newIndex > currentIndex)
  5939. {
  5940. memmove (data.elements + currentIndex,
  5941. data.elements + currentIndex + 1,
  5942. (newIndex - currentIndex) * sizeof (ElementType));
  5943. }
  5944. else
  5945. {
  5946. memmove (data.elements + newIndex + 1,
  5947. data.elements + newIndex,
  5948. (currentIndex - newIndex) * sizeof (ElementType));
  5949. }
  5950. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  5951. }
  5952. }
  5953. }
  5954. /** Reduces the amount of storage being used by the array.
  5955. Arrays typically allocate slightly more storage than they need, and after
  5956. removing elements, they may have quite a lot of unused space allocated.
  5957. This method will reduce the amount of allocated storage to a minimum.
  5958. */
  5959. void minimiseStorageOverheads()
  5960. {
  5961. const ScopedLockType lock (getLock());
  5962. data.shrinkToNoMoreThan (numUsed);
  5963. }
  5964. /** Increases the array's internal storage to hold a minimum number of elements.
  5965. Calling this before adding a large known number of elements means that
  5966. the array won't have to keep dynamically resizing itself as the elements
  5967. are added, and it'll therefore be more efficient.
  5968. */
  5969. void ensureStorageAllocated (const int minNumElements)
  5970. {
  5971. const ScopedLockType lock (getLock());
  5972. data.ensureAllocatedSize (minNumElements);
  5973. }
  5974. /** Sorts the elements in the array.
  5975. This will use a comparator object to sort the elements into order. The object
  5976. passed must have a method of the form:
  5977. @code
  5978. int compareElements (ElementType first, ElementType second);
  5979. @endcode
  5980. ..and this method must return:
  5981. - a value of < 0 if the first comes before the second
  5982. - a value of 0 if the two objects are equivalent
  5983. - a value of > 0 if the second comes before the first
  5984. To improve performance, the compareElements() method can be declared as static or const.
  5985. @param comparator the comparator to use for comparing elements.
  5986. @param retainOrderOfEquivalentItems if this is true, then items
  5987. which the comparator says are equivalent will be
  5988. kept in the order in which they currently appear
  5989. in the array. This is slower to perform, but may
  5990. be important in some cases. If it's false, a faster
  5991. algorithm is used, but equivalent elements may be
  5992. rearranged.
  5993. @see addSorted, indexOfSorted, sortArray
  5994. */
  5995. template <class ElementComparator>
  5996. void sort (ElementComparator& comparator,
  5997. const bool retainOrderOfEquivalentItems = false) const
  5998. {
  5999. const ScopedLockType lock (getLock());
  6000. (void) comparator; // if you pass in an object with a static compareElements() method, this
  6001. // avoids getting warning messages about the parameter being unused
  6002. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  6003. }
  6004. /** Returns the CriticalSection that locks this array.
  6005. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  6006. an object of ScopedLockType as an RAII lock for it.
  6007. */
  6008. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  6009. /** Returns the type of scoped lock to use for locking this array */
  6010. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  6011. private:
  6012. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  6013. int numUsed;
  6014. };
  6015. #endif // __JUCE_ARRAY_JUCEHEADER__
  6016. /*** End of inlined file: juce_Array.h ***/
  6017. #endif
  6018. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  6019. #endif
  6020. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6021. /*** Start of inlined file: juce_DynamicObject.h ***/
  6022. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6023. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  6024. /*** Start of inlined file: juce_NamedValueSet.h ***/
  6025. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  6026. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  6027. /*** Start of inlined file: juce_Variant.h ***/
  6028. #ifndef __JUCE_VARIANT_JUCEHEADER__
  6029. #define __JUCE_VARIANT_JUCEHEADER__
  6030. /*** Start of inlined file: juce_Identifier.h ***/
  6031. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  6032. #define __JUCE_IDENTIFIER_JUCEHEADER__
  6033. /*** Start of inlined file: juce_StringPool.h ***/
  6034. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  6035. #define __JUCE_STRINGPOOL_JUCEHEADER__
  6036. /**
  6037. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  6038. comparison speed when dealing with many duplicate strings.
  6039. When you add a string to a pool using getPooledString, it'll return a character
  6040. array containing the same string. This array is owned by the pool, and the same array
  6041. is returned every time a matching string is asked for. This means that it's trivial to
  6042. compare two pooled strings for equality, as you can simply compare their pointers. It
  6043. also cuts down on storage if you're using many copies of the same string.
  6044. */
  6045. class JUCE_API StringPool
  6046. {
  6047. public:
  6048. /** Creates an empty pool. */
  6049. StringPool() throw();
  6050. /** Destructor */
  6051. ~StringPool();
  6052. /** Returns a pointer to a copy of the string that is passed in.
  6053. The pool will always return the same pointer when asked for a string that matches it.
  6054. The pool will own all the pointers that it returns, deleting them when the pool itself
  6055. is deleted.
  6056. */
  6057. const String::CharPointerType getPooledString (const String& original);
  6058. /** Returns a pointer to a copy of the string that is passed in.
  6059. The pool will always return the same pointer when asked for a string that matches it.
  6060. The pool will own all the pointers that it returns, deleting them when the pool itself
  6061. is deleted.
  6062. */
  6063. const String::CharPointerType getPooledString (const char* original);
  6064. /** Returns a pointer to a copy of the string that is passed in.
  6065. The pool will always return the same pointer when asked for a string that matches it.
  6066. The pool will own all the pointers that it returns, deleting them when the pool itself
  6067. is deleted.
  6068. */
  6069. const String::CharPointerType getPooledString (const wchar_t* original);
  6070. /** Returns the number of strings in the pool. */
  6071. int size() const throw();
  6072. /** Returns one of the strings in the pool, by index. */
  6073. const String::CharPointerType operator[] (int index) const throw();
  6074. private:
  6075. Array <String> strings;
  6076. };
  6077. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  6078. /*** End of inlined file: juce_StringPool.h ***/
  6079. /**
  6080. Represents a string identifier, designed for accessing properties by name.
  6081. Identifier objects are very light and fast to copy, but slower to initialise
  6082. from a string, so it's much faster to keep a static identifier object to refer
  6083. to frequently-used names, rather than constructing them each time you need it.
  6084. @see NamedPropertySet, ValueTree
  6085. */
  6086. class JUCE_API Identifier
  6087. {
  6088. public:
  6089. /** Creates a null identifier. */
  6090. Identifier() throw();
  6091. /** Creates an identifier with a specified name.
  6092. Because this name may need to be used in contexts such as script variables or XML
  6093. tags, it must only contain ascii letters and digits, or the underscore character.
  6094. */
  6095. Identifier (const char* name);
  6096. /** Creates an identifier with a specified name.
  6097. Because this name may need to be used in contexts such as script variables or XML
  6098. tags, it must only contain ascii letters and digits, or the underscore character.
  6099. */
  6100. Identifier (const String& name);
  6101. /** Creates a copy of another identifier. */
  6102. Identifier (const Identifier& other) throw();
  6103. /** Creates a copy of another identifier. */
  6104. Identifier& operator= (const Identifier& other) throw();
  6105. /** Destructor */
  6106. ~Identifier();
  6107. /** Compares two identifiers. This is a very fast operation. */
  6108. inline bool operator== (const Identifier& other) const throw() { return name == other.name; }
  6109. /** Compares two identifiers. This is a very fast operation. */
  6110. inline bool operator!= (const Identifier& other) const throw() { return name != other.name; }
  6111. /** Returns this identifier as a string. */
  6112. const String toString() const { return name; }
  6113. /** Returns this identifier's raw string pointer. */
  6114. operator const String::CharPointerType() const throw() { return name; }
  6115. private:
  6116. String::CharPointerType name;
  6117. static StringPool& getPool();
  6118. };
  6119. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  6120. /*** End of inlined file: juce_Identifier.h ***/
  6121. /*** Start of inlined file: juce_OutputStream.h ***/
  6122. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6123. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6124. /*** Start of inlined file: juce_NewLine.h ***/
  6125. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  6126. #define __JUCE_NEWLINE_JUCEHEADER__
  6127. /** This class is used for represent a new-line character sequence.
  6128. To write a new-line to a stream, you can use the predefined 'newLine' variable, e.g.
  6129. @code
  6130. myOutputStream << "Hello World" << newLine << newLine;
  6131. @endcode
  6132. The exact character sequence that will be used for the new-line can be set and
  6133. retrieved with OutputStream::setNewLineString() and OutputStream::getNewLineString().
  6134. */
  6135. class JUCE_API NewLine
  6136. {
  6137. public:
  6138. /** Returns the default new-line sequence that the library uses.
  6139. @see OutputStream::setNewLineString()
  6140. */
  6141. static const char* getDefault() throw() { return "\r\n"; }
  6142. /** Returns the default new-line sequence that the library uses.
  6143. @see getDefault()
  6144. */
  6145. operator const String() const { return getDefault(); }
  6146. };
  6147. /** An predefined object representing a new-line, which can be written to a string or stream.
  6148. To write a new-line to a stream, you can use the predefined 'newLine' variable like this:
  6149. @code
  6150. myOutputStream << "Hello World" << newLine << newLine;
  6151. @endcode
  6152. */
  6153. extern NewLine newLine;
  6154. /** Writes a new-line sequence to a string.
  6155. You can use the predefined object 'newLine' to invoke this, e.g.
  6156. @code
  6157. myString << "Hello World" << newLine << newLine;
  6158. @endcode
  6159. */
  6160. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&);
  6161. #endif // __JUCE_NEWLINE_JUCEHEADER__
  6162. /*** End of inlined file: juce_NewLine.h ***/
  6163. /*** Start of inlined file: juce_InputStream.h ***/
  6164. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6165. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6166. /*** Start of inlined file: juce_MemoryBlock.h ***/
  6167. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  6168. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  6169. /**
  6170. A class to hold a resizable block of raw data.
  6171. */
  6172. class JUCE_API MemoryBlock
  6173. {
  6174. public:
  6175. /** Create an uninitialised block with 0 size. */
  6176. MemoryBlock() throw();
  6177. /** Creates a memory block with a given initial size.
  6178. @param initialSize the size of block to create
  6179. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  6180. */
  6181. MemoryBlock (const size_t initialSize,
  6182. bool initialiseToZero = false);
  6183. /** Creates a copy of another memory block. */
  6184. MemoryBlock (const MemoryBlock& other);
  6185. /** Creates a memory block using a copy of a block of data.
  6186. @param dataToInitialiseFrom some data to copy into this block
  6187. @param sizeInBytes how much space to use
  6188. */
  6189. MemoryBlock (const void* dataToInitialiseFrom, size_t sizeInBytes);
  6190. /** Destructor. */
  6191. ~MemoryBlock() throw();
  6192. /** Copies another memory block onto this one.
  6193. This block will be resized and copied to exactly match the other one.
  6194. */
  6195. MemoryBlock& operator= (const MemoryBlock& other);
  6196. /** Compares two memory blocks.
  6197. @returns true only if the two blocks are the same size and have identical contents.
  6198. */
  6199. bool operator== (const MemoryBlock& other) const throw();
  6200. /** Compares two memory blocks.
  6201. @returns true if the two blocks are different sizes or have different contents.
  6202. */
  6203. bool operator!= (const MemoryBlock& other) const throw();
  6204. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  6205. */
  6206. bool matches (const void* data, size_t dataSize) const throw();
  6207. /** Returns a void pointer to the data.
  6208. Note that the pointer returned will probably become invalid when the
  6209. block is resized.
  6210. */
  6211. void* getData() const throw() { return data; }
  6212. /** Returns a byte from the memory block.
  6213. This returns a reference, so you can also use it to set a byte.
  6214. */
  6215. template <typename Type>
  6216. char& operator[] (const Type offset) const throw() { return data [offset]; }
  6217. /** Returns the block's current allocated size, in bytes. */
  6218. size_t getSize() const throw() { return size; }
  6219. /** Resizes the memory block.
  6220. This will try to keep as much of the block's current content as it can,
  6221. and can optionally be made to clear any new space that gets allocated at
  6222. the end of the block.
  6223. @param newSize the new desired size for the block
  6224. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  6225. whether to clear the new section or just leave it
  6226. uninitialised
  6227. @see ensureSize
  6228. */
  6229. void setSize (const size_t newSize,
  6230. bool initialiseNewSpaceToZero = false);
  6231. /** Increases the block's size only if it's smaller than a given size.
  6232. @param minimumSize if the block is already bigger than this size, no action
  6233. will be taken; otherwise it will be increased to this size
  6234. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  6235. whether to clear the new section or just leave it
  6236. uninitialised
  6237. @see setSize
  6238. */
  6239. void ensureSize (const size_t minimumSize,
  6240. bool initialiseNewSpaceToZero = false);
  6241. /** Fills the entire memory block with a repeated byte value.
  6242. This is handy for clearing a block of memory to zero.
  6243. */
  6244. void fillWith (uint8 valueToUse) throw();
  6245. /** Adds another block of data to the end of this one.
  6246. This block's size will be increased accordingly.
  6247. */
  6248. void append (const void* data, size_t numBytes);
  6249. /** Exchanges the contents of this and another memory block.
  6250. No actual copying is required for this, so it's very fast.
  6251. */
  6252. void swapWith (MemoryBlock& other) throw();
  6253. /** Copies data into this MemoryBlock from a memory address.
  6254. @param srcData the memory location of the data to copy into this block
  6255. @param destinationOffset the offset in this block at which the data being copied should begin
  6256. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  6257. it will be clipped so not to do anything nasty)
  6258. */
  6259. void copyFrom (const void* srcData,
  6260. int destinationOffset,
  6261. size_t numBytes) throw();
  6262. /** Copies data from this MemoryBlock to a memory address.
  6263. @param destData the memory location to write to
  6264. @param sourceOffset the offset within this block from which the copied data will be read
  6265. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  6266. zeros will be used for that portion of the data)
  6267. */
  6268. void copyTo (void* destData,
  6269. int sourceOffset,
  6270. size_t numBytes) const throw();
  6271. /** Chops out a section of the block.
  6272. This will remove a section of the memory block and close the gap around it,
  6273. shifting any subsequent data downwards and reducing the size of the block.
  6274. If the range specified goes beyond the size of the block, it will be clipped.
  6275. */
  6276. void removeSection (size_t startByte, size_t numBytesToRemove);
  6277. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  6278. characters in the system's default encoding. */
  6279. const String toString() const;
  6280. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  6281. The block will be resized to the number of valid bytes read from the string.
  6282. Non-hex characters in the string will be ignored.
  6283. @see String::toHexString()
  6284. */
  6285. void loadFromHexString (const String& sourceHexString);
  6286. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  6287. void setBitRange (size_t bitRangeStart,
  6288. size_t numBits,
  6289. int binaryNumberToApply) throw();
  6290. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  6291. int getBitRange (size_t bitRangeStart,
  6292. size_t numBitsToRead) const throw();
  6293. /** Returns a string of characters that represent the binary contents of this block.
  6294. Uses a 64-bit encoding system to allow binary data to be turned into a string
  6295. of simple non-extended characters, e.g. for storage in XML.
  6296. @see fromBase64Encoding
  6297. */
  6298. const String toBase64Encoding() const;
  6299. /** Takes a string of encoded characters and turns it into binary data.
  6300. The string passed in must have been created by to64BitEncoding(), and this
  6301. block will be resized to recreate the original data block.
  6302. @see toBase64Encoding
  6303. */
  6304. bool fromBase64Encoding (const String& encodedString);
  6305. private:
  6306. HeapBlock <char> data;
  6307. size_t size;
  6308. static const char* const encodingTable;
  6309. JUCE_LEAK_DETECTOR (MemoryBlock);
  6310. };
  6311. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  6312. /*** End of inlined file: juce_MemoryBlock.h ***/
  6313. /** The base class for streams that read data.
  6314. Input and output streams are used throughout the library - subclasses can override
  6315. some or all of the virtual functions to implement their behaviour.
  6316. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6317. */
  6318. class JUCE_API InputStream
  6319. {
  6320. public:
  6321. /** Destructor. */
  6322. virtual ~InputStream() {}
  6323. /** Returns the total number of bytes available for reading in this stream.
  6324. Note that this is the number of bytes available from the start of the
  6325. stream, not from the current position.
  6326. If the size of the stream isn't actually known, this may return -1.
  6327. */
  6328. virtual int64 getTotalLength() = 0;
  6329. /** Returns true if the stream has no more data to read. */
  6330. virtual bool isExhausted() = 0;
  6331. /** Reads a set of bytes from the stream into a memory buffer.
  6332. This is the only read method that subclasses actually need to implement, as the
  6333. InputStream base class implements the other read methods in terms of this one (although
  6334. it's often more efficient for subclasses to implement them directly).
  6335. @param destBuffer the destination buffer for the data
  6336. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6337. memory block passed in is big enough to contain this
  6338. many bytes.
  6339. @returns the actual number of bytes that were read, which may be less than
  6340. maxBytesToRead if the stream is exhausted before it gets that far
  6341. */
  6342. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  6343. /** Reads a byte from the stream.
  6344. If the stream is exhausted, this will return zero.
  6345. @see OutputStream::writeByte
  6346. */
  6347. virtual char readByte();
  6348. /** Reads a boolean from the stream.
  6349. The bool is encoded as a single byte - 1 for true, 0 for false.
  6350. If the stream is exhausted, this will return false.
  6351. @see OutputStream::writeBool
  6352. */
  6353. virtual bool readBool();
  6354. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6355. If the next two bytes read are byte1 and byte2, this returns
  6356. (byte1 | (byte2 << 8)).
  6357. If the stream is exhausted partway through reading the bytes, this will return zero.
  6358. @see OutputStream::writeShort, readShortBigEndian
  6359. */
  6360. virtual short readShort();
  6361. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6362. If the next two bytes read are byte1 and byte2, this returns
  6363. (byte2 | (byte1 << 8)).
  6364. If the stream is exhausted partway through reading the bytes, this will return zero.
  6365. @see OutputStream::writeShortBigEndian, readShort
  6366. */
  6367. virtual short readShortBigEndian();
  6368. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6369. If the next four bytes are byte1 to byte4, this returns
  6370. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6371. If the stream is exhausted partway through reading the bytes, this will return zero.
  6372. @see OutputStream::writeInt, readIntBigEndian
  6373. */
  6374. virtual int readInt();
  6375. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6376. If the next four bytes are byte1 to byte4, this returns
  6377. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6378. If the stream is exhausted partway through reading the bytes, this will return zero.
  6379. @see OutputStream::writeIntBigEndian, readInt
  6380. */
  6381. virtual int readIntBigEndian();
  6382. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6383. If the next eight bytes are byte1 to byte8, this returns
  6384. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6385. If the stream is exhausted partway through reading the bytes, this will return zero.
  6386. @see OutputStream::writeInt64, readInt64BigEndian
  6387. */
  6388. virtual int64 readInt64();
  6389. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6390. If the next eight bytes are byte1 to byte8, this returns
  6391. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6392. If the stream is exhausted partway through reading the bytes, this will return zero.
  6393. @see OutputStream::writeInt64BigEndian, readInt64
  6394. */
  6395. virtual int64 readInt64BigEndian();
  6396. /** Reads four bytes as a 32-bit floating point value.
  6397. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6398. If the stream is exhausted partway through reading the bytes, this will return zero.
  6399. @see OutputStream::writeFloat, readDouble
  6400. */
  6401. virtual float readFloat();
  6402. /** Reads four bytes as a 32-bit floating point value.
  6403. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6404. If the stream is exhausted partway through reading the bytes, this will return zero.
  6405. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6406. */
  6407. virtual float readFloatBigEndian();
  6408. /** Reads eight bytes as a 64-bit floating point value.
  6409. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6410. If the stream is exhausted partway through reading the bytes, this will return zero.
  6411. @see OutputStream::writeDouble, readFloat
  6412. */
  6413. virtual double readDouble();
  6414. /** Reads eight bytes as a 64-bit floating point value.
  6415. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6416. If the stream is exhausted partway through reading the bytes, this will return zero.
  6417. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6418. */
  6419. virtual double readDoubleBigEndian();
  6420. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6421. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6422. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6423. @see OutputStream::writeCompressedInt()
  6424. */
  6425. virtual int readCompressedInt();
  6426. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  6427. This will read up to the next "\n" or "\r\n" or end-of-stream.
  6428. After this call, the stream's position will be left pointing to the next character
  6429. following the line-feed, but the linefeeds aren't included in the string that
  6430. is returned.
  6431. */
  6432. virtual const String readNextLine();
  6433. /** Reads a zero-terminated UTF8 string from the stream.
  6434. This will read characters from the stream until it hits a zero character or
  6435. end-of-stream.
  6436. @see OutputStream::writeString, readEntireStreamAsString
  6437. */
  6438. virtual const String readString();
  6439. /** Tries to read the whole stream and turn it into a string.
  6440. This will read from the stream's current position until the end-of-stream, and
  6441. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6442. */
  6443. virtual const String readEntireStreamAsString();
  6444. /** Reads from the stream and appends the data to a MemoryBlock.
  6445. @param destBlock the block to append the data onto
  6446. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6447. of bytes that will be read - if it's negative, data
  6448. will be read until the stream is exhausted.
  6449. @returns the number of bytes that were added to the memory block
  6450. */
  6451. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6452. int maxNumBytesToRead = -1);
  6453. /** Returns the offset of the next byte that will be read from the stream.
  6454. @see setPosition
  6455. */
  6456. virtual int64 getPosition() = 0;
  6457. /** Tries to move the current read position of the stream.
  6458. The position is an absolute number of bytes from the stream's start.
  6459. Some streams might not be able to do this, in which case they should do
  6460. nothing and return false. Others might be able to manage it by resetting
  6461. themselves and skipping to the correct position, although this is
  6462. obviously a bit slow.
  6463. @returns true if the stream manages to reposition itself correctly
  6464. @see getPosition
  6465. */
  6466. virtual bool setPosition (int64 newPosition) = 0;
  6467. /** Reads and discards a number of bytes from the stream.
  6468. Some input streams might implement this efficiently, but the base
  6469. class will just keep reading data until the requisite number of bytes
  6470. have been done.
  6471. */
  6472. virtual void skipNextBytes (int64 numBytesToSkip);
  6473. protected:
  6474. InputStream() throw() {}
  6475. private:
  6476. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InputStream);
  6477. };
  6478. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6479. /*** End of inlined file: juce_InputStream.h ***/
  6480. class File;
  6481. /**
  6482. The base class for streams that write data to some kind of destination.
  6483. Input and output streams are used throughout the library - subclasses can override
  6484. some or all of the virtual functions to implement their behaviour.
  6485. @see InputStream, MemoryOutputStream, FileOutputStream
  6486. */
  6487. class JUCE_API OutputStream
  6488. {
  6489. protected:
  6490. OutputStream();
  6491. public:
  6492. /** Destructor.
  6493. Some subclasses might want to do things like call flush() during their
  6494. destructors.
  6495. */
  6496. virtual ~OutputStream();
  6497. /** If the stream is using a buffer, this will ensure it gets written
  6498. out to the destination. */
  6499. virtual void flush() = 0;
  6500. /** Tries to move the stream's output position.
  6501. Not all streams will be able to seek to a new position - this will return
  6502. false if it fails to work.
  6503. @see getPosition
  6504. */
  6505. virtual bool setPosition (int64 newPosition) = 0;
  6506. /** Returns the stream's current position.
  6507. @see setPosition
  6508. */
  6509. virtual int64 getPosition() = 0;
  6510. /** Writes a block of data to the stream.
  6511. When creating a subclass of OutputStream, this is the only write method
  6512. that needs to be overloaded - the base class has methods for writing other
  6513. types of data which use this to do the work.
  6514. @returns false if the write operation fails for some reason
  6515. */
  6516. virtual bool write (const void* dataToWrite,
  6517. int howManyBytes) = 0;
  6518. /** Writes a single byte to the stream.
  6519. @see InputStream::readByte
  6520. */
  6521. virtual void writeByte (char byte);
  6522. /** Writes a boolean to the stream as a single byte.
  6523. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  6524. @see InputStream::readBool
  6525. */
  6526. virtual void writeBool (bool boolValue);
  6527. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6528. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6529. @see InputStream::readShort
  6530. */
  6531. virtual void writeShort (short value);
  6532. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6533. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6534. @see InputStream::readShortBigEndian
  6535. */
  6536. virtual void writeShortBigEndian (short value);
  6537. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6538. @see InputStream::readInt
  6539. */
  6540. virtual void writeInt (int value);
  6541. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6542. @see InputStream::readIntBigEndian
  6543. */
  6544. virtual void writeIntBigEndian (int value);
  6545. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6546. @see InputStream::readInt64
  6547. */
  6548. virtual void writeInt64 (int64 value);
  6549. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6550. @see InputStream::readInt64BigEndian
  6551. */
  6552. virtual void writeInt64BigEndian (int64 value);
  6553. /** Writes a 32-bit floating point value to the stream in a binary format.
  6554. The binary 32-bit encoding of the float is written as a little-endian int.
  6555. @see InputStream::readFloat
  6556. */
  6557. virtual void writeFloat (float value);
  6558. /** Writes a 32-bit floating point value to the stream in a binary format.
  6559. The binary 32-bit encoding of the float is written as a big-endian int.
  6560. @see InputStream::readFloatBigEndian
  6561. */
  6562. virtual void writeFloatBigEndian (float value);
  6563. /** Writes a 64-bit floating point value to the stream in a binary format.
  6564. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6565. @see InputStream::readDouble
  6566. */
  6567. virtual void writeDouble (double value);
  6568. /** Writes a 64-bit floating point value to the stream in a binary format.
  6569. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6570. @see InputStream::readDoubleBigEndian
  6571. */
  6572. virtual void writeDoubleBigEndian (double value);
  6573. /** Writes a byte to the output stream a given number of times. */
  6574. virtual void writeRepeatedByte (uint8 byte, int numTimesToRepeat);
  6575. /** Writes a condensed binary encoding of a 32-bit integer.
  6576. If you're storing a lot of integers which are unlikely to have very large values,
  6577. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6578. under 0xffff only 3 bytes, etc.
  6579. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6580. @see InputStream::readCompressedInt
  6581. */
  6582. virtual void writeCompressedInt (int value);
  6583. /** Stores a string in the stream in a binary format.
  6584. This isn't the method to use if you're trying to append text to the end of a
  6585. text-file! It's intended for storing a string so that it can be retrieved later
  6586. by InputStream::readString().
  6587. It writes the string to the stream as UTF8, including the null termination character.
  6588. For appending text to a file, instead use writeText, or operator<<
  6589. @see InputStream::readString, writeText, operator<<
  6590. */
  6591. virtual void writeString (const String& text);
  6592. /** Writes a string of text to the stream.
  6593. It can either write the text as UTF-8 or UTF-16, and can also add the UTF-16 byte-order-mark
  6594. bytes (0xff, 0xfe) to indicate the endianness (these should only be used at the start
  6595. of a file).
  6596. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6597. */
  6598. virtual void writeText (const String& text,
  6599. bool asUTF16,
  6600. bool writeUTF16ByteOrderMark);
  6601. /** Reads data from an input stream and writes it to this stream.
  6602. @param source the stream to read from
  6603. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6604. less than zero, it will keep reading until the input
  6605. is exhausted)
  6606. */
  6607. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  6608. /** Sets the string that will be written to the stream when the writeNewLine()
  6609. method is called.
  6610. By default this will be set the the value of NewLine::getDefault().
  6611. */
  6612. void setNewLineString (const String& newLineString);
  6613. /** Returns the current new-line string that was set by setNewLineString(). */
  6614. const String& getNewLineString() const throw() { return newLineString; }
  6615. private:
  6616. String newLineString;
  6617. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OutputStream);
  6618. };
  6619. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6620. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  6621. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6622. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  6623. /** Writes a character to a stream. */
  6624. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  6625. /** Writes a null-terminated text string to a stream. */
  6626. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  6627. /** Writes a block of data from a MemoryBlock to a stream. */
  6628. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  6629. /** Writes the contents of a file to a stream. */
  6630. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  6631. /** Writes a new-line to a stream.
  6632. You can use the predefined symbol 'newLine' to invoke this, e.g.
  6633. @code
  6634. myOutputStream << "Hello World" << newLine << newLine;
  6635. @endcode
  6636. @see OutputStream::setNewLineString
  6637. */
  6638. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&);
  6639. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6640. /*** End of inlined file: juce_OutputStream.h ***/
  6641. #ifndef DOXYGEN
  6642. class DynamicObject;
  6643. #endif
  6644. /**
  6645. A variant class, that can be used to hold a range of primitive values.
  6646. A var object can hold a range of simple primitive values, strings, or
  6647. a reference-counted pointer to a DynamicObject. The var class is intended
  6648. to act like the values used in dynamic scripting languages.
  6649. @see DynamicObject
  6650. */
  6651. class JUCE_API var
  6652. {
  6653. public:
  6654. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  6655. typedef Identifier identifier;
  6656. /** Creates a void variant. */
  6657. var() throw();
  6658. /** Destructor. */
  6659. ~var() throw();
  6660. /** A static var object that can be used where you need an empty variant object. */
  6661. static const var null;
  6662. var (const var& valueToCopy);
  6663. var (int value) throw();
  6664. var (int64 value) throw();
  6665. var (bool value) throw();
  6666. var (double value) throw();
  6667. var (const char* value);
  6668. var (const wchar_t* value);
  6669. var (const String& value);
  6670. var (DynamicObject* object);
  6671. var (MethodFunction method) throw();
  6672. var& operator= (const var& valueToCopy);
  6673. var& operator= (int value);
  6674. var& operator= (int64 value);
  6675. var& operator= (bool value);
  6676. var& operator= (double value);
  6677. var& operator= (const char* value);
  6678. var& operator= (const wchar_t* value);
  6679. var& operator= (const String& value);
  6680. var& operator= (DynamicObject* object);
  6681. var& operator= (MethodFunction method);
  6682. void swapWith (var& other) throw();
  6683. operator int() const;
  6684. operator int64() const;
  6685. operator bool() const;
  6686. operator float() const;
  6687. operator double() const;
  6688. operator const String() const;
  6689. const String toString() const;
  6690. DynamicObject* getObject() const;
  6691. bool isVoid() const throw();
  6692. bool isInt() const throw();
  6693. bool isInt64() const throw();
  6694. bool isBool() const throw();
  6695. bool isDouble() const throw();
  6696. bool isString() const throw();
  6697. bool isObject() const throw();
  6698. bool isMethod() const throw();
  6699. /** Writes a binary representation of this value to a stream.
  6700. The data can be read back later using readFromStream().
  6701. */
  6702. void writeToStream (OutputStream& output) const;
  6703. /** Reads back a stored binary representation of a value.
  6704. The data in the stream must have been written using writeToStream(), or this
  6705. will have unpredictable results.
  6706. */
  6707. static const var readFromStream (InputStream& input);
  6708. /** If this variant is an object, this returns one of its properties. */
  6709. const var operator[] (const Identifier& propertyName) const;
  6710. /** If this variant is an object, this invokes one of its methods with no arguments. */
  6711. const var call (const Identifier& method) const;
  6712. /** If this variant is an object, this invokes one of its methods with one argument. */
  6713. const var call (const Identifier& method, const var& arg1) const;
  6714. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  6715. const var call (const Identifier& method, const var& arg1, const var& arg2) const;
  6716. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  6717. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  6718. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  6719. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  6720. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  6721. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  6722. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  6723. const var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  6724. /** If this variant is a method pointer, this invokes it on a target object. */
  6725. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  6726. /** Returns true if this var has the same value as the one supplied. */
  6727. bool equals (const var& other) const throw();
  6728. /** Returns true if this var has the same value and type as the one supplied.
  6729. This differs from equals() because e.g. "0" and 0 will be considered different.
  6730. */
  6731. bool equalsWithSameType (const var& other) const throw();
  6732. private:
  6733. class VariantType;
  6734. friend class VariantType;
  6735. class VariantType_Void;
  6736. friend class VariantType_Void;
  6737. class VariantType_Int;
  6738. friend class VariantType_Int;
  6739. class VariantType_Int64;
  6740. friend class VariantType_Int64;
  6741. class VariantType_Double;
  6742. friend class VariantType_Double;
  6743. class VariantType_Float;
  6744. friend class VariantType_Float;
  6745. class VariantType_Bool;
  6746. friend class VariantType_Bool;
  6747. class VariantType_String;
  6748. friend class VariantType_String;
  6749. class VariantType_Object;
  6750. friend class VariantType_Object;
  6751. class VariantType_Method;
  6752. friend class VariantType_Method;
  6753. union ValueUnion
  6754. {
  6755. int intValue;
  6756. int64 int64Value;
  6757. bool boolValue;
  6758. double doubleValue;
  6759. String* stringValue;
  6760. DynamicObject* objectValue;
  6761. MethodFunction methodValue;
  6762. };
  6763. const VariantType* type;
  6764. ValueUnion value;
  6765. };
  6766. bool operator== (const var& v1, const var& v2) throw();
  6767. bool operator!= (const var& v1, const var& v2) throw();
  6768. bool operator== (const var& v1, const String& v2) throw();
  6769. bool operator!= (const var& v1, const String& v2) throw();
  6770. #endif // __JUCE_VARIANT_JUCEHEADER__
  6771. /*** End of inlined file: juce_Variant.h ***/
  6772. /*** Start of inlined file: juce_LinkedListPointer.h ***/
  6773. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  6774. #define __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  6775. /**
  6776. Helps to manipulate singly-linked lists of objects.
  6777. For objects that are designed to contain a pointer to the subsequent item in the
  6778. list, this class contains methods to deal with the list. To use it, the ObjectType
  6779. class that it points to must contain a LinkedListPointer called nextListItem, e.g.
  6780. @code
  6781. struct MyObject
  6782. {
  6783. int x, y, z;
  6784. // A linkable object must contain a member with this name and type, which must be
  6785. // accessible by the LinkedListPointer class. (This doesn't mean it has to be public -
  6786. // you could make your class a friend of a LinkedListPointer<MyObject> instead).
  6787. LinkedListPointer<MyObject> nextListItem;
  6788. };
  6789. LinkedListPointer<MyObject> myList;
  6790. myList.append (new MyObject());
  6791. myList.append (new MyObject());
  6792. int numItems = myList.size(); // returns 2
  6793. MyObject* lastInList = myList.getLast();
  6794. @endcode
  6795. */
  6796. template <class ObjectType>
  6797. class LinkedListPointer
  6798. {
  6799. public:
  6800. /** Creates a null pointer to an empty list. */
  6801. LinkedListPointer() throw()
  6802. : item (0)
  6803. {
  6804. }
  6805. /** Creates a pointer to a list whose head is the item provided. */
  6806. explicit LinkedListPointer (ObjectType* const headItem) throw()
  6807. : item (headItem)
  6808. {
  6809. }
  6810. /** Sets this pointer to point to a new list. */
  6811. LinkedListPointer& operator= (ObjectType* const newItem) throw()
  6812. {
  6813. item = newItem;
  6814. return *this;
  6815. }
  6816. /** Returns the item which this pointer points to. */
  6817. inline operator ObjectType*() const throw()
  6818. {
  6819. return item;
  6820. }
  6821. /** Returns the item which this pointer points to. */
  6822. inline ObjectType* get() const throw()
  6823. {
  6824. return item;
  6825. }
  6826. /** Returns the last item in the list which this pointer points to.
  6827. This will iterate the list and return the last item found. Obviously the speed
  6828. of this operation will be proportional to the size of the list. If the list is
  6829. empty the return value will be this object.
  6830. If you're planning on appending a number of items to your list, it's much more
  6831. efficient to use the Appender class than to repeatedly call getLast() to find the end.
  6832. */
  6833. LinkedListPointer& getLast() throw()
  6834. {
  6835. LinkedListPointer* l = this;
  6836. while (l->item != 0)
  6837. l = &(l->item->nextListItem);
  6838. return *l;
  6839. }
  6840. /** Returns the number of items in the list.
  6841. Obviously with a simple linked list, getting the size involves iterating the list, so
  6842. this can be a lengthy operation - be careful when using this method in your code.
  6843. */
  6844. int size() const throw()
  6845. {
  6846. int total = 0;
  6847. for (ObjectType* i = item; i != 0; i = i->nextListItem)
  6848. ++total;
  6849. return total;
  6850. }
  6851. /** Returns the item at a given index in the list.
  6852. Since the only way to find an item is to iterate the list, this operation can obviously
  6853. be slow, depending on its size, so you should be careful when using this in algorithms.
  6854. */
  6855. LinkedListPointer& operator[] (int index) throw()
  6856. {
  6857. LinkedListPointer* l = this;
  6858. while (--index >= 0 && l->item != 0)
  6859. l = &(l->item->nextListItem);
  6860. return *l;
  6861. }
  6862. /** Returns the item at a given index in the list.
  6863. Since the only way to find an item is to iterate the list, this operation can obviously
  6864. be slow, depending on its size, so you should be careful when using this in algorithms.
  6865. */
  6866. const LinkedListPointer& operator[] (int index) const throw()
  6867. {
  6868. const LinkedListPointer* l = this;
  6869. while (--index >= 0 && l->item != 0)
  6870. l = &(l->item->nextListItem);
  6871. return *l;
  6872. }
  6873. /** Returns true if the list contains the given item. */
  6874. bool contains (const ObjectType* const itemToLookFor) const throw()
  6875. {
  6876. for (ObjectType* i = item; i != 0; i = i->nextListItem)
  6877. if (itemToLookFor == i)
  6878. return true;
  6879. return false;
  6880. }
  6881. /** Inserts an item into the list, placing it before the item that this pointer
  6882. currently points to.
  6883. */
  6884. void insertNext (ObjectType* const newItem)
  6885. {
  6886. jassert (newItem != 0);
  6887. jassert (newItem->nextListItem == 0);
  6888. newItem->nextListItem = item;
  6889. item = newItem;
  6890. }
  6891. /** Inserts an item at a numeric index in the list.
  6892. Obviously this will involve iterating the list to find the item at the given index,
  6893. so be careful about the impact this may have on execution time.
  6894. */
  6895. void insertAtIndex (int index, ObjectType* newItem)
  6896. {
  6897. jassert (newItem != 0);
  6898. LinkedListPointer* l = this;
  6899. while (index != 0 && l->item != 0)
  6900. {
  6901. l = &(l->item->nextListItem);
  6902. --index;
  6903. }
  6904. l->insertNext (newItem);
  6905. }
  6906. /** Replaces the object that this pointer points to, appending the rest of the list to
  6907. the new object, and returning the old one.
  6908. */
  6909. ObjectType* replaceNext (ObjectType* const newItem) throw()
  6910. {
  6911. jassert (newItem != 0);
  6912. jassert (newItem->nextListItem == 0);
  6913. ObjectType* const oldItem = item;
  6914. item = newItem;
  6915. item->nextListItem = oldItem->nextListItem.item;
  6916. oldItem->nextListItem = (ObjectType*) 0;
  6917. return oldItem;
  6918. }
  6919. /** Adds an item to the end of the list.
  6920. This operation involves iterating the whole list, so can be slow - if you need to
  6921. append a number of items to your list, it's much more efficient to use the Appender
  6922. class than to repeatedly call append().
  6923. */
  6924. void append (ObjectType* const newItem)
  6925. {
  6926. getLast().item = newItem;
  6927. }
  6928. /** Creates copies of all the items in another list and adds them to this one.
  6929. This will use the ObjectType's copy constructor to try to create copies of each
  6930. item in the other list, and appends them to this list.
  6931. */
  6932. void addCopyOfList (const LinkedListPointer& other)
  6933. {
  6934. LinkedListPointer* insertPoint = this;
  6935. for (ObjectType* i = other.item; i != 0; i = i->nextListItem)
  6936. {
  6937. insertPoint->insertNext (new ObjectType (*i));
  6938. insertPoint = &(insertPoint->item->nextListItem);
  6939. }
  6940. }
  6941. /** Removes the head item from the list.
  6942. This won't delete the object that is removed, but returns it, so the caller can
  6943. delete it if necessary.
  6944. */
  6945. ObjectType* removeNext() throw()
  6946. {
  6947. ObjectType* const oldItem = item;
  6948. if (oldItem != 0)
  6949. {
  6950. item = oldItem->nextListItem;
  6951. oldItem->nextListItem = (ObjectType*) 0;
  6952. }
  6953. return oldItem;
  6954. }
  6955. /** Removes a specific item from the list.
  6956. Note that this will not delete the item, it simply unlinks it from the list.
  6957. */
  6958. void remove (ObjectType* const itemToRemove)
  6959. {
  6960. LinkedListPointer* const l = findPointerTo (itemToRemove);
  6961. if (l != 0)
  6962. l->removeNext();
  6963. }
  6964. /** Iterates the list, calling the delete operator on all of its elements and
  6965. leaving this pointer empty.
  6966. */
  6967. void deleteAll()
  6968. {
  6969. while (item != 0)
  6970. {
  6971. ObjectType* const oldItem = item;
  6972. item = oldItem->nextListItem;
  6973. delete oldItem;
  6974. }
  6975. }
  6976. /** Finds a pointer to a given item.
  6977. If the item is found in the list, this returns the pointer that points to it. If
  6978. the item isn't found, this returns null.
  6979. */
  6980. LinkedListPointer* findPointerTo (ObjectType* const itemToLookFor) throw()
  6981. {
  6982. LinkedListPointer* l = this;
  6983. while (l->item != 0)
  6984. {
  6985. if (l->item == itemToLookFor)
  6986. return l;
  6987. l = &(l->item->nextListItem);
  6988. }
  6989. return 0;
  6990. }
  6991. /** Copies the items in the list to an array.
  6992. The destArray must contain enough elements to hold the entire list - no checks are
  6993. made for this!
  6994. */
  6995. void copyToArray (ObjectType** destArray) const throw()
  6996. {
  6997. jassert (destArray != 0);
  6998. for (ObjectType* i = item; i != 0; i = i->nextListItem)
  6999. *destArray++ = i;
  7000. }
  7001. /**
  7002. Allows efficient repeated insertions into a list.
  7003. You can create an Appender object which points to the last element in your
  7004. list, and then repeatedly call Appender::append() to add items to the end
  7005. of the list in O(1) time.
  7006. */
  7007. class Appender
  7008. {
  7009. public:
  7010. /** Creates an appender which will add items to the given list.
  7011. */
  7012. Appender (LinkedListPointer& endOfListPointer) throw()
  7013. : endOfList (&endOfListPointer)
  7014. {
  7015. // This can only be used to add to the end of a list.
  7016. jassert (endOfListPointer.item == 0);
  7017. }
  7018. /** Appends an item to the list. */
  7019. void append (ObjectType* const newItem) throw()
  7020. {
  7021. *endOfList = newItem;
  7022. endOfList = &(newItem->nextListItem);
  7023. }
  7024. private:
  7025. LinkedListPointer* endOfList;
  7026. JUCE_DECLARE_NON_COPYABLE (Appender);
  7027. };
  7028. private:
  7029. ObjectType* item;
  7030. JUCE_DECLARE_NON_COPYABLE (LinkedListPointer);
  7031. };
  7032. #endif // __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7033. /*** End of inlined file: juce_LinkedListPointer.h ***/
  7034. class XmlElement;
  7035. /** Holds a set of named var objects.
  7036. This can be used as a basic structure to hold a set of var object, which can
  7037. be retrieved by using their identifier.
  7038. */
  7039. class JUCE_API NamedValueSet
  7040. {
  7041. public:
  7042. /** Creates an empty set. */
  7043. NamedValueSet() throw();
  7044. /** Creates a copy of another set. */
  7045. NamedValueSet (const NamedValueSet& other);
  7046. /** Replaces this set with a copy of another set. */
  7047. NamedValueSet& operator= (const NamedValueSet& other);
  7048. /** Destructor. */
  7049. ~NamedValueSet();
  7050. bool operator== (const NamedValueSet& other) const;
  7051. bool operator!= (const NamedValueSet& other) const;
  7052. /** Returns the total number of values that the set contains. */
  7053. int size() const throw();
  7054. /** Returns the value of a named item.
  7055. If the name isn't found, this will return a void variant.
  7056. @see getProperty
  7057. */
  7058. const var& operator[] (const Identifier& name) const;
  7059. /** Tries to return the named value, but if no such value is found, this will
  7060. instead return the supplied default value.
  7061. */
  7062. const var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  7063. /** Changes or adds a named value.
  7064. @returns true if a value was changed or added; false if the
  7065. value was already set the the value passed-in.
  7066. */
  7067. bool set (const Identifier& name, const var& newValue);
  7068. /** Returns true if the set contains an item with the specified name. */
  7069. bool contains (const Identifier& name) const;
  7070. /** Removes a value from the set.
  7071. @returns true if a value was removed; false if there was no value
  7072. with the name that was given.
  7073. */
  7074. bool remove (const Identifier& name);
  7075. /** Returns the name of the value at a given index.
  7076. The index must be between 0 and size() - 1.
  7077. */
  7078. const Identifier getName (int index) const;
  7079. /** Returns the value of the item at a given index.
  7080. The index must be between 0 and size() - 1.
  7081. */
  7082. const var getValueAt (int index) const;
  7083. /** Removes all values. */
  7084. void clear();
  7085. /** Returns a pointer to the var that holds a named value, or null if there is
  7086. no value with this name.
  7087. Do not use this method unless you really need access to the internal var object
  7088. for some reason - for normal reading and writing always prefer operator[]() and set().
  7089. */
  7090. var* getVarPointer (const Identifier& name) const;
  7091. /** Sets properties to the values of all of an XML element's attributes. */
  7092. void setFromXmlAttributes (const XmlElement& xml);
  7093. /** Sets attributes in an XML element corresponding to each of this object's
  7094. properties.
  7095. */
  7096. void copyToXmlAttributes (XmlElement& xml) const;
  7097. private:
  7098. class NamedValue
  7099. {
  7100. public:
  7101. NamedValue() throw();
  7102. NamedValue (const NamedValue&);
  7103. NamedValue (const Identifier& name, const var& value);
  7104. NamedValue& operator= (const NamedValue&);
  7105. bool operator== (const NamedValue& other) const throw();
  7106. LinkedListPointer<NamedValue> nextListItem;
  7107. Identifier name;
  7108. var value;
  7109. private:
  7110. JUCE_LEAK_DETECTOR (NamedValue);
  7111. };
  7112. friend class LinkedListPointer<NamedValue>;
  7113. LinkedListPointer<NamedValue> values;
  7114. };
  7115. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  7116. /*** End of inlined file: juce_NamedValueSet.h ***/
  7117. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  7118. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7119. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7120. /**
  7121. Adds reference-counting to an object.
  7122. To add reference-counting to a class, derive it from this class, and
  7123. use the ReferenceCountedObjectPtr class to point to it.
  7124. e.g. @code
  7125. class MyClass : public ReferenceCountedObject
  7126. {
  7127. void foo();
  7128. // This is a neat way of declaring a typedef for a pointer class,
  7129. // rather than typing out the full templated name each time..
  7130. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7131. };
  7132. MyClass::Ptr p = new MyClass();
  7133. MyClass::Ptr p2 = p;
  7134. p = 0;
  7135. p2->foo();
  7136. @endcode
  7137. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7138. careful not to delete the object manually.
  7139. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  7140. */
  7141. class JUCE_API ReferenceCountedObject
  7142. {
  7143. public:
  7144. /** Increments the object's reference count.
  7145. This is done automatically by the smart pointer, but is public just
  7146. in case it's needed for nefarious purposes.
  7147. */
  7148. inline void incReferenceCount() throw()
  7149. {
  7150. ++refCount;
  7151. }
  7152. /** Decreases the object's reference count.
  7153. If the count gets to zero, the object will be deleted.
  7154. */
  7155. inline void decReferenceCount() throw()
  7156. {
  7157. jassert (getReferenceCount() > 0);
  7158. if (--refCount == 0)
  7159. delete this;
  7160. }
  7161. /** Returns the object's current reference count. */
  7162. inline int getReferenceCount() const throw()
  7163. {
  7164. return refCount.get();
  7165. }
  7166. protected:
  7167. /** Creates the reference-counted object (with an initial ref count of zero). */
  7168. ReferenceCountedObject()
  7169. {
  7170. }
  7171. /** Destructor. */
  7172. virtual ~ReferenceCountedObject()
  7173. {
  7174. // it's dangerous to delete an object that's still referenced by something else!
  7175. jassert (getReferenceCount() == 0);
  7176. }
  7177. private:
  7178. Atomic <int> refCount;
  7179. };
  7180. /**
  7181. A smart-pointer class which points to a reference-counted object.
  7182. The template parameter specifies the class of the object you want to point to - the easiest
  7183. way to make a class reference-countable is to simply make it inherit from ReferenceCountedObject,
  7184. but if you need to, you could roll your own reference-countable class by implementing a pair of
  7185. mathods called incReferenceCount() and decReferenceCount().
  7186. When using this class, you'll probably want to create a typedef to abbreviate the full
  7187. templated name - e.g.
  7188. @code typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;@endcode
  7189. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7190. */
  7191. template <class ReferenceCountedObjectClass>
  7192. class ReferenceCountedObjectPtr
  7193. {
  7194. public:
  7195. /** Creates a pointer to a null object. */
  7196. inline ReferenceCountedObjectPtr() throw()
  7197. : referencedObject (0)
  7198. {
  7199. }
  7200. /** Creates a pointer to an object.
  7201. This will increment the object's reference-count if it is non-null.
  7202. */
  7203. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  7204. : referencedObject (refCountedObject)
  7205. {
  7206. if (refCountedObject != 0)
  7207. refCountedObject->incReferenceCount();
  7208. }
  7209. /** Copies another pointer.
  7210. This will increment the object's reference-count (if it is non-null).
  7211. */
  7212. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  7213. : referencedObject (other.referencedObject)
  7214. {
  7215. if (referencedObject != 0)
  7216. referencedObject->incReferenceCount();
  7217. }
  7218. /** Changes this pointer to point at a different object.
  7219. The reference count of the old object is decremented, and it might be
  7220. deleted if it hits zero. The new object's count is incremented.
  7221. */
  7222. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7223. {
  7224. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7225. if (newObject != referencedObject)
  7226. {
  7227. if (newObject != 0)
  7228. newObject->incReferenceCount();
  7229. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7230. referencedObject = newObject;
  7231. if (oldObject != 0)
  7232. oldObject->decReferenceCount();
  7233. }
  7234. return *this;
  7235. }
  7236. /** Changes this pointer to point at a different object.
  7237. The reference count of the old object is decremented, and it might be
  7238. deleted if it hits zero. The new object's count is incremented.
  7239. */
  7240. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7241. {
  7242. if (referencedObject != newObject)
  7243. {
  7244. if (newObject != 0)
  7245. newObject->incReferenceCount();
  7246. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7247. referencedObject = newObject;
  7248. if (oldObject != 0)
  7249. oldObject->decReferenceCount();
  7250. }
  7251. return *this;
  7252. }
  7253. /** Destructor.
  7254. This will decrement the object's reference-count, and may delete it if it
  7255. gets to zero.
  7256. */
  7257. inline ~ReferenceCountedObjectPtr()
  7258. {
  7259. if (referencedObject != 0)
  7260. referencedObject->decReferenceCount();
  7261. }
  7262. /** Returns the object that this pointer references.
  7263. The pointer returned may be zero, of course.
  7264. */
  7265. inline operator ReferenceCountedObjectClass*() const throw()
  7266. {
  7267. return referencedObject;
  7268. }
  7269. // the -> operator is called on the referenced object
  7270. inline ReferenceCountedObjectClass* operator->() const throw()
  7271. {
  7272. return referencedObject;
  7273. }
  7274. /** Returns the object that this pointer references.
  7275. The pointer returned may be zero, of course.
  7276. */
  7277. inline ReferenceCountedObjectClass* getObject() const throw()
  7278. {
  7279. return referencedObject;
  7280. }
  7281. private:
  7282. ReferenceCountedObjectClass* referencedObject;
  7283. };
  7284. /** Compares two ReferenceCountedObjectPointers. */
  7285. template <class ReferenceCountedObjectClass>
  7286. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectClass* const object2) throw()
  7287. {
  7288. return object1.getObject() == object2;
  7289. }
  7290. /** Compares two ReferenceCountedObjectPointers. */
  7291. template <class ReferenceCountedObjectClass>
  7292. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7293. {
  7294. return object1.getObject() == object2.getObject();
  7295. }
  7296. /** Compares two ReferenceCountedObjectPointers. */
  7297. template <class ReferenceCountedObjectClass>
  7298. bool operator== (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7299. {
  7300. return object1 == object2.getObject();
  7301. }
  7302. /** Compares two ReferenceCountedObjectPointers. */
  7303. template <class ReferenceCountedObjectClass>
  7304. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectClass* object2) throw()
  7305. {
  7306. return object1.getObject() != object2;
  7307. }
  7308. /** Compares two ReferenceCountedObjectPointers. */
  7309. template <class ReferenceCountedObjectClass>
  7310. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7311. {
  7312. return object1.getObject() != object2.getObject();
  7313. }
  7314. /** Compares two ReferenceCountedObjectPointers. */
  7315. template <class ReferenceCountedObjectClass>
  7316. bool operator!= (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7317. {
  7318. return object1 != object2.getObject();
  7319. }
  7320. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7321. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  7322. /**
  7323. Represents a dynamically implemented object.
  7324. This class is primarily intended for wrapping scripting language objects,
  7325. but could be used for other purposes.
  7326. An instance of a DynamicObject can be used to store named properties, and
  7327. by subclassing hasMethod() and invokeMethod(), you can give your object
  7328. methods.
  7329. */
  7330. class JUCE_API DynamicObject : public ReferenceCountedObject
  7331. {
  7332. public:
  7333. DynamicObject();
  7334. /** Destructor. */
  7335. virtual ~DynamicObject();
  7336. /** Returns true if the object has a property with this name.
  7337. Note that if the property is actually a method, this will return false.
  7338. */
  7339. virtual bool hasProperty (const Identifier& propertyName) const;
  7340. /** Returns a named property.
  7341. This returns a void if no such property exists.
  7342. */
  7343. virtual const var getProperty (const Identifier& propertyName) const;
  7344. /** Sets a named property. */
  7345. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  7346. /** Removes a named property. */
  7347. virtual void removeProperty (const Identifier& propertyName);
  7348. /** Checks whether this object has the specified method.
  7349. The default implementation of this just checks whether there's a property
  7350. with this name that's actually a method, but this can be overridden for
  7351. building objects with dynamic invocation.
  7352. */
  7353. virtual bool hasMethod (const Identifier& methodName) const;
  7354. /** Invokes a named method on this object.
  7355. The default implementation looks up the named property, and if it's a method
  7356. call, then it invokes it.
  7357. This method is virtual to allow more dynamic invocation to used for objects
  7358. where the methods may not already be set as properies.
  7359. */
  7360. virtual const var invokeMethod (const Identifier& methodName,
  7361. const var* parameters,
  7362. int numParameters);
  7363. /** Sets up a method.
  7364. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  7365. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  7366. the code easier to read,
  7367. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  7368. @code
  7369. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  7370. @endcode
  7371. */
  7372. void setMethod (const Identifier& methodName,
  7373. var::MethodFunction methodFunction);
  7374. /** Removes all properties and methods from the object. */
  7375. void clear();
  7376. private:
  7377. NamedValueSet properties;
  7378. JUCE_LEAK_DETECTOR (DynamicObject);
  7379. };
  7380. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  7381. /*** End of inlined file: juce_DynamicObject.h ***/
  7382. #endif
  7383. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  7384. #endif
  7385. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7386. #endif
  7387. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  7388. #endif
  7389. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  7390. /*** Start of inlined file: juce_OwnedArray.h ***/
  7391. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  7392. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  7393. /** An array designed for holding objects.
  7394. This holds a list of pointers to objects, and will automatically
  7395. delete the objects when they are removed from the array, or when the
  7396. array is itself deleted.
  7397. Declare it in the form: OwnedArray<MyObjectClass>
  7398. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  7399. After adding objects, they are 'owned' by the array and will be deleted when
  7400. removed or replaced.
  7401. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7402. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7403. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  7404. */
  7405. template <class ObjectClass,
  7406. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7407. class OwnedArray
  7408. {
  7409. public:
  7410. /** Creates an empty array. */
  7411. OwnedArray() throw()
  7412. : numUsed (0)
  7413. {
  7414. }
  7415. /** Deletes the array and also deletes any objects inside it.
  7416. To get rid of the array without deleting its objects, use its
  7417. clear (false) method before deleting it.
  7418. */
  7419. ~OwnedArray()
  7420. {
  7421. clear (true);
  7422. }
  7423. /** Clears the array, optionally deleting the objects inside it first. */
  7424. void clear (const bool deleteObjects = true)
  7425. {
  7426. const ScopedLockType lock (getLock());
  7427. if (deleteObjects)
  7428. {
  7429. while (numUsed > 0)
  7430. delete data.elements [--numUsed];
  7431. }
  7432. data.setAllocatedSize (0);
  7433. numUsed = 0;
  7434. }
  7435. /** Returns the number of items currently in the array.
  7436. @see operator[]
  7437. */
  7438. inline int size() const throw()
  7439. {
  7440. return numUsed;
  7441. }
  7442. /** Returns a pointer to the object at this index in the array.
  7443. If the index is out-of-range, this will return a null pointer, (and
  7444. it could be null anyway, because it's ok for the array to hold null
  7445. pointers as well as objects).
  7446. @see getUnchecked
  7447. */
  7448. inline ObjectClass* operator[] (const int index) const throw()
  7449. {
  7450. const ScopedLockType lock (getLock());
  7451. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  7452. : static_cast <ObjectClass*> (0);
  7453. }
  7454. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7455. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7456. it can be used when you're sure the index if always going to be legal.
  7457. */
  7458. inline ObjectClass* getUnchecked (const int index) const throw()
  7459. {
  7460. const ScopedLockType lock (getLock());
  7461. jassert (isPositiveAndBelow (index, numUsed));
  7462. return data.elements [index];
  7463. }
  7464. /** Returns a pointer to the first object in the array.
  7465. This will return a null pointer if the array's empty.
  7466. @see getLast
  7467. */
  7468. inline ObjectClass* getFirst() const throw()
  7469. {
  7470. const ScopedLockType lock (getLock());
  7471. return numUsed > 0 ? data.elements [0]
  7472. : static_cast <ObjectClass*> (0);
  7473. }
  7474. /** Returns a pointer to the last object in the array.
  7475. This will return a null pointer if the array's empty.
  7476. @see getFirst
  7477. */
  7478. inline ObjectClass* getLast() const throw()
  7479. {
  7480. const ScopedLockType lock (getLock());
  7481. return numUsed > 0 ? data.elements [numUsed - 1]
  7482. : static_cast <ObjectClass*> (0);
  7483. }
  7484. /** Returns a pointer to the actual array data.
  7485. This pointer will only be valid until the next time a non-const method
  7486. is called on the array.
  7487. */
  7488. inline ObjectClass** getRawDataPointer() throw()
  7489. {
  7490. return data.elements;
  7491. }
  7492. /** Finds the index of an object which might be in the array.
  7493. @param objectToLookFor the object to look for
  7494. @returns the index at which the object was found, or -1 if it's not found
  7495. */
  7496. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7497. {
  7498. const ScopedLockType lock (getLock());
  7499. ObjectClass* const* e = data.elements.getData();
  7500. ObjectClass* const* const end = e + numUsed;
  7501. for (; e != end; ++e)
  7502. if (objectToLookFor == *e)
  7503. return static_cast <int> (e - data.elements.getData());
  7504. return -1;
  7505. }
  7506. /** Returns true if the array contains a specified object.
  7507. @param objectToLookFor the object to look for
  7508. @returns true if the object is in the array
  7509. */
  7510. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7511. {
  7512. const ScopedLockType lock (getLock());
  7513. ObjectClass* const* e = data.elements.getData();
  7514. ObjectClass* const* const end = e + numUsed;
  7515. for (; e != end; ++e)
  7516. if (objectToLookFor == *e)
  7517. return true;
  7518. return false;
  7519. }
  7520. /** Appends a new object to the end of the array.
  7521. Note that the this object will be deleted by the OwnedArray when it
  7522. is removed, so be careful not to delete it somewhere else.
  7523. Also be careful not to add the same object to the array more than once,
  7524. as this will obviously cause deletion of dangling pointers.
  7525. @param newObject the new object to add to the array
  7526. @see set, insert, addIfNotAlreadyThere, addSorted
  7527. */
  7528. void add (const ObjectClass* const newObject) throw()
  7529. {
  7530. const ScopedLockType lock (getLock());
  7531. data.ensureAllocatedSize (numUsed + 1);
  7532. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7533. }
  7534. /** Inserts a new object into the array at the given index.
  7535. Note that the this object will be deleted by the OwnedArray when it
  7536. is removed, so be careful not to delete it somewhere else.
  7537. If the index is less than 0 or greater than the size of the array, the
  7538. element will be added to the end of the array.
  7539. Otherwise, it will be inserted into the array, moving all the later elements
  7540. along to make room.
  7541. Be careful not to add the same object to the array more than once,
  7542. as this will obviously cause deletion of dangling pointers.
  7543. @param indexToInsertAt the index at which the new element should be inserted
  7544. @param newObject the new object to add to the array
  7545. @see add, addSorted, addIfNotAlreadyThere, set
  7546. */
  7547. void insert (int indexToInsertAt,
  7548. const ObjectClass* const newObject) throw()
  7549. {
  7550. if (indexToInsertAt >= 0)
  7551. {
  7552. const ScopedLockType lock (getLock());
  7553. if (indexToInsertAt > numUsed)
  7554. indexToInsertAt = numUsed;
  7555. data.ensureAllocatedSize (numUsed + 1);
  7556. ObjectClass** const e = data.elements + indexToInsertAt;
  7557. const int numToMove = numUsed - indexToInsertAt;
  7558. if (numToMove > 0)
  7559. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7560. *e = const_cast <ObjectClass*> (newObject);
  7561. ++numUsed;
  7562. }
  7563. else
  7564. {
  7565. add (newObject);
  7566. }
  7567. }
  7568. /** Appends a new object at the end of the array as long as the array doesn't
  7569. already contain it.
  7570. If the array already contains a matching object, nothing will be done.
  7571. @param newObject the new object to add to the array
  7572. */
  7573. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  7574. {
  7575. const ScopedLockType lock (getLock());
  7576. if (! contains (newObject))
  7577. add (newObject);
  7578. }
  7579. /** Replaces an object in the array with a different one.
  7580. If the index is less than zero, this method does nothing.
  7581. If the index is beyond the end of the array, the new object is added to the end of the array.
  7582. Be careful not to add the same object to the array more than once,
  7583. as this will obviously cause deletion of dangling pointers.
  7584. @param indexToChange the index whose value you want to change
  7585. @param newObject the new value to set for this index.
  7586. @param deleteOldElement whether to delete the object that's being replaced with the new one
  7587. @see add, insert, remove
  7588. */
  7589. void set (const int indexToChange,
  7590. const ObjectClass* const newObject,
  7591. const bool deleteOldElement = true)
  7592. {
  7593. if (indexToChange >= 0)
  7594. {
  7595. ObjectClass* toDelete = 0;
  7596. {
  7597. const ScopedLockType lock (getLock());
  7598. if (indexToChange < numUsed)
  7599. {
  7600. if (deleteOldElement)
  7601. {
  7602. toDelete = data.elements [indexToChange];
  7603. if (toDelete == newObject)
  7604. toDelete = 0;
  7605. }
  7606. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  7607. }
  7608. else
  7609. {
  7610. data.ensureAllocatedSize (numUsed + 1);
  7611. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7612. }
  7613. }
  7614. delete toDelete; // don't want to use a ScopedPointer here because if the
  7615. // object has a private destructor, both OwnedArray and
  7616. // ScopedPointer would need to be friend classes..
  7617. }
  7618. else
  7619. {
  7620. jassertfalse; // you're trying to set an object at a negative index, which doesn't have
  7621. // any effect - but since the object is not being added, it may be leaking..
  7622. }
  7623. }
  7624. /** Adds elements from another array to the end of this array.
  7625. @param arrayToAddFrom the array from which to copy the elements
  7626. @param startIndex the first element of the other array to start copying from
  7627. @param numElementsToAdd how many elements to add from the other array. If this
  7628. value is negative or greater than the number of available elements,
  7629. all available elements will be copied.
  7630. @see add
  7631. */
  7632. template <class OtherArrayType>
  7633. void addArray (const OtherArrayType& arrayToAddFrom,
  7634. int startIndex = 0,
  7635. int numElementsToAdd = -1)
  7636. {
  7637. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7638. const ScopedLockType lock2 (getLock());
  7639. if (startIndex < 0)
  7640. {
  7641. jassertfalse;
  7642. startIndex = 0;
  7643. }
  7644. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7645. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7646. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7647. while (--numElementsToAdd >= 0)
  7648. {
  7649. data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++);
  7650. ++numUsed;
  7651. }
  7652. }
  7653. /** Adds copies of the elements in another array to the end of this array.
  7654. The other array must be either an OwnedArray of a compatible type of object, or an Array
  7655. containing pointers to the same kind of object. The objects involved must provide
  7656. a copy constructor, and this will be used to create new copies of each element, and
  7657. add them to this array.
  7658. @param arrayToAddFrom the array from which to copy the elements
  7659. @param startIndex the first element of the other array to start copying from
  7660. @param numElementsToAdd how many elements to add from the other array. If this
  7661. value is negative or greater than the number of available elements,
  7662. all available elements will be copied.
  7663. @see add
  7664. */
  7665. template <class OtherArrayType>
  7666. void addCopiesOf (const OtherArrayType& arrayToAddFrom,
  7667. int startIndex = 0,
  7668. int numElementsToAdd = -1)
  7669. {
  7670. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7671. const ScopedLockType lock2 (getLock());
  7672. if (startIndex < 0)
  7673. {
  7674. jassertfalse;
  7675. startIndex = 0;
  7676. }
  7677. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7678. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7679. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7680. while (--numElementsToAdd >= 0)
  7681. {
  7682. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  7683. ++numUsed;
  7684. }
  7685. }
  7686. /** Inserts a new object into the array assuming that the array is sorted.
  7687. This will use a comparator to find the position at which the new object
  7688. should go. If the array isn't sorted, the behaviour of this
  7689. method will be unpredictable.
  7690. @param comparator the comparator to use to compare the elements - see the sort method
  7691. for details about this object's structure
  7692. @param newObject the new object to insert to the array
  7693. @see add, sort, indexOfSorted
  7694. */
  7695. template <class ElementComparator>
  7696. void addSorted (ElementComparator& comparator,
  7697. ObjectClass* const newObject) throw()
  7698. {
  7699. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7700. // avoids getting warning messages about the parameter being unused
  7701. const ScopedLockType lock (getLock());
  7702. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  7703. }
  7704. /** Finds the index of an object in the array, assuming that the array is sorted.
  7705. This will use a comparator to do a binary-chop to find the index of the given
  7706. element, if it exists. If the array isn't sorted, the behaviour of this
  7707. method will be unpredictable.
  7708. @param comparator the comparator to use to compare the elements - see the sort()
  7709. method for details about the form this object should take
  7710. @param objectToLookFor the object to search for
  7711. @returns the index of the element, or -1 if it's not found
  7712. @see addSorted, sort
  7713. */
  7714. template <class ElementComparator>
  7715. int indexOfSorted (ElementComparator& comparator,
  7716. const ObjectClass* const objectToLookFor) const throw()
  7717. {
  7718. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7719. // avoids getting warning messages about the parameter being unused
  7720. const ScopedLockType lock (getLock());
  7721. int start = 0;
  7722. int end = numUsed;
  7723. for (;;)
  7724. {
  7725. if (start >= end)
  7726. {
  7727. return -1;
  7728. }
  7729. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  7730. {
  7731. return start;
  7732. }
  7733. else
  7734. {
  7735. const int halfway = (start + end) >> 1;
  7736. if (halfway == start)
  7737. return -1;
  7738. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  7739. start = halfway;
  7740. else
  7741. end = halfway;
  7742. }
  7743. }
  7744. }
  7745. /** Removes an object from the array.
  7746. This will remove the object at a given index (optionally also
  7747. deleting it) and move back all the subsequent objects to close the gap.
  7748. If the index passed in is out-of-range, nothing will happen.
  7749. @param indexToRemove the index of the element to remove
  7750. @param deleteObject whether to delete the object that is removed
  7751. @see removeObject, removeRange
  7752. */
  7753. void remove (const int indexToRemove,
  7754. const bool deleteObject = true)
  7755. {
  7756. ObjectClass* toDelete = 0;
  7757. {
  7758. const ScopedLockType lock (getLock());
  7759. if (isPositiveAndBelow (indexToRemove, numUsed))
  7760. {
  7761. ObjectClass** const e = data.elements + indexToRemove;
  7762. if (deleteObject)
  7763. toDelete = *e;
  7764. --numUsed;
  7765. const int numToShift = numUsed - indexToRemove;
  7766. if (numToShift > 0)
  7767. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  7768. }
  7769. }
  7770. delete toDelete; // don't want to use a ScopedPointer here because if the
  7771. // object has a private destructor, both OwnedArray and
  7772. // ScopedPointer would need to be friend classes..
  7773. if ((numUsed << 1) < data.numAllocated)
  7774. minimiseStorageOverheads();
  7775. }
  7776. /** Removes and returns an object from the array without deleting it.
  7777. This will remove the object at a given index and return it, moving back all
  7778. the subsequent objects to close the gap. If the index passed in is out-of-range,
  7779. nothing will happen.
  7780. @param indexToRemove the index of the element to remove
  7781. @see remove, removeObject, removeRange
  7782. */
  7783. ObjectClass* removeAndReturn (const int indexToRemove)
  7784. {
  7785. ObjectClass* removedItem = 0;
  7786. const ScopedLockType lock (getLock());
  7787. if (isPositiveAndBelow (indexToRemove, numUsed))
  7788. {
  7789. ObjectClass** const e = data.elements + indexToRemove;
  7790. removedItem = *e;
  7791. --numUsed;
  7792. const int numToShift = numUsed - indexToRemove;
  7793. if (numToShift > 0)
  7794. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  7795. if ((numUsed << 1) < data.numAllocated)
  7796. minimiseStorageOverheads();
  7797. }
  7798. return removedItem;
  7799. }
  7800. /** Removes a specified object from the array.
  7801. If the item isn't found, no action is taken.
  7802. @param objectToRemove the object to try to remove
  7803. @param deleteObject whether to delete the object (if it's found)
  7804. @see remove, removeRange
  7805. */
  7806. void removeObject (const ObjectClass* const objectToRemove,
  7807. const bool deleteObject = true)
  7808. {
  7809. const ScopedLockType lock (getLock());
  7810. ObjectClass** const e = data.elements.getData();
  7811. for (int i = 0; i < numUsed; ++i)
  7812. {
  7813. if (objectToRemove == e[i])
  7814. {
  7815. remove (i, deleteObject);
  7816. break;
  7817. }
  7818. }
  7819. }
  7820. /** Removes a range of objects from the array.
  7821. This will remove a set of objects, starting from the given index,
  7822. and move any subsequent elements down to close the gap.
  7823. If the range extends beyond the bounds of the array, it will
  7824. be safely clipped to the size of the array.
  7825. @param startIndex the index of the first object to remove
  7826. @param numberToRemove how many objects should be removed
  7827. @param deleteObjects whether to delete the objects that get removed
  7828. @see remove, removeObject
  7829. */
  7830. void removeRange (int startIndex,
  7831. const int numberToRemove,
  7832. const bool deleteObjects = true)
  7833. {
  7834. const ScopedLockType lock (getLock());
  7835. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  7836. startIndex = jlimit (0, numUsed, startIndex);
  7837. if (endIndex > startIndex)
  7838. {
  7839. if (deleteObjects)
  7840. {
  7841. for (int i = startIndex; i < endIndex; ++i)
  7842. {
  7843. delete data.elements [i];
  7844. data.elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  7845. }
  7846. }
  7847. const int rangeSize = endIndex - startIndex;
  7848. ObjectClass** e = data.elements + startIndex;
  7849. int numToShift = numUsed - endIndex;
  7850. numUsed -= rangeSize;
  7851. while (--numToShift >= 0)
  7852. {
  7853. *e = e [rangeSize];
  7854. ++e;
  7855. }
  7856. if ((numUsed << 1) < data.numAllocated)
  7857. minimiseStorageOverheads();
  7858. }
  7859. }
  7860. /** Removes the last n objects from the array.
  7861. @param howManyToRemove how many objects to remove from the end of the array
  7862. @param deleteObjects whether to also delete the objects that are removed
  7863. @see remove, removeObject, removeRange
  7864. */
  7865. void removeLast (int howManyToRemove = 1,
  7866. const bool deleteObjects = true)
  7867. {
  7868. const ScopedLockType lock (getLock());
  7869. if (howManyToRemove >= numUsed)
  7870. clear (deleteObjects);
  7871. else
  7872. removeRange (numUsed - howManyToRemove, howManyToRemove, deleteObjects);
  7873. }
  7874. /** Swaps a pair of objects in the array.
  7875. If either of the indexes passed in is out-of-range, nothing will happen,
  7876. otherwise the two objects at these positions will be exchanged.
  7877. */
  7878. void swap (const int index1,
  7879. const int index2) throw()
  7880. {
  7881. const ScopedLockType lock (getLock());
  7882. if (isPositiveAndBelow (index1, numUsed)
  7883. && isPositiveAndBelow (index2, numUsed))
  7884. {
  7885. swapVariables (data.elements [index1],
  7886. data.elements [index2]);
  7887. }
  7888. }
  7889. /** Moves one of the objects to a different position.
  7890. This will move the object to a specified index, shuffling along
  7891. any intervening elements as required.
  7892. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  7893. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  7894. @param currentIndex the index of the object to be moved. If this isn't a
  7895. valid index, then nothing will be done
  7896. @param newIndex the index at which you'd like this object to end up. If this
  7897. is less than zero, it will be moved to the end of the array
  7898. */
  7899. void move (const int currentIndex,
  7900. int newIndex) throw()
  7901. {
  7902. if (currentIndex != newIndex)
  7903. {
  7904. const ScopedLockType lock (getLock());
  7905. if (isPositiveAndBelow (currentIndex, numUsed))
  7906. {
  7907. if (! isPositiveAndBelow (newIndex, numUsed))
  7908. newIndex = numUsed - 1;
  7909. ObjectClass* const value = data.elements [currentIndex];
  7910. if (newIndex > currentIndex)
  7911. {
  7912. memmove (data.elements + currentIndex,
  7913. data.elements + currentIndex + 1,
  7914. (newIndex - currentIndex) * sizeof (ObjectClass*));
  7915. }
  7916. else
  7917. {
  7918. memmove (data.elements + newIndex + 1,
  7919. data.elements + newIndex,
  7920. (currentIndex - newIndex) * sizeof (ObjectClass*));
  7921. }
  7922. data.elements [newIndex] = value;
  7923. }
  7924. }
  7925. }
  7926. /** This swaps the contents of this array with those of another array.
  7927. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  7928. because it just swaps their internal pointers.
  7929. */
  7930. void swapWithArray (OwnedArray& otherArray) throw()
  7931. {
  7932. const ScopedLockType lock1 (getLock());
  7933. const ScopedLockType lock2 (otherArray.getLock());
  7934. data.swapWith (otherArray.data);
  7935. swapVariables (numUsed, otherArray.numUsed);
  7936. }
  7937. /** Reduces the amount of storage being used by the array.
  7938. Arrays typically allocate slightly more storage than they need, and after
  7939. removing elements, they may have quite a lot of unused space allocated.
  7940. This method will reduce the amount of allocated storage to a minimum.
  7941. */
  7942. void minimiseStorageOverheads() throw()
  7943. {
  7944. const ScopedLockType lock (getLock());
  7945. data.shrinkToNoMoreThan (numUsed);
  7946. }
  7947. /** Increases the array's internal storage to hold a minimum number of elements.
  7948. Calling this before adding a large known number of elements means that
  7949. the array won't have to keep dynamically resizing itself as the elements
  7950. are added, and it'll therefore be more efficient.
  7951. */
  7952. void ensureStorageAllocated (const int minNumElements) throw()
  7953. {
  7954. const ScopedLockType lock (getLock());
  7955. data.ensureAllocatedSize (minNumElements);
  7956. }
  7957. /** Sorts the elements in the array.
  7958. This will use a comparator object to sort the elements into order. The object
  7959. passed must have a method of the form:
  7960. @code
  7961. int compareElements (ElementType first, ElementType second);
  7962. @endcode
  7963. ..and this method must return:
  7964. - a value of < 0 if the first comes before the second
  7965. - a value of 0 if the two objects are equivalent
  7966. - a value of > 0 if the second comes before the first
  7967. To improve performance, the compareElements() method can be declared as static or const.
  7968. @param comparator the comparator to use for comparing elements.
  7969. @param retainOrderOfEquivalentItems if this is true, then items
  7970. which the comparator says are equivalent will be
  7971. kept in the order in which they currently appear
  7972. in the array. This is slower to perform, but may
  7973. be important in some cases. If it's false, a faster
  7974. algorithm is used, but equivalent elements may be
  7975. rearranged.
  7976. @see sortArray, indexOfSorted
  7977. */
  7978. template <class ElementComparator>
  7979. void sort (ElementComparator& comparator,
  7980. const bool retainOrderOfEquivalentItems = false) const throw()
  7981. {
  7982. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7983. // avoids getting warning messages about the parameter being unused
  7984. const ScopedLockType lock (getLock());
  7985. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  7986. }
  7987. /** Returns the CriticalSection that locks this array.
  7988. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  7989. an object of ScopedLockType as an RAII lock for it.
  7990. */
  7991. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  7992. /** Returns the type of scoped lock to use for locking this array */
  7993. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  7994. private:
  7995. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  7996. int numUsed;
  7997. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OwnedArray);
  7998. };
  7999. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  8000. /*** End of inlined file: juce_OwnedArray.h ***/
  8001. #endif
  8002. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8003. /*** Start of inlined file: juce_PropertySet.h ***/
  8004. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  8005. #define __JUCE_PROPERTYSET_JUCEHEADER__
  8006. /*** Start of inlined file: juce_StringPairArray.h ***/
  8007. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8008. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8009. /*** Start of inlined file: juce_StringArray.h ***/
  8010. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  8011. #define __JUCE_STRINGARRAY_JUCEHEADER__
  8012. /**
  8013. A special array for holding a list of strings.
  8014. @see String, StringPairArray
  8015. */
  8016. class JUCE_API StringArray
  8017. {
  8018. public:
  8019. /** Creates an empty string array */
  8020. StringArray() throw();
  8021. /** Creates a copy of another string array */
  8022. StringArray (const StringArray& other);
  8023. /** Creates an array containing a single string. */
  8024. explicit StringArray (const String& firstValue);
  8025. /** Creates a copy of an array of string literals.
  8026. @param strings an array of strings to add. Null pointers in the array will be
  8027. treated as empty strings
  8028. @param numberOfStrings how many items there are in the array
  8029. */
  8030. StringArray (const char* const* strings, int numberOfStrings);
  8031. /** Creates a copy of a null-terminated array of string literals.
  8032. Each item from the array passed-in is added, until it encounters a null pointer,
  8033. at which point it stops.
  8034. */
  8035. explicit StringArray (const char* const* strings);
  8036. /** Creates a copy of a null-terminated array of string literals.
  8037. Each item from the array passed-in is added, until it encounters a null pointer,
  8038. at which point it stops.
  8039. */
  8040. explicit StringArray (const wchar_t* const* strings);
  8041. /** Creates a copy of an array of string literals.
  8042. @param strings an array of strings to add. Null pointers in the array will be
  8043. treated as empty strings
  8044. @param numberOfStrings how many items there are in the array
  8045. */
  8046. StringArray (const wchar_t* const* strings, int numberOfStrings);
  8047. /** Destructor. */
  8048. ~StringArray();
  8049. /** Copies the contents of another string array into this one */
  8050. StringArray& operator= (const StringArray& other);
  8051. /** Compares two arrays.
  8052. Comparisons are case-sensitive.
  8053. @returns true only if the other array contains exactly the same strings in the same order
  8054. */
  8055. bool operator== (const StringArray& other) const throw();
  8056. /** Compares two arrays.
  8057. Comparisons are case-sensitive.
  8058. @returns false if the other array contains exactly the same strings in the same order
  8059. */
  8060. bool operator!= (const StringArray& other) const throw();
  8061. /** Returns the number of strings in the array */
  8062. inline int size() const throw() { return strings.size(); };
  8063. /** Returns one of the strings from the array.
  8064. If the index is out-of-range, an empty string is returned.
  8065. Obviously the reference returned shouldn't be stored for later use, as the
  8066. string it refers to may disappear when the array changes.
  8067. */
  8068. const String& operator[] (int index) const throw();
  8069. /** Returns a reference to one of the strings in the array.
  8070. This lets you modify a string in-place in the array, but you must be sure that
  8071. the index is in-range.
  8072. */
  8073. String& getReference (int index) throw();
  8074. /** Searches for a string in the array.
  8075. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8076. @returns true if the string is found inside the array
  8077. */
  8078. bool contains (const String& stringToLookFor,
  8079. bool ignoreCase = false) const;
  8080. /** Searches for a string in the array.
  8081. The comparison will be case-insensitive if the ignoreCase parameter is true.
  8082. @param stringToLookFor the string to try to find
  8083. @param ignoreCase whether the comparison should be case-insensitive
  8084. @param startIndex the first index to start searching from
  8085. @returns the index of the first occurrence of the string in this array,
  8086. or -1 if it isn't found.
  8087. */
  8088. int indexOf (const String& stringToLookFor,
  8089. bool ignoreCase = false,
  8090. int startIndex = 0) const;
  8091. /** Appends a string at the end of the array. */
  8092. void add (const String& stringToAdd);
  8093. /** Inserts a string into the array.
  8094. This will insert a string into the array at the given index, moving
  8095. up the other elements to make room for it.
  8096. If the index is less than zero or greater than the size of the array,
  8097. the new string will be added to the end of the array.
  8098. */
  8099. void insert (int index, const String& stringToAdd);
  8100. /** Adds a string to the array as long as it's not already in there.
  8101. The search can optionally be case-insensitive.
  8102. */
  8103. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  8104. /** Replaces one of the strings in the array with another one.
  8105. If the index is higher than the array's size, the new string will be
  8106. added to the end of the array; if it's less than zero nothing happens.
  8107. */
  8108. void set (int index, const String& newString);
  8109. /** Appends some strings from another array to the end of this one.
  8110. @param other the array to add
  8111. @param startIndex the first element of the other array to add
  8112. @param numElementsToAdd the maximum number of elements to add (if this is
  8113. less than zero, they are all added)
  8114. */
  8115. void addArray (const StringArray& other,
  8116. int startIndex = 0,
  8117. int numElementsToAdd = -1);
  8118. /** Breaks up a string into tokens and adds them to this array.
  8119. This will tokenise the given string using whitespace characters as the
  8120. token delimiters, and will add these tokens to the end of the array.
  8121. @returns the number of tokens added
  8122. */
  8123. int addTokens (const String& stringToTokenise,
  8124. bool preserveQuotedStrings);
  8125. /** Breaks up a string into tokens and adds them to this array.
  8126. This will tokenise the given string (using the string passed in to define the
  8127. token delimiters), and will add these tokens to the end of the array.
  8128. @param stringToTokenise the string to tokenise
  8129. @param breakCharacters a string of characters, any of which will be considered
  8130. to be a token delimiter.
  8131. @param quoteCharacters if this string isn't empty, it defines a set of characters
  8132. which are treated as quotes. Any text occurring
  8133. between quotes is not broken up into tokens.
  8134. @returns the number of tokens added
  8135. */
  8136. int addTokens (const String& stringToTokenise,
  8137. const String& breakCharacters,
  8138. const String& quoteCharacters);
  8139. /** Breaks up a string into lines and adds them to this array.
  8140. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  8141. to the array. Line-break characters are omitted from the strings that are added to
  8142. the array.
  8143. */
  8144. int addLines (const String& stringToBreakUp);
  8145. /** Removes all elements from the array. */
  8146. void clear();
  8147. /** Removes a string from the array.
  8148. If the index is out-of-range, no action will be taken.
  8149. */
  8150. void remove (int index);
  8151. /** Finds a string in the array and removes it.
  8152. This will remove the first occurrence of the given string from the array. The
  8153. comparison may be case-insensitive depending on the ignoreCase parameter.
  8154. */
  8155. void removeString (const String& stringToRemove,
  8156. bool ignoreCase = false);
  8157. /** Removes a range of elements from the array.
  8158. This will remove a set of elements, starting from the given index,
  8159. and move subsequent elements down to close the gap.
  8160. If the range extends beyond the bounds of the array, it will
  8161. be safely clipped to the size of the array.
  8162. @param startIndex the index of the first element to remove
  8163. @param numberToRemove how many elements should be removed
  8164. */
  8165. void removeRange (int startIndex, int numberToRemove);
  8166. /** Removes any duplicated elements from the array.
  8167. If any string appears in the array more than once, only the first occurrence of
  8168. it will be retained.
  8169. @param ignoreCase whether to use a case-insensitive comparison
  8170. */
  8171. void removeDuplicates (bool ignoreCase);
  8172. /** Removes empty strings from the array.
  8173. @param removeWhitespaceStrings if true, strings that only contain whitespace
  8174. characters will also be removed
  8175. */
  8176. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  8177. /** Moves one of the strings to a different position.
  8178. This will move the string to a specified index, shuffling along
  8179. any intervening elements as required.
  8180. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8181. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8182. @param currentIndex the index of the value to be moved. If this isn't a
  8183. valid index, then nothing will be done
  8184. @param newIndex the index at which you'd like this value to end up. If this
  8185. is less than zero, the value will be moved to the end
  8186. of the array
  8187. */
  8188. void move (int currentIndex, int newIndex) throw();
  8189. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  8190. void trim();
  8191. /** Adds numbers to the strings in the array, to make each string unique.
  8192. This will add numbers to the ends of groups of similar strings.
  8193. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  8194. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  8195. @param appendNumberToFirstInstance whether the first of a group of similar strings
  8196. also has a number appended to it.
  8197. @param preNumberString when adding a number, this string is added before the number.
  8198. If you pass 0, a default string will be used, which adds
  8199. brackets around the number.
  8200. @param postNumberString this string is appended after any numbers that are added.
  8201. If you pass 0, a default string will be used, which adds
  8202. brackets around the number.
  8203. */
  8204. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  8205. bool appendNumberToFirstInstance,
  8206. CharPointer_UTF8 preNumberString = CharPointer_UTF8 (0),
  8207. CharPointer_UTF8 postNumberString = CharPointer_UTF8 (0));
  8208. /** Joins the strings in the array together into one string.
  8209. This will join a range of elements from the array into a string, separating
  8210. them with a given string.
  8211. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  8212. @param separatorString the string to insert between all the strings
  8213. @param startIndex the first element to join
  8214. @param numberOfElements how many elements to join together. If this is less
  8215. than zero, all available elements will be used.
  8216. */
  8217. const String joinIntoString (const String& separatorString,
  8218. int startIndex = 0,
  8219. int numberOfElements = -1) const;
  8220. /** Sorts the array into alphabetical order.
  8221. @param ignoreCase if true, the comparisons used will be case-sensitive.
  8222. */
  8223. void sort (bool ignoreCase);
  8224. /** Reduces the amount of storage being used by the array.
  8225. Arrays typically allocate slightly more storage than they need, and after
  8226. removing elements, they may have quite a lot of unused space allocated.
  8227. This method will reduce the amount of allocated storage to a minimum.
  8228. */
  8229. void minimiseStorageOverheads();
  8230. private:
  8231. Array <String> strings;
  8232. JUCE_LEAK_DETECTOR (StringArray);
  8233. };
  8234. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  8235. /*** End of inlined file: juce_StringArray.h ***/
  8236. /**
  8237. A container for holding a set of strings which are keyed by another string.
  8238. @see StringArray
  8239. */
  8240. class JUCE_API StringPairArray
  8241. {
  8242. public:
  8243. /** Creates an empty array */
  8244. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  8245. /** Creates a copy of another array */
  8246. StringPairArray (const StringPairArray& other);
  8247. /** Destructor. */
  8248. ~StringPairArray();
  8249. /** Copies the contents of another string array into this one */
  8250. StringPairArray& operator= (const StringPairArray& other);
  8251. /** Compares two arrays.
  8252. Comparisons are case-sensitive.
  8253. @returns true only if the other array contains exactly the same strings with the same keys
  8254. */
  8255. bool operator== (const StringPairArray& other) const;
  8256. /** Compares two arrays.
  8257. Comparisons are case-sensitive.
  8258. @returns false if the other array contains exactly the same strings with the same keys
  8259. */
  8260. bool operator!= (const StringPairArray& other) const;
  8261. /** Finds the value corresponding to a key string.
  8262. If no such key is found, this will just return an empty string. To check whether
  8263. a given key actually exists (because it might actually be paired with an empty string), use
  8264. the getAllKeys() method to obtain a list.
  8265. Obviously the reference returned shouldn't be stored for later use, as the
  8266. string it refers to may disappear when the array changes.
  8267. @see getValue
  8268. */
  8269. const String& operator[] (const String& key) const;
  8270. /** Finds the value corresponding to a key string.
  8271. If no such key is found, this will just return the value provided as a default.
  8272. @see operator[]
  8273. */
  8274. const String getValue (const String& key, const String& defaultReturnValue) const;
  8275. /** Returns a list of all keys in the array. */
  8276. const StringArray& getAllKeys() const throw() { return keys; }
  8277. /** Returns a list of all values in the array. */
  8278. const StringArray& getAllValues() const throw() { return values; }
  8279. /** Returns the number of strings in the array */
  8280. inline int size() const throw() { return keys.size(); };
  8281. /** Adds or amends a key/value pair.
  8282. If a value already exists with this key, its value will be overwritten,
  8283. otherwise the key/value pair will be added to the array.
  8284. */
  8285. void set (const String& key, const String& value);
  8286. /** Adds the items from another array to this one.
  8287. This is equivalent to using set() to add each of the pairs from the other array.
  8288. */
  8289. void addArray (const StringPairArray& other);
  8290. /** Removes all elements from the array. */
  8291. void clear();
  8292. /** Removes a string from the array based on its key.
  8293. If the key isn't found, nothing will happen.
  8294. */
  8295. void remove (const String& key);
  8296. /** Removes a string from the array based on its index.
  8297. If the index is out-of-range, no action will be taken.
  8298. */
  8299. void remove (int index);
  8300. /** Indicates whether to use a case-insensitive search when looking up a key string.
  8301. */
  8302. void setIgnoresCase (bool shouldIgnoreCase);
  8303. /** Returns a descriptive string containing the items.
  8304. This is handy for dumping the contents of an array.
  8305. */
  8306. const String getDescription() const;
  8307. /** Reduces the amount of storage being used by the array.
  8308. Arrays typically allocate slightly more storage than they need, and after
  8309. removing elements, they may have quite a lot of unused space allocated.
  8310. This method will reduce the amount of allocated storage to a minimum.
  8311. */
  8312. void minimiseStorageOverheads();
  8313. private:
  8314. StringArray keys, values;
  8315. bool ignoreCase;
  8316. JUCE_LEAK_DETECTOR (StringPairArray);
  8317. };
  8318. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8319. /*** End of inlined file: juce_StringPairArray.h ***/
  8320. /*** Start of inlined file: juce_XmlElement.h ***/
  8321. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  8322. #define __JUCE_XMLELEMENT_JUCEHEADER__
  8323. /*** Start of inlined file: juce_File.h ***/
  8324. #ifndef __JUCE_FILE_JUCEHEADER__
  8325. #define __JUCE_FILE_JUCEHEADER__
  8326. /*** Start of inlined file: juce_Time.h ***/
  8327. #ifndef __JUCE_TIME_JUCEHEADER__
  8328. #define __JUCE_TIME_JUCEHEADER__
  8329. /*** Start of inlined file: juce_RelativeTime.h ***/
  8330. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  8331. #define __JUCE_RELATIVETIME_JUCEHEADER__
  8332. /** A relative measure of time.
  8333. The time is stored as a number of seconds, at double-precision floating
  8334. point accuracy, and may be positive or negative.
  8335. If you need an absolute time, (i.e. a date + time), see the Time class.
  8336. */
  8337. class JUCE_API RelativeTime
  8338. {
  8339. public:
  8340. /** Creates a RelativeTime.
  8341. @param seconds the number of seconds, which may be +ve or -ve.
  8342. @see milliseconds, minutes, hours, days, weeks
  8343. */
  8344. explicit RelativeTime (double seconds = 0.0) throw();
  8345. /** Copies another relative time. */
  8346. RelativeTime (const RelativeTime& other) throw();
  8347. /** Copies another relative time. */
  8348. RelativeTime& operator= (const RelativeTime& other) throw();
  8349. /** Destructor. */
  8350. ~RelativeTime() throw();
  8351. /** Creates a new RelativeTime object representing a number of milliseconds.
  8352. @see minutes, hours, days, weeks
  8353. */
  8354. static const RelativeTime milliseconds (int milliseconds) throw();
  8355. /** Creates a new RelativeTime object representing a number of milliseconds.
  8356. @see minutes, hours, days, weeks
  8357. */
  8358. static const RelativeTime milliseconds (int64 milliseconds) throw();
  8359. /** Creates a new RelativeTime object representing a number of minutes.
  8360. @see milliseconds, hours, days, weeks
  8361. */
  8362. static const RelativeTime minutes (double numberOfMinutes) throw();
  8363. /** Creates a new RelativeTime object representing a number of hours.
  8364. @see milliseconds, minutes, days, weeks
  8365. */
  8366. static const RelativeTime hours (double numberOfHours) throw();
  8367. /** Creates a new RelativeTime object representing a number of days.
  8368. @see milliseconds, minutes, hours, weeks
  8369. */
  8370. static const RelativeTime days (double numberOfDays) throw();
  8371. /** Creates a new RelativeTime object representing a number of weeks.
  8372. @see milliseconds, minutes, hours, days
  8373. */
  8374. static const RelativeTime weeks (double numberOfWeeks) throw();
  8375. /** Returns the number of milliseconds this time represents.
  8376. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  8377. */
  8378. int64 inMilliseconds() const throw();
  8379. /** Returns the number of seconds this time represents.
  8380. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  8381. */
  8382. double inSeconds() const throw() { return seconds; }
  8383. /** Returns the number of minutes this time represents.
  8384. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  8385. */
  8386. double inMinutes() const throw();
  8387. /** Returns the number of hours this time represents.
  8388. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  8389. */
  8390. double inHours() const throw();
  8391. /** Returns the number of days this time represents.
  8392. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  8393. */
  8394. double inDays() const throw();
  8395. /** Returns the number of weeks this time represents.
  8396. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  8397. */
  8398. double inWeeks() const throw();
  8399. /** Returns a readable textual description of the time.
  8400. The exact format of the string returned will depend on
  8401. the magnitude of the time - e.g.
  8402. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  8403. so that only the two most significant units are printed.
  8404. The returnValueForZeroTime value is the result that is returned if the
  8405. length is zero. Depending on your application you might want to use this
  8406. to return something more relevant like "empty" or "0 secs", etc.
  8407. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  8408. */
  8409. const String getDescription (const String& returnValueForZeroTime = "0") const;
  8410. /** Adds another RelativeTime to this one. */
  8411. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  8412. /** Subtracts another RelativeTime from this one. */
  8413. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  8414. /** Adds a number of seconds to this time. */
  8415. const RelativeTime& operator+= (double secondsToAdd) throw();
  8416. /** Subtracts a number of seconds from this time. */
  8417. const RelativeTime& operator-= (double secondsToSubtract) throw();
  8418. private:
  8419. double seconds;
  8420. };
  8421. /** Compares two RelativeTimes. */
  8422. bool operator== (const RelativeTime& t1, const RelativeTime& t2) throw();
  8423. /** Compares two RelativeTimes. */
  8424. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) throw();
  8425. /** Compares two RelativeTimes. */
  8426. bool operator> (const RelativeTime& t1, const RelativeTime& t2) throw();
  8427. /** Compares two RelativeTimes. */
  8428. bool operator< (const RelativeTime& t1, const RelativeTime& t2) throw();
  8429. /** Compares two RelativeTimes. */
  8430. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) throw();
  8431. /** Compares two RelativeTimes. */
  8432. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) throw();
  8433. /** Adds two RelativeTimes together. */
  8434. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) throw();
  8435. /** Subtracts two RelativeTimes. */
  8436. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) throw();
  8437. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  8438. /*** End of inlined file: juce_RelativeTime.h ***/
  8439. /**
  8440. Holds an absolute date and time.
  8441. Internally, the time is stored at millisecond precision.
  8442. @see RelativeTime
  8443. */
  8444. class JUCE_API Time
  8445. {
  8446. public:
  8447. /** Creates a Time object.
  8448. This default constructor creates a time of 1st January 1970, (which is
  8449. represented internally as 0ms).
  8450. To create a time object representing the current time, use getCurrentTime().
  8451. @see getCurrentTime
  8452. */
  8453. Time() throw();
  8454. /** Creates a time based on a number of milliseconds.
  8455. The internal millisecond count is set to 0 (1st January 1970). To create a
  8456. time object set to the current time, use getCurrentTime().
  8457. @param millisecondsSinceEpoch the number of milliseconds since the unix
  8458. 'epoch' (midnight Jan 1st 1970).
  8459. @see getCurrentTime, currentTimeMillis
  8460. */
  8461. explicit Time (int64 millisecondsSinceEpoch) throw();
  8462. /** Creates a time from a set of date components.
  8463. The timezone is assumed to be whatever the system is using as its locale.
  8464. @param year the year, in 4-digit format, e.g. 2004
  8465. @param month the month, in the range 0 to 11
  8466. @param day the day of the month, in the range 1 to 31
  8467. @param hours hours in 24-hour clock format, 0 to 23
  8468. @param minutes minutes 0 to 59
  8469. @param seconds seconds 0 to 59
  8470. @param milliseconds milliseconds 0 to 999
  8471. @param useLocalTime if true, encode using the current machine's local time; if
  8472. false, it will always work in GMT.
  8473. */
  8474. Time (int year,
  8475. int month,
  8476. int day,
  8477. int hours,
  8478. int minutes,
  8479. int seconds = 0,
  8480. int milliseconds = 0,
  8481. bool useLocalTime = true) throw();
  8482. /** Creates a copy of another Time object. */
  8483. Time (const Time& other) throw();
  8484. /** Destructor. */
  8485. ~Time() throw();
  8486. /** Copies this time from another one. */
  8487. Time& operator= (const Time& other) throw();
  8488. /** Returns a Time object that is set to the current system time.
  8489. @see currentTimeMillis
  8490. */
  8491. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  8492. /** Returns the time as a number of milliseconds.
  8493. @returns the number of milliseconds this Time object represents, since
  8494. midnight jan 1st 1970.
  8495. @see getMilliseconds
  8496. */
  8497. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  8498. /** Returns the year.
  8499. A 4-digit format is used, e.g. 2004.
  8500. */
  8501. int getYear() const throw();
  8502. /** Returns the number of the month.
  8503. The value returned is in the range 0 to 11.
  8504. @see getMonthName
  8505. */
  8506. int getMonth() const throw();
  8507. /** Returns the name of the month.
  8508. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  8509. it'll return the long form, e.g. "January"
  8510. @see getMonth
  8511. */
  8512. const String getMonthName (bool threeLetterVersion) const;
  8513. /** Returns the day of the month.
  8514. The value returned is in the range 1 to 31.
  8515. */
  8516. int getDayOfMonth() const throw();
  8517. /** Returns the number of the day of the week.
  8518. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  8519. */
  8520. int getDayOfWeek() const throw();
  8521. /** Returns the name of the weekday.
  8522. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  8523. false, it'll return the full version, e.g. "Tuesday".
  8524. */
  8525. const String getWeekdayName (bool threeLetterVersion) const;
  8526. /** Returns the number of hours since midnight.
  8527. This is in 24-hour clock format, in the range 0 to 23.
  8528. @see getHoursInAmPmFormat, isAfternoon
  8529. */
  8530. int getHours() const throw();
  8531. /** Returns true if the time is in the afternoon.
  8532. So it returns true for "PM", false for "AM".
  8533. @see getHoursInAmPmFormat, getHours
  8534. */
  8535. bool isAfternoon() const throw();
  8536. /** Returns the hours in 12-hour clock format.
  8537. This will return a value 1 to 12 - use isAfternoon() to find out
  8538. whether this is in the afternoon or morning.
  8539. @see getHours, isAfternoon
  8540. */
  8541. int getHoursInAmPmFormat() const throw();
  8542. /** Returns the number of minutes, 0 to 59. */
  8543. int getMinutes() const throw();
  8544. /** Returns the number of seconds, 0 to 59. */
  8545. int getSeconds() const throw();
  8546. /** Returns the number of milliseconds, 0 to 999.
  8547. Unlike toMilliseconds(), this just returns the position within the
  8548. current second rather than the total number since the epoch.
  8549. @see toMilliseconds
  8550. */
  8551. int getMilliseconds() const throw();
  8552. /** Returns true if the local timezone uses a daylight saving correction. */
  8553. bool isDaylightSavingTime() const throw();
  8554. /** Returns a 3-character string to indicate the local timezone. */
  8555. const String getTimeZone() const throw();
  8556. /** Quick way of getting a string version of a date and time.
  8557. For a more powerful way of formatting the date and time, see the formatted() method.
  8558. @param includeDate whether to include the date in the string
  8559. @param includeTime whether to include the time in the string
  8560. @param includeSeconds if the time is being included, this provides an option not to include
  8561. the seconds in it
  8562. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  8563. hour notation.
  8564. @see formatted
  8565. */
  8566. const String toString (bool includeDate,
  8567. bool includeTime,
  8568. bool includeSeconds = true,
  8569. bool use24HourClock = false) const throw();
  8570. /** Converts this date/time to a string with a user-defined format.
  8571. This uses the C strftime() function to format this time as a string. To save you
  8572. looking it up, these are the escape codes that strftime uses (other codes might
  8573. work on some platforms and not others, but these are the common ones):
  8574. %a is replaced by the locale's abbreviated weekday name.
  8575. %A is replaced by the locale's full weekday name.
  8576. %b is replaced by the locale's abbreviated month name.
  8577. %B is replaced by the locale's full month name.
  8578. %c is replaced by the locale's appropriate date and time representation.
  8579. %d is replaced by the day of the month as a decimal number [01,31].
  8580. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  8581. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  8582. %j is replaced by the day of the year as a decimal number [001,366].
  8583. %m is replaced by the month as a decimal number [01,12].
  8584. %M is replaced by the minute as a decimal number [00,59].
  8585. %p is replaced by the locale's equivalent of either a.m. or p.m.
  8586. %S is replaced by the second as a decimal number [00,61].
  8587. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  8588. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  8589. %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.
  8590. %x is replaced by the locale's appropriate date representation.
  8591. %X is replaced by the locale's appropriate time representation.
  8592. %y is replaced by the year without century as a decimal number [00,99].
  8593. %Y is replaced by the year with century as a decimal number.
  8594. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  8595. %% is replaced by %.
  8596. @see toString
  8597. */
  8598. const String formatted (const String& format) const;
  8599. /** Adds a RelativeTime to this time. */
  8600. Time& operator+= (const RelativeTime& delta);
  8601. /** Subtracts a RelativeTime from this time. */
  8602. Time& operator-= (const RelativeTime& delta);
  8603. /** Tries to set the computer's clock.
  8604. @returns true if this succeeds, although depending on the system, the
  8605. application might not have sufficient privileges to do this.
  8606. */
  8607. bool setSystemTimeToThisTime() const;
  8608. /** Returns the name of a day of the week.
  8609. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  8610. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  8611. false, it'll return the full version, e.g. "Tuesday".
  8612. */
  8613. static const String getWeekdayName (int dayNumber,
  8614. bool threeLetterVersion);
  8615. /** Returns the name of one of the months.
  8616. @param monthNumber the month, 0 to 11
  8617. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  8618. it'll return the long form, e.g. "January"
  8619. */
  8620. static const String getMonthName (int monthNumber,
  8621. bool threeLetterVersion);
  8622. // Static methods for getting system timers directly..
  8623. /** Returns the current system time.
  8624. Returns the number of milliseconds since midnight jan 1st 1970.
  8625. Should be accurate to within a few millisecs, depending on platform,
  8626. hardware, etc.
  8627. */
  8628. static int64 currentTimeMillis() throw();
  8629. /** Returns the number of millisecs since a fixed event (usually system startup).
  8630. This returns a monotonically increasing value which it unaffected by changes to the
  8631. system clock. It should be accurate to within a few millisecs, depending on platform,
  8632. hardware, etc.
  8633. @see getApproximateMillisecondCounter
  8634. */
  8635. static uint32 getMillisecondCounter() throw();
  8636. /** Returns the number of millisecs since a fixed event (usually system startup).
  8637. This has the same function as getMillisecondCounter(), but returns a more accurate
  8638. value, using a higher-resolution timer if one is available.
  8639. @see getMillisecondCounter
  8640. */
  8641. static double getMillisecondCounterHiRes() throw();
  8642. /** Waits until the getMillisecondCounter() reaches a given value.
  8643. This will make the thread sleep as efficiently as it can while it's waiting.
  8644. */
  8645. static void waitForMillisecondCounter (uint32 targetTime) throw();
  8646. /** Less-accurate but faster version of getMillisecondCounter().
  8647. This will return the last value that getMillisecondCounter() returned, so doesn't
  8648. need to make a system call, but is less accurate - it shouldn't be more than
  8649. 100ms away from the correct time, though, so is still accurate enough for a
  8650. lot of purposes.
  8651. @see getMillisecondCounter
  8652. */
  8653. static uint32 getApproximateMillisecondCounter() throw();
  8654. // High-resolution timers..
  8655. /** Returns the current high-resolution counter's tick-count.
  8656. This is a similar idea to getMillisecondCounter(), but with a higher
  8657. resolution.
  8658. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  8659. secondsToHighResolutionTicks
  8660. */
  8661. static int64 getHighResolutionTicks() throw();
  8662. /** Returns the resolution of the high-resolution counter in ticks per second.
  8663. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  8664. secondsToHighResolutionTicks
  8665. */
  8666. static int64 getHighResolutionTicksPerSecond() throw();
  8667. /** Converts a number of high-resolution ticks into seconds.
  8668. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  8669. secondsToHighResolutionTicks
  8670. */
  8671. static double highResolutionTicksToSeconds (int64 ticks) throw();
  8672. /** Converts a number seconds into high-resolution ticks.
  8673. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  8674. highResolutionTicksToSeconds
  8675. */
  8676. static int64 secondsToHighResolutionTicks (double seconds) throw();
  8677. private:
  8678. int64 millisSinceEpoch;
  8679. };
  8680. /** Adds a RelativeTime to a Time. */
  8681. JUCE_API const Time operator+ (const Time& time, const RelativeTime& delta);
  8682. /** Adds a RelativeTime to a Time. */
  8683. JUCE_API const Time operator+ (const RelativeTime& delta, const Time& time);
  8684. /** Subtracts a RelativeTime from a Time. */
  8685. JUCE_API const Time operator- (const Time& time, const RelativeTime& delta);
  8686. /** Returns the relative time difference between two times. */
  8687. JUCE_API const RelativeTime operator- (const Time& time1, const Time& time2);
  8688. /** Compares two Time objects. */
  8689. JUCE_API bool operator== (const Time& time1, const Time& time2);
  8690. /** Compares two Time objects. */
  8691. JUCE_API bool operator!= (const Time& time1, const Time& time2);
  8692. /** Compares two Time objects. */
  8693. JUCE_API bool operator< (const Time& time1, const Time& time2);
  8694. /** Compares two Time objects. */
  8695. JUCE_API bool operator<= (const Time& time1, const Time& time2);
  8696. /** Compares two Time objects. */
  8697. JUCE_API bool operator> (const Time& time1, const Time& time2);
  8698. /** Compares two Time objects. */
  8699. JUCE_API bool operator>= (const Time& time1, const Time& time2);
  8700. #endif // __JUCE_TIME_JUCEHEADER__
  8701. /*** End of inlined file: juce_Time.h ***/
  8702. /*** Start of inlined file: juce_ScopedPointer.h ***/
  8703. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8704. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8705. /**
  8706. This class holds a pointer which is automatically deleted when this object goes
  8707. out of scope.
  8708. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  8709. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  8710. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  8711. created objects.
  8712. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  8713. to an object. If you use the assignment operator to assign a different object to a
  8714. ScopedPointer, the old one will be automatically deleted.
  8715. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  8716. object to which it points during its lifetime. This means that making a copy of a const
  8717. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  8718. old one.
  8719. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  8720. can use the release() method.
  8721. */
  8722. template <class ObjectType>
  8723. class ScopedPointer
  8724. {
  8725. public:
  8726. /** Creates a ScopedPointer containing a null pointer. */
  8727. inline ScopedPointer() throw() : object (0)
  8728. {
  8729. }
  8730. /** Creates a ScopedPointer that owns the specified object. */
  8731. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) throw()
  8732. : object (objectToTakePossessionOf)
  8733. {
  8734. }
  8735. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  8736. Because a pointer can only belong to one ScopedPointer, this transfers
  8737. the pointer from the other object to this one, and the other object is reset to
  8738. be a null pointer.
  8739. */
  8740. ScopedPointer (ScopedPointer& objectToTransferFrom) throw()
  8741. : object (objectToTransferFrom.object)
  8742. {
  8743. objectToTransferFrom.object = 0;
  8744. }
  8745. /** Destructor.
  8746. This will delete the object that this ScopedPointer currently refers to.
  8747. */
  8748. inline ~ScopedPointer() { delete object; }
  8749. /** Changes this ScopedPointer to point to a new object.
  8750. Because a pointer can only belong to one ScopedPointer, this transfers
  8751. the pointer from the other object to this one, and the other object is reset to
  8752. be a null pointer.
  8753. If this ScopedPointer already points to an object, that object
  8754. will first be deleted.
  8755. */
  8756. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  8757. {
  8758. if (this != objectToTransferFrom.getAddress())
  8759. {
  8760. // Two ScopedPointers should never be able to refer to the same object - if
  8761. // this happens, you must have done something dodgy!
  8762. jassert (object == 0 || object != objectToTransferFrom.object);
  8763. ObjectType* const oldObject = object;
  8764. object = objectToTransferFrom.object;
  8765. objectToTransferFrom.object = 0;
  8766. delete oldObject;
  8767. }
  8768. return *this;
  8769. }
  8770. /** Changes this ScopedPointer to point to a new object.
  8771. If this ScopedPointer already points to an object, that object
  8772. will first be deleted.
  8773. The pointer that you pass is may be null.
  8774. */
  8775. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  8776. {
  8777. if (object != newObjectToTakePossessionOf)
  8778. {
  8779. ObjectType* const oldObject = object;
  8780. object = newObjectToTakePossessionOf;
  8781. delete oldObject;
  8782. }
  8783. return *this;
  8784. }
  8785. /** Returns the object that this ScopedPointer refers to. */
  8786. inline operator ObjectType*() const throw() { return object; }
  8787. /** Returns the object that this ScopedPointer refers to. */
  8788. inline ObjectType& operator*() const throw() { return *object; }
  8789. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  8790. inline ObjectType* operator->() const throw() { return object; }
  8791. /** Removes the current object from this ScopedPointer without deleting it.
  8792. This will return the current object, and set the ScopedPointer to a null pointer.
  8793. */
  8794. ObjectType* release() throw() { ObjectType* const o = object; object = 0; return o; }
  8795. /** Swaps this object with that of another ScopedPointer.
  8796. The two objects simply exchange their pointers.
  8797. */
  8798. void swapWith (ScopedPointer <ObjectType>& other) throw()
  8799. {
  8800. // Two ScopedPointers should never be able to refer to the same object - if
  8801. // this happens, you must have done something dodgy!
  8802. jassert (object != other.object);
  8803. swapVariables (object, other.object);
  8804. }
  8805. private:
  8806. ObjectType* object;
  8807. // (Required as an alternative to the overloaded & operator).
  8808. const ScopedPointer* getAddress() const throw() { return this; }
  8809. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  8810. /* This is private to stop people accidentally copying a const ScopedPointer (the compiler
  8811. would let you do so by implicitly casting the source to its raw object pointer).
  8812. A side effect of this is that you may hit a puzzling compiler error when you write something
  8813. like this:
  8814. ScopedPointer<MyClass> m = new MyClass(); // Compile error: copy constructor is private.
  8815. Even though the compiler would normally ignore the assignment here, it can't do so when the
  8816. copy constructor is private. It's very easy to fis though - just write it like this:
  8817. ScopedPointer<MyClass> m (new MyClass()); // Compiles OK
  8818. It's good practice to always use the latter form when writing your object declarations anyway,
  8819. rather than writing them as assignments and assuming (or hoping) that the compiler will be
  8820. smart enough to replace your construction + assignment with a single constructor.
  8821. */
  8822. ScopedPointer (const ScopedPointer&);
  8823. #endif
  8824. };
  8825. /** Compares a ScopedPointer with another pointer.
  8826. This can be handy for checking whether this is a null pointer.
  8827. */
  8828. template <class ObjectType>
  8829. bool operator== (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) throw()
  8830. {
  8831. return static_cast <ObjectType*> (pointer1) == pointer2;
  8832. }
  8833. /** Compares a ScopedPointer with another pointer.
  8834. This can be handy for checking whether this is a null pointer.
  8835. */
  8836. template <class ObjectType>
  8837. bool operator!= (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) throw()
  8838. {
  8839. return static_cast <ObjectType*> (pointer1) != pointer2;
  8840. }
  8841. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8842. /*** End of inlined file: juce_ScopedPointer.h ***/
  8843. class FileInputStream;
  8844. class FileOutputStream;
  8845. /**
  8846. Represents a local file or directory.
  8847. This class encapsulates the absolute pathname of a file or directory, and
  8848. has methods for finding out about the file and changing its properties.
  8849. To read or write to the file, there are methods for returning an input or
  8850. output stream.
  8851. @see FileInputStream, FileOutputStream
  8852. */
  8853. class JUCE_API File
  8854. {
  8855. public:
  8856. /** Creates an (invalid) file object.
  8857. The file is initially set to an empty path, so getFullPath() will return
  8858. an empty string, and comparing the file to File::nonexistent will return
  8859. true.
  8860. You can use its operator= method to point it at a proper file.
  8861. */
  8862. File() {}
  8863. /** Creates a file from an absolute path.
  8864. If the path supplied is a relative path, it is taken to be relative
  8865. to the current working directory (see File::getCurrentWorkingDirectory()),
  8866. but this isn't a recommended way of creating a file, because you
  8867. never know what the CWD is going to be.
  8868. On the Mac/Linux, the path can include "~" notation for referring to
  8869. user home directories.
  8870. */
  8871. File (const String& path);
  8872. /** Creates a copy of another file object. */
  8873. File (const File& other);
  8874. /** Destructor. */
  8875. ~File() {}
  8876. /** Sets the file based on an absolute pathname.
  8877. If the path supplied is a relative path, it is taken to be relative
  8878. to the current working directory (see File::getCurrentWorkingDirectory()),
  8879. but this isn't a recommended way of creating a file, because you
  8880. never know what the CWD is going to be.
  8881. On the Mac/Linux, the path can include "~" notation for referring to
  8882. user home directories.
  8883. */
  8884. File& operator= (const String& newFilePath);
  8885. /** Copies from another file object. */
  8886. File& operator= (const File& otherFile);
  8887. /** This static constant is used for referring to an 'invalid' file. */
  8888. static const File nonexistent;
  8889. /** Checks whether the file actually exists.
  8890. @returns true if the file exists, either as a file or a directory.
  8891. @see existsAsFile, isDirectory
  8892. */
  8893. bool exists() const;
  8894. /** Checks whether the file exists and is a file rather than a directory.
  8895. @returns true only if this is a real file, false if it's a directory
  8896. or doesn't exist
  8897. @see exists, isDirectory
  8898. */
  8899. bool existsAsFile() const;
  8900. /** Checks whether the file is a directory that exists.
  8901. @returns true only if the file is a directory which actually exists, so
  8902. false if it's a file or doesn't exist at all
  8903. @see exists, existsAsFile
  8904. */
  8905. bool isDirectory() const;
  8906. /** Returns the size of the file in bytes.
  8907. @returns the number of bytes in the file, or 0 if it doesn't exist.
  8908. */
  8909. int64 getSize() const;
  8910. /** Utility function to convert a file size in bytes to a neat string description.
  8911. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  8912. 2000000 would produce "2 MB", etc.
  8913. */
  8914. static const String descriptionOfSizeInBytes (int64 bytes);
  8915. /** Returns the complete, absolute path of this file.
  8916. This includes the filename and all its parent folders. On Windows it'll
  8917. also include the drive letter prefix; on Mac or Linux it'll be a complete
  8918. path starting from the root folder.
  8919. If you just want the file's name, you should use getFileName() or
  8920. getFileNameWithoutExtension().
  8921. @see getFileName, getRelativePathFrom
  8922. */
  8923. const String& getFullPathName() const throw() { return fullPath; }
  8924. /** Returns the last section of the pathname.
  8925. Returns just the final part of the path - e.g. if the whole path
  8926. is "/moose/fish/foo.txt" this will return "foo.txt".
  8927. For a directory, it returns the final part of the path - e.g. for the
  8928. directory "/moose/fish" it'll return "fish".
  8929. If the filename begins with a dot, it'll return the whole filename, e.g. for
  8930. "/moose/.fish", it'll return ".fish"
  8931. @see getFullPathName, getFileNameWithoutExtension
  8932. */
  8933. const String getFileName() const;
  8934. /** Creates a relative path that refers to a file relatively to a given directory.
  8935. e.g. File ("/moose/foo.txt").getRelativePathFrom (File ("/moose/fish/haddock"))
  8936. would return "../../foo.txt".
  8937. If it's not possible to navigate from one file to the other, an absolute
  8938. path is returned. If the paths are invalid, an empty string may also be
  8939. returned.
  8940. @param directoryToBeRelativeTo the directory which the resultant string will
  8941. be relative to. If this is actually a file rather than
  8942. a directory, its parent directory will be used instead.
  8943. If it doesn't exist, it's assumed to be a directory.
  8944. @see getChildFile, isAbsolutePath
  8945. */
  8946. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  8947. /** Returns the file's extension.
  8948. Returns the file extension of this file, also including the dot.
  8949. e.g. "/moose/fish/foo.txt" would return ".txt"
  8950. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  8951. */
  8952. const String getFileExtension() const;
  8953. /** Checks whether the file has a given extension.
  8954. @param extensionToTest the extension to look for - it doesn't matter whether or
  8955. not this string has a dot at the start, so ".wav" and "wav"
  8956. will have the same effect. The comparison used is
  8957. case-insensitve. To compare with multiple extensions, this
  8958. parameter can contain multiple strings, separated by semi-colons -
  8959. so, for example: hasFileExtension (".jpeg;png;gif") would return
  8960. true if the file has any of those three extensions.
  8961. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  8962. */
  8963. bool hasFileExtension (const String& extensionToTest) const;
  8964. /** Returns a version of this file with a different file extension.
  8965. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  8966. @param newExtension the new extension, either with or without a dot at the start (this
  8967. doesn't make any difference). To get remove a file's extension altogether,
  8968. pass an empty string into this function.
  8969. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  8970. */
  8971. const File withFileExtension (const String& newExtension) const;
  8972. /** Returns the last part of the filename, without its file extension.
  8973. e.g. for "/moose/fish/foo.txt" this will return "foo".
  8974. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  8975. */
  8976. const String getFileNameWithoutExtension() const;
  8977. /** Returns a 32-bit hash-code that identifies this file.
  8978. This is based on the filename. Obviously it's possible, although unlikely, that
  8979. two files will have the same hash-code.
  8980. */
  8981. int hashCode() const;
  8982. /** Returns a 64-bit hash-code that identifies this file.
  8983. This is based on the filename. Obviously it's possible, although unlikely, that
  8984. two files will have the same hash-code.
  8985. */
  8986. int64 hashCode64() const;
  8987. /** Returns a file based on a relative path.
  8988. This will find a child file or directory of the current object.
  8989. e.g.
  8990. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  8991. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  8992. If the string is actually an absolute path, it will be treated as such, e.g.
  8993. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  8994. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  8995. */
  8996. const File getChildFile (String relativePath) const;
  8997. /** Returns a file which is in the same directory as this one.
  8998. This is equivalent to getParentDirectory().getChildFile (name).
  8999. @see getChildFile, getParentDirectory
  9000. */
  9001. const File getSiblingFile (const String& siblingFileName) const;
  9002. /** Returns the directory that contains this file or directory.
  9003. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  9004. */
  9005. const File getParentDirectory() const;
  9006. /** Checks whether a file is somewhere inside a directory.
  9007. Returns true if this file is somewhere inside a subdirectory of the directory
  9008. that is passed in. Neither file actually has to exist, because the function
  9009. just checks the paths for similarities.
  9010. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  9011. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  9012. */
  9013. bool isAChildOf (const File& potentialParentDirectory) const;
  9014. /** Chooses a filename relative to this one that doesn't already exist.
  9015. If this file is a directory, this will return a child file of this
  9016. directory that doesn't exist, by adding numbers to a prefix and suffix until
  9017. it finds one that isn't already there.
  9018. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  9019. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  9020. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  9021. @param prefix the string to use for the filename before the number
  9022. @param suffix the string to add to the filename after the number
  9023. @param putNumbersInBrackets if true, this will create filenames in the
  9024. format "prefix(number)suffix", if false, it will leave the
  9025. brackets out.
  9026. */
  9027. const File getNonexistentChildFile (const String& prefix,
  9028. const String& suffix,
  9029. bool putNumbersInBrackets = true) const;
  9030. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  9031. If this file doesn't exist, this will just return itself, otherwise it
  9032. will return an appropriate sibling that doesn't exist, e.g. if a file
  9033. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  9034. @param putNumbersInBrackets whether to add brackets around the numbers that
  9035. get appended to the new filename.
  9036. */
  9037. const File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  9038. /** Compares the pathnames for two files. */
  9039. bool operator== (const File& otherFile) const;
  9040. /** Compares the pathnames for two files. */
  9041. bool operator!= (const File& otherFile) const;
  9042. /** Compares the pathnames for two files. */
  9043. bool operator< (const File& otherFile) const;
  9044. /** Compares the pathnames for two files. */
  9045. bool operator> (const File& otherFile) const;
  9046. /** Checks whether a file can be created or written to.
  9047. @returns true if it's possible to create and write to this file. If the file
  9048. doesn't already exist, this will check its parent directory to
  9049. see if writing is allowed.
  9050. @see setReadOnly
  9051. */
  9052. bool hasWriteAccess() const;
  9053. /** Changes the write-permission of a file or directory.
  9054. @param shouldBeReadOnly whether to add or remove write-permission
  9055. @param applyRecursively if the file is a directory and this is true, it will
  9056. recurse through all the subfolders changing the permissions
  9057. of all files
  9058. @returns true if it manages to change the file's permissions.
  9059. @see hasWriteAccess
  9060. */
  9061. bool setReadOnly (bool shouldBeReadOnly,
  9062. bool applyRecursively = false) const;
  9063. /** Returns true if this file is a hidden or system file.
  9064. The criteria for deciding whether a file is hidden are platform-dependent.
  9065. */
  9066. bool isHidden() const;
  9067. /** If this file is a link, this returns the file that it points to.
  9068. If this file isn't actually link, it'll just return itself.
  9069. */
  9070. const File getLinkedTarget() const;
  9071. /** Returns the last modification time of this file.
  9072. @returns the time, or an invalid time if the file doesn't exist.
  9073. @see setLastModificationTime, getLastAccessTime, getCreationTime
  9074. */
  9075. const Time getLastModificationTime() const;
  9076. /** Returns the last time this file was accessed.
  9077. @returns the time, or an invalid time if the file doesn't exist.
  9078. @see setLastAccessTime, getLastModificationTime, getCreationTime
  9079. */
  9080. const Time getLastAccessTime() const;
  9081. /** Returns the time that this file was created.
  9082. @returns the time, or an invalid time if the file doesn't exist.
  9083. @see getLastModificationTime, getLastAccessTime
  9084. */
  9085. const Time getCreationTime() const;
  9086. /** Changes the modification time for this file.
  9087. @param newTime the time to apply to the file
  9088. @returns true if it manages to change the file's time.
  9089. @see getLastModificationTime, setLastAccessTime, setCreationTime
  9090. */
  9091. bool setLastModificationTime (const Time& newTime) const;
  9092. /** Changes the last-access time for this file.
  9093. @param newTime the time to apply to the file
  9094. @returns true if it manages to change the file's time.
  9095. @see getLastAccessTime, setLastModificationTime, setCreationTime
  9096. */
  9097. bool setLastAccessTime (const Time& newTime) const;
  9098. /** Changes the creation date for this file.
  9099. @param newTime the time to apply to the file
  9100. @returns true if it manages to change the file's time.
  9101. @see getCreationTime, setLastModificationTime, setLastAccessTime
  9102. */
  9103. bool setCreationTime (const Time& newTime) const;
  9104. /** If possible, this will try to create a version string for the given file.
  9105. The OS may be able to look at the file and give a version for it - e.g. with
  9106. executables, bundles, dlls, etc. If no version is available, this will
  9107. return an empty string.
  9108. */
  9109. const String getVersion() const;
  9110. /** Creates an empty file if it doesn't already exist.
  9111. If the file that this object refers to doesn't exist, this will create a file
  9112. of zero size.
  9113. If it already exists or is a directory, this method will do nothing.
  9114. @returns true if the file has been created (or if it already existed).
  9115. @see createDirectory
  9116. */
  9117. bool create() const;
  9118. /** Creates a new directory for this filename.
  9119. This will try to create the file as a directory, and fill also create
  9120. any parent directories it needs in order to complete the operation.
  9121. @returns true if the directory has been created successfully, (or if it
  9122. already existed beforehand).
  9123. @see create
  9124. */
  9125. bool createDirectory() const;
  9126. /** Deletes a file.
  9127. If this file is actually a directory, it may not be deleted correctly if it
  9128. contains files. See deleteRecursively() as a better way of deleting directories.
  9129. @returns true if the file has been successfully deleted (or if it didn't exist to
  9130. begin with).
  9131. @see deleteRecursively
  9132. */
  9133. bool deleteFile() const;
  9134. /** Deletes a file or directory and all its subdirectories.
  9135. If this file is a directory, this will try to delete it and all its subfolders. If
  9136. it's just a file, it will just try to delete the file.
  9137. @returns true if the file and all its subfolders have been successfully deleted
  9138. (or if it didn't exist to begin with).
  9139. @see deleteFile
  9140. */
  9141. bool deleteRecursively() const;
  9142. /** Moves this file or folder to the trash.
  9143. @returns true if the operation succeeded. It could fail if the trash is full, or
  9144. if the file is write-protected, so you should check the return value
  9145. and act appropriately.
  9146. */
  9147. bool moveToTrash() const;
  9148. /** Moves or renames a file.
  9149. Tries to move a file to a different location.
  9150. If the target file already exists, this will attempt to delete it first, and
  9151. will fail if this can't be done.
  9152. Note that the destination file isn't the directory to put it in, it's the actual
  9153. filename that you want the new file to have.
  9154. @returns true if the operation succeeds
  9155. */
  9156. bool moveFileTo (const File& targetLocation) const;
  9157. /** Copies a file.
  9158. Tries to copy a file to a different location.
  9159. If the target file already exists, this will attempt to delete it first, and
  9160. will fail if this can't be done.
  9161. @returns true if the operation succeeds
  9162. */
  9163. bool copyFileTo (const File& targetLocation) const;
  9164. /** Copies a directory.
  9165. Tries to copy an entire directory, recursively.
  9166. If this file isn't a directory or if any target files can't be created, this
  9167. will return false.
  9168. @param newDirectory the directory that this one should be copied to. Note that this
  9169. is the name of the actual directory to create, not the directory
  9170. into which the new one should be placed, so there must be enough
  9171. write privileges to create it if it doesn't exist. Any files inside
  9172. it will be overwritten by similarly named ones that are copied.
  9173. */
  9174. bool copyDirectoryTo (const File& newDirectory) const;
  9175. /** Used in file searching, to specify whether to return files, directories, or both.
  9176. */
  9177. enum TypesOfFileToFind
  9178. {
  9179. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  9180. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  9181. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  9182. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  9183. };
  9184. /** Searches inside a directory for files matching a wildcard pattern.
  9185. Assuming that this file is a directory, this method will search it
  9186. for either files or subdirectories whose names match a filename pattern.
  9187. @param results an array to which File objects will be added for the
  9188. files that the search comes up with
  9189. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9190. return files, directories, or both. If the ignoreHiddenFiles flag
  9191. is also added to this value, hidden files won't be returned
  9192. @param searchRecursively if true, all subdirectories will be recursed into to do
  9193. an exhaustive search
  9194. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9195. @returns the number of results that have been found
  9196. @see getNumberOfChildFiles, DirectoryIterator
  9197. */
  9198. int findChildFiles (Array<File>& results,
  9199. int whatToLookFor,
  9200. bool searchRecursively,
  9201. const String& wildCardPattern = "*") const;
  9202. /** Searches inside a directory and counts how many files match a wildcard pattern.
  9203. Assuming that this file is a directory, this method will search it
  9204. for either files or subdirectories whose names match a filename pattern,
  9205. and will return the number of matches found.
  9206. This isn't a recursive call, and will only search this directory, not
  9207. its children.
  9208. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9209. count files, directories, or both. If the ignoreHiddenFiles flag
  9210. is also added to this value, hidden files won't be counted
  9211. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9212. @returns the number of matches found
  9213. @see findChildFiles, DirectoryIterator
  9214. */
  9215. int getNumberOfChildFiles (int whatToLookFor,
  9216. const String& wildCardPattern = "*") const;
  9217. /** Returns true if this file is a directory that contains one or more subdirectories.
  9218. @see isDirectory, findChildFiles
  9219. */
  9220. bool containsSubDirectories() const;
  9221. /** Creates a stream to read from this file.
  9222. @returns a stream that will read from this file (initially positioned at the
  9223. start of the file), or 0 if the file can't be opened for some reason
  9224. @see createOutputStream, loadFileAsData
  9225. */
  9226. FileInputStream* createInputStream() const;
  9227. /** Creates a stream to write to this file.
  9228. If the file exists, the stream that is returned will be positioned ready for
  9229. writing at the end of the file, so you might want to use deleteFile() first
  9230. to write to an empty file.
  9231. @returns a stream that will write to this file (initially positioned at the
  9232. end of the file), or 0 if the file can't be opened for some reason
  9233. @see createInputStream, appendData, appendText
  9234. */
  9235. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  9236. /** Loads a file's contents into memory as a block of binary data.
  9237. Of course, trying to load a very large file into memory will blow up, so
  9238. it's better to check first.
  9239. @param result the data block to which the file's contents should be appended - note
  9240. that if the memory block might already contain some data, you
  9241. might want to clear it first
  9242. @returns true if the file could all be read into memory
  9243. */
  9244. bool loadFileAsData (MemoryBlock& result) const;
  9245. /** Reads a file into memory as a string.
  9246. Attempts to load the entire file as a zero-terminated string.
  9247. This makes use of InputStream::readEntireStreamAsString, which should
  9248. automatically cope with unicode/acsii file formats.
  9249. */
  9250. const String loadFileAsString() const;
  9251. /** Appends a block of binary data to the end of the file.
  9252. This will try to write the given buffer to the end of the file.
  9253. @returns false if it can't write to the file for some reason
  9254. */
  9255. bool appendData (const void* dataToAppend,
  9256. int numberOfBytes) const;
  9257. /** Replaces this file's contents with a given block of data.
  9258. This will delete the file and replace it with the given data.
  9259. A nice feature of this method is that it's safe - instead of deleting
  9260. the file first and then re-writing it, it creates a new temporary file,
  9261. writes the data to that, and then moves the new file to replace the existing
  9262. file. This means that if the power gets pulled out or something crashes,
  9263. you're a lot less likely to end up with a corrupted or unfinished file..
  9264. Returns true if the operation succeeds, or false if it fails.
  9265. @see appendText
  9266. */
  9267. bool replaceWithData (const void* dataToWrite,
  9268. int numberOfBytes) const;
  9269. /** Appends a string to the end of the file.
  9270. This will try to append a text string to the file, as either 16-bit unicode
  9271. or 8-bit characters in the default system encoding.
  9272. It can also write the 'ff fe' unicode header bytes before the text to indicate
  9273. the endianness of the file.
  9274. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  9275. @see replaceWithText
  9276. */
  9277. bool appendText (const String& textToAppend,
  9278. bool asUnicode = false,
  9279. bool writeUnicodeHeaderBytes = false) const;
  9280. /** Replaces this file's contents with a given text string.
  9281. This will delete the file and replace it with the given text.
  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 text 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 an empty file..
  9287. For an explanation of the parameters here, see the appendText() method.
  9288. Returns true if the operation succeeds, or false if it fails.
  9289. @see appendText
  9290. */
  9291. bool replaceWithText (const String& textToWrite,
  9292. bool asUnicode = false,
  9293. bool writeUnicodeHeaderBytes = false) const;
  9294. /** Attempts to scan the contents of this file and compare it to another file, returning
  9295. true if this is possible and they match byte-for-byte.
  9296. */
  9297. bool hasIdenticalContentTo (const File& other) const;
  9298. /** Creates a set of files to represent each file root.
  9299. e.g. on Windows this will create files for "c:\", "d:\" etc according
  9300. to which ones are available. On the Mac/Linux, this will probably
  9301. just add a single entry for "/".
  9302. */
  9303. static void findFileSystemRoots (Array<File>& results);
  9304. /** Finds the name of the drive on which this file lives.
  9305. @returns the volume label of the drive, or an empty string if this isn't possible
  9306. */
  9307. const String getVolumeLabel() const;
  9308. /** Returns the serial number of the volume on which this file lives.
  9309. @returns the serial number, or zero if there's a problem doing this
  9310. */
  9311. int getVolumeSerialNumber() const;
  9312. /** Returns the number of bytes free on the drive that this file lives on.
  9313. @returns the number of bytes free, or 0 if there's a problem finding this out
  9314. @see getVolumeTotalSize
  9315. */
  9316. int64 getBytesFreeOnVolume() const;
  9317. /** Returns the total size of the drive that contains this file.
  9318. @returns the total number of bytes that the volume can hold
  9319. @see getBytesFreeOnVolume
  9320. */
  9321. int64 getVolumeTotalSize() const;
  9322. /** Returns true if this file is on a CD or DVD drive. */
  9323. bool isOnCDRomDrive() const;
  9324. /** Returns true if this file is on a hard disk.
  9325. This will fail if it's a network drive, but will still be true for
  9326. removable hard-disks.
  9327. */
  9328. bool isOnHardDisk() const;
  9329. /** Returns true if this file is on a removable disk drive.
  9330. This might be a usb-drive, a CD-rom, or maybe a network drive.
  9331. */
  9332. bool isOnRemovableDrive() const;
  9333. /** Launches the file as a process.
  9334. - if the file is executable, this will run it.
  9335. - if it's a document of some kind, it will launch the document with its
  9336. default viewer application.
  9337. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  9338. @see revealToUser
  9339. */
  9340. bool startAsProcess (const String& parameters = String::empty) const;
  9341. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  9342. @see startAsProcess
  9343. */
  9344. void revealToUser() const;
  9345. /** A set of types of location that can be passed to the getSpecialLocation() method.
  9346. */
  9347. enum SpecialLocationType
  9348. {
  9349. /** The user's home folder. This is the same as using File ("~"). */
  9350. userHomeDirectory,
  9351. /** The user's default documents folder. On Windows, this might be the user's
  9352. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  9353. doesn't tend to have one of these, so it might just return their home folder.
  9354. */
  9355. userDocumentsDirectory,
  9356. /** The folder that contains the user's desktop objects. */
  9357. userDesktopDirectory,
  9358. /** The folder in which applications store their persistent user-specific settings.
  9359. On Windows, this might be "\Documents and Settings\username\Application Data".
  9360. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  9361. always create your own sub-folder to put them in, to avoid making a mess.
  9362. */
  9363. userApplicationDataDirectory,
  9364. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  9365. of the computer, rather than just the current user.
  9366. On the Mac it'll be "/Library", on Windows, it could be something like
  9367. "\Documents and Settings\All Users\Application Data".
  9368. Depending on the setup, this folder may be read-only.
  9369. */
  9370. commonApplicationDataDirectory,
  9371. /** The folder that should be used for temporary files.
  9372. Always delete them when you're finished, to keep the user's computer tidy!
  9373. */
  9374. tempDirectory,
  9375. /** Returns this application's executable file.
  9376. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  9377. host app.
  9378. On the mac this will return the unix binary, not the package folder - see
  9379. currentApplicationFile for that.
  9380. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  9381. file link, invokedExecutableFile will return the name of the link.
  9382. */
  9383. currentExecutableFile,
  9384. /** Returns this application's location.
  9385. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  9386. host app.
  9387. On the mac this will return the package folder (if it's in one), not the unix binary
  9388. that's inside it - compare with currentExecutableFile.
  9389. */
  9390. currentApplicationFile,
  9391. /** Returns the file that was invoked to launch this executable.
  9392. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  9393. will return the name of the link that was used, whereas currentExecutableFile will return
  9394. the actual location of the target executable.
  9395. */
  9396. invokedExecutableFile,
  9397. /** In a plugin, this will return the path of the host executable. */
  9398. hostApplicationPath,
  9399. /** The directory in which applications normally get installed.
  9400. So on windows, this would be something like "c:\program files", on the
  9401. Mac "/Applications", or "/usr" on linux.
  9402. */
  9403. globalApplicationsDirectory,
  9404. /** The most likely place where a user might store their music files.
  9405. */
  9406. userMusicDirectory,
  9407. /** The most likely place where a user might store their movie files.
  9408. */
  9409. userMoviesDirectory,
  9410. };
  9411. /** Finds the location of a special type of file or directory, such as a home folder or
  9412. documents folder.
  9413. @see SpecialLocationType
  9414. */
  9415. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  9416. /** Returns a temporary file in the system's temp directory.
  9417. This will try to return the name of a non-existent temp file.
  9418. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  9419. */
  9420. static const File createTempFile (const String& fileNameEnding);
  9421. /** Returns the current working directory.
  9422. @see setAsCurrentWorkingDirectory
  9423. */
  9424. static const File getCurrentWorkingDirectory();
  9425. /** Sets the current working directory to be this file.
  9426. For this to work the file must point to a valid directory.
  9427. @returns true if the current directory has been changed.
  9428. @see getCurrentWorkingDirectory
  9429. */
  9430. bool setAsCurrentWorkingDirectory() const;
  9431. /** The system-specific file separator character.
  9432. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  9433. */
  9434. static const juce_wchar separator;
  9435. /** The system-specific file separator character, as a string.
  9436. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  9437. */
  9438. static const String separatorString;
  9439. /** Removes illegal characters from a filename.
  9440. This will return a copy of the given string after removing characters
  9441. that are not allowed in a legal filename, and possibly shortening the
  9442. string if it's too long.
  9443. Because this will remove slashes, don't use it on an absolute pathname.
  9444. @see createLegalPathName
  9445. */
  9446. static const String createLegalFileName (const String& fileNameToFix);
  9447. /** Removes illegal characters from a pathname.
  9448. Similar to createLegalFileName(), but this won't remove slashes, so can
  9449. be used on a complete pathname.
  9450. @see createLegalFileName
  9451. */
  9452. static const String createLegalPathName (const String& pathNameToFix);
  9453. /** Indicates whether filenames are case-sensitive on the current operating system.
  9454. */
  9455. static bool areFileNamesCaseSensitive();
  9456. /** Returns true if the string seems to be a fully-specified absolute path.
  9457. */
  9458. static bool isAbsolutePath (const String& path);
  9459. /** Creates a file that simply contains this string, without doing the sanity-checking
  9460. that the normal constructors do.
  9461. Best to avoid this unless you really know what you're doing.
  9462. */
  9463. static const File createFileWithoutCheckingPath (const String& path);
  9464. /** Adds a separator character to the end of a path if it doesn't already have one. */
  9465. static const String addTrailingSeparator (const String& path);
  9466. private:
  9467. String fullPath;
  9468. // internal way of contructing a file without checking the path
  9469. friend class DirectoryIterator;
  9470. File (const String&, int);
  9471. const String getPathUpToLastSlash() const;
  9472. void createDirectoryInternal (const String& fileName) const;
  9473. bool copyInternal (const File& dest) const;
  9474. bool moveInternal (const File& dest) const;
  9475. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  9476. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  9477. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  9478. static const String parseAbsolutePath (const String& path);
  9479. JUCE_LEAK_DETECTOR (File);
  9480. };
  9481. #endif // __JUCE_FILE_JUCEHEADER__
  9482. /*** End of inlined file: juce_File.h ***/
  9483. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  9484. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  9485. will be the name of a pointer to each child element.
  9486. E.g. @code
  9487. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  9488. forEachXmlChildElement (*myParentXml, child)
  9489. {
  9490. if (child->hasTagName ("FOO"))
  9491. doSomethingWithXmlElement (child);
  9492. }
  9493. @endcode
  9494. @see forEachXmlChildElementWithTagName
  9495. */
  9496. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  9497. \
  9498. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  9499. childElementVariableName != 0; \
  9500. childElementVariableName = childElementVariableName->getNextElement())
  9501. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  9502. which have a specified tag.
  9503. This does the same job as the forEachXmlChildElement macro, but only for those
  9504. elements that have a particular tag name.
  9505. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  9506. will be the name of a pointer to each child element. The requiredTagName is the
  9507. tag name to match.
  9508. E.g. @code
  9509. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  9510. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  9511. {
  9512. // the child object is now guaranteed to be a <MYTAG> element..
  9513. doSomethingWithMYTAGElement (child);
  9514. }
  9515. @endcode
  9516. @see forEachXmlChildElement
  9517. */
  9518. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  9519. \
  9520. for (JUCE_NAMESPACE::XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  9521. childElementVariableName != 0; \
  9522. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  9523. /** Used to build a tree of elements representing an XML document.
  9524. An XML document can be parsed into a tree of XmlElements, each of which
  9525. represents an XML tag structure, and which may itself contain other
  9526. nested elements.
  9527. An XmlElement can also be converted back into a text document, and has
  9528. lots of useful methods for manipulating its attributes and sub-elements,
  9529. so XmlElements can actually be used as a handy general-purpose data
  9530. structure.
  9531. Here's an example of parsing some elements: @code
  9532. // check we're looking at the right kind of document..
  9533. if (myElement->hasTagName ("ANIMALS"))
  9534. {
  9535. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  9536. forEachXmlChildElement (*myElement, e)
  9537. {
  9538. if (e->hasTagName ("GIRAFFE"))
  9539. {
  9540. // found a giraffe, so use some of its attributes..
  9541. String giraffeName = e->getStringAttribute ("name");
  9542. int giraffeAge = e->getIntAttribute ("age");
  9543. bool isFriendly = e->getBoolAttribute ("friendly");
  9544. }
  9545. }
  9546. }
  9547. @endcode
  9548. And here's an example of how to create an XML document from scratch: @code
  9549. // create an outer node called "ANIMALS"
  9550. XmlElement animalsList ("ANIMALS");
  9551. for (int i = 0; i < numAnimals; ++i)
  9552. {
  9553. // create an inner element..
  9554. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  9555. giraffe->setAttribute ("name", "nigel");
  9556. giraffe->setAttribute ("age", 10);
  9557. giraffe->setAttribute ("friendly", true);
  9558. // ..and add our new element to the parent node
  9559. animalsList.addChildElement (giraffe);
  9560. }
  9561. // now we can turn the whole thing into a text document..
  9562. String myXmlDoc = animalsList.createDocument (String::empty);
  9563. @endcode
  9564. @see XmlDocument
  9565. */
  9566. class JUCE_API XmlElement
  9567. {
  9568. public:
  9569. /** Creates an XmlElement with this tag name. */
  9570. explicit XmlElement (const String& tagName) throw();
  9571. /** Creates a (deep) copy of another element. */
  9572. XmlElement (const XmlElement& other);
  9573. /** Creates a (deep) copy of another element. */
  9574. XmlElement& operator= (const XmlElement& other);
  9575. /** Deleting an XmlElement will also delete all its child elements. */
  9576. ~XmlElement() throw();
  9577. /** Compares two XmlElements to see if they contain the same text and attiributes.
  9578. The elements are only considered equivalent if they contain the same attiributes
  9579. with the same values, and have the same sub-nodes.
  9580. @param other the other element to compare to
  9581. @param ignoreOrderOfAttributes if true, this means that two elements with the
  9582. same attributes in a different order will be
  9583. considered the same; if false, the attributes must
  9584. be in the same order as well
  9585. */
  9586. bool isEquivalentTo (const XmlElement* other,
  9587. bool ignoreOrderOfAttributes) const throw();
  9588. /** Returns an XML text document that represents this element.
  9589. The string returned can be parsed to recreate the same XmlElement that
  9590. was used to create it.
  9591. @param dtdToUse the DTD to add to the document
  9592. @param allOnOneLine if true, this means that the document will not contain any
  9593. linefeeds, so it'll be smaller but not very easy to read.
  9594. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  9595. document
  9596. @param encodingType the character encoding format string to put into the xml
  9597. header
  9598. @param lineWrapLength the line length that will be used before items get placed on
  9599. a new line. This isn't an absolute maximum length, it just
  9600. determines how lists of attributes get broken up
  9601. @see writeToStream, writeToFile
  9602. */
  9603. const String createDocument (const String& dtdToUse,
  9604. bool allOnOneLine = false,
  9605. bool includeXmlHeader = true,
  9606. const String& encodingType = "UTF-8",
  9607. int lineWrapLength = 60) const;
  9608. /** Writes the document to a stream as UTF-8.
  9609. @param output the stream to write to
  9610. @param dtdToUse the DTD to add to the document
  9611. @param allOnOneLine if true, this means that the document will not contain any
  9612. linefeeds, so it'll be smaller but not very easy to read.
  9613. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  9614. document
  9615. @param encodingType the character encoding format string to put into the xml
  9616. header
  9617. @param lineWrapLength the line length that will be used before items get placed on
  9618. a new line. This isn't an absolute maximum length, it just
  9619. determines how lists of attributes get broken up
  9620. @see writeToFile, createDocument
  9621. */
  9622. void writeToStream (OutputStream& output,
  9623. const String& dtdToUse,
  9624. bool allOnOneLine = false,
  9625. bool includeXmlHeader = true,
  9626. const String& encodingType = "UTF-8",
  9627. int lineWrapLength = 60) const;
  9628. /** Writes the element to a file as an XML document.
  9629. To improve safety in case something goes wrong while writing the file, this
  9630. will actually write the document to a new temporary file in the same
  9631. directory as the destination file, and if this succeeds, it will rename this
  9632. new file as the destination file (overwriting any existing file that was there).
  9633. @param destinationFile the file to write to. If this already exists, it will be
  9634. overwritten.
  9635. @param dtdToUse the DTD to add to the document
  9636. @param encodingType the character encoding format string to put into the xml
  9637. header
  9638. @param lineWrapLength the line length that will be used before items get placed on
  9639. a new line. This isn't an absolute maximum length, it just
  9640. determines how lists of attributes get broken up
  9641. @returns true if the file is written successfully; false if something goes wrong
  9642. in the process
  9643. @see createDocument
  9644. */
  9645. bool writeToFile (const File& destinationFile,
  9646. const String& dtdToUse,
  9647. const String& encodingType = "UTF-8",
  9648. int lineWrapLength = 60) const;
  9649. /** Returns this element's tag type name.
  9650. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  9651. "MOOSE".
  9652. @see hasTagName
  9653. */
  9654. inline const String& getTagName() const throw() { return tagName; }
  9655. /** Tests whether this element has a particular tag name.
  9656. @param possibleTagName the tag name you're comparing it with
  9657. @see getTagName
  9658. */
  9659. bool hasTagName (const String& possibleTagName) const throw();
  9660. /** Returns the number of XML attributes this element contains.
  9661. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  9662. return 2.
  9663. */
  9664. int getNumAttributes() const throw();
  9665. /** Returns the name of one of the elements attributes.
  9666. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  9667. getAttributeName(1) would return "antlers".
  9668. @see getAttributeValue, getStringAttribute
  9669. */
  9670. const String& getAttributeName (int attributeIndex) const throw();
  9671. /** Returns the value of one of the elements attributes.
  9672. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  9673. getAttributeName(1) would return "2".
  9674. @see getAttributeName, getStringAttribute
  9675. */
  9676. const String& getAttributeValue (int attributeIndex) const throw();
  9677. // Attribute-handling methods..
  9678. /** Checks whether the element contains an attribute with a certain name. */
  9679. bool hasAttribute (const String& attributeName) const throw();
  9680. /** Returns the value of a named attribute.
  9681. @param attributeName the name of the attribute to look up
  9682. */
  9683. const String& getStringAttribute (const String& attributeName) const throw();
  9684. /** Returns the value of a named attribute.
  9685. @param attributeName the name of the attribute to look up
  9686. @param defaultReturnValue a value to return if the element doesn't have an attribute
  9687. with this name
  9688. */
  9689. const String getStringAttribute (const String& attributeName,
  9690. const String& defaultReturnValue) const;
  9691. /** Compares the value of a named attribute with a value passed-in.
  9692. @param attributeName the name of the attribute to look up
  9693. @param stringToCompareAgainst the value to compare it with
  9694. @param ignoreCase whether the comparison should be case-insensitive
  9695. @returns true if the value of the attribute is the same as the string passed-in;
  9696. false if it's different (or if no such attribute exists)
  9697. */
  9698. bool compareAttribute (const String& attributeName,
  9699. const String& stringToCompareAgainst,
  9700. bool ignoreCase = false) const throw();
  9701. /** Returns the value of a named attribute as an integer.
  9702. This will try to find the attribute and convert it to an integer (using
  9703. the String::getIntValue() method).
  9704. @param attributeName the name of the attribute to look up
  9705. @param defaultReturnValue a value to return if the element doesn't have an attribute
  9706. with this name
  9707. @see setAttribute
  9708. */
  9709. int getIntAttribute (const String& attributeName,
  9710. int defaultReturnValue = 0) const;
  9711. /** Returns the value of a named attribute as floating-point.
  9712. This will try to find the attribute and convert it to an integer (using
  9713. the String::getDoubleValue() method).
  9714. @param attributeName the name of the attribute to look up
  9715. @param defaultReturnValue a value to return if the element doesn't have an attribute
  9716. with this name
  9717. @see setAttribute
  9718. */
  9719. double getDoubleAttribute (const String& attributeName,
  9720. double defaultReturnValue = 0.0) const;
  9721. /** Returns the value of a named attribute as a boolean.
  9722. This will try to find the attribute and interpret it as a boolean. To do this,
  9723. it'll return true if the value is "1", "true", "y", etc, or false for other
  9724. values.
  9725. @param attributeName the name of the attribute to look up
  9726. @param defaultReturnValue a value to return if the element doesn't have an attribute
  9727. with this name
  9728. */
  9729. bool getBoolAttribute (const String& attributeName,
  9730. bool defaultReturnValue = false) const;
  9731. /** Adds a named attribute to the element.
  9732. If the element already contains an attribute with this name, it's value will
  9733. be updated to the new value. If there's no such attribute yet, a new one will
  9734. be added.
  9735. Note that there are other setAttribute() methods that take integers,
  9736. doubles, etc. to make it easy to store numbers.
  9737. @param attributeName the name of the attribute to set
  9738. @param newValue the value to set it to
  9739. @see removeAttribute
  9740. */
  9741. void setAttribute (const String& attributeName,
  9742. const String& newValue);
  9743. /** Adds a named attribute to the element, setting it to an integer value.
  9744. If the element already contains an attribute with this name, it's value will
  9745. be updated to the new value. If there's no such attribute yet, a new one will
  9746. be added.
  9747. Note that there are other setAttribute() methods that take integers,
  9748. doubles, etc. to make it easy to store numbers.
  9749. @param attributeName the name of the attribute to set
  9750. @param newValue the value to set it to
  9751. */
  9752. void setAttribute (const String& attributeName,
  9753. int newValue);
  9754. /** Adds a named attribute to the element, setting it to a floating-point value.
  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. */
  9763. void setAttribute (const String& attributeName,
  9764. double newValue);
  9765. /** Removes a named attribute from the element.
  9766. @param attributeName the name of the attribute to remove
  9767. @see removeAllAttributes
  9768. */
  9769. void removeAttribute (const String& attributeName) throw();
  9770. /** Removes all attributes from this element.
  9771. */
  9772. void removeAllAttributes() throw();
  9773. // Child element methods..
  9774. /** Returns the first of this element's sub-elements.
  9775. see getNextElement() for an example of how to iterate the sub-elements.
  9776. @see forEachXmlChildElement
  9777. */
  9778. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  9779. /** Returns the next of this element's siblings.
  9780. This can be used for iterating an element's sub-elements, e.g.
  9781. @code
  9782. XmlElement* child = myXmlDocument->getFirstChildElement();
  9783. while (child != 0)
  9784. {
  9785. ...do stuff with this child..
  9786. child = child->getNextElement();
  9787. }
  9788. @endcode
  9789. Note that when iterating the child elements, some of them might be
  9790. text elements as well as XML tags - use isTextElement() to work this
  9791. out.
  9792. Also, it's much easier and neater to use this method indirectly via the
  9793. forEachXmlChildElement macro.
  9794. @returns the sibling element that follows this one, or zero if this is the last
  9795. element in its parent
  9796. @see getNextElement, isTextElement, forEachXmlChildElement
  9797. */
  9798. inline XmlElement* getNextElement() const throw() { return nextListItem; }
  9799. /** Returns the next of this element's siblings which has the specified tag
  9800. name.
  9801. This is like getNextElement(), but will scan through the list until it
  9802. finds an element with the given tag name.
  9803. @see getNextElement, forEachXmlChildElementWithTagName
  9804. */
  9805. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  9806. /** Returns the number of sub-elements in this element.
  9807. @see getChildElement
  9808. */
  9809. int getNumChildElements() const throw();
  9810. /** Returns the sub-element at a certain index.
  9811. It's not very efficient to iterate the sub-elements by index - see
  9812. getNextElement() for an example of how best to iterate.
  9813. @returns the n'th child of this element, or 0 if the index is out-of-range
  9814. @see getNextElement, isTextElement, getChildByName
  9815. */
  9816. XmlElement* getChildElement (int index) const throw();
  9817. /** Returns the first sub-element with a given tag-name.
  9818. @param tagNameToLookFor the tag name of the element you want to find
  9819. @returns the first element with this tag name, or 0 if none is found
  9820. @see getNextElement, isTextElement, getChildElement
  9821. */
  9822. XmlElement* getChildByName (const String& tagNameToLookFor) const throw();
  9823. /** Appends an element to this element's list of children.
  9824. Child elements are deleted automatically when their parent is deleted, so
  9825. make sure the object that you pass in will not be deleted by anything else,
  9826. and make sure it's not already the child of another element.
  9827. @see getFirstChildElement, getNextElement, getNumChildElements,
  9828. getChildElement, removeChildElement
  9829. */
  9830. void addChildElement (XmlElement* newChildElement) throw();
  9831. /** Inserts an element into this element's list of children.
  9832. Child elements are deleted automatically when their parent is deleted, so
  9833. make sure the object that you pass in will not be deleted by anything else,
  9834. and make sure it's not already the child of another element.
  9835. @param newChildNode the element to add
  9836. @param indexToInsertAt the index at which to insert the new element - if this is
  9837. below zero, it will be added to the end of the list
  9838. @see addChildElement, insertChildElement
  9839. */
  9840. void insertChildElement (XmlElement* newChildNode,
  9841. int indexToInsertAt) throw();
  9842. /** Creates a new element with the given name and returns it, after adding it
  9843. as a child element.
  9844. This is a handy method that means that instead of writing this:
  9845. @code
  9846. XmlElement* newElement = new XmlElement ("foobar");
  9847. myParentElement->addChildElement (newElement);
  9848. @endcode
  9849. ..you could just write this:
  9850. @code
  9851. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  9852. @endcode
  9853. */
  9854. XmlElement* createNewChildElement (const String& tagName);
  9855. /** Replaces one of this element's children with another node.
  9856. If the current element passed-in isn't actually a child of this element,
  9857. this will return false and the new one won't be added. Otherwise, the
  9858. existing element will be deleted, replaced with the new one, and it
  9859. will return true.
  9860. */
  9861. bool replaceChildElement (XmlElement* currentChildElement,
  9862. XmlElement* newChildNode) throw();
  9863. /** Removes a child element.
  9864. @param childToRemove the child to look for and remove
  9865. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  9866. just remove it
  9867. */
  9868. void removeChildElement (XmlElement* childToRemove,
  9869. bool shouldDeleteTheChild) throw();
  9870. /** Deletes all the child elements in the element.
  9871. @see removeChildElement, deleteAllChildElementsWithTagName
  9872. */
  9873. void deleteAllChildElements() throw();
  9874. /** Deletes all the child elements with a given tag name.
  9875. @see removeChildElement
  9876. */
  9877. void deleteAllChildElementsWithTagName (const String& tagName) throw();
  9878. /** Returns true if the given element is a child of this one. */
  9879. bool containsChildElement (const XmlElement* possibleChild) const throw();
  9880. /** Recursively searches all sub-elements to find one that contains the specified
  9881. child element.
  9882. */
  9883. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) throw();
  9884. /** Sorts the child elements using a comparator.
  9885. This will use a comparator object to sort the elements into order. The object
  9886. passed must have a method of the form:
  9887. @code
  9888. int compareElements (const XmlElement* first, const XmlElement* second);
  9889. @endcode
  9890. ..and this method must return:
  9891. - a value of < 0 if the first comes before the second
  9892. - a value of 0 if the two objects are equivalent
  9893. - a value of > 0 if the second comes before the first
  9894. To improve performance, the compareElements() method can be declared as static or const.
  9895. @param comparator the comparator to use for comparing elements.
  9896. @param retainOrderOfEquivalentItems if this is true, then items which the comparator
  9897. says are equivalent will be kept in the order in which they
  9898. currently appear in the array. This is slower to perform, but
  9899. may be important in some cases. If it's false, a faster algorithm
  9900. is used, but equivalent elements may be rearranged.
  9901. */
  9902. template <class ElementComparator>
  9903. void sortChildElements (ElementComparator& comparator,
  9904. bool retainOrderOfEquivalentItems = false)
  9905. {
  9906. const int num = getNumChildElements();
  9907. if (num > 1)
  9908. {
  9909. HeapBlock <XmlElement*> elems (num);
  9910. getChildElementsAsArray (elems);
  9911. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  9912. reorderChildElements (elems, num);
  9913. }
  9914. }
  9915. /** Returns true if this element is a section of text.
  9916. Elements can either be an XML tag element or a secton of text, so this
  9917. is used to find out what kind of element this one is.
  9918. @see getAllText, addTextElement, deleteAllTextElements
  9919. */
  9920. bool isTextElement() const throw();
  9921. /** Returns the text for a text element.
  9922. Note that if you have an element like this:
  9923. @code<xyz>hello</xyz>@endcode
  9924. then calling getText on the "xyz" element won't return "hello", because that is
  9925. actually stored in a special text sub-element inside the xyz element. To get the
  9926. "hello" string, you could either call getText on the (unnamed) sub-element, or
  9927. use getAllSubText() to do this automatically.
  9928. Note that leading and trailing whitespace will be included in the string - to remove
  9929. if, just call String::trim() on the result.
  9930. @see isTextElement, getAllSubText, getChildElementAllSubText
  9931. */
  9932. const String& getText() const throw();
  9933. /** Sets the text in a text element.
  9934. Note that this is only a valid call if this element is a text element. If it's
  9935. not, then no action will be performed. If you're trying to add text inside a normal
  9936. element, you probably want to use addTextElement() instead.
  9937. */
  9938. void setText (const String& newText);
  9939. /** Returns all the text from this element's child nodes.
  9940. This iterates all the child elements and when it finds text elements,
  9941. it concatenates their text into a big string which it returns.
  9942. E.g. @code<xyz>hello <x>there</x> world</xyz>@endcode
  9943. if you called getAllSubText on the "xyz" element, it'd return "hello there world".
  9944. Note that leading and trailing whitespace will be included in the string - to remove
  9945. if, just call String::trim() on the result.
  9946. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  9947. */
  9948. const String getAllSubText() const;
  9949. /** Returns all the sub-text of a named child element.
  9950. If there is a child element with the given tag name, this will return
  9951. all of its sub-text (by calling getAllSubText() on it). If there is
  9952. no such child element, this will return the default string passed-in.
  9953. @see getAllSubText
  9954. */
  9955. const String getChildElementAllSubText (const String& childTagName,
  9956. const String& defaultReturnValue) const;
  9957. /** Appends a section of text to this element.
  9958. @see isTextElement, getText, getAllSubText
  9959. */
  9960. void addTextElement (const String& text);
  9961. /** Removes all the text elements from this element.
  9962. @see isTextElement, getText, getAllSubText, addTextElement
  9963. */
  9964. void deleteAllTextElements() throw();
  9965. /** Creates a text element that can be added to a parent element.
  9966. */
  9967. static XmlElement* createTextElement (const String& text);
  9968. private:
  9969. struct XmlAttributeNode
  9970. {
  9971. XmlAttributeNode (const XmlAttributeNode& other) throw();
  9972. XmlAttributeNode (const String& name, const String& value) throw();
  9973. LinkedListPointer<XmlAttributeNode> nextListItem;
  9974. String name, value;
  9975. bool hasName (const String& name) const throw();
  9976. private:
  9977. XmlAttributeNode& operator= (const XmlAttributeNode&);
  9978. };
  9979. friend class XmlDocument;
  9980. friend class LinkedListPointer<XmlAttributeNode>;
  9981. friend class LinkedListPointer <XmlElement>;
  9982. friend class LinkedListPointer <XmlElement>::Appender;
  9983. LinkedListPointer <XmlElement> nextListItem;
  9984. LinkedListPointer <XmlElement> firstChildElement;
  9985. LinkedListPointer <XmlAttributeNode> attributes;
  9986. String tagName;
  9987. XmlElement (int) throw();
  9988. void copyChildrenAndAttributesFrom (const XmlElement& other);
  9989. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  9990. void getChildElementsAsArray (XmlElement**) const throw();
  9991. void reorderChildElements (XmlElement**, int) throw();
  9992. JUCE_LEAK_DETECTOR (XmlElement);
  9993. };
  9994. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  9995. /*** End of inlined file: juce_XmlElement.h ***/
  9996. /**
  9997. A set of named property values, which can be strings, integers, floating point, etc.
  9998. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  9999. to load and save types other than strings.
  10000. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  10001. messages and saves/loads the list from a file.
  10002. */
  10003. class JUCE_API PropertySet
  10004. {
  10005. public:
  10006. /** Creates an empty PropertySet.
  10007. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  10008. case-insensitive way
  10009. */
  10010. PropertySet (bool ignoreCaseOfKeyNames = false);
  10011. /** Creates a copy of another PropertySet.
  10012. */
  10013. PropertySet (const PropertySet& other);
  10014. /** Copies another PropertySet over this one.
  10015. */
  10016. PropertySet& operator= (const PropertySet& other);
  10017. /** Destructor. */
  10018. virtual ~PropertySet();
  10019. /** Returns one of the properties as a string.
  10020. If the value isn't found in this set, then this will look for it in a fallback
  10021. property set (if you've specified one with the setFallbackPropertySet() method),
  10022. and if it can't find one there, it'll return the default value passed-in.
  10023. @param keyName the name of the property to retrieve
  10024. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10025. */
  10026. const String getValue (const String& keyName,
  10027. const String& defaultReturnValue = String::empty) const throw();
  10028. /** Returns one of the properties as an integer.
  10029. If the value isn't found in this set, then this will look for it in a fallback
  10030. property set (if you've specified one with the setFallbackPropertySet() method),
  10031. and if it can't find one there, it'll return the default value passed-in.
  10032. @param keyName the name of the property to retrieve
  10033. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10034. */
  10035. int getIntValue (const String& keyName,
  10036. const int defaultReturnValue = 0) const throw();
  10037. /** Returns one of the properties as an double.
  10038. If the value isn't found in this set, then this will look for it in a fallback
  10039. property set (if you've specified one with the setFallbackPropertySet() method),
  10040. and if it can't find one there, it'll return the default value passed-in.
  10041. @param keyName the name of the property to retrieve
  10042. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10043. */
  10044. double getDoubleValue (const String& keyName,
  10045. const double defaultReturnValue = 0.0) const throw();
  10046. /** Returns one of the properties as an boolean.
  10047. The result will be true if the string found for this key name can be parsed as a non-zero
  10048. integer.
  10049. If the value isn't found in this set, then this will look for it in a fallback
  10050. property set (if you've specified one with the setFallbackPropertySet() method),
  10051. and if it can't find one there, it'll return the default value passed-in.
  10052. @param keyName the name of the property to retrieve
  10053. @param defaultReturnValue a value to return if the named property doesn't actually exist
  10054. */
  10055. bool getBoolValue (const String& keyName,
  10056. const bool defaultReturnValue = false) const throw();
  10057. /** Returns one of the properties as an XML element.
  10058. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  10059. key isn't found, or if the entry contains an string that isn't valid XML.
  10060. If the value isn't found in this set, then this will look for it in a fallback
  10061. property set (if you've specified one with the setFallbackPropertySet() method),
  10062. and if it can't find one there, it'll return the default value passed-in.
  10063. @param keyName the name of the property to retrieve
  10064. */
  10065. XmlElement* getXmlValue (const String& keyName) const;
  10066. /** Sets a named property.
  10067. @param keyName the name of the property to set. (This mustn't be an empty string)
  10068. @param value the new value to set it to
  10069. */
  10070. void setValue (const String& keyName, const var& value);
  10071. /** Sets a named property to an XML element.
  10072. @param keyName the name of the property to set. (This mustn't be an empty string)
  10073. @param xml the new element to set it to. If this is zero, the value will be set to
  10074. an empty string
  10075. @see getXmlValue
  10076. */
  10077. void setValue (const String& keyName, const XmlElement* xml);
  10078. /** Deletes a property.
  10079. @param keyName the name of the property to delete. (This mustn't be an empty string)
  10080. */
  10081. void removeValue (const String& keyName);
  10082. /** Returns true if the properies include the given key. */
  10083. bool containsKey (const String& keyName) const throw();
  10084. /** Removes all values. */
  10085. void clear();
  10086. /** Returns the keys/value pair array containing all the properties. */
  10087. StringPairArray& getAllProperties() throw() { return properties; }
  10088. /** Returns the lock used when reading or writing to this set */
  10089. const CriticalSection& getLock() const throw() { return lock; }
  10090. /** Returns an XML element which encapsulates all the items in this property set.
  10091. The string parameter is the tag name that should be used for the node.
  10092. @see restoreFromXml
  10093. */
  10094. XmlElement* createXml (const String& nodeName) const;
  10095. /** Reloads a set of properties that were previously stored as XML.
  10096. The node passed in must have been created by the createXml() method.
  10097. @see createXml
  10098. */
  10099. void restoreFromXml (const XmlElement& xml);
  10100. /** Sets up a second PopertySet that will be used to look up any values that aren't
  10101. set in this one.
  10102. If you set this up to be a pointer to a second property set, then whenever one
  10103. of the getValue() methods fails to find an entry in this set, it will look up that
  10104. value in the fallback set, and if it finds it, it will return that.
  10105. Make sure that you don't delete the fallback set while it's still being used by
  10106. another set! To remove the fallback set, just call this method with a null pointer.
  10107. @see getFallbackPropertySet
  10108. */
  10109. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  10110. /** Returns the fallback property set.
  10111. @see setFallbackPropertySet
  10112. */
  10113. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  10114. protected:
  10115. /** Subclasses can override this to be told when one of the properies has been changed. */
  10116. virtual void propertyChanged();
  10117. private:
  10118. StringPairArray properties;
  10119. PropertySet* fallbackProperties;
  10120. CriticalSection lock;
  10121. bool ignoreCaseOfKeys;
  10122. JUCE_LEAK_DETECTOR (PropertySet);
  10123. };
  10124. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  10125. /*** End of inlined file: juce_PropertySet.h ***/
  10126. #endif
  10127. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10128. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  10129. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10130. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10131. /**
  10132. Holds a list of objects derived from ReferenceCountedObject.
  10133. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  10134. and takes care of incrementing and decrementing their ref counts when they
  10135. are added and removed from the array.
  10136. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  10137. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  10138. @see Array, OwnedArray, StringArray
  10139. */
  10140. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  10141. class ReferenceCountedArray
  10142. {
  10143. public:
  10144. typedef ReferenceCountedObjectPtr<ObjectClass> ObjectClassPtr;
  10145. /** Creates an empty array.
  10146. @see ReferenceCountedObject, Array, OwnedArray
  10147. */
  10148. ReferenceCountedArray() throw()
  10149. : numUsed (0)
  10150. {
  10151. }
  10152. /** Creates a copy of another array */
  10153. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  10154. {
  10155. const ScopedLockType lock (other.getLock());
  10156. numUsed = other.numUsed;
  10157. data.setAllocatedSize (numUsed);
  10158. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  10159. for (int i = numUsed; --i >= 0;)
  10160. if (data.elements[i] != 0)
  10161. data.elements[i]->incReferenceCount();
  10162. }
  10163. /** Copies another array into this one.
  10164. Any existing objects in this array will first be released.
  10165. */
  10166. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  10167. {
  10168. if (this != &other)
  10169. {
  10170. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  10171. swapWithArray (otherCopy);
  10172. }
  10173. return *this;
  10174. }
  10175. /** Destructor.
  10176. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  10177. */
  10178. ~ReferenceCountedArray()
  10179. {
  10180. clear();
  10181. }
  10182. /** Removes all objects from the array.
  10183. Any objects in the array that are not referenced from elsewhere will be deleted.
  10184. */
  10185. void clear()
  10186. {
  10187. const ScopedLockType lock (getLock());
  10188. while (numUsed > 0)
  10189. if (data.elements [--numUsed] != 0)
  10190. data.elements [numUsed]->decReferenceCount();
  10191. jassert (numUsed == 0);
  10192. data.setAllocatedSize (0);
  10193. }
  10194. /** Returns the current number of objects in the array. */
  10195. inline int size() const throw()
  10196. {
  10197. return numUsed;
  10198. }
  10199. /** Returns a pointer to the object at this index in the array.
  10200. If the index is out-of-range, this will return a null pointer, (and
  10201. it could be null anyway, because it's ok for the array to hold null
  10202. pointers as well as objects).
  10203. @see getUnchecked
  10204. */
  10205. inline const ObjectClassPtr operator[] (const int index) const throw()
  10206. {
  10207. const ScopedLockType lock (getLock());
  10208. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  10209. : static_cast <ObjectClass*> (0);
  10210. }
  10211. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  10212. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  10213. it can be used when you're sure the index if always going to be legal.
  10214. */
  10215. inline const ObjectClassPtr getUnchecked (const int index) const throw()
  10216. {
  10217. const ScopedLockType lock (getLock());
  10218. jassert (isPositiveAndBelow (index, numUsed));
  10219. return data.elements [index];
  10220. }
  10221. /** Returns a pointer to the first object in the array.
  10222. This will return a null pointer if the array's empty.
  10223. @see getLast
  10224. */
  10225. inline const ObjectClassPtr getFirst() const throw()
  10226. {
  10227. const ScopedLockType lock (getLock());
  10228. return numUsed > 0 ? data.elements [0]
  10229. : static_cast <ObjectClass*> (0);
  10230. }
  10231. /** Returns a pointer to the last object in the array.
  10232. This will return a null pointer if the array's empty.
  10233. @see getFirst
  10234. */
  10235. inline const ObjectClassPtr getLast() const throw()
  10236. {
  10237. const ScopedLockType lock (getLock());
  10238. return numUsed > 0 ? data.elements [numUsed - 1]
  10239. : static_cast <ObjectClass*> (0);
  10240. }
  10241. /** Finds the index of the first occurrence of an object in the array.
  10242. @param objectToLookFor the object to look for
  10243. @returns the index at which the object was found, or -1 if it's not found
  10244. */
  10245. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  10246. {
  10247. const ScopedLockType lock (getLock());
  10248. ObjectClass** e = data.elements.getData();
  10249. ObjectClass** const end = e + numUsed;
  10250. while (e != end)
  10251. {
  10252. if (objectToLookFor == *e)
  10253. return static_cast <int> (e - data.elements.getData());
  10254. ++e;
  10255. }
  10256. return -1;
  10257. }
  10258. /** Returns true if the array contains a specified object.
  10259. @param objectToLookFor the object to look for
  10260. @returns true if the object is in the array
  10261. */
  10262. bool contains (const ObjectClass* const objectToLookFor) const throw()
  10263. {
  10264. const ScopedLockType lock (getLock());
  10265. ObjectClass** e = data.elements.getData();
  10266. ObjectClass** const end = e + numUsed;
  10267. while (e != end)
  10268. {
  10269. if (objectToLookFor == *e)
  10270. return true;
  10271. ++e;
  10272. }
  10273. return false;
  10274. }
  10275. /** Appends a new object to the end of the array.
  10276. This will increase the new object's reference count.
  10277. @param newObject the new object to add to the array
  10278. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  10279. */
  10280. void add (ObjectClass* const newObject) throw()
  10281. {
  10282. const ScopedLockType lock (getLock());
  10283. data.ensureAllocatedSize (numUsed + 1);
  10284. data.elements [numUsed++] = newObject;
  10285. if (newObject != 0)
  10286. newObject->incReferenceCount();
  10287. }
  10288. /** Inserts a new object into the array at the given index.
  10289. If the index is less than 0 or greater than the size of the array, the
  10290. element will be added to the end of the array.
  10291. Otherwise, it will be inserted into the array, moving all the later elements
  10292. along to make room.
  10293. This will increase the new object's reference count.
  10294. @param indexToInsertAt the index at which the new element should be inserted
  10295. @param newObject the new object to add to the array
  10296. @see add, addSorted, addIfNotAlreadyThere, set
  10297. */
  10298. void insert (int indexToInsertAt,
  10299. ObjectClass* const newObject) throw()
  10300. {
  10301. if (indexToInsertAt >= 0)
  10302. {
  10303. const ScopedLockType lock (getLock());
  10304. if (indexToInsertAt > numUsed)
  10305. indexToInsertAt = numUsed;
  10306. data.ensureAllocatedSize (numUsed + 1);
  10307. ObjectClass** const e = data.elements + indexToInsertAt;
  10308. const int numToMove = numUsed - indexToInsertAt;
  10309. if (numToMove > 0)
  10310. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  10311. *e = newObject;
  10312. if (newObject != 0)
  10313. newObject->incReferenceCount();
  10314. ++numUsed;
  10315. }
  10316. else
  10317. {
  10318. add (newObject);
  10319. }
  10320. }
  10321. /** Appends a new object at the end of the array as long as the array doesn't
  10322. already contain it.
  10323. If the array already contains a matching object, nothing will be done.
  10324. @param newObject the new object to add to the array
  10325. */
  10326. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  10327. {
  10328. const ScopedLockType lock (getLock());
  10329. if (! contains (newObject))
  10330. add (newObject);
  10331. }
  10332. /** Replaces an object in the array with a different one.
  10333. If the index is less than zero, this method does nothing.
  10334. If the index is beyond the end of the array, the new object is added to the end of the array.
  10335. The object being added has its reference count increased, and if it's replacing
  10336. another object, then that one has its reference count decreased, and may be deleted.
  10337. @param indexToChange the index whose value you want to change
  10338. @param newObject the new value to set for this index.
  10339. @see add, insert, remove
  10340. */
  10341. void set (const int indexToChange,
  10342. ObjectClass* const newObject)
  10343. {
  10344. if (indexToChange >= 0)
  10345. {
  10346. const ScopedLockType lock (getLock());
  10347. if (newObject != 0)
  10348. newObject->incReferenceCount();
  10349. if (indexToChange < numUsed)
  10350. {
  10351. if (data.elements [indexToChange] != 0)
  10352. data.elements [indexToChange]->decReferenceCount();
  10353. data.elements [indexToChange] = newObject;
  10354. }
  10355. else
  10356. {
  10357. data.ensureAllocatedSize (numUsed + 1);
  10358. data.elements [numUsed++] = newObject;
  10359. }
  10360. }
  10361. }
  10362. /** Adds elements from another array to the end of this array.
  10363. @param arrayToAddFrom the array from which to copy the elements
  10364. @param startIndex the first element of the other array to start copying from
  10365. @param numElementsToAdd how many elements to add from the other array. If this
  10366. value is negative or greater than the number of available elements,
  10367. all available elements will be copied.
  10368. @see add
  10369. */
  10370. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  10371. int startIndex = 0,
  10372. int numElementsToAdd = -1) throw()
  10373. {
  10374. const ScopedLockType lock1 (arrayToAddFrom.getLock());
  10375. {
  10376. const ScopedLockType lock2 (getLock());
  10377. if (startIndex < 0)
  10378. {
  10379. jassertfalse;
  10380. startIndex = 0;
  10381. }
  10382. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  10383. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  10384. if (numElementsToAdd > 0)
  10385. {
  10386. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  10387. while (--numElementsToAdd >= 0)
  10388. add (arrayToAddFrom.getUnchecked (startIndex++));
  10389. }
  10390. }
  10391. }
  10392. /** Inserts a new object into the array assuming that the array is sorted.
  10393. This will use a comparator to find the position at which the new object
  10394. should go. If the array isn't sorted, the behaviour of this
  10395. method will be unpredictable.
  10396. @param comparator the comparator object to use to compare the elements - see the
  10397. sort() method for details about this object's form
  10398. @param newObject the new object to insert to the array
  10399. @see add, sort
  10400. */
  10401. template <class ElementComparator>
  10402. void addSorted (ElementComparator& comparator,
  10403. ObjectClass* newObject) throw()
  10404. {
  10405. const ScopedLockType lock (getLock());
  10406. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  10407. }
  10408. /** Inserts or replaces an object in the array, assuming it is sorted.
  10409. This is similar to addSorted, but if a matching element already exists, then it will be
  10410. replaced by the new one, rather than the new one being added as well.
  10411. */
  10412. template <class ElementComparator>
  10413. void addOrReplaceSorted (ElementComparator& comparator,
  10414. ObjectClass* newObject) throw()
  10415. {
  10416. const ScopedLockType lock (getLock());
  10417. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  10418. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  10419. set (index - 1, newObject); // replace an existing object that matches
  10420. else
  10421. insert (index, newObject); // no match, so insert the new one
  10422. }
  10423. /** Removes an object from the array.
  10424. This will remove the object at a given index and move back all the
  10425. subsequent objects to close the gap.
  10426. If the index passed in is out-of-range, nothing will happen.
  10427. The object that is removed will have its reference count decreased,
  10428. and may be deleted if not referenced from elsewhere.
  10429. @param indexToRemove the index of the element to remove
  10430. @see removeObject, removeRange
  10431. */
  10432. void remove (const int indexToRemove)
  10433. {
  10434. const ScopedLockType lock (getLock());
  10435. if (isPositiveAndBelow (indexToRemove, numUsed))
  10436. {
  10437. ObjectClass** const e = data.elements + indexToRemove;
  10438. if (*e != 0)
  10439. (*e)->decReferenceCount();
  10440. --numUsed;
  10441. const int numberToShift = numUsed - indexToRemove;
  10442. if (numberToShift > 0)
  10443. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  10444. if ((numUsed << 1) < data.numAllocated)
  10445. minimiseStorageOverheads();
  10446. }
  10447. }
  10448. /** Removes and returns an object from the array.
  10449. This will remove the object at a given index and return it, moving back all
  10450. the subsequent objects to close the gap. If the index passed in is out-of-range,
  10451. nothing will happen and a null pointer will be returned.
  10452. @param indexToRemove the index of the element to remove
  10453. @see remove, removeObject, removeRange
  10454. */
  10455. const ObjectClassPtr removeAndReturn (const int indexToRemove)
  10456. {
  10457. ObjectClassPtr removedItem;
  10458. const ScopedLockType lock (getLock());
  10459. if (isPositiveAndBelow (indexToRemove, numUsed))
  10460. {
  10461. ObjectClass** const e = data.elements + indexToRemove;
  10462. if (*e != 0)
  10463. {
  10464. removedItem = *e;
  10465. (*e)->decReferenceCount();
  10466. }
  10467. --numUsed;
  10468. const int numberToShift = numUsed - indexToRemove;
  10469. if (numberToShift > 0)
  10470. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  10471. if ((numUsed << 1) < data.numAllocated)
  10472. minimiseStorageOverheads();
  10473. }
  10474. return removedItem;
  10475. }
  10476. /** Removes the first occurrence of a specified object from the array.
  10477. If the item isn't found, no action is taken. If it is found, it is
  10478. removed and has its reference count decreased.
  10479. @param objectToRemove the object to try to remove
  10480. @see remove, removeRange
  10481. */
  10482. void removeObject (ObjectClass* const objectToRemove)
  10483. {
  10484. const ScopedLockType lock (getLock());
  10485. remove (indexOf (objectToRemove));
  10486. }
  10487. /** Removes a range of objects from the array.
  10488. This will remove a set of objects, starting from the given index,
  10489. and move any subsequent elements down to close the gap.
  10490. If the range extends beyond the bounds of the array, it will
  10491. be safely clipped to the size of the array.
  10492. The objects that are removed will have their reference counts decreased,
  10493. and may be deleted if not referenced from elsewhere.
  10494. @param startIndex the index of the first object to remove
  10495. @param numberToRemove how many objects should be removed
  10496. @see remove, removeObject
  10497. */
  10498. void removeRange (const int startIndex,
  10499. const int numberToRemove)
  10500. {
  10501. const ScopedLockType lock (getLock());
  10502. const int start = jlimit (0, numUsed, startIndex);
  10503. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  10504. if (end > start)
  10505. {
  10506. int i;
  10507. for (i = start; i < end; ++i)
  10508. {
  10509. if (data.elements[i] != 0)
  10510. {
  10511. data.elements[i]->decReferenceCount();
  10512. data.elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  10513. }
  10514. }
  10515. const int rangeSize = end - start;
  10516. ObjectClass** e = data.elements + start;
  10517. i = numUsed - end;
  10518. numUsed -= rangeSize;
  10519. while (--i >= 0)
  10520. {
  10521. *e = e [rangeSize];
  10522. ++e;
  10523. }
  10524. if ((numUsed << 1) < data.numAllocated)
  10525. minimiseStorageOverheads();
  10526. }
  10527. }
  10528. /** Removes the last n objects from the array.
  10529. The objects that are removed will have their reference counts decreased,
  10530. and may be deleted if not referenced from elsewhere.
  10531. @param howManyToRemove how many objects to remove from the end of the array
  10532. @see remove, removeObject, removeRange
  10533. */
  10534. void removeLast (int howManyToRemove = 1)
  10535. {
  10536. const ScopedLockType lock (getLock());
  10537. if (howManyToRemove > numUsed)
  10538. howManyToRemove = numUsed;
  10539. while (--howManyToRemove >= 0)
  10540. remove (numUsed - 1);
  10541. }
  10542. /** Swaps a pair of objects in the array.
  10543. If either of the indexes passed in is out-of-range, nothing will happen,
  10544. otherwise the two objects at these positions will be exchanged.
  10545. */
  10546. void swap (const int index1,
  10547. const int index2) throw()
  10548. {
  10549. const ScopedLockType lock (getLock());
  10550. if (isPositiveAndBelow (index1, numUsed)
  10551. && isPositiveAndBelow (index2, numUsed))
  10552. {
  10553. swapVariables (data.elements [index1],
  10554. data.elements [index2]);
  10555. }
  10556. }
  10557. /** Moves one of the objects to a different position.
  10558. This will move the object to a specified index, shuffling along
  10559. any intervening elements as required.
  10560. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  10561. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  10562. @param currentIndex the index of the object to be moved. If this isn't a
  10563. valid index, then nothing will be done
  10564. @param newIndex the index at which you'd like this object to end up. If this
  10565. is less than zero, it will be moved to the end of the array
  10566. */
  10567. void move (const int currentIndex,
  10568. int newIndex) throw()
  10569. {
  10570. if (currentIndex != newIndex)
  10571. {
  10572. const ScopedLockType lock (getLock());
  10573. if (isPositiveAndBelow (currentIndex, numUsed))
  10574. {
  10575. if (! isPositiveAndBelow (newIndex, numUsed))
  10576. newIndex = numUsed - 1;
  10577. ObjectClass* const value = data.elements [currentIndex];
  10578. if (newIndex > currentIndex)
  10579. {
  10580. memmove (data.elements + currentIndex,
  10581. data.elements + currentIndex + 1,
  10582. (newIndex - currentIndex) * sizeof (ObjectClass*));
  10583. }
  10584. else
  10585. {
  10586. memmove (data.elements + newIndex + 1,
  10587. data.elements + newIndex,
  10588. (currentIndex - newIndex) * sizeof (ObjectClass*));
  10589. }
  10590. data.elements [newIndex] = value;
  10591. }
  10592. }
  10593. }
  10594. /** This swaps the contents of this array with those of another array.
  10595. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  10596. because it just swaps their internal pointers.
  10597. */
  10598. void swapWithArray (ReferenceCountedArray& otherArray) throw()
  10599. {
  10600. const ScopedLockType lock1 (getLock());
  10601. const ScopedLockType lock2 (otherArray.getLock());
  10602. data.swapWith (otherArray.data);
  10603. swapVariables (numUsed, otherArray.numUsed);
  10604. }
  10605. /** Compares this array to another one.
  10606. @returns true only if the other array contains the same objects in the same order
  10607. */
  10608. bool operator== (const ReferenceCountedArray& other) const throw()
  10609. {
  10610. const ScopedLockType lock2 (other.getLock());
  10611. const ScopedLockType lock1 (getLock());
  10612. if (numUsed != other.numUsed)
  10613. return false;
  10614. for (int i = numUsed; --i >= 0;)
  10615. if (data.elements [i] != other.data.elements [i])
  10616. return false;
  10617. return true;
  10618. }
  10619. /** Compares this array to another one.
  10620. @see operator==
  10621. */
  10622. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  10623. {
  10624. return ! operator== (other);
  10625. }
  10626. /** Sorts the elements in the array.
  10627. This will use a comparator object to sort the elements into order. The object
  10628. passed must have a method of the form:
  10629. @code
  10630. int compareElements (ElementType first, ElementType second);
  10631. @endcode
  10632. ..and this method must return:
  10633. - a value of < 0 if the first comes before the second
  10634. - a value of 0 if the two objects are equivalent
  10635. - a value of > 0 if the second comes before the first
  10636. To improve performance, the compareElements() method can be declared as static or const.
  10637. @param comparator the comparator to use for comparing elements.
  10638. @param retainOrderOfEquivalentItems if this is true, then items
  10639. which the comparator says are equivalent will be
  10640. kept in the order in which they currently appear
  10641. in the array. This is slower to perform, but may
  10642. be important in some cases. If it's false, a faster
  10643. algorithm is used, but equivalent elements may be
  10644. rearranged.
  10645. @see sortArray
  10646. */
  10647. template <class ElementComparator>
  10648. void sort (ElementComparator& comparator,
  10649. const bool retainOrderOfEquivalentItems = false) const throw()
  10650. {
  10651. (void) comparator; // if you pass in an object with a static compareElements() method, this
  10652. // avoids getting warning messages about the parameter being unused
  10653. const ScopedLockType lock (getLock());
  10654. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  10655. }
  10656. /** Reduces the amount of storage being used by the array.
  10657. Arrays typically allocate slightly more storage than they need, and after
  10658. removing elements, they may have quite a lot of unused space allocated.
  10659. This method will reduce the amount of allocated storage to a minimum.
  10660. */
  10661. void minimiseStorageOverheads() throw()
  10662. {
  10663. const ScopedLockType lock (getLock());
  10664. data.shrinkToNoMoreThan (numUsed);
  10665. }
  10666. /** Returns the CriticalSection that locks this array.
  10667. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  10668. an object of ScopedLockType as an RAII lock for it.
  10669. */
  10670. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  10671. /** Returns the type of scoped lock to use for locking this array */
  10672. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  10673. private:
  10674. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  10675. int numUsed;
  10676. };
  10677. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10678. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  10679. #endif
  10680. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  10681. /*** Start of inlined file: juce_ScopedValueSetter.h ***/
  10682. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  10683. #define __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  10684. /**
  10685. Helper class providing an RAII-based mechanism for temporarily setting and
  10686. then re-setting a value.
  10687. E.g. @code
  10688. int x = 1;
  10689. {
  10690. ScopedValueSetter setter (x, 2);
  10691. // x is now 2
  10692. }
  10693. // x is now 1 again
  10694. {
  10695. ScopedValueSetter setter (x, 3, 4);
  10696. // x is now 3
  10697. }
  10698. // x is now 4
  10699. @endcode
  10700. */
  10701. template <typename ValueType>
  10702. class ScopedValueSetter
  10703. {
  10704. public:
  10705. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  10706. given new value, and will then reset it to its original value when this object is deleted.
  10707. */
  10708. ScopedValueSetter (ValueType& valueToSet,
  10709. const ValueType& newValue)
  10710. : value (valueToSet),
  10711. originalValue (valueToSet)
  10712. {
  10713. valueToSet = newValue;
  10714. }
  10715. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  10716. given new value, and will then reset it to be valueWhenDeleted when this object is deleted.
  10717. */
  10718. ScopedValueSetter (ValueType& valueToSet,
  10719. const ValueType& newValue,
  10720. const ValueType& valueWhenDeleted)
  10721. : value (valueToSet),
  10722. originalValue (valueWhenDeleted)
  10723. {
  10724. valueToSet = newValue;
  10725. }
  10726. ~ScopedValueSetter()
  10727. {
  10728. value = originalValue;
  10729. }
  10730. private:
  10731. ValueType& value;
  10732. const ValueType originalValue;
  10733. JUCE_DECLARE_NON_COPYABLE (ScopedValueSetter);
  10734. };
  10735. #endif // __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  10736. /*** End of inlined file: juce_ScopedValueSetter.h ***/
  10737. #endif
  10738. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  10739. /*** Start of inlined file: juce_SortedSet.h ***/
  10740. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  10741. #define __JUCE_SORTEDSET_JUCEHEADER__
  10742. #if JUCE_MSVC
  10743. #pragma warning (push)
  10744. #pragma warning (disable: 4512)
  10745. #endif
  10746. /**
  10747. Holds a set of unique primitive objects, such as ints or doubles.
  10748. A set can only hold one item with a given value, so if for example it's a
  10749. set of integers, attempting to add the same integer twice will do nothing
  10750. the second time.
  10751. Internally, the list of items is kept sorted (which means that whatever
  10752. kind of primitive type is used must support the ==, <, >, <= and >= operators
  10753. to determine the order), and searching the set for known values is very fast
  10754. because it uses a binary-chop method.
  10755. Note that if you're using a class or struct as the element type, it must be
  10756. capable of being copied or moved with a straightforward memcpy, rather than
  10757. needing construction and destruction code.
  10758. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  10759. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  10760. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  10761. */
  10762. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  10763. class SortedSet
  10764. {
  10765. public:
  10766. /** Creates an empty set. */
  10767. SortedSet() throw()
  10768. : numUsed (0)
  10769. {
  10770. }
  10771. /** Creates a copy of another set.
  10772. @param other the set to copy
  10773. */
  10774. SortedSet (const SortedSet& other) throw()
  10775. {
  10776. const ScopedLockType lock (other.getLock());
  10777. numUsed = other.numUsed;
  10778. data.setAllocatedSize (other.numUsed);
  10779. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  10780. }
  10781. /** Destructor. */
  10782. ~SortedSet() throw()
  10783. {
  10784. }
  10785. /** Copies another set over this one.
  10786. @param other the set to copy
  10787. */
  10788. SortedSet& operator= (const SortedSet& other) throw()
  10789. {
  10790. if (this != &other)
  10791. {
  10792. const ScopedLockType lock1 (other.getLock());
  10793. const ScopedLockType lock2 (getLock());
  10794. data.ensureAllocatedSize (other.size());
  10795. numUsed = other.numUsed;
  10796. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  10797. minimiseStorageOverheads();
  10798. }
  10799. return *this;
  10800. }
  10801. /** Compares this set to another one.
  10802. Two sets are considered equal if they both contain the same set of
  10803. elements.
  10804. @param other the other set to compare with
  10805. */
  10806. bool operator== (const SortedSet<ElementType>& other) const throw()
  10807. {
  10808. const ScopedLockType lock (getLock());
  10809. if (numUsed != other.numUsed)
  10810. return false;
  10811. for (int i = numUsed; --i >= 0;)
  10812. if (data.elements[i] != other.data.elements[i])
  10813. return false;
  10814. return true;
  10815. }
  10816. /** Compares this set to another one.
  10817. Two sets are considered equal if they both contain the same set of
  10818. elements.
  10819. @param other the other set to compare with
  10820. */
  10821. bool operator!= (const SortedSet<ElementType>& other) const throw()
  10822. {
  10823. return ! operator== (other);
  10824. }
  10825. /** Removes all elements from the set.
  10826. This will remove all the elements, and free any storage that the set is
  10827. using. To clear it without freeing the storage, use the clearQuick()
  10828. method instead.
  10829. @see clearQuick
  10830. */
  10831. void clear() throw()
  10832. {
  10833. const ScopedLockType lock (getLock());
  10834. data.setAllocatedSize (0);
  10835. numUsed = 0;
  10836. }
  10837. /** Removes all elements from the set without freeing the array's allocated storage.
  10838. @see clear
  10839. */
  10840. void clearQuick() throw()
  10841. {
  10842. const ScopedLockType lock (getLock());
  10843. numUsed = 0;
  10844. }
  10845. /** Returns the current number of elements in the set.
  10846. */
  10847. inline int size() const throw()
  10848. {
  10849. return numUsed;
  10850. }
  10851. /** Returns one of the elements in the set.
  10852. If the index passed in is beyond the range of valid elements, this
  10853. will return zero.
  10854. If you're certain that the index will always be a valid element, you
  10855. can call getUnchecked() instead, which is faster.
  10856. @param index the index of the element being requested (0 is the first element in the set)
  10857. @see getUnchecked, getFirst, getLast
  10858. */
  10859. inline ElementType operator[] (const int index) const throw()
  10860. {
  10861. const ScopedLockType lock (getLock());
  10862. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  10863. : ElementType();
  10864. }
  10865. /** Returns one of the elements in the set, without checking the index passed in.
  10866. Unlike the operator[] method, this will try to return an element without
  10867. checking that the index is within the bounds of the set, so should only
  10868. be used when you're confident that it will always be a valid index.
  10869. @param index the index of the element being requested (0 is the first element in the set)
  10870. @see operator[], getFirst, getLast
  10871. */
  10872. inline ElementType getUnchecked (const int index) const throw()
  10873. {
  10874. const ScopedLockType lock (getLock());
  10875. jassert (isPositiveAndBelow (index, numUsed));
  10876. return data.elements [index];
  10877. }
  10878. /** Returns the first element in the set, or 0 if the set is empty.
  10879. @see operator[], getUnchecked, getLast
  10880. */
  10881. inline ElementType getFirst() const throw()
  10882. {
  10883. const ScopedLockType lock (getLock());
  10884. return numUsed > 0 ? data.elements [0] : ElementType();
  10885. }
  10886. /** Returns the last element in the set, or 0 if the set is empty.
  10887. @see operator[], getUnchecked, getFirst
  10888. */
  10889. inline ElementType getLast() const throw()
  10890. {
  10891. const ScopedLockType lock (getLock());
  10892. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  10893. }
  10894. /** Finds the index of the first element which matches the value passed in.
  10895. This will search the set for the given object, and return the index
  10896. of its first occurrence. If the object isn't found, the method will return -1.
  10897. @param elementToLookFor the value or object to look for
  10898. @returns the index of the object, or -1 if it's not found
  10899. */
  10900. int indexOf (const ElementType elementToLookFor) const throw()
  10901. {
  10902. const ScopedLockType lock (getLock());
  10903. int start = 0;
  10904. int end = numUsed;
  10905. for (;;)
  10906. {
  10907. if (start >= end)
  10908. {
  10909. return -1;
  10910. }
  10911. else if (elementToLookFor == data.elements [start])
  10912. {
  10913. return start;
  10914. }
  10915. else
  10916. {
  10917. const int halfway = (start + end) >> 1;
  10918. if (halfway == start)
  10919. return -1;
  10920. else if (elementToLookFor >= data.elements [halfway])
  10921. start = halfway;
  10922. else
  10923. end = halfway;
  10924. }
  10925. }
  10926. }
  10927. /** Returns true if the set contains at least one occurrence of an object.
  10928. @param elementToLookFor the value or object to look for
  10929. @returns true if the item is found
  10930. */
  10931. bool contains (const ElementType elementToLookFor) const throw()
  10932. {
  10933. const ScopedLockType lock (getLock());
  10934. int start = 0;
  10935. int end = numUsed;
  10936. for (;;)
  10937. {
  10938. if (start >= end)
  10939. {
  10940. return false;
  10941. }
  10942. else if (elementToLookFor == data.elements [start])
  10943. {
  10944. return true;
  10945. }
  10946. else
  10947. {
  10948. const int halfway = (start + end) >> 1;
  10949. if (halfway == start)
  10950. return false;
  10951. else if (elementToLookFor >= data.elements [halfway])
  10952. start = halfway;
  10953. else
  10954. end = halfway;
  10955. }
  10956. }
  10957. }
  10958. /** Adds a new element to the set, (as long as it's not already in there).
  10959. @param newElement the new object to add to the set
  10960. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  10961. */
  10962. void add (const ElementType newElement) throw()
  10963. {
  10964. const ScopedLockType lock (getLock());
  10965. int start = 0;
  10966. int end = numUsed;
  10967. for (;;)
  10968. {
  10969. if (start >= end)
  10970. {
  10971. jassert (start <= end);
  10972. insertInternal (start, newElement);
  10973. break;
  10974. }
  10975. else if (newElement == data.elements [start])
  10976. {
  10977. break;
  10978. }
  10979. else
  10980. {
  10981. const int halfway = (start + end) >> 1;
  10982. if (halfway == start)
  10983. {
  10984. if (newElement >= data.elements [halfway])
  10985. insertInternal (start + 1, newElement);
  10986. else
  10987. insertInternal (start, newElement);
  10988. break;
  10989. }
  10990. else if (newElement >= data.elements [halfway])
  10991. start = halfway;
  10992. else
  10993. end = halfway;
  10994. }
  10995. }
  10996. }
  10997. /** Adds elements from an array to this set.
  10998. @param elementsToAdd the array of elements to add
  10999. @param numElementsToAdd how many elements are in this other array
  11000. @see add
  11001. */
  11002. void addArray (const ElementType* elementsToAdd,
  11003. int numElementsToAdd) throw()
  11004. {
  11005. const ScopedLockType lock (getLock());
  11006. while (--numElementsToAdd >= 0)
  11007. add (*elementsToAdd++);
  11008. }
  11009. /** Adds elements from another set to this one.
  11010. @param setToAddFrom the set from which to copy the elements
  11011. @param startIndex the first element of the other set to start copying from
  11012. @param numElementsToAdd how many elements to add from the other set. If this
  11013. value is negative or greater than the number of available elements,
  11014. all available elements will be copied.
  11015. @see add
  11016. */
  11017. template <class OtherSetType>
  11018. void addSet (const OtherSetType& setToAddFrom,
  11019. int startIndex = 0,
  11020. int numElementsToAdd = -1) throw()
  11021. {
  11022. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  11023. {
  11024. const ScopedLockType lock2 (getLock());
  11025. jassert (this != &setToAddFrom);
  11026. if (this != &setToAddFrom)
  11027. {
  11028. if (startIndex < 0)
  11029. {
  11030. jassertfalse;
  11031. startIndex = 0;
  11032. }
  11033. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  11034. numElementsToAdd = setToAddFrom.size() - startIndex;
  11035. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  11036. }
  11037. }
  11038. }
  11039. /** Removes an element from the set.
  11040. This will remove the element at a given index.
  11041. If the index passed in is out-of-range, nothing will happen.
  11042. @param indexToRemove the index of the element to remove
  11043. @returns the element that has been removed
  11044. @see removeValue, removeRange
  11045. */
  11046. ElementType remove (const int indexToRemove) throw()
  11047. {
  11048. const ScopedLockType lock (getLock());
  11049. if (isPositiveAndBelow (indexToRemove, numUsed))
  11050. {
  11051. --numUsed;
  11052. ElementType* const e = data.elements + indexToRemove;
  11053. ElementType const removed = *e;
  11054. const int numberToShift = numUsed - indexToRemove;
  11055. if (numberToShift > 0)
  11056. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  11057. if ((numUsed << 1) < data.numAllocated)
  11058. minimiseStorageOverheads();
  11059. return removed;
  11060. }
  11061. return 0;
  11062. }
  11063. /** Removes an item from the set.
  11064. This will remove the given element from the set, if it's there.
  11065. @param valueToRemove the object to try to remove
  11066. @see remove, removeRange
  11067. */
  11068. void removeValue (const ElementType valueToRemove) throw()
  11069. {
  11070. const ScopedLockType lock (getLock());
  11071. remove (indexOf (valueToRemove));
  11072. }
  11073. /** Removes any elements which are also in another set.
  11074. @param otherSet the other set in which to look for elements to remove
  11075. @see removeValuesNotIn, remove, removeValue, removeRange
  11076. */
  11077. template <class OtherSetType>
  11078. void removeValuesIn (const OtherSetType& otherSet) throw()
  11079. {
  11080. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11081. const ScopedLockType lock2 (getLock());
  11082. if (this == &otherSet)
  11083. {
  11084. clear();
  11085. }
  11086. else
  11087. {
  11088. if (otherSet.size() > 0)
  11089. {
  11090. for (int i = numUsed; --i >= 0;)
  11091. if (otherSet.contains (data.elements [i]))
  11092. remove (i);
  11093. }
  11094. }
  11095. }
  11096. /** Removes any elements which are not found in another set.
  11097. Only elements which occur in this other set will be retained.
  11098. @param otherSet the set in which to look for elements NOT to remove
  11099. @see removeValuesIn, remove, removeValue, removeRange
  11100. */
  11101. template <class OtherSetType>
  11102. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  11103. {
  11104. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  11105. const ScopedLockType lock2 (getLock());
  11106. if (this != &otherSet)
  11107. {
  11108. if (otherSet.size() <= 0)
  11109. {
  11110. clear();
  11111. }
  11112. else
  11113. {
  11114. for (int i = numUsed; --i >= 0;)
  11115. if (! otherSet.contains (data.elements [i]))
  11116. remove (i);
  11117. }
  11118. }
  11119. }
  11120. /** Reduces the amount of storage being used by the set.
  11121. Sets typically allocate slightly more storage than they need, and after
  11122. removing elements, they may have quite a lot of unused space allocated.
  11123. This method will reduce the amount of allocated storage to a minimum.
  11124. */
  11125. void minimiseStorageOverheads() throw()
  11126. {
  11127. const ScopedLockType lock (getLock());
  11128. data.shrinkToNoMoreThan (numUsed);
  11129. }
  11130. /** Returns the CriticalSection that locks this array.
  11131. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  11132. an object of ScopedLockType as an RAII lock for it.
  11133. */
  11134. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  11135. /** Returns the type of scoped lock to use for locking this array */
  11136. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  11137. private:
  11138. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  11139. int numUsed;
  11140. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  11141. {
  11142. data.ensureAllocatedSize (numUsed + 1);
  11143. ElementType* const insertPos = data.elements + indexToInsertAt;
  11144. const int numberToMove = numUsed - indexToInsertAt;
  11145. if (numberToMove > 0)
  11146. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  11147. *insertPos = newElement;
  11148. ++numUsed;
  11149. }
  11150. };
  11151. #if JUCE_MSVC
  11152. #pragma warning (pop)
  11153. #endif
  11154. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  11155. /*** End of inlined file: juce_SortedSet.h ***/
  11156. #endif
  11157. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11158. /*** Start of inlined file: juce_SparseSet.h ***/
  11159. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11160. #define __JUCE_SPARSESET_JUCEHEADER__
  11161. /*** Start of inlined file: juce_Range.h ***/
  11162. #ifndef __JUCE_RANGE_JUCEHEADER__
  11163. #define __JUCE_RANGE_JUCEHEADER__
  11164. /** A general-purpose range object, that simply represents any linear range with
  11165. a start and end point.
  11166. The templated parameter is expected to be a primitive integer or floating point
  11167. type, though class types could also be used if they behave in a number-like way.
  11168. */
  11169. template <typename ValueType>
  11170. class Range
  11171. {
  11172. public:
  11173. /** Constructs an empty range. */
  11174. Range() throw()
  11175. : start (ValueType()), end (ValueType())
  11176. {
  11177. }
  11178. /** Constructs a range with given start and end values. */
  11179. Range (const ValueType start_, const ValueType end_) throw()
  11180. : start (start_), end (jmax (start_, end_))
  11181. {
  11182. }
  11183. /** Constructs a copy of another range. */
  11184. Range (const Range& other) throw()
  11185. : start (other.start), end (other.end)
  11186. {
  11187. }
  11188. /** Copies another range object. */
  11189. Range& operator= (const Range& other) throw()
  11190. {
  11191. start = other.start;
  11192. end = other.end;
  11193. return *this;
  11194. }
  11195. /** Destructor. */
  11196. ~Range() throw()
  11197. {
  11198. }
  11199. /** Returns the range that lies between two positions (in either order). */
  11200. static const Range between (const ValueType position1, const ValueType position2) throw()
  11201. {
  11202. return (position1 < position2) ? Range (position1, position2)
  11203. : Range (position2, position1);
  11204. }
  11205. /** Returns a range with the specified start position and a length of zero. */
  11206. static const Range emptyRange (const ValueType start) throw()
  11207. {
  11208. return Range (start, start);
  11209. }
  11210. /** Returns the start of the range. */
  11211. inline ValueType getStart() const throw() { return start; }
  11212. /** Returns the length of the range. */
  11213. inline ValueType getLength() const throw() { return end - start; }
  11214. /** Returns the end of the range. */
  11215. inline ValueType getEnd() const throw() { return end; }
  11216. /** Returns true if the range has a length of zero. */
  11217. inline bool isEmpty() const throw() { return start == end; }
  11218. /** Changes the start position of the range, leaving the end position unchanged.
  11219. If the new start position is higher than the current end of the range, the end point
  11220. will be pushed along to equal it, leaving an empty range at the new position.
  11221. */
  11222. void setStart (const ValueType newStart) throw()
  11223. {
  11224. start = newStart;
  11225. if (end < newStart)
  11226. end = newStart;
  11227. }
  11228. /** Returns a range with the same end as this one, but a different start.
  11229. If the new start position is higher than the current end of the range, the end point
  11230. will be pushed along to equal it, returning an empty range at the new position.
  11231. */
  11232. const Range withStart (const ValueType newStart) const throw()
  11233. {
  11234. return Range (newStart, jmax (newStart, end));
  11235. }
  11236. /** Returns a range with the same length as this one, but moved to have the given start position. */
  11237. const Range movedToStartAt (const ValueType newStart) const throw()
  11238. {
  11239. return Range (newStart, end + (newStart - start));
  11240. }
  11241. /** Changes the end position of the range, leaving the start unchanged.
  11242. If the new end position is below the current start of the range, the start point
  11243. will be pushed back to equal the new end point.
  11244. */
  11245. void setEnd (const ValueType newEnd) throw()
  11246. {
  11247. end = newEnd;
  11248. if (newEnd < start)
  11249. start = newEnd;
  11250. }
  11251. /** Returns a range with the same start position as this one, but a different end.
  11252. If the new end position is below the current start of the range, the start point
  11253. will be pushed back to equal the new end point.
  11254. */
  11255. const Range withEnd (const ValueType newEnd) const throw()
  11256. {
  11257. return Range (jmin (start, newEnd), newEnd);
  11258. }
  11259. /** Returns a range with the same length as this one, but moved to have the given start position. */
  11260. const Range movedToEndAt (const ValueType newEnd) const throw()
  11261. {
  11262. return Range (start + (newEnd - end), newEnd);
  11263. }
  11264. /** Changes the length of the range.
  11265. Lengths less than zero are treated as zero.
  11266. */
  11267. void setLength (const ValueType newLength) throw()
  11268. {
  11269. end = start + jmax (ValueType(), newLength);
  11270. }
  11271. /** Returns a range with the same start as this one, but a different length.
  11272. Lengths less than zero are treated as zero.
  11273. */
  11274. const Range withLength (const ValueType newLength) const throw()
  11275. {
  11276. return Range (start, start + newLength);
  11277. }
  11278. /** Adds an amount to the start and end of the range. */
  11279. inline const Range& operator+= (const ValueType amountToAdd) throw()
  11280. {
  11281. start += amountToAdd;
  11282. end += amountToAdd;
  11283. return *this;
  11284. }
  11285. /** Subtracts an amount from the start and end of the range. */
  11286. inline const Range& operator-= (const ValueType amountToSubtract) throw()
  11287. {
  11288. start -= amountToSubtract;
  11289. end -= amountToSubtract;
  11290. return *this;
  11291. }
  11292. /** Returns a range that is equal to this one with an amount added to its
  11293. start and end.
  11294. */
  11295. const Range operator+ (const ValueType amountToAdd) const throw()
  11296. {
  11297. return Range (start + amountToAdd, end + amountToAdd);
  11298. }
  11299. /** Returns a range that is equal to this one with the specified amount
  11300. subtracted from its start and end. */
  11301. const Range operator- (const ValueType amountToSubtract) const throw()
  11302. {
  11303. return Range (start - amountToSubtract, end - amountToSubtract);
  11304. }
  11305. bool operator== (const Range& other) const throw() { return start == other.start && end == other.end; }
  11306. bool operator!= (const Range& other) const throw() { return start != other.start || end != other.end; }
  11307. /** Returns true if the given position lies inside this range. */
  11308. bool contains (const ValueType position) const throw()
  11309. {
  11310. return start <= position && position < end;
  11311. }
  11312. /** Returns the nearest value to the one supplied, which lies within the range. */
  11313. ValueType clipValue (const ValueType value) const throw()
  11314. {
  11315. return jlimit (start, end, value);
  11316. }
  11317. /** Returns true if the given range lies entirely inside this range. */
  11318. bool contains (const Range& other) const throw()
  11319. {
  11320. return start <= other.start && end >= other.end;
  11321. }
  11322. /** Returns true if the given range intersects this one. */
  11323. bool intersects (const Range& other) const throw()
  11324. {
  11325. return other.start < end && start < other.end;
  11326. }
  11327. /** Returns the range that is the intersection of the two ranges, or an empty range
  11328. with an undefined start position if they don't overlap. */
  11329. const Range getIntersectionWith (const Range& other) const throw()
  11330. {
  11331. return Range (jmax (start, other.start),
  11332. jmin (end, other.end));
  11333. }
  11334. /** Returns the smallest range that contains both this one and the other one. */
  11335. const Range getUnionWith (const Range& other) const throw()
  11336. {
  11337. return Range (jmin (start, other.start),
  11338. jmax (end, other.end));
  11339. }
  11340. /** Returns a given range, after moving it forwards or backwards to fit it
  11341. within this range.
  11342. If the supplied range has a greater length than this one, the return value
  11343. will be this range.
  11344. Otherwise, if the supplied range is smaller than this one, the return value
  11345. will be the new range, shifted forwards or backwards so that it doesn't extend
  11346. beyond this one, but keeping its original length.
  11347. */
  11348. const Range constrainRange (const Range& rangeToConstrain) const throw()
  11349. {
  11350. const ValueType otherLen = rangeToConstrain.getLength();
  11351. return getLength() <= otherLen
  11352. ? *this
  11353. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  11354. }
  11355. private:
  11356. ValueType start, end;
  11357. };
  11358. #endif // __JUCE_RANGE_JUCEHEADER__
  11359. /*** End of inlined file: juce_Range.h ***/
  11360. /**
  11361. Holds a set of primitive values, storing them as a set of ranges.
  11362. This container acts like an array, but can efficiently hold large continguous
  11363. ranges of values. It's quite a specialised class, mostly useful for things
  11364. like keeping the set of selected rows in a listbox.
  11365. The type used as a template paramter must be an integer type, such as int, short,
  11366. int64, etc.
  11367. */
  11368. template <class Type>
  11369. class SparseSet
  11370. {
  11371. public:
  11372. /** Creates a new empty set. */
  11373. SparseSet()
  11374. {
  11375. }
  11376. /** Creates a copy of another SparseSet. */
  11377. SparseSet (const SparseSet<Type>& other)
  11378. : values (other.values)
  11379. {
  11380. }
  11381. /** Clears the set. */
  11382. void clear()
  11383. {
  11384. values.clear();
  11385. }
  11386. /** Checks whether the set is empty.
  11387. This is much quicker than using (size() == 0).
  11388. */
  11389. bool isEmpty() const throw()
  11390. {
  11391. return values.size() == 0;
  11392. }
  11393. /** Returns the number of values in the set.
  11394. Because of the way the data is stored, this method can take longer if there
  11395. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  11396. are any items.
  11397. */
  11398. Type size() const
  11399. {
  11400. Type total (0);
  11401. for (int i = 0; i < values.size(); i += 2)
  11402. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  11403. return total;
  11404. }
  11405. /** Returns one of the values in the set.
  11406. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  11407. @returns the value at this index, or 0 if it's out-of-range
  11408. */
  11409. Type operator[] (Type index) const
  11410. {
  11411. for (int i = 0; i < values.size(); i += 2)
  11412. {
  11413. const Type start (values.getUnchecked (i));
  11414. const Type len (values.getUnchecked (i + 1) - start);
  11415. if (index < len)
  11416. return start + index;
  11417. index -= len;
  11418. }
  11419. return Type();
  11420. }
  11421. /** Checks whether a particular value is in the set. */
  11422. bool contains (const Type valueToLookFor) const
  11423. {
  11424. for (int i = 0; i < values.size(); ++i)
  11425. if (valueToLookFor < values.getUnchecked(i))
  11426. return (i & 1) != 0;
  11427. return false;
  11428. }
  11429. /** Returns the number of contiguous blocks of values.
  11430. @see getRange
  11431. */
  11432. int getNumRanges() const throw()
  11433. {
  11434. return values.size() >> 1;
  11435. }
  11436. /** Returns one of the contiguous ranges of values stored.
  11437. @param rangeIndex the index of the range to look up, between 0
  11438. and (getNumRanges() - 1)
  11439. @see getTotalRange
  11440. */
  11441. const Range<Type> getRange (const int rangeIndex) const
  11442. {
  11443. if (isPositiveAndBelow (rangeIndex, getNumRanges()))
  11444. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  11445. values.getUnchecked ((rangeIndex << 1) + 1));
  11446. else
  11447. return Range<Type>();
  11448. }
  11449. /** Returns the range between the lowest and highest values in the set.
  11450. @see getRange
  11451. */
  11452. const Range<Type> getTotalRange() const
  11453. {
  11454. if (values.size() > 0)
  11455. {
  11456. jassert ((values.size() & 1) == 0);
  11457. return Range<Type> (values.getUnchecked (0),
  11458. values.getUnchecked (values.size() - 1));
  11459. }
  11460. return Range<Type>();
  11461. }
  11462. /** Adds a range of contiguous values to the set.
  11463. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  11464. */
  11465. void addRange (const Range<Type>& range)
  11466. {
  11467. jassert (range.getLength() >= 0);
  11468. if (range.getLength() > 0)
  11469. {
  11470. removeRange (range);
  11471. values.addUsingDefaultSort (range.getStart());
  11472. values.addUsingDefaultSort (range.getEnd());
  11473. simplify();
  11474. }
  11475. }
  11476. /** Removes a range of values from the set.
  11477. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  11478. */
  11479. void removeRange (const Range<Type>& rangeToRemove)
  11480. {
  11481. jassert (rangeToRemove.getLength() >= 0);
  11482. if (rangeToRemove.getLength() > 0
  11483. && values.size() > 0
  11484. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  11485. && values.getUnchecked(0) < rangeToRemove.getEnd())
  11486. {
  11487. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  11488. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  11489. const bool onAtEnd = contains (lastValue);
  11490. for (int i = values.size(); --i >= 0;)
  11491. {
  11492. if (values.getUnchecked(i) <= lastValue)
  11493. {
  11494. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  11495. {
  11496. values.remove (i);
  11497. if (--i < 0)
  11498. break;
  11499. }
  11500. break;
  11501. }
  11502. }
  11503. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  11504. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  11505. simplify();
  11506. }
  11507. }
  11508. /** Does an XOR of the values in a given range. */
  11509. void invertRange (const Range<Type>& range)
  11510. {
  11511. SparseSet newItems;
  11512. newItems.addRange (range);
  11513. int i;
  11514. for (i = getNumRanges(); --i >= 0;)
  11515. newItems.removeRange (getRange (i));
  11516. removeRange (range);
  11517. for (i = newItems.getNumRanges(); --i >= 0;)
  11518. addRange (newItems.getRange(i));
  11519. }
  11520. /** Checks whether any part of a given range overlaps any part of this set. */
  11521. bool overlapsRange (const Range<Type>& range)
  11522. {
  11523. if (range.getLength() > 0)
  11524. {
  11525. for (int i = getNumRanges(); --i >= 0;)
  11526. {
  11527. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  11528. return false;
  11529. if (values.getUnchecked (i << 1) < range.getEnd())
  11530. return true;
  11531. }
  11532. }
  11533. return false;
  11534. }
  11535. /** Checks whether the whole of a given range is contained within this one. */
  11536. bool containsRange (const Range<Type>& range)
  11537. {
  11538. if (range.getLength() > 0)
  11539. {
  11540. for (int i = getNumRanges(); --i >= 0;)
  11541. {
  11542. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  11543. return false;
  11544. if (values.getUnchecked (i << 1) <= range.getStart()
  11545. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  11546. return true;
  11547. }
  11548. }
  11549. return false;
  11550. }
  11551. bool operator== (const SparseSet<Type>& other) throw()
  11552. {
  11553. return values == other.values;
  11554. }
  11555. bool operator!= (const SparseSet<Type>& other) throw()
  11556. {
  11557. return values != other.values;
  11558. }
  11559. private:
  11560. // alternating start/end values of ranges of values that are present.
  11561. Array<Type, DummyCriticalSection> values;
  11562. void simplify()
  11563. {
  11564. jassert ((values.size() & 1) == 0);
  11565. for (int i = values.size(); --i > 0;)
  11566. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  11567. values.removeRange (--i, 2);
  11568. }
  11569. };
  11570. #endif // __JUCE_SPARSESET_JUCEHEADER__
  11571. /*** End of inlined file: juce_SparseSet.h ***/
  11572. #endif
  11573. #ifndef __JUCE_VALUE_JUCEHEADER__
  11574. /*** Start of inlined file: juce_Value.h ***/
  11575. #ifndef __JUCE_VALUE_JUCEHEADER__
  11576. #define __JUCE_VALUE_JUCEHEADER__
  11577. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  11578. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  11579. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  11580. /*** Start of inlined file: juce_CallbackMessage.h ***/
  11581. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  11582. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  11583. /*** Start of inlined file: juce_Message.h ***/
  11584. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  11585. #define __JUCE_MESSAGE_JUCEHEADER__
  11586. class MessageListener;
  11587. class MessageManager;
  11588. /** The base class for objects that can be delivered to a MessageListener.
  11589. The simplest Message object contains a few integer and pointer parameters
  11590. that the user can set, and this is enough for a lot of purposes. For passing more
  11591. complex data, subclasses of Message can also be used.
  11592. @see MessageListener, MessageManager, ActionListener, ChangeListener
  11593. */
  11594. class JUCE_API Message : public ReferenceCountedObject
  11595. {
  11596. public:
  11597. /** Creates an uninitialised message.
  11598. The class's variables will also be left uninitialised.
  11599. */
  11600. Message() throw();
  11601. /** Creates a message object, filling in the member variables.
  11602. The corresponding public member variables will be set from the parameters
  11603. passed in.
  11604. */
  11605. Message (int intParameter1,
  11606. int intParameter2,
  11607. int intParameter3,
  11608. void* pointerParameter) throw();
  11609. /** Destructor. */
  11610. virtual ~Message();
  11611. // These values can be used for carrying simple data that the application needs to
  11612. // pass around. For more complex messages, just create a subclass.
  11613. int intParameter1; /**< user-defined integer value. */
  11614. int intParameter2; /**< user-defined integer value. */
  11615. int intParameter3; /**< user-defined integer value. */
  11616. void* pointerParameter; /**< user-defined pointer value. */
  11617. /** A typedef for pointers to messages. */
  11618. typedef ReferenceCountedObjectPtr <Message> Ptr;
  11619. private:
  11620. friend class MessageListener;
  11621. friend class MessageManager;
  11622. MessageListener* messageRecipient;
  11623. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Message);
  11624. };
  11625. #endif // __JUCE_MESSAGE_JUCEHEADER__
  11626. /*** End of inlined file: juce_Message.h ***/
  11627. /**
  11628. A message that calls a custom function when it gets delivered.
  11629. You can use this class to fire off actions that you want to be performed later
  11630. on the message thread.
  11631. Unlike other Message objects, these don't get sent to a MessageListener, you
  11632. just call the post() method to send them, and when they arrive, your
  11633. messageCallback() method will automatically be invoked.
  11634. Always create an instance of a CallbackMessage on the heap, as it will be
  11635. deleted automatically after the message has been delivered.
  11636. @see MessageListener, MessageManager, ActionListener, ChangeListener
  11637. */
  11638. class JUCE_API CallbackMessage : public Message
  11639. {
  11640. public:
  11641. CallbackMessage() throw();
  11642. /** Destructor. */
  11643. ~CallbackMessage();
  11644. /** Called when the message is delivered.
  11645. You should implement this method and make it do whatever action you want
  11646. to perform.
  11647. Note that like all other messages, this object will be deleted immediately
  11648. after this method has been invoked.
  11649. */
  11650. virtual void messageCallback() = 0;
  11651. /** Instead of sending this message to a MessageListener, just call this method
  11652. to post it to the event queue.
  11653. After you've called this, this object will belong to the MessageManager,
  11654. which will delete it later. So make sure you don't delete the object yourself,
  11655. call post() more than once, or call post() on a stack-based obect!
  11656. */
  11657. void post();
  11658. private:
  11659. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallbackMessage);
  11660. };
  11661. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  11662. /*** End of inlined file: juce_CallbackMessage.h ***/
  11663. /**
  11664. Has a callback method that is triggered asynchronously.
  11665. This object allows an asynchronous callback function to be triggered, for
  11666. tasks such as coalescing multiple updates into a single callback later on.
  11667. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  11668. message thread calling handleAsyncUpdate() as soon as it can.
  11669. */
  11670. class JUCE_API AsyncUpdater
  11671. {
  11672. public:
  11673. /** Creates an AsyncUpdater object. */
  11674. AsyncUpdater();
  11675. /** Destructor.
  11676. If there are any pending callbacks when the object is deleted, these are lost.
  11677. */
  11678. virtual ~AsyncUpdater();
  11679. /** Causes the callback to be triggered at a later time.
  11680. This method returns immediately, having made sure that a callback
  11681. to the handleAsyncUpdate() method will occur as soon as possible.
  11682. If an update callback is already pending but hasn't happened yet, calls
  11683. to this method will be ignored.
  11684. It's thread-safe to call this method from any number of threads without
  11685. needing to worry about locking.
  11686. */
  11687. void triggerAsyncUpdate();
  11688. /** This will stop any pending updates from happening.
  11689. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  11690. callback happens, this will cancel the handleAsyncUpdate() callback.
  11691. Note that this method simply cancels the next callback - if a callback is already
  11692. in progress on a different thread, this won't block until it finishes, so there's
  11693. no guarantee that the callback isn't still running when you return from
  11694. */
  11695. void cancelPendingUpdate() throw();
  11696. /** If an update has been triggered and is pending, this will invoke it
  11697. synchronously.
  11698. Use this as a kind of "flush" operation - if an update is pending, the
  11699. handleAsyncUpdate() method will be called immediately; if no update is
  11700. pending, then nothing will be done.
  11701. Because this may invoke the callback, this method must only be called on
  11702. the main event thread.
  11703. */
  11704. void handleUpdateNowIfNeeded();
  11705. /** Returns true if there's an update callback in the pipeline. */
  11706. bool isUpdatePending() const throw();
  11707. /** Called back to do whatever your class needs to do.
  11708. This method is called by the message thread at the next convenient time
  11709. after the triggerAsyncUpdate() method has been called.
  11710. */
  11711. virtual void handleAsyncUpdate() = 0;
  11712. private:
  11713. ReferenceCountedObjectPtr<CallbackMessage> message;
  11714. Atomic<int>& getDeliveryFlag() const throw();
  11715. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AsyncUpdater);
  11716. };
  11717. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  11718. /*** End of inlined file: juce_AsyncUpdater.h ***/
  11719. /*** Start of inlined file: juce_ListenerList.h ***/
  11720. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  11721. #define __JUCE_LISTENERLIST_JUCEHEADER__
  11722. /**
  11723. Holds a set of objects and can invoke a member function callback on each object
  11724. in the set with a single call.
  11725. Use a ListenerList to manage a set of objects which need a callback, and you
  11726. can invoke a member function by simply calling call() or callChecked().
  11727. E.g.
  11728. @code
  11729. class MyListenerType
  11730. {
  11731. public:
  11732. void myCallbackMethod (int foo, bool bar);
  11733. };
  11734. ListenerList <MyListenerType> listeners;
  11735. listeners.add (someCallbackObjects...);
  11736. // This will invoke myCallbackMethod (1234, true) on each of the objects
  11737. // in the list...
  11738. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  11739. @endcode
  11740. If you add or remove listeners from the list during one of the callbacks - i.e. while
  11741. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  11742. will be mistakenly called after they've been removed, but it may mean that some of the
  11743. listeners could be called more than once, or not at all, depending on the list's order.
  11744. Sometimes, there's a chance that invoking one of the callbacks might result in the
  11745. list itself being deleted while it's still iterating - to survive this situation, you can
  11746. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  11747. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  11748. the list will check this after each callback to determine whether it should abort the
  11749. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  11750. which can be used to check when a Component has been deleted. See also
  11751. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  11752. */
  11753. template <class ListenerClass,
  11754. class ArrayType = Array <ListenerClass*> >
  11755. class ListenerList
  11756. {
  11757. // Horrible macros required to support VC6/7..
  11758. #ifndef DOXYGEN
  11759. #if JUCE_VC8_OR_EARLIER
  11760. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  11761. #define LL_PARAM(a) Q##a& param##a
  11762. #else
  11763. #define LL_TEMPLATE(a) typename P##a
  11764. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  11765. #endif
  11766. #endif
  11767. public:
  11768. /** Creates an empty list. */
  11769. ListenerList()
  11770. {
  11771. }
  11772. /** Destructor. */
  11773. ~ListenerList()
  11774. {
  11775. }
  11776. /** Adds a listener to the list.
  11777. A listener can only be added once, so if the listener is already in the list,
  11778. this method has no effect.
  11779. @see remove
  11780. */
  11781. void add (ListenerClass* const listenerToAdd)
  11782. {
  11783. // Listeners can't be null pointers!
  11784. jassert (listenerToAdd != 0);
  11785. if (listenerToAdd != 0)
  11786. listeners.addIfNotAlreadyThere (listenerToAdd);
  11787. }
  11788. /** Removes a listener from the list.
  11789. If the listener wasn't in the list, this has no effect.
  11790. */
  11791. void remove (ListenerClass* const listenerToRemove)
  11792. {
  11793. // Listeners can't be null pointers!
  11794. jassert (listenerToRemove != 0);
  11795. listeners.removeValue (listenerToRemove);
  11796. }
  11797. /** Returns the number of registered listeners. */
  11798. int size() const throw()
  11799. {
  11800. return listeners.size();
  11801. }
  11802. /** Returns true if any listeners are registered. */
  11803. bool isEmpty() const throw()
  11804. {
  11805. return listeners.size() == 0;
  11806. }
  11807. /** Clears the list. */
  11808. void clear()
  11809. {
  11810. listeners.clear();
  11811. }
  11812. /** Returns true if the specified listener has been added to the list. */
  11813. bool contains (ListenerClass* const listener) const throw()
  11814. {
  11815. return listeners.contains (listener);
  11816. }
  11817. /** Calls a member function on each listener in the list, with no parameters. */
  11818. void call (void (ListenerClass::*callbackFunction) ())
  11819. {
  11820. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  11821. }
  11822. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  11823. See the class description for info about writing a bail-out checker. */
  11824. template <class BailOutCheckerType>
  11825. void callChecked (const BailOutCheckerType& bailOutChecker,
  11826. void (ListenerClass::*callbackFunction) ())
  11827. {
  11828. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11829. (iter.getListener()->*callbackFunction) ();
  11830. }
  11831. /** Calls a member function on each listener in the list, with 1 parameter. */
  11832. template <LL_TEMPLATE(1)>
  11833. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  11834. {
  11835. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  11836. (iter.getListener()->*callbackFunction) (param1);
  11837. }
  11838. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  11839. See the class description for info about writing a bail-out checker. */
  11840. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  11841. void callChecked (const BailOutCheckerType& bailOutChecker,
  11842. void (ListenerClass::*callbackFunction) (P1),
  11843. LL_PARAM(1))
  11844. {
  11845. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11846. (iter.getListener()->*callbackFunction) (param1);
  11847. }
  11848. /** Calls a member function on each listener in the list, with 2 parameters. */
  11849. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  11850. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  11851. LL_PARAM(1), LL_PARAM(2))
  11852. {
  11853. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  11854. (iter.getListener()->*callbackFunction) (param1, param2);
  11855. }
  11856. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  11857. See the class description for info about writing a bail-out checker. */
  11858. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  11859. void callChecked (const BailOutCheckerType& bailOutChecker,
  11860. void (ListenerClass::*callbackFunction) (P1, P2),
  11861. LL_PARAM(1), LL_PARAM(2))
  11862. {
  11863. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11864. (iter.getListener()->*callbackFunction) (param1, param2);
  11865. }
  11866. /** Calls a member function on each listener in the list, with 3 parameters. */
  11867. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  11868. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  11869. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  11870. {
  11871. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  11872. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  11873. }
  11874. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  11875. See the class description for info about writing a bail-out checker. */
  11876. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  11877. void callChecked (const BailOutCheckerType& bailOutChecker,
  11878. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  11879. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  11880. {
  11881. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11882. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  11883. }
  11884. /** Calls a member function on each listener in the list, with 4 parameters. */
  11885. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  11886. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  11887. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  11888. {
  11889. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  11890. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  11891. }
  11892. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  11893. See the class description for info about writing a bail-out checker. */
  11894. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  11895. void callChecked (const BailOutCheckerType& bailOutChecker,
  11896. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  11897. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  11898. {
  11899. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11900. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  11901. }
  11902. /** Calls a member function on each listener in the list, with 5 parameters. */
  11903. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  11904. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  11905. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  11906. {
  11907. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  11908. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  11909. }
  11910. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  11911. See the class description for info about writing a bail-out checker. */
  11912. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  11913. void callChecked (const BailOutCheckerType& bailOutChecker,
  11914. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  11915. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  11916. {
  11917. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11918. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  11919. }
  11920. /** A dummy bail-out checker that always returns false.
  11921. See the ListenerList notes for more info about bail-out checkers.
  11922. */
  11923. class DummyBailOutChecker
  11924. {
  11925. public:
  11926. inline bool shouldBailOut() const throw() { return false; }
  11927. };
  11928. /** Iterates the listeners in a ListenerList. */
  11929. template <class BailOutCheckerType, class ListType>
  11930. class Iterator
  11931. {
  11932. public:
  11933. Iterator (const ListType& list_)
  11934. : list (list_), index (list_.size())
  11935. {}
  11936. ~Iterator() {}
  11937. bool next()
  11938. {
  11939. if (index <= 0)
  11940. return false;
  11941. const int listSize = list.size();
  11942. if (--index < listSize)
  11943. return true;
  11944. index = listSize - 1;
  11945. return index >= 0;
  11946. }
  11947. bool next (const BailOutCheckerType& bailOutChecker)
  11948. {
  11949. return (! bailOutChecker.shouldBailOut()) && next();
  11950. }
  11951. typename ListType::ListenerType* getListener() const throw()
  11952. {
  11953. return list.getListeners().getUnchecked (index);
  11954. }
  11955. private:
  11956. const ListType& list;
  11957. int index;
  11958. JUCE_DECLARE_NON_COPYABLE (Iterator);
  11959. };
  11960. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  11961. typedef ListenerClass ListenerType;
  11962. const ArrayType& getListeners() const throw() { return listeners; }
  11963. private:
  11964. ArrayType listeners;
  11965. JUCE_DECLARE_NON_COPYABLE (ListenerList);
  11966. #undef LL_TEMPLATE
  11967. #undef LL_PARAM
  11968. };
  11969. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  11970. /*** End of inlined file: juce_ListenerList.h ***/
  11971. /**
  11972. Represents a shared variant value.
  11973. A Value object contains a reference to a var object, and can get and set its value.
  11974. Listeners can be attached to be told when the value is changed.
  11975. The Value class is a wrapper around a shared, reference-counted underlying data
  11976. object - this means that multiple Value objects can all refer to the same piece of
  11977. data, allowing all of them to be notified when any of them changes it.
  11978. When you create a Value with its default constructor, it acts as a wrapper around a
  11979. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  11980. you can map the Value onto any kind of underlying data.
  11981. */
  11982. class JUCE_API Value
  11983. {
  11984. public:
  11985. /** Creates an empty Value, containing a void var. */
  11986. Value();
  11987. /** Creates a Value that refers to the same value as another one.
  11988. Note that this doesn't make a copy of the other value - both this and the other
  11989. Value will share the same underlying value, so that when either one alters it, both
  11990. will see it change.
  11991. */
  11992. Value (const Value& other);
  11993. /** Creates a Value that is set to the specified value. */
  11994. explicit Value (const var& initialValue);
  11995. /** Destructor. */
  11996. ~Value();
  11997. /** Returns the current value. */
  11998. const var getValue() const;
  11999. /** Returns the current value. */
  12000. operator const var() const;
  12001. /** Returns the value as a string.
  12002. This is alternative to writing things like "myValue.getValue().toString()".
  12003. */
  12004. const String toString() const;
  12005. /** Sets the current value.
  12006. You can also use operator= to set the value.
  12007. If there are any listeners registered, they will be notified of the
  12008. change asynchronously.
  12009. */
  12010. void setValue (const var& newValue);
  12011. /** Sets the current value.
  12012. This is the same as calling setValue().
  12013. If there are any listeners registered, they will be notified of the
  12014. change asynchronously.
  12015. */
  12016. Value& operator= (const var& newValue);
  12017. /** Makes this object refer to the same underlying ValueSource as another one.
  12018. Once this object has been connected to another one, changing either one
  12019. will update the other.
  12020. Existing listeners will still be registered after you call this method, and
  12021. they'll continue to receive messages when the new value changes.
  12022. */
  12023. void referTo (const Value& valueToReferTo);
  12024. /** Returns true if this value and the other one are references to the same value.
  12025. */
  12026. bool refersToSameSourceAs (const Value& other) const;
  12027. /** Compares two values.
  12028. This is a compare-by-value comparison, so is effectively the same as
  12029. saying (this->getValue() == other.getValue()).
  12030. */
  12031. bool operator== (const Value& other) const;
  12032. /** Compares two values.
  12033. This is a compare-by-value comparison, so is effectively the same as
  12034. saying (this->getValue() != other.getValue()).
  12035. */
  12036. bool operator!= (const Value& other) const;
  12037. /** Receives callbacks when a Value object changes.
  12038. @see Value::addListener
  12039. */
  12040. class JUCE_API Listener
  12041. {
  12042. public:
  12043. Listener() {}
  12044. virtual ~Listener() {}
  12045. /** Called when a Value object is changed.
  12046. Note that the Value object passed as a parameter may not be exactly the same
  12047. object that you registered the listener with - it might be a copy that refers
  12048. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  12049. */
  12050. virtual void valueChanged (Value& value) = 0;
  12051. };
  12052. /** Adds a listener to receive callbacks when the value changes.
  12053. The listener is added to this specific Value object, and not to the shared
  12054. object that it refers to. When this object is deleted, all the listeners will
  12055. be lost, even if other references to the same Value still exist. So when you're
  12056. adding a listener, make sure that you add it to a ValueTree instance that will last
  12057. for as long as you need the listener. In general, you'd never want to add a listener
  12058. to a local stack-based ValueTree, but more likely to one that's a member variable.
  12059. @see removeListener
  12060. */
  12061. void addListener (Listener* listener);
  12062. /** Removes a listener that was previously added with addListener(). */
  12063. void removeListener (Listener* listener);
  12064. /**
  12065. Used internally by the Value class as the base class for its shared value objects.
  12066. The Value class is essentially a reference-counted pointer to a shared instance
  12067. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  12068. ValueSource classes to allow Value objects to represent your own custom data items.
  12069. */
  12070. class JUCE_API ValueSource : public ReferenceCountedObject,
  12071. public AsyncUpdater
  12072. {
  12073. public:
  12074. ValueSource();
  12075. virtual ~ValueSource();
  12076. /** Returns the current value of this object. */
  12077. virtual const var getValue() const = 0;
  12078. /** Changes the current value.
  12079. This must also trigger a change message if the value actually changes.
  12080. */
  12081. virtual void setValue (const var& newValue) = 0;
  12082. /** Delivers a change message to all the listeners that are registered with
  12083. this value.
  12084. If dispatchSynchronously is true, the method will call all the listeners
  12085. before returning; otherwise it'll dispatch a message and make the call later.
  12086. */
  12087. void sendChangeMessage (bool dispatchSynchronously);
  12088. protected:
  12089. friend class Value;
  12090. SortedSet <Value*> valuesWithListeners;
  12091. void handleAsyncUpdate();
  12092. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueSource);
  12093. };
  12094. /** Creates a Value object that uses this valueSource object as its underlying data. */
  12095. explicit Value (ValueSource* valueSource);
  12096. /** Returns the ValueSource that this value is referring to. */
  12097. ValueSource& getValueSource() throw() { return *value; }
  12098. private:
  12099. friend class ValueSource;
  12100. ReferenceCountedObjectPtr <ValueSource> value;
  12101. ListenerList <Listener> listeners;
  12102. void callListeners();
  12103. // This is disallowed to avoid confusion about whether it should
  12104. // do a by-value or by-reference copy.
  12105. Value& operator= (const Value& other);
  12106. };
  12107. /** Writes a Value to an OutputStream as a UTF8 string. */
  12108. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  12109. /** This typedef is just for compatibility with old code - newer code should use the Value::Listener class directly. */
  12110. typedef Value::Listener ValueListener;
  12111. #endif // __JUCE_VALUE_JUCEHEADER__
  12112. /*** End of inlined file: juce_Value.h ***/
  12113. #endif
  12114. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12115. /*** Start of inlined file: juce_ValueTree.h ***/
  12116. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  12117. #define __JUCE_VALUETREE_JUCEHEADER__
  12118. /*** Start of inlined file: juce_UndoManager.h ***/
  12119. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  12120. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  12121. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  12122. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12123. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12124. /*** Start of inlined file: juce_ChangeListener.h ***/
  12125. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  12126. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  12127. class ChangeBroadcaster;
  12128. /**
  12129. Receives change event callbacks that are sent out by a ChangeBroadcaster.
  12130. A ChangeBroadcaster keeps a set of listeners to which it broadcasts a message when
  12131. the ChangeBroadcaster::sendChangeMessage() method is called. A subclass of
  12132. ChangeListener is used to receive these callbacks.
  12133. Note that the major difference between an ActionListener and a ChangeListener
  12134. is that for a ChangeListener, multiple changes will be coalesced into fewer
  12135. callbacks, but ActionListeners perform one callback for every event posted.
  12136. @see ChangeBroadcaster, ActionListener
  12137. */
  12138. class JUCE_API ChangeListener
  12139. {
  12140. public:
  12141. /** Destructor. */
  12142. virtual ~ChangeListener() {}
  12143. /** Your subclass should implement this method to receive the callback.
  12144. @param source the ChangeBroadcaster that triggered the callback.
  12145. */
  12146. virtual void changeListenerCallback (ChangeBroadcaster* source) = 0;
  12147. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  12148. // This method's signature has changed to take a ChangeBroadcaster parameter - please update your code!
  12149. private: virtual int changeListenerCallback (void*) { return 0; }
  12150. #endif
  12151. };
  12152. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  12153. /*** End of inlined file: juce_ChangeListener.h ***/
  12154. /**
  12155. Holds a list of ChangeListeners, and sends messages to them when instructed.
  12156. @see ChangeListener
  12157. */
  12158. class JUCE_API ChangeBroadcaster
  12159. {
  12160. public:
  12161. /** Creates an ChangeBroadcaster. */
  12162. ChangeBroadcaster() throw();
  12163. /** Destructor. */
  12164. virtual ~ChangeBroadcaster();
  12165. /** Registers a listener to receive change callbacks from this broadcaster.
  12166. Trying to add a listener that's already on the list will have no effect.
  12167. */
  12168. void addChangeListener (ChangeListener* listener);
  12169. /** Unregisters a listener from the list.
  12170. If the listener isn't on the list, this won't have any effect.
  12171. */
  12172. void removeChangeListener (ChangeListener* listener);
  12173. /** Removes all listeners from the list. */
  12174. void removeAllChangeListeners();
  12175. /** Causes an asynchronous change message to be sent to all the registered listeners.
  12176. The message will be delivered asynchronously by the main message thread, so this
  12177. method will return immediately. To call the listeners synchronously use
  12178. sendSynchronousChangeMessage().
  12179. */
  12180. void sendChangeMessage();
  12181. /** Sends a synchronous change message to all the registered listeners.
  12182. This will immediately call all the listeners that are registered. For thread-safety
  12183. reasons, you must only call this method on the main message thread.
  12184. @see dispatchPendingMessages
  12185. */
  12186. void sendSynchronousChangeMessage();
  12187. /** If a change message has been sent but not yet dispatched, this will call
  12188. sendSynchronousChangeMessage() to make the callback immediately.
  12189. For thread-safety reasons, you must only call this method on the main message thread.
  12190. */
  12191. void dispatchPendingMessages();
  12192. private:
  12193. class ChangeBroadcasterCallback : public AsyncUpdater
  12194. {
  12195. public:
  12196. ChangeBroadcasterCallback();
  12197. void handleAsyncUpdate();
  12198. ChangeBroadcaster* owner;
  12199. };
  12200. friend class ChangeBroadcasterCallback;
  12201. ChangeBroadcasterCallback callback;
  12202. ListenerList <ChangeListener> changeListeners;
  12203. void callListeners();
  12204. JUCE_DECLARE_NON_COPYABLE (ChangeBroadcaster);
  12205. };
  12206. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12207. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  12208. /*** Start of inlined file: juce_UndoableAction.h ***/
  12209. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  12210. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  12211. /**
  12212. Used by the UndoManager class to store an action which can be done
  12213. and undone.
  12214. @see UndoManager
  12215. */
  12216. class JUCE_API UndoableAction
  12217. {
  12218. protected:
  12219. /** Creates an action. */
  12220. UndoableAction() throw() {}
  12221. public:
  12222. /** Destructor. */
  12223. virtual ~UndoableAction() {}
  12224. /** Overridden by a subclass to perform the action.
  12225. This method is called by the UndoManager, and shouldn't be used directly by
  12226. applications.
  12227. Be careful not to make any calls in a perform() method that could call
  12228. recursively back into the UndoManager::perform() method
  12229. @returns true if the action could be performed.
  12230. @see UndoManager::perform
  12231. */
  12232. virtual bool perform() = 0;
  12233. /** Overridden by a subclass to undo the action.
  12234. This method is called by the UndoManager, and shouldn't be used directly by
  12235. applications.
  12236. Be careful not to make any calls in an undo() method that could call
  12237. recursively back into the UndoManager::perform() method
  12238. @returns true if the action could be undone without any errors.
  12239. @see UndoManager::perform
  12240. */
  12241. virtual bool undo() = 0;
  12242. /** Returns a value to indicate how much memory this object takes up.
  12243. Because the UndoManager keeps a list of UndoableActions, this is used
  12244. to work out how much space each one will take up, so that the UndoManager
  12245. can work out how many to keep.
  12246. The default value returned here is 10 - units are arbitrary and
  12247. don't have to be accurate.
  12248. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  12249. UndoManager::setMaxNumberOfStoredUnits
  12250. */
  12251. virtual int getSizeInUnits() { return 10; }
  12252. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  12253. If possible, this method should create and return a single action that does the same job as
  12254. this one followed by the supplied action.
  12255. If it's not possible to merge the two actions, the method should return zero.
  12256. */
  12257. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return 0; }
  12258. };
  12259. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  12260. /*** End of inlined file: juce_UndoableAction.h ***/
  12261. /**
  12262. Manages a list of undo/redo commands.
  12263. An UndoManager object keeps a list of past actions and can use these actions
  12264. to move backwards and forwards through an undo history.
  12265. To use it, create subclasses of UndoableAction which perform all the
  12266. actions you need, then when you need to actually perform an action, create one
  12267. and pass it to the UndoManager's perform() method.
  12268. The manager also uses the concept of 'transactions' to group the actions
  12269. together - all actions performed between calls to beginNewTransaction() are
  12270. grouped together and are all undone/redone as a group.
  12271. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  12272. when actions are performed or undone.
  12273. @see UndoableAction
  12274. */
  12275. class JUCE_API UndoManager : public ChangeBroadcaster
  12276. {
  12277. public:
  12278. /** Creates an UndoManager.
  12279. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  12280. to indicate how much storage it takes up
  12281. (UndoableAction::getSizeInUnits()), so this
  12282. lets you specify the maximum total number of
  12283. units that the undomanager is allowed to
  12284. keep in memory before letting the older actions
  12285. drop off the end of the list.
  12286. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  12287. that will be kept, even if this involves exceeding
  12288. the amount of space specified in maxNumberOfUnitsToKeep
  12289. */
  12290. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  12291. int minimumTransactionsToKeep = 30);
  12292. /** Destructor. */
  12293. ~UndoManager();
  12294. /** Deletes all stored actions in the list. */
  12295. void clearUndoHistory();
  12296. /** Returns the current amount of space to use for storing UndoableAction objects.
  12297. @see setMaxNumberOfStoredUnits
  12298. */
  12299. int getNumberOfUnitsTakenUpByStoredCommands() const;
  12300. /** Sets the amount of space that can be used for storing UndoableAction objects.
  12301. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  12302. to indicate how much storage it takes up
  12303. (UndoableAction::getSizeInUnits()), so this
  12304. lets you specify the maximum total number of
  12305. units that the undomanager is allowed to
  12306. keep in memory before letting the older actions
  12307. drop off the end of the list.
  12308. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  12309. that will be kept, even if this involves exceeding
  12310. the amount of space specified in maxNumberOfUnitsToKeep
  12311. @see getNumberOfUnitsTakenUpByStoredCommands
  12312. */
  12313. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  12314. int minimumTransactionsToKeep);
  12315. /** Performs an action and adds it to the undo history list.
  12316. @param action the action to perform - this will be deleted by the UndoManager
  12317. when no longer needed
  12318. @param actionName if this string is non-empty, the current transaction will be
  12319. given this name; if it's empty, the current transaction name will
  12320. be left unchanged. See setCurrentTransactionName()
  12321. @returns true if the command succeeds - see UndoableAction::perform
  12322. @see beginNewTransaction
  12323. */
  12324. bool perform (UndoableAction* action,
  12325. const String& actionName = String::empty);
  12326. /** Starts a new group of actions that together will be treated as a single transaction.
  12327. All actions that are passed to the perform() method between calls to this
  12328. method are grouped together and undone/redone together by a single call to
  12329. undo() or redo().
  12330. @param actionName a description of the transaction that is about to be
  12331. performed
  12332. */
  12333. void beginNewTransaction (const String& actionName = String::empty);
  12334. /** Changes the name stored for the current transaction.
  12335. Each transaction is given a name when the beginNewTransaction() method is
  12336. called, but this can be used to change that name without starting a new
  12337. transaction.
  12338. */
  12339. void setCurrentTransactionName (const String& newName);
  12340. /** Returns true if there's at least one action in the list to undo.
  12341. @see getUndoDescription, undo, canRedo
  12342. */
  12343. bool canUndo() const;
  12344. /** Returns the description of the transaction that would be next to get undone.
  12345. The description returned is the one that was passed into beginNewTransaction
  12346. before the set of actions was performed.
  12347. @see undo
  12348. */
  12349. const String getUndoDescription() const;
  12350. /** Tries to roll-back the last transaction.
  12351. @returns true if the transaction can be undone, and false if it fails, or
  12352. if there aren't any transactions to undo
  12353. */
  12354. bool undo();
  12355. /** Tries to roll-back any actions that were added to the current transaction.
  12356. This will perform an undo() only if there are some actions in the undo list
  12357. that were added after the last call to beginNewTransaction().
  12358. This is useful because it lets you call beginNewTransaction(), then
  12359. perform an operation which may or may not actually perform some actions, and
  12360. then call this method to get rid of any actions that might have been done
  12361. without it rolling back the previous transaction if nothing was actually
  12362. done.
  12363. @returns true if any actions were undone.
  12364. */
  12365. bool undoCurrentTransactionOnly();
  12366. /** Returns a list of the UndoableAction objects that have been performed during the
  12367. transaction that is currently open.
  12368. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  12369. were to be called now.
  12370. The first item in the list is the earliest action performed.
  12371. */
  12372. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  12373. /** Returns the number of UndoableAction objects that have been performed during the
  12374. transaction that is currently open.
  12375. @see getActionsInCurrentTransaction
  12376. */
  12377. int getNumActionsInCurrentTransaction() const;
  12378. /** Returns true if there's at least one action in the list to redo.
  12379. @see getRedoDescription, redo, canUndo
  12380. */
  12381. bool canRedo() const;
  12382. /** Returns the description of the transaction that would be next to get redone.
  12383. The description returned is the one that was passed into beginNewTransaction
  12384. before the set of actions was performed.
  12385. @see redo
  12386. */
  12387. const String getRedoDescription() const;
  12388. /** Tries to redo the last transaction that was undone.
  12389. @returns true if the transaction can be redone, and false if it fails, or
  12390. if there aren't any transactions to redo
  12391. */
  12392. bool redo();
  12393. private:
  12394. OwnedArray <OwnedArray <UndoableAction> > transactions;
  12395. StringArray transactionNames;
  12396. String currentTransactionName;
  12397. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  12398. bool newTransaction, reentrancyCheck;
  12399. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UndoManager);
  12400. };
  12401. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  12402. /*** End of inlined file: juce_UndoManager.h ***/
  12403. /**
  12404. A powerful tree structure that can be used to hold free-form data, and which can
  12405. handle its own undo and redo behaviour.
  12406. A ValueTree contains a list of named properties as var objects, and also holds
  12407. any number of sub-trees.
  12408. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  12409. they're simply a lightweight reference to a shared data container. Creating a copy
  12410. of another ValueTree simply creates a new reference to the same underlying object - to
  12411. make a separate, deep copy of a tree you should explicitly call createCopy().
  12412. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  12413. and much of the structure of a ValueTree is similar to an XmlElement tree.
  12414. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  12415. contain text elements, the conversion works well and makes a good serialisation
  12416. format. They can also be serialised to a binary format, which is very fast and compact.
  12417. All the methods that change data take an optional UndoManager, which will be used
  12418. to track any changes to the object. For this to work, you have to be careful to
  12419. consistently always use the same UndoManager for all operations to any node inside
  12420. the tree.
  12421. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  12422. one tree to another, be careful to always remove it first, before adding it. This
  12423. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  12424. assertions if you try to do anything dangerous, but there are still plenty of ways it
  12425. could go wrong.
  12426. Listeners can be added to a ValueTree to be told when properies change and when
  12427. nodes are added or removed.
  12428. @see var, XmlElement
  12429. */
  12430. class JUCE_API ValueTree
  12431. {
  12432. public:
  12433. /** Creates an empty, invalid ValueTree.
  12434. A ValueTree that is created with this constructor can't actually be used for anything,
  12435. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  12436. To create a real one, use the constructor that takes a string.
  12437. @see ValueTree::invalid
  12438. */
  12439. ValueTree() throw();
  12440. /** Creates an empty ValueTree with the given type name.
  12441. Like an XmlElement, each ValueTree node has a type, which you can access with
  12442. getType() and hasType().
  12443. */
  12444. explicit ValueTree (const Identifier& type);
  12445. /** Creates a reference to another ValueTree. */
  12446. ValueTree (const ValueTree& other);
  12447. /** Makes this object reference another node. */
  12448. ValueTree& operator= (const ValueTree& other);
  12449. /** Destructor. */
  12450. ~ValueTree();
  12451. /** Returns true if both this and the other tree node refer to the same underlying structure.
  12452. Note that this isn't a value comparison - two independently-created trees which
  12453. contain identical data are not considered equal.
  12454. */
  12455. bool operator== (const ValueTree& other) const throw();
  12456. /** Returns true if this and the other node refer to different underlying structures.
  12457. Note that this isn't a value comparison - two independently-created trees which
  12458. contain identical data are not considered equal.
  12459. */
  12460. bool operator!= (const ValueTree& other) const throw();
  12461. /** Performs a deep comparison between the properties and children of two trees.
  12462. If all the properties and children of the two trees are the same (recursively), this
  12463. returns true.
  12464. The normal operator==() only checks whether two trees refer to the same shared data
  12465. structure, so use this method if you need to do a proper value comparison.
  12466. */
  12467. bool isEquivalentTo (const ValueTree& other) const;
  12468. /** Returns true if this node refers to some valid data.
  12469. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  12470. call to getChild().
  12471. */
  12472. bool isValid() const { return object != 0; }
  12473. /** Returns a deep copy of this tree and all its sub-nodes. */
  12474. ValueTree createCopy() const;
  12475. /** Returns the type of this node.
  12476. The type is specified when the ValueTree is created.
  12477. @see hasType
  12478. */
  12479. const Identifier getType() const;
  12480. /** Returns true if the node has this type.
  12481. The comparison is case-sensitive.
  12482. */
  12483. bool hasType (const Identifier& typeName) const;
  12484. /** Returns the value of a named property.
  12485. If no such property has been set, this will return a void variant.
  12486. You can also use operator[] to get a property.
  12487. @see var, setProperty, hasProperty
  12488. */
  12489. const var& getProperty (const Identifier& name) const;
  12490. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  12491. If no such property has been set, this will return the value of defaultReturnValue.
  12492. You can also use operator[] and getProperty to get a property.
  12493. @see var, getProperty, setProperty, hasProperty
  12494. */
  12495. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  12496. /** Returns the value of a named property.
  12497. If no such property has been set, this will return a void variant. This is the same as
  12498. calling getProperty().
  12499. @see getProperty
  12500. */
  12501. const var& operator[] (const Identifier& name) const;
  12502. /** Changes a named property of the node.
  12503. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12504. so that this change can be undone.
  12505. @see var, getProperty, removeProperty
  12506. */
  12507. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  12508. /** Returns true if the node contains a named property. */
  12509. bool hasProperty (const Identifier& name) const;
  12510. /** Removes a property from the node.
  12511. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12512. so that this change can be undone.
  12513. */
  12514. void removeProperty (const Identifier& name, UndoManager* undoManager);
  12515. /** Removes all properties from the node.
  12516. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12517. so that this change can be undone.
  12518. */
  12519. void removeAllProperties (UndoManager* undoManager);
  12520. /** Returns the total number of properties that the node contains.
  12521. @see getProperty.
  12522. */
  12523. int getNumProperties() const;
  12524. /** Returns the identifier of the property with a given index.
  12525. @see getNumProperties
  12526. */
  12527. const Identifier getPropertyName (int index) const;
  12528. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  12529. The Value object will maintain a reference to this tree, and will use the undo manager when
  12530. it needs to change the value. Attaching a Value::Listener to the value object will provide
  12531. callbacks whenever the property changes.
  12532. */
  12533. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  12534. /** Returns the number of child nodes belonging to this one.
  12535. @see getChild
  12536. */
  12537. int getNumChildren() const;
  12538. /** Returns one of this node's child nodes.
  12539. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  12540. whether a node is valid).
  12541. */
  12542. ValueTree getChild (int index) const;
  12543. /** Returns the first child node with the speficied type name.
  12544. If no such node is found, it'll return an invalid node. (See isValid() to find out
  12545. whether a node is valid).
  12546. @see getOrCreateChildWithName
  12547. */
  12548. ValueTree getChildWithName (const Identifier& type) const;
  12549. /** Returns the first child node with the speficied type name, creating and adding
  12550. a child with this name if there wasn't already one there.
  12551. The only time this will return an invalid object is when the object that you're calling
  12552. the method on is itself invalid.
  12553. @see getChildWithName
  12554. */
  12555. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  12556. /** Looks for the first child node that has the speficied property value.
  12557. This will scan the child nodes in order, until it finds one that has property that matches
  12558. the specified value.
  12559. If no such node is found, it'll return an invalid node. (See isValid() to find out
  12560. whether a node is valid).
  12561. */
  12562. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  12563. /** Adds a child to this node.
  12564. Make sure that the child is removed from any former parent node before calling this, or
  12565. you'll hit an assertion.
  12566. If the index is < 0 or greater than the current number of child nodes, the new node will
  12567. be added at the end of the list.
  12568. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12569. so that this change can be undone.
  12570. */
  12571. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  12572. /** Removes the specified child from this node's child-list.
  12573. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12574. so that this change can be undone.
  12575. */
  12576. void removeChild (const ValueTree& child, UndoManager* undoManager);
  12577. /** Removes a child from this node's child-list.
  12578. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12579. so that this change can be undone.
  12580. */
  12581. void removeChild (int childIndex, UndoManager* undoManager);
  12582. /** Removes all child-nodes from this node.
  12583. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12584. so that this change can be undone.
  12585. */
  12586. void removeAllChildren (UndoManager* undoManager);
  12587. /** Moves one of the children to a different index.
  12588. This will move the child to a specified index, shuffling along any intervening
  12589. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  12590. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  12591. @param currentIndex the index of the item to be moved. If this isn't a
  12592. valid index, then nothing will be done
  12593. @param newIndex the index at which you'd like this item to end up. If this
  12594. is less than zero, the value will be moved to the end
  12595. of the list
  12596. @param undoManager the optional UndoManager to use to store this transaction
  12597. */
  12598. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  12599. /** Returns true if this node is anywhere below the specified parent node.
  12600. This returns true if the node is a child-of-a-child, as well as a direct child.
  12601. */
  12602. bool isAChildOf (const ValueTree& possibleParent) const;
  12603. /** Returns the index of a child item in this parent.
  12604. If the child isn't found, this returns -1.
  12605. */
  12606. int indexOf (const ValueTree& child) const;
  12607. /** Returns the parent node that contains this one.
  12608. If the node has no parent, this will return an invalid node. (See isValid() to find out
  12609. whether a node is valid).
  12610. */
  12611. ValueTree getParent() const;
  12612. /** Returns one of this node's siblings in its parent's child list.
  12613. The delta specifies how far to move through the list, so a value of 1 would return the node
  12614. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  12615. If the requested position is beyond the range of available nodes, this will return ValueTree::invalid.
  12616. */
  12617. ValueTree getSibling (int delta) const;
  12618. /** Creates an XmlElement that holds a complete image of this node and all its children.
  12619. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  12620. be used to recreate a similar node by calling fromXml()
  12621. @see fromXml
  12622. */
  12623. XmlElement* createXml() const;
  12624. /** Tries to recreate a node from its XML representation.
  12625. This isn't designed to cope with random XML data - for a sensible result, it should only
  12626. be fed XML that was created by the createXml() method.
  12627. */
  12628. static ValueTree fromXml (const XmlElement& xml);
  12629. /** Stores this tree (and all its children) in a binary format.
  12630. Once written, the data can be read back with readFromStream().
  12631. It's much faster to load/save your tree in binary form than as XML, but
  12632. obviously isn't human-readable.
  12633. */
  12634. void writeToStream (OutputStream& output);
  12635. /** Reloads a tree from a stream that was written with writeToStream(). */
  12636. static ValueTree readFromStream (InputStream& input);
  12637. /** Reloads a tree from a data block that was written with writeToStream(). */
  12638. static ValueTree readFromData (const void* data, size_t numBytes);
  12639. /** Listener class for events that happen to a ValueTree.
  12640. To get events from a ValueTree, make your class implement this interface, and use
  12641. ValueTree::addListener() and ValueTree::removeListener() to register it.
  12642. */
  12643. class JUCE_API Listener
  12644. {
  12645. public:
  12646. /** Destructor. */
  12647. virtual ~Listener() {}
  12648. /** This method is called when a property of this node (or of one of its sub-nodes) has
  12649. changed.
  12650. The tree parameter indicates which tree has had its property changed, and the property
  12651. parameter indicates the property.
  12652. Note that when you register a listener to a tree, it will receive this callback for
  12653. property changes in that tree, and also for any of its children, (recursively, at any depth).
  12654. If your tree has sub-trees but you only want to know about changes to the top level tree,
  12655. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  12656. */
  12657. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  12658. const Identifier& property) = 0;
  12659. /** This method is called when a child sub-tree is added.
  12660. Note that when you register a listener to a tree, it will receive this callback for
  12661. child changes in both that tree and any of its children, (recursively, at any depth).
  12662. If your tree has sub-trees but you only want to know about changes to the top level tree,
  12663. just check the parentTree parameter to make sure it's the one that you're interested in.
  12664. */
  12665. virtual void valueTreeChildAdded (ValueTree& parentTree,
  12666. ValueTree& childWhichHasBeenAdded) = 0;
  12667. /** This method is called when a child sub-tree is removed.
  12668. Note that when you register a listener to a tree, it will receive this callback for
  12669. child changes in both that tree and any of its children, (recursively, at any depth).
  12670. If your tree has sub-trees but you only want to know about changes to the top level tree,
  12671. just check the parentTree parameter to make sure it's the one that you're interested in.
  12672. */
  12673. virtual void valueTreeChildRemoved (ValueTree& parentTree,
  12674. ValueTree& childWhichHasBeenRemoved) = 0;
  12675. /** This method is called when a tree's children have been re-shuffled.
  12676. Note that when you register a listener to a tree, it will receive this callback for
  12677. child changes in both that tree and any of its children, (recursively, at any depth).
  12678. If your tree has sub-trees but you only want to know about changes to the top level tree,
  12679. just check the parameter to make sure it's the tree that you're interested in.
  12680. */
  12681. virtual void valueTreeChildOrderChanged (ValueTree& parentTreeWhoseChildrenHaveMoved) = 0;
  12682. /** This method is called when a tree has been added or removed from a parent node.
  12683. This callback happens when the tree to which the listener was registered is added or
  12684. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  12685. the listener is registered, and not to any of its children.
  12686. */
  12687. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  12688. };
  12689. /** Adds a listener to receive callbacks when this node is changed.
  12690. The listener is added to this specific ValueTree object, and not to the shared
  12691. object that it refers to. When this object is deleted, all the listeners will
  12692. be lost, even if other references to the same ValueTree still exist. And if you
  12693. use the operator= to make this refer to a different ValueTree, any listeners will
  12694. begin listening to changes to the new tree instead of the old one.
  12695. When you're adding a listener, make sure that you add it to a ValueTree instance that
  12696. will last for as long as you need the listener. In general, you'd never want to add a
  12697. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  12698. @see removeListener
  12699. */
  12700. void addListener (Listener* listener);
  12701. /** Removes a listener that was previously added with addListener(). */
  12702. void removeListener (Listener* listener);
  12703. /** This method uses a comparator object to sort the tree's children into order.
  12704. The object provided must have a method of the form:
  12705. @code
  12706. int compareElements (const ValueTree& first, const ValueTree& second);
  12707. @endcode
  12708. ..and this method must return:
  12709. - a value of < 0 if the first comes before the second
  12710. - a value of 0 if the two objects are equivalent
  12711. - a value of > 0 if the second comes before the first
  12712. To improve performance, the compareElements() method can be declared as static or const.
  12713. @param comparator the comparator to use for comparing elements.
  12714. @param undoManager optional UndoManager for storing the changes
  12715. @param retainOrderOfEquivalentItems if this is true, then items which the comparator says are
  12716. equivalent will be kept in the order in which they currently appear in the array.
  12717. This is slower to perform, but may be important in some cases. If it's false, a
  12718. faster algorithm is used, but equivalent elements may be rearranged.
  12719. */
  12720. template <typename ElementComparator>
  12721. void sort (ElementComparator& comparator, UndoManager* undoManager, bool retainOrderOfEquivalentItems)
  12722. {
  12723. if (object != 0)
  12724. {
  12725. ReferenceCountedArray <SharedObject> sortedList (object->children);
  12726. ComparatorAdapter <ElementComparator> adapter (comparator);
  12727. sortedList.sort (adapter, retainOrderOfEquivalentItems);
  12728. object->reorderChildren (sortedList, undoManager);
  12729. }
  12730. }
  12731. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  12732. This invalid object is equivalent to ValueTree created with its default constructor.
  12733. */
  12734. static const ValueTree invalid;
  12735. private:
  12736. class SetPropertyAction;
  12737. friend class SetPropertyAction;
  12738. class AddOrRemoveChildAction;
  12739. friend class AddOrRemoveChildAction;
  12740. class MoveChildAction;
  12741. friend class MoveChildAction;
  12742. class JUCE_API SharedObject : public ReferenceCountedObject
  12743. {
  12744. public:
  12745. explicit SharedObject (const Identifier& type);
  12746. SharedObject (const SharedObject& other);
  12747. ~SharedObject();
  12748. const Identifier type;
  12749. NamedValueSet properties;
  12750. ReferenceCountedArray <SharedObject> children;
  12751. SortedSet <ValueTree*> valueTreesWithListeners;
  12752. SharedObject* parent;
  12753. void sendPropertyChangeMessage (const Identifier& property);
  12754. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  12755. void sendChildAddedMessage (ValueTree& parent, ValueTree& child);
  12756. void sendChildAddedMessage (ValueTree child);
  12757. void sendChildRemovedMessage (ValueTree& parent, ValueTree& child);
  12758. void sendChildRemovedMessage (ValueTree child);
  12759. void sendChildOrderChangedMessage (ValueTree& parent);
  12760. void sendChildOrderChangedMessage();
  12761. void sendParentChangeMessage();
  12762. const var& getProperty (const Identifier& name) const;
  12763. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  12764. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  12765. bool hasProperty (const Identifier& name) const;
  12766. void removeProperty (const Identifier& name, UndoManager*);
  12767. void removeAllProperties (UndoManager*);
  12768. bool isAChildOf (const SharedObject* possibleParent) const;
  12769. int indexOf (const ValueTree& child) const;
  12770. ValueTree getChildWithName (const Identifier& type) const;
  12771. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  12772. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  12773. void addChild (SharedObject* child, int index, UndoManager*);
  12774. void removeChild (int childIndex, UndoManager*);
  12775. void removeAllChildren (UndoManager*);
  12776. void moveChild (int currentIndex, int newIndex, UndoManager*);
  12777. void reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager*);
  12778. bool isEquivalentTo (const SharedObject& other) const;
  12779. XmlElement* createXml() const;
  12780. private:
  12781. SharedObject& operator= (const SharedObject&);
  12782. JUCE_LEAK_DETECTOR (SharedObject);
  12783. };
  12784. template <typename ElementComparator>
  12785. class ComparatorAdapter
  12786. {
  12787. public:
  12788. ComparatorAdapter (ElementComparator& comparator_) throw() : comparator (comparator_) {}
  12789. int compareElements (SharedObject* const first, SharedObject* const second)
  12790. {
  12791. return comparator.compareElements (ValueTree (first), ValueTree (second));
  12792. }
  12793. private:
  12794. ElementComparator& comparator;
  12795. JUCE_DECLARE_NON_COPYABLE (ComparatorAdapter);
  12796. };
  12797. friend class SharedObject;
  12798. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  12799. SharedObjectPtr object;
  12800. ListenerList <Listener> listeners;
  12801. #if JUCE_MSVC && ! DOXYGEN
  12802. public: // (workaround for VC6)
  12803. #endif
  12804. explicit ValueTree (SharedObject*);
  12805. };
  12806. #endif // __JUCE_VALUETREE_JUCEHEADER__
  12807. /*** End of inlined file: juce_ValueTree.h ***/
  12808. #endif
  12809. #ifndef __JUCE_VARIANT_JUCEHEADER__
  12810. #endif
  12811. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  12812. /*** Start of inlined file: juce_FileLogger.h ***/
  12813. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  12814. #define __JUCE_FILELOGGER_JUCEHEADER__
  12815. /**
  12816. A simple implemenation of a Logger that writes to a file.
  12817. @see Logger
  12818. */
  12819. class JUCE_API FileLogger : public Logger
  12820. {
  12821. public:
  12822. /** Creates a FileLogger for a given file.
  12823. @param fileToWriteTo the file that to use - new messages will be appended
  12824. to the file. If the file doesn't exist, it will be created,
  12825. along with any parent directories that are needed.
  12826. @param welcomeMessage when opened, the logger will write a header to the log, along
  12827. with the current date and time, and this welcome message
  12828. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  12829. but is larger than this number of bytes, then the start of the
  12830. file will be truncated to keep the size down. This prevents a log
  12831. file getting ridiculously large over time. The file will be truncated
  12832. at a new-line boundary. If this value is less than zero, no size limit
  12833. will be imposed; if it's zero, the file will always be deleted. Note that
  12834. the size is only checked once when this object is created - any logging
  12835. that is done later will be appended without any checking
  12836. */
  12837. FileLogger (const File& fileToWriteTo,
  12838. const String& welcomeMessage,
  12839. const int maxInitialFileSizeBytes = 128 * 1024);
  12840. /** Destructor. */
  12841. ~FileLogger();
  12842. void logMessage (const String& message);
  12843. const File getLogFile() const { return logFile; }
  12844. /** Helper function to create a log file in the correct place for this platform.
  12845. On Windows this will return a logger with a path such as:
  12846. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  12847. On the Mac it'll create something like:
  12848. ~/Library/Logs/[logFileName]
  12849. The method might return 0 if the file can't be created for some reason.
  12850. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  12851. it's best to use the something like the name of your application here.
  12852. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  12853. call it "log.txt" because if it goes in a directory with logs
  12854. from other applications (as it will do on the Mac) then no-one
  12855. will know which one is yours!
  12856. @param welcomeMessage a message that will be written to the log when it's opened.
  12857. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  12858. */
  12859. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  12860. const String& logFileName,
  12861. const String& welcomeMessage,
  12862. const int maxInitialFileSizeBytes = 128 * 1024);
  12863. private:
  12864. File logFile;
  12865. CriticalSection logLock;
  12866. void trimFileSize (int maxFileSizeBytes) const;
  12867. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileLogger);
  12868. };
  12869. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  12870. /*** End of inlined file: juce_FileLogger.h ***/
  12871. #endif
  12872. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  12873. /*** Start of inlined file: juce_Initialisation.h ***/
  12874. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  12875. #define __JUCE_INITIALISATION_JUCEHEADER__
  12876. /** Initialises Juce's GUI classes.
  12877. If you're embedding Juce into an application that uses its own event-loop rather
  12878. than using the START_JUCE_APPLICATION macro, call this function before making any
  12879. Juce calls, to make sure things are initialised correctly.
  12880. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  12881. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  12882. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  12883. */
  12884. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI();
  12885. /** Clears up any static data being used by Juce's GUI classes.
  12886. If you're embedding Juce into an application that uses its own event-loop rather
  12887. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  12888. code to clean up any juce objects that might be lying around.
  12889. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  12890. */
  12891. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  12892. /** Initialises the core parts of Juce.
  12893. If you're embedding Juce into either a command-line program, call this function
  12894. at the start of your main() function to make sure that Juce is initialised correctly.
  12895. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  12896. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  12897. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  12898. */
  12899. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI();
  12900. /** Clears up any static data being used by Juce's non-gui core classes.
  12901. If you're embedding Juce into either a command-line program, call this function
  12902. at the end of your main() function if you want to make sure any Juce objects are
  12903. cleaned up correctly.
  12904. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  12905. */
  12906. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI();
  12907. /** A utility object that helps you initialise and shutdown Juce correctly
  12908. using an RAII pattern.
  12909. When an instance of this class is created, it calls initialiseJuce_NonGUI(),
  12910. and when it's deleted, it calls shutdownJuce_NonGUI(), which lets you easily
  12911. make sure that these functions are matched correctly.
  12912. This class is particularly handy to use at the beginning of a console app's
  12913. main() function, because it'll take care of shutting down whenever you return
  12914. from the main() call.
  12915. @see ScopedJuceInitialiser_GUI
  12916. */
  12917. class ScopedJuceInitialiser_NonGUI
  12918. {
  12919. public:
  12920. /** The constructor simply calls initialiseJuce_NonGUI(). */
  12921. ScopedJuceInitialiser_NonGUI() { initialiseJuce_NonGUI(); }
  12922. /** The destructor simply calls shutdownJuce_NonGUI(). */
  12923. ~ScopedJuceInitialiser_NonGUI() { shutdownJuce_NonGUI(); }
  12924. };
  12925. /** A utility object that helps you initialise and shutdown Juce correctly
  12926. using an RAII pattern.
  12927. When an instance of this class is created, it calls initialiseJuce_GUI(),
  12928. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  12929. make sure that these functions are matched correctly.
  12930. This class is particularly handy to use at the beginning of a console app's
  12931. main() function, because it'll take care of shutting down whenever you return
  12932. from the main() call.
  12933. @see ScopedJuceInitialiser_NonGUI
  12934. */
  12935. class ScopedJuceInitialiser_GUI
  12936. {
  12937. public:
  12938. /** The constructor simply calls initialiseJuce_GUI(). */
  12939. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  12940. /** The destructor simply calls shutdownJuce_GUI(). */
  12941. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  12942. };
  12943. /*
  12944. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  12945. AppSubClass is the name of a class derived from JUCEApplication.
  12946. See the JUCEApplication class documentation (juce_Application.h) for more details.
  12947. */
  12948. #if JUCE_ANDROID
  12949. #define START_JUCE_APPLICATION(AppClass) \
  12950. JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); }
  12951. #elif defined (JUCE_GCC) || defined (__MWERKS__)
  12952. #define START_JUCE_APPLICATION(AppClass) \
  12953. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  12954. int main (int argc, char* argv[]) \
  12955. { \
  12956. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  12957. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv); \
  12958. }
  12959. #elif JUCE_WINDOWS
  12960. #ifdef _CONSOLE
  12961. #define START_JUCE_APPLICATION(AppClass) \
  12962. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  12963. int main (int, char* argv[]) \
  12964. { \
  12965. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  12966. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  12967. }
  12968. #elif ! defined (_AFXDLL)
  12969. #ifdef _WINDOWS_
  12970. #define START_JUCE_APPLICATION(AppClass) \
  12971. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  12972. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  12973. { \
  12974. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  12975. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  12976. }
  12977. #else
  12978. #define START_JUCE_APPLICATION(AppClass) \
  12979. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  12980. int __stdcall WinMain (int, int, const char*, int) \
  12981. { \
  12982. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  12983. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  12984. }
  12985. #endif
  12986. #endif
  12987. #endif
  12988. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  12989. /*** End of inlined file: juce_Initialisation.h ***/
  12990. #endif
  12991. #ifndef __JUCE_LOGGER_JUCEHEADER__
  12992. #endif
  12993. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  12994. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  12995. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  12996. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  12997. /** A timer for measuring performance of code and dumping the results to a file.
  12998. e.g. @code
  12999. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  13000. for (;;)
  13001. {
  13002. pc.start();
  13003. doSomethingFishy();
  13004. pc.stop();
  13005. }
  13006. @endcode
  13007. In this example, the time of each period between calling start/stop will be
  13008. measured and averaged over 50 runs, and the results printed to a file
  13009. every 50 times round the loop.
  13010. */
  13011. class JUCE_API PerformanceCounter
  13012. {
  13013. public:
  13014. /** Creates a PerformanceCounter object.
  13015. @param counterName the name used when printing out the statistics
  13016. @param runsPerPrintout the number of start/stop iterations before calling
  13017. printStatistics()
  13018. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  13019. the results are just written to the debugger output
  13020. */
  13021. PerformanceCounter (const String& counterName,
  13022. int runsPerPrintout = 100,
  13023. const File& loggingFile = File::nonexistent);
  13024. /** Destructor. */
  13025. ~PerformanceCounter();
  13026. /** Starts timing.
  13027. @see stop
  13028. */
  13029. void start();
  13030. /** Stops timing and prints out the results.
  13031. The number of iterations before doing a printout of the
  13032. results is set in the constructor.
  13033. @see start
  13034. */
  13035. void stop();
  13036. /** Dumps the current metrics to the debugger output and to a file.
  13037. As well as using Logger::outputDebugString to print the results,
  13038. this will write then to the file specified in the constructor (if
  13039. this was valid).
  13040. */
  13041. void printStatistics();
  13042. private:
  13043. String name;
  13044. int numRuns, runsPerPrint;
  13045. double totalTime;
  13046. int64 started;
  13047. File outputFile;
  13048. };
  13049. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  13050. /*** End of inlined file: juce_PerformanceCounter.h ***/
  13051. #endif
  13052. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  13053. #endif
  13054. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13055. /*** Start of inlined file: juce_PlatformUtilities.h ***/
  13056. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13057. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13058. /**
  13059. A collection of miscellaneous platform-specific utilities.
  13060. */
  13061. class JUCE_API PlatformUtilities
  13062. {
  13063. public:
  13064. /** Plays the operating system's default alert 'beep' sound. */
  13065. static void beep();
  13066. /** Tries to launch the system's default reader for a given file or URL. */
  13067. static bool openDocument (const String& documentURL, const String& parameters);
  13068. /** Tries to launch the system's default email app to let the user create an email.
  13069. */
  13070. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  13071. const String& emailSubject,
  13072. const String& bodyText,
  13073. const StringArray& filesToAttach);
  13074. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  13075. /** MAC ONLY - Turns a Core CF String into a juce one. */
  13076. static const String cfStringToJuceString (CFStringRef cfString);
  13077. /** MAC ONLY - Turns a juce string into a Core CF one. */
  13078. static CFStringRef juceStringToCFString (const String& s);
  13079. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  13080. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  13081. /** MAC ONLY - Turns an FSRef into a juce string path. */
  13082. static const String makePathFromFSRef (FSRef* file);
  13083. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  13084. their precomposed equivalents.
  13085. */
  13086. static const String convertToPrecomposedUnicode (const String& s);
  13087. /** MAC ONLY - Gets the type of a file from the file's resources. */
  13088. static OSType getTypeOfFile (const String& filename);
  13089. /** MAC ONLY - Returns true if this file is actually a bundle. */
  13090. static bool isBundle (const String& filename);
  13091. /** MAC ONLY - Adds an item to the dock */
  13092. static void addItemToDock (const File& file);
  13093. /** MAC ONLY - Returns the current OS version number.
  13094. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  13095. */
  13096. static int getOSXMinorVersionNumber();
  13097. #endif
  13098. #if JUCE_WINDOWS || DOXYGEN
  13099. // Some registry helper functions:
  13100. /** WIN32 ONLY - Returns a string from the registry.
  13101. The path is a string for the entire path of a value in the registry,
  13102. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  13103. */
  13104. static const String getRegistryValue (const String& regValuePath,
  13105. const String& defaultValue = String::empty);
  13106. /** WIN32 ONLY - Sets a registry value as a string.
  13107. This will take care of creating any groups needed to get to the given
  13108. registry value.
  13109. */
  13110. static void setRegistryValue (const String& regValuePath,
  13111. const String& value);
  13112. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  13113. static bool registryValueExists (const String& regValuePath);
  13114. /** WIN32 ONLY - Deletes a registry value. */
  13115. static void deleteRegistryValue (const String& regValuePath);
  13116. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  13117. static void deleteRegistryKey (const String& regKeyPath);
  13118. /** WIN32 ONLY - Creates a file association in the registry.
  13119. This lets you set the exe that should be launched by a given file extension.
  13120. @param fileExtension the file extension to associate, including the
  13121. initial dot, e.g. ".txt"
  13122. @param symbolicDescription a space-free short token to identify the file type
  13123. @param fullDescription a human-readable description of the file type
  13124. @param targetExecutable the executable that should be launched
  13125. @param iconResourceNumber the icon that gets displayed for the file type will be
  13126. found by looking up this resource number in the
  13127. executable. Pass 0 here to not use an icon
  13128. */
  13129. static void registerFileAssociation (const String& fileExtension,
  13130. const String& symbolicDescription,
  13131. const String& fullDescription,
  13132. const File& targetExecutable,
  13133. int iconResourceNumber);
  13134. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  13135. In a normal Juce application this will be set to the module handle
  13136. of the application executable.
  13137. If you're writing a DLL using Juce and plan to use any Juce messaging or
  13138. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  13139. to set the correct module handle in your DllMain() function, because
  13140. the win32 system relies on the correct instance handle when opening windows.
  13141. */
  13142. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  13143. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  13144. @see getCurrentModuleInstanceHandle()
  13145. */
  13146. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  13147. /** WIN32 ONLY - Gets the command-line params as a string.
  13148. This is needed to avoid unicode problems with the argc type params.
  13149. */
  13150. static const String JUCE_CALLTYPE getCurrentCommandLineParams();
  13151. #endif
  13152. /** Clears the floating point unit's flags.
  13153. Only has an effect under win32, currently.
  13154. */
  13155. static void fpuReset();
  13156. #if JUCE_LINUX || JUCE_WINDOWS
  13157. /** Loads a dynamically-linked library into the process's address space.
  13158. @param pathOrFilename the platform-dependent name and search path
  13159. @returns a handle which can be used by getProcedureEntryPoint(), or
  13160. zero if it fails.
  13161. @see freeDynamicLibrary, getProcedureEntryPoint
  13162. */
  13163. static void* loadDynamicLibrary (const String& pathOrFilename);
  13164. /** Frees a dynamically-linked library.
  13165. @param libraryHandle a handle created by loadDynamicLibrary
  13166. @see loadDynamicLibrary, getProcedureEntryPoint
  13167. */
  13168. static void freeDynamicLibrary (void* libraryHandle);
  13169. /** Finds a procedure call in a dynamically-linked library.
  13170. @param libraryHandle a library handle returned by loadDynamicLibrary
  13171. @param procedureName the name of the procedure call to try to load
  13172. @returns a pointer to the function if found, or 0 if it fails
  13173. @see loadDynamicLibrary
  13174. */
  13175. static void* getProcedureEntryPoint (void* libraryHandle,
  13176. const String& procedureName);
  13177. #endif
  13178. private:
  13179. PlatformUtilities();
  13180. JUCE_DECLARE_NON_COPYABLE (PlatformUtilities);
  13181. };
  13182. #if JUCE_MAC || JUCE_IOS
  13183. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object using RAII.
  13184. */
  13185. class JUCE_API ScopedAutoReleasePool
  13186. {
  13187. public:
  13188. ScopedAutoReleasePool();
  13189. ~ScopedAutoReleasePool();
  13190. private:
  13191. void* pool;
  13192. JUCE_DECLARE_NON_COPYABLE (ScopedAutoReleasePool);
  13193. };
  13194. #define JUCE_AUTORELEASEPOOL const JUCE_NAMESPACE::ScopedAutoReleasePool pool;
  13195. #else
  13196. #define JUCE_AUTORELEASEPOOL
  13197. #endif
  13198. #if JUCE_LINUX
  13199. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  13200. using an RAII approach.
  13201. */
  13202. class ScopedXLock
  13203. {
  13204. public:
  13205. /** Creating a ScopedXLock object locks the X display.
  13206. This uses XLockDisplay() to grab the display that Juce is using.
  13207. */
  13208. ScopedXLock();
  13209. /** Deleting a ScopedXLock object unlocks the X display.
  13210. This calls XUnlockDisplay() to release the lock.
  13211. */
  13212. ~ScopedXLock();
  13213. };
  13214. #endif
  13215. #if JUCE_MAC
  13216. /**
  13217. A wrapper class for picking up events from an Apple IR remote control device.
  13218. To use it, just create a subclass of this class, implementing the buttonPressed()
  13219. callback, then call start() and stop() to start or stop receiving events.
  13220. */
  13221. class JUCE_API AppleRemoteDevice
  13222. {
  13223. public:
  13224. AppleRemoteDevice();
  13225. virtual ~AppleRemoteDevice();
  13226. /** The set of buttons that may be pressed.
  13227. @see buttonPressed
  13228. */
  13229. enum ButtonType
  13230. {
  13231. menuButton = 0, /**< The menu button (if it's held for a short time). */
  13232. playButton, /**< The play button. */
  13233. plusButton, /**< The plus or volume-up button. */
  13234. minusButton, /**< The minus or volume-down button. */
  13235. rightButton, /**< The right button (if it's held for a short time). */
  13236. leftButton, /**< The left button (if it's held for a short time). */
  13237. rightButton_Long, /**< The right button (if it's held for a long time). */
  13238. leftButton_Long, /**< The menu button (if it's held for a long time). */
  13239. menuButton_Long, /**< The menu button (if it's held for a long time). */
  13240. playButtonSleepMode,
  13241. switched
  13242. };
  13243. /** Override this method to receive the callback about a button press.
  13244. The callback will happen on the application's message thread.
  13245. Some buttons trigger matching up and down events, in which the isDown parameter
  13246. will be true and then false. Others only send a single event when the
  13247. button is pressed.
  13248. */
  13249. virtual void buttonPressed (ButtonType buttonId, bool isDown) = 0;
  13250. /** Starts the device running and responding to events.
  13251. Returns true if it managed to open the device.
  13252. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  13253. and will not be available to any other part of the system. If
  13254. false, it will be shared with other apps.
  13255. @see stop
  13256. */
  13257. bool start (bool inExclusiveMode);
  13258. /** Stops the device running.
  13259. @see start
  13260. */
  13261. void stop();
  13262. /** Returns true if the device has been started successfully.
  13263. */
  13264. bool isActive() const;
  13265. /** Returns the ID number of the remote, if it has sent one.
  13266. */
  13267. int getRemoteId() const { return remoteId; }
  13268. /** @internal */
  13269. void handleCallbackInternal();
  13270. private:
  13271. void* device;
  13272. void* queue;
  13273. int remoteId;
  13274. bool open (bool openInExclusiveMode);
  13275. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AppleRemoteDevice);
  13276. };
  13277. #endif
  13278. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13279. /*** End of inlined file: juce_PlatformUtilities.h ***/
  13280. #endif
  13281. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  13282. #endif
  13283. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  13284. /*** Start of inlined file: juce_Singleton.h ***/
  13285. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  13286. #define __JUCE_SINGLETON_JUCEHEADER__
  13287. /*** Start of inlined file: juce_ScopedLock.h ***/
  13288. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  13289. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  13290. /**
  13291. Automatically locks and unlocks a CriticalSection object.
  13292. Use one of these as a local variable to control access to a CriticalSection.
  13293. e.g. @code
  13294. CriticalSection myCriticalSection;
  13295. for (;;)
  13296. {
  13297. const ScopedLock myScopedLock (myCriticalSection);
  13298. // myCriticalSection is now locked
  13299. ...do some stuff...
  13300. // myCriticalSection gets unlocked here.
  13301. }
  13302. @endcode
  13303. @see CriticalSection, ScopedUnlock
  13304. */
  13305. class ScopedLock
  13306. {
  13307. public:
  13308. /** Creates a ScopedLock.
  13309. As soon as it is created, this will lock the CriticalSection, and
  13310. when the ScopedLock object is deleted, the CriticalSection will
  13311. be unlocked.
  13312. Make sure this object is created and deleted by the same thread,
  13313. otherwise there are no guarantees what will happen! Best just to use it
  13314. as a local stack object, rather than creating one with the new() operator.
  13315. */
  13316. inline explicit ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  13317. /** Destructor.
  13318. The CriticalSection will be unlocked when the destructor is called.
  13319. Make sure this object is created and deleted by the same thread,
  13320. otherwise there are no guarantees what will happen!
  13321. */
  13322. inline ~ScopedLock() throw() { lock_.exit(); }
  13323. private:
  13324. const CriticalSection& lock_;
  13325. JUCE_DECLARE_NON_COPYABLE (ScopedLock);
  13326. };
  13327. /**
  13328. Automatically unlocks and re-locks a CriticalSection object.
  13329. This is the reverse of a ScopedLock object - instead of locking the critical
  13330. section for the lifetime of this object, it unlocks it.
  13331. Make sure you don't try to unlock critical sections that aren't actually locked!
  13332. e.g. @code
  13333. CriticalSection myCriticalSection;
  13334. for (;;)
  13335. {
  13336. const ScopedLock myScopedLock (myCriticalSection);
  13337. // myCriticalSection is now locked
  13338. ... do some stuff with it locked ..
  13339. while (xyz)
  13340. {
  13341. ... do some stuff with it locked ..
  13342. const ScopedUnlock unlocker (myCriticalSection);
  13343. // myCriticalSection is now unlocked for the remainder of this block,
  13344. // and re-locked at the end.
  13345. ...do some stuff with it unlocked ...
  13346. }
  13347. // myCriticalSection gets unlocked here.
  13348. }
  13349. @endcode
  13350. @see CriticalSection, ScopedLock
  13351. */
  13352. class ScopedUnlock
  13353. {
  13354. public:
  13355. /** Creates a ScopedUnlock.
  13356. As soon as it is created, this will unlock the CriticalSection, and
  13357. when the ScopedLock object is deleted, the CriticalSection will
  13358. be re-locked.
  13359. Make sure this object is created and deleted by the same thread,
  13360. otherwise there are no guarantees what will happen! Best just to use it
  13361. as a local stack object, rather than creating one with the new() operator.
  13362. */
  13363. inline explicit ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  13364. /** Destructor.
  13365. The CriticalSection will be unlocked when the destructor is called.
  13366. Make sure this object is created and deleted by the same thread,
  13367. otherwise there are no guarantees what will happen!
  13368. */
  13369. inline ~ScopedUnlock() throw() { lock_.enter(); }
  13370. private:
  13371. const CriticalSection& lock_;
  13372. JUCE_DECLARE_NON_COPYABLE (ScopedUnlock);
  13373. };
  13374. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  13375. /*** End of inlined file: juce_ScopedLock.h ***/
  13376. /**
  13377. Macro to declare member variables and methods for a singleton class.
  13378. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  13379. to the class's definition.
  13380. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  13381. implementation code.
  13382. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  13383. destructor, in case it is deleted by other means than deleteInstance()
  13384. Clients can then call the static method MyClass::getInstance() to get a pointer
  13385. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  13386. no instance currently exists.
  13387. e.g. @code
  13388. class MySingleton
  13389. {
  13390. public:
  13391. MySingleton()
  13392. {
  13393. }
  13394. ~MySingleton()
  13395. {
  13396. // this ensures that no dangling pointers are left when the
  13397. // singleton is deleted.
  13398. clearSingletonInstance();
  13399. }
  13400. juce_DeclareSingleton (MySingleton, false)
  13401. };
  13402. juce_ImplementSingleton (MySingleton)
  13403. // example of usage:
  13404. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  13405. ...
  13406. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  13407. @endcode
  13408. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  13409. than once during the process's lifetime - i.e. after you've created and deleted the
  13410. object, getInstance() will refuse to create another one. This can be useful to stop
  13411. objects being accidentally re-created during your app's shutdown code.
  13412. If you know that your object will only be created and deleted by a single thread, you
  13413. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  13414. of this one.
  13415. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  13416. */
  13417. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  13418. \
  13419. static classname* _singletonInstance; \
  13420. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  13421. \
  13422. static classname* JUCE_CALLTYPE getInstance() \
  13423. { \
  13424. if (_singletonInstance == 0) \
  13425. {\
  13426. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  13427. \
  13428. if (_singletonInstance == 0) \
  13429. { \
  13430. static bool alreadyInside = false; \
  13431. static bool createdOnceAlready = false; \
  13432. \
  13433. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  13434. jassert (! problem); \
  13435. if (! problem) \
  13436. { \
  13437. createdOnceAlready = true; \
  13438. alreadyInside = true; \
  13439. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  13440. alreadyInside = false; \
  13441. \
  13442. _singletonInstance = newObject; \
  13443. } \
  13444. } \
  13445. } \
  13446. \
  13447. return _singletonInstance; \
  13448. } \
  13449. \
  13450. static inline classname* JUCE_CALLTYPE getInstanceWithoutCreating() throw() \
  13451. { \
  13452. return _singletonInstance; \
  13453. } \
  13454. \
  13455. static void JUCE_CALLTYPE deleteInstance() \
  13456. { \
  13457. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  13458. if (_singletonInstance != 0) \
  13459. { \
  13460. classname* const old = _singletonInstance; \
  13461. _singletonInstance = 0; \
  13462. delete old; \
  13463. } \
  13464. } \
  13465. \
  13466. void clearSingletonInstance() throw() \
  13467. { \
  13468. if (_singletonInstance == this) \
  13469. _singletonInstance = 0; \
  13470. }
  13471. /** This is a counterpart to the juce_DeclareSingleton macro.
  13472. After adding the juce_DeclareSingleton to the class definition, this macro has
  13473. to be used in the cpp file.
  13474. */
  13475. #define juce_ImplementSingleton(classname) \
  13476. \
  13477. classname* classname::_singletonInstance = 0; \
  13478. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  13479. /**
  13480. Macro to declare member variables and methods for a singleton class.
  13481. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  13482. section to make access to it thread-safe. If you know that your object will
  13483. only ever be created or deleted by a single thread, then this is a
  13484. more efficient version to use.
  13485. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  13486. than once during the process's lifetime - i.e. after you've created and deleted the
  13487. object, getInstance() will refuse to create another one. This can be useful to stop
  13488. objects being accidentally re-created during your app's shutdown code.
  13489. See the documentation for juce_DeclareSingleton for more information about
  13490. how to use it, the only difference being that you have to use
  13491. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  13492. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  13493. */
  13494. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  13495. \
  13496. static classname* _singletonInstance; \
  13497. \
  13498. static classname* getInstance() \
  13499. { \
  13500. if (_singletonInstance == 0) \
  13501. { \
  13502. static bool alreadyInside = false; \
  13503. static bool createdOnceAlready = false; \
  13504. \
  13505. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  13506. jassert (! problem); \
  13507. if (! problem) \
  13508. { \
  13509. createdOnceAlready = true; \
  13510. alreadyInside = true; \
  13511. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  13512. alreadyInside = false; \
  13513. \
  13514. _singletonInstance = newObject; \
  13515. } \
  13516. } \
  13517. \
  13518. return _singletonInstance; \
  13519. } \
  13520. \
  13521. static inline classname* getInstanceWithoutCreating() throw() \
  13522. { \
  13523. return _singletonInstance; \
  13524. } \
  13525. \
  13526. static void deleteInstance() \
  13527. { \
  13528. if (_singletonInstance != 0) \
  13529. { \
  13530. classname* const old = _singletonInstance; \
  13531. _singletonInstance = 0; \
  13532. delete old; \
  13533. } \
  13534. } \
  13535. \
  13536. void clearSingletonInstance() throw() \
  13537. { \
  13538. if (_singletonInstance == this) \
  13539. _singletonInstance = 0; \
  13540. }
  13541. /**
  13542. Macro to declare member variables and methods for a singleton class.
  13543. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  13544. for recursion or repeated instantiation. It's intended for use as a lightweight
  13545. version of a singleton, where you're using it in very straightforward
  13546. circumstances and don't need the extra checking.
  13547. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  13548. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  13549. See the documentation for juce_DeclareSingleton for more information about
  13550. how to use it, the only difference being that you have to use
  13551. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  13552. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  13553. */
  13554. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  13555. \
  13556. static classname* _singletonInstance; \
  13557. \
  13558. static classname* getInstance() \
  13559. { \
  13560. if (_singletonInstance == 0) \
  13561. _singletonInstance = new classname(); \
  13562. \
  13563. return _singletonInstance; \
  13564. } \
  13565. \
  13566. static inline classname* getInstanceWithoutCreating() throw() \
  13567. { \
  13568. return _singletonInstance; \
  13569. } \
  13570. \
  13571. static void deleteInstance() \
  13572. { \
  13573. if (_singletonInstance != 0) \
  13574. { \
  13575. classname* const old = _singletonInstance; \
  13576. _singletonInstance = 0; \
  13577. delete old; \
  13578. } \
  13579. } \
  13580. \
  13581. void clearSingletonInstance() throw() \
  13582. { \
  13583. if (_singletonInstance == this) \
  13584. _singletonInstance = 0; \
  13585. }
  13586. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  13587. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  13588. to the class definition, this macro has to be used somewhere in the cpp file.
  13589. */
  13590. #define juce_ImplementSingleton_SingleThreaded(classname) \
  13591. \
  13592. classname* classname::_singletonInstance = 0;
  13593. #endif // __JUCE_SINGLETON_JUCEHEADER__
  13594. /*** End of inlined file: juce_Singleton.h ***/
  13595. #endif
  13596. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  13597. #endif
  13598. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  13599. /*** Start of inlined file: juce_SystemStats.h ***/
  13600. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  13601. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  13602. /**
  13603. Contains methods for finding out about the current hardware and OS configuration.
  13604. */
  13605. class JUCE_API SystemStats
  13606. {
  13607. public:
  13608. /** Returns the current version of JUCE,
  13609. (just in case you didn't already know at compile-time.)
  13610. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  13611. */
  13612. static const String getJUCEVersion();
  13613. /** The set of possible results of the getOperatingSystemType() method.
  13614. */
  13615. enum OperatingSystemType
  13616. {
  13617. UnknownOS = 0,
  13618. MacOSX = 0x1000,
  13619. Linux = 0x2000,
  13620. Android = 0x3000,
  13621. Win95 = 0x4001,
  13622. Win98 = 0x4002,
  13623. WinNT351 = 0x4103,
  13624. WinNT40 = 0x4104,
  13625. Win2000 = 0x4105,
  13626. WinXP = 0x4106,
  13627. WinVista = 0x4107,
  13628. Windows7 = 0x4108,
  13629. Windows = 0x4000, /**< To test whether any version of Windows is running,
  13630. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  13631. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  13632. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  13633. };
  13634. /** Returns the type of operating system we're running on.
  13635. @returns one of the values from the OperatingSystemType enum.
  13636. @see getOperatingSystemName
  13637. */
  13638. static OperatingSystemType getOperatingSystemType();
  13639. /** Returns the name of the type of operating system we're running on.
  13640. @returns a string describing the OS type.
  13641. @see getOperatingSystemType
  13642. */
  13643. static const String getOperatingSystemName();
  13644. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  13645. */
  13646. static bool isOperatingSystem64Bit();
  13647. /** Returns the current user's name, if available.
  13648. @see getFullUserName()
  13649. */
  13650. static const String getLogonName();
  13651. /** Returns the current user's full name, if available.
  13652. On some OSes, this may just return the same value as getLogonName().
  13653. @see getLogonName()
  13654. */
  13655. static const String getFullUserName();
  13656. // CPU and memory information..
  13657. /** Returns the approximate CPU speed.
  13658. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  13659. what year you're reading this...)
  13660. */
  13661. static int getCpuSpeedInMegaherz();
  13662. /** Returns a string to indicate the CPU vendor.
  13663. Might not be known on some systems.
  13664. */
  13665. static const String getCpuVendor();
  13666. /** Checks whether Intel MMX instructions are available. */
  13667. static bool hasMMX() throw() { return cpuFlags.hasMMX; }
  13668. /** Checks whether Intel SSE instructions are available. */
  13669. static bool hasSSE() throw() { return cpuFlags.hasSSE; }
  13670. /** Checks whether Intel SSE2 instructions are available. */
  13671. static bool hasSSE2() throw() { return cpuFlags.hasSSE2; }
  13672. /** Checks whether AMD 3DNOW instructions are available. */
  13673. static bool has3DNow() throw() { return cpuFlags.has3DNow; }
  13674. /** Returns the number of CPUs. */
  13675. static int getNumCpus() throw() { return cpuFlags.numCpus; }
  13676. /** Finds out how much RAM is in the machine.
  13677. @returns the approximate number of megabytes of memory, or zero if
  13678. something goes wrong when finding out.
  13679. */
  13680. static int getMemorySizeInMegabytes();
  13681. /** Returns the system page-size.
  13682. This is only used by programmers with beards.
  13683. */
  13684. static int getPageSize();
  13685. // not-for-public-use platform-specific method gets called at startup to initialise things.
  13686. static void initialiseStats();
  13687. private:
  13688. struct CPUFlags
  13689. {
  13690. int numCpus;
  13691. bool hasMMX : 1;
  13692. bool hasSSE : 1;
  13693. bool hasSSE2 : 1;
  13694. bool has3DNow : 1;
  13695. };
  13696. static CPUFlags cpuFlags;
  13697. SystemStats();
  13698. JUCE_DECLARE_NON_COPYABLE (SystemStats);
  13699. };
  13700. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  13701. /*** End of inlined file: juce_SystemStats.h ***/
  13702. #endif
  13703. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  13704. #endif
  13705. #ifndef __JUCE_TIME_JUCEHEADER__
  13706. #endif
  13707. #ifndef __JUCE_UUID_JUCEHEADER__
  13708. /*** Start of inlined file: juce_Uuid.h ***/
  13709. #ifndef __JUCE_UUID_JUCEHEADER__
  13710. #define __JUCE_UUID_JUCEHEADER__
  13711. /**
  13712. A universally unique 128-bit identifier.
  13713. This class generates very random unique numbers based on the system time
  13714. and MAC addresses if any are available. It's extremely unlikely that two identical
  13715. UUIDs would ever be created by chance.
  13716. The class includes methods for saving the ID as a string or as raw binary data.
  13717. */
  13718. class JUCE_API Uuid
  13719. {
  13720. public:
  13721. /** Creates a new unique ID. */
  13722. Uuid();
  13723. /** Destructor. */
  13724. ~Uuid() throw();
  13725. /** Creates a copy of another UUID. */
  13726. Uuid (const Uuid& other);
  13727. /** Copies another UUID. */
  13728. Uuid& operator= (const Uuid& other);
  13729. /** Returns true if the ID is zero. */
  13730. bool isNull() const throw();
  13731. /** Compares two UUIDs. */
  13732. bool operator== (const Uuid& other) const;
  13733. /** Compares two UUIDs. */
  13734. bool operator!= (const Uuid& other) const;
  13735. /** Returns a stringified version of this UUID.
  13736. A Uuid object can later be reconstructed from this string using operator= or
  13737. the constructor that takes a string parameter.
  13738. @returns a 32 character hex string.
  13739. */
  13740. const String toString() const;
  13741. /** Creates an ID from an encoded string version.
  13742. @see toString
  13743. */
  13744. Uuid (const String& uuidString);
  13745. /** Copies from a stringified UUID.
  13746. The string passed in should be one that was created with the toString() method.
  13747. */
  13748. Uuid& operator= (const String& uuidString);
  13749. /** Returns a pointer to the internal binary representation of the ID.
  13750. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  13751. the constructor or operator= method that takes an array of uint8s.
  13752. */
  13753. const uint8* getRawData() const throw() { return value.asBytes; }
  13754. /** Creates a UUID from a 16-byte array.
  13755. @see getRawData
  13756. */
  13757. Uuid (const uint8* rawData);
  13758. /** Sets this UUID from 16-bytes of raw data. */
  13759. Uuid& operator= (const uint8* rawData);
  13760. private:
  13761. #ifndef DOXYGEN
  13762. union
  13763. {
  13764. uint8 asBytes [16];
  13765. int asInt[4];
  13766. int64 asInt64[2];
  13767. } value;
  13768. #endif
  13769. JUCE_LEAK_DETECTOR (Uuid);
  13770. };
  13771. #endif // __JUCE_UUID_JUCEHEADER__
  13772. /*** End of inlined file: juce_Uuid.h ***/
  13773. #endif
  13774. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  13775. /*** Start of inlined file: juce_BlowFish.h ***/
  13776. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  13777. #define __JUCE_BLOWFISH_JUCEHEADER__
  13778. /**
  13779. BlowFish encryption class.
  13780. */
  13781. class JUCE_API BlowFish
  13782. {
  13783. public:
  13784. /** Creates an object that can encode/decode based on the specified key.
  13785. The key data can be up to 72 bytes long.
  13786. */
  13787. BlowFish (const void* keyData, int keyBytes);
  13788. /** Creates a copy of another blowfish object. */
  13789. BlowFish (const BlowFish& other);
  13790. /** Copies another blowfish object. */
  13791. BlowFish& operator= (const BlowFish& other);
  13792. /** Destructor. */
  13793. ~BlowFish();
  13794. /** Encrypts a pair of 32-bit integers. */
  13795. void encrypt (uint32& data1, uint32& data2) const throw();
  13796. /** Decrypts a pair of 32-bit integers. */
  13797. void decrypt (uint32& data1, uint32& data2) const throw();
  13798. private:
  13799. uint32 p[18];
  13800. HeapBlock <uint32> s[4];
  13801. uint32 F (uint32 x) const throw();
  13802. JUCE_LEAK_DETECTOR (BlowFish);
  13803. };
  13804. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  13805. /*** End of inlined file: juce_BlowFish.h ***/
  13806. #endif
  13807. #ifndef __JUCE_MD5_JUCEHEADER__
  13808. /*** Start of inlined file: juce_MD5.h ***/
  13809. #ifndef __JUCE_MD5_JUCEHEADER__
  13810. #define __JUCE_MD5_JUCEHEADER__
  13811. /**
  13812. MD5 checksum class.
  13813. Create one of these with a block of source data or a string, and it calculates the
  13814. MD5 checksum of that data.
  13815. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  13816. */
  13817. class JUCE_API MD5
  13818. {
  13819. public:
  13820. /** Creates a null MD5 object. */
  13821. MD5();
  13822. /** Creates a copy of another MD5. */
  13823. MD5 (const MD5& other);
  13824. /** Copies another MD5. */
  13825. MD5& operator= (const MD5& other);
  13826. /** Creates a checksum for a block of binary data. */
  13827. explicit MD5 (const MemoryBlock& data);
  13828. /** Creates a checksum for a block of binary data. */
  13829. MD5 (const void* data, size_t numBytes);
  13830. /** Creates a checksum for a string.
  13831. Note that this operates on the string as a block of unicode characters, so the
  13832. result you get will differ from the value you'd get if the string was treated
  13833. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  13834. of this method with a checksum created by a different framework, which may have
  13835. used a different encoding.
  13836. */
  13837. explicit MD5 (const String& text);
  13838. /** Creates a checksum for the input from a stream.
  13839. This will read up to the given number of bytes from the stream, and produce the
  13840. checksum of that. If the number of bytes to read is negative, it'll read
  13841. until the stream is exhausted.
  13842. */
  13843. MD5 (InputStream& input, int64 numBytesToRead = -1);
  13844. /** Creates a checksum for a file. */
  13845. explicit MD5 (const File& file);
  13846. /** Destructor. */
  13847. ~MD5();
  13848. /** Returns the checksum as a 16-byte block of data. */
  13849. const MemoryBlock getRawChecksumData() const;
  13850. /** Returns the checksum as a 32-digit hex string. */
  13851. const String toHexString() const;
  13852. /** Compares this to another MD5. */
  13853. bool operator== (const MD5& other) const;
  13854. /** Compares this to another MD5. */
  13855. bool operator!= (const MD5& other) const;
  13856. private:
  13857. uint8 result [16];
  13858. struct ProcessContext
  13859. {
  13860. uint8 buffer [64];
  13861. uint32 state [4];
  13862. uint32 count [2];
  13863. ProcessContext();
  13864. void processBlock (const void* data, size_t dataSize);
  13865. void transform (const void* buffer);
  13866. void finish (void* result);
  13867. };
  13868. void processStream (InputStream& input, int64 numBytesToRead);
  13869. JUCE_LEAK_DETECTOR (MD5);
  13870. };
  13871. #endif // __JUCE_MD5_JUCEHEADER__
  13872. /*** End of inlined file: juce_MD5.h ***/
  13873. #endif
  13874. #ifndef __JUCE_PRIMES_JUCEHEADER__
  13875. /*** Start of inlined file: juce_Primes.h ***/
  13876. #ifndef __JUCE_PRIMES_JUCEHEADER__
  13877. #define __JUCE_PRIMES_JUCEHEADER__
  13878. /*** Start of inlined file: juce_BigInteger.h ***/
  13879. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  13880. #define __JUCE_BIGINTEGER_JUCEHEADER__
  13881. class MemoryBlock;
  13882. /**
  13883. An arbitrarily large integer class.
  13884. A BigInteger can be used in a similar way to a normal integer, but has no size
  13885. limit (except for memory and performance constraints).
  13886. Negative values are possible, but the value isn't stored as 2s-complement, so
  13887. be careful if you use negative values and look at the values of individual bits.
  13888. */
  13889. class JUCE_API BigInteger
  13890. {
  13891. public:
  13892. /** Creates an empty BigInteger */
  13893. BigInteger();
  13894. /** Creates a BigInteger containing an integer value in its low bits.
  13895. The low 32 bits of the number are initialised with this value.
  13896. */
  13897. BigInteger (uint32 value);
  13898. /** Creates a BigInteger containing an integer value in its low bits.
  13899. The low 32 bits of the number are initialised with the absolute value
  13900. passed in, and its sign is set to reflect the sign of the number.
  13901. */
  13902. BigInteger (int32 value);
  13903. /** Creates a BigInteger containing an integer value in its low bits.
  13904. The low 64 bits of the number are initialised with the absolute value
  13905. passed in, and its sign is set to reflect the sign of the number.
  13906. */
  13907. BigInteger (int64 value);
  13908. /** Creates a copy of another BigInteger. */
  13909. BigInteger (const BigInteger& other);
  13910. /** Destructor. */
  13911. ~BigInteger();
  13912. /** Copies another BigInteger onto this one. */
  13913. BigInteger& operator= (const BigInteger& other);
  13914. /** Swaps the internal contents of this with another object. */
  13915. void swapWith (BigInteger& other) throw();
  13916. /** Returns the value of a specified bit in the number.
  13917. If the index is out-of-range, the result will be false.
  13918. */
  13919. bool operator[] (int bit) const throw();
  13920. /** Returns true if no bits are set. */
  13921. bool isZero() const throw();
  13922. /** Returns true if the value is 1. */
  13923. bool isOne() const throw();
  13924. /** Attempts to get the lowest bits of the value as an integer.
  13925. If the value is bigger than the integer limits, this will return only the lower bits.
  13926. */
  13927. int toInteger() const throw();
  13928. /** Resets the value to 0. */
  13929. void clear();
  13930. /** Clears a particular bit in the number. */
  13931. void clearBit (int bitNumber) throw();
  13932. /** Sets a specified bit to 1. */
  13933. void setBit (int bitNumber);
  13934. /** Sets or clears a specified bit. */
  13935. void setBit (int bitNumber, bool shouldBeSet);
  13936. /** Sets a range of bits to be either on or off.
  13937. @param startBit the first bit to change
  13938. @param numBits the number of bits to change
  13939. @param shouldBeSet whether to turn these bits on or off
  13940. */
  13941. void setRange (int startBit, int numBits, bool shouldBeSet);
  13942. /** Inserts a bit an a given position, shifting up any bits above it. */
  13943. void insertBit (int bitNumber, bool shouldBeSet);
  13944. /** Returns a range of bits as a new BigInteger.
  13945. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  13946. @see getBitRangeAsInt
  13947. */
  13948. const BigInteger getBitRange (int startBit, int numBits) const;
  13949. /** Returns a range of bits as an integer value.
  13950. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  13951. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  13952. getBitRange().
  13953. */
  13954. int getBitRangeAsInt (int startBit, int numBits) const throw();
  13955. /** Sets a range of bits to an integer value.
  13956. Copies the given integer onto a range of bits, starting at startBit,
  13957. and using up to numBits of the available bits.
  13958. */
  13959. void setBitRangeAsInt (int startBit, int numBits, uint32 valueToSet);
  13960. /** Shifts a section of bits left or right.
  13961. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  13962. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  13963. */
  13964. void shiftBits (int howManyBitsLeft, int startBit);
  13965. /** Returns the total number of set bits in the value. */
  13966. int countNumberOfSetBits() const throw();
  13967. /** Looks for the index of the next set bit after a given starting point.
  13968. This searches from startIndex (inclusive) upwards for the first set bit,
  13969. and returns its index. If no set bits are found, it returns -1.
  13970. */
  13971. int findNextSetBit (int startIndex = 0) const throw();
  13972. /** Looks for the index of the next clear bit after a given starting point.
  13973. This searches from startIndex (inclusive) upwards for the first clear bit,
  13974. and returns its index.
  13975. */
  13976. int findNextClearBit (int startIndex = 0) const throw();
  13977. /** Returns the index of the highest set bit in the number.
  13978. If the value is zero, this will return -1.
  13979. */
  13980. int getHighestBit() const throw();
  13981. // All the standard arithmetic ops...
  13982. BigInteger& operator+= (const BigInteger& other);
  13983. BigInteger& operator-= (const BigInteger& other);
  13984. BigInteger& operator*= (const BigInteger& other);
  13985. BigInteger& operator/= (const BigInteger& other);
  13986. BigInteger& operator|= (const BigInteger& other);
  13987. BigInteger& operator&= (const BigInteger& other);
  13988. BigInteger& operator^= (const BigInteger& other);
  13989. BigInteger& operator%= (const BigInteger& other);
  13990. BigInteger& operator<<= (int numBitsToShift);
  13991. BigInteger& operator>>= (int numBitsToShift);
  13992. BigInteger& operator++();
  13993. BigInteger& operator--();
  13994. const BigInteger operator++ (int);
  13995. const BigInteger operator-- (int);
  13996. const BigInteger operator-() const;
  13997. const BigInteger operator+ (const BigInteger& other) const;
  13998. const BigInteger operator- (const BigInteger& other) const;
  13999. const BigInteger operator* (const BigInteger& other) const;
  14000. const BigInteger operator/ (const BigInteger& other) const;
  14001. const BigInteger operator| (const BigInteger& other) const;
  14002. const BigInteger operator& (const BigInteger& other) const;
  14003. const BigInteger operator^ (const BigInteger& other) const;
  14004. const BigInteger operator% (const BigInteger& other) const;
  14005. const BigInteger operator<< (int numBitsToShift) const;
  14006. const BigInteger operator>> (int numBitsToShift) const;
  14007. bool operator== (const BigInteger& other) const throw();
  14008. bool operator!= (const BigInteger& other) const throw();
  14009. bool operator< (const BigInteger& other) const throw();
  14010. bool operator<= (const BigInteger& other) const throw();
  14011. bool operator> (const BigInteger& other) const throw();
  14012. bool operator>= (const BigInteger& other) const throw();
  14013. /** Does a signed comparison of two BigIntegers.
  14014. Return values are:
  14015. - 0 if the numbers are the same
  14016. - < 0 if this number is smaller than the other
  14017. - > 0 if this number is bigger than the other
  14018. */
  14019. int compare (const BigInteger& other) const throw();
  14020. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  14021. Return values are:
  14022. - 0 if the numbers are the same
  14023. - < 0 if this number is smaller than the other
  14024. - > 0 if this number is bigger than the other
  14025. */
  14026. int compareAbsolute (const BigInteger& other) const throw();
  14027. /** Divides this value by another one and returns the remainder.
  14028. This number is divided by other, leaving the quotient in this number,
  14029. with the remainder being copied to the other BigInteger passed in.
  14030. */
  14031. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  14032. /** Returns the largest value that will divide both this value and the one passed-in.
  14033. */
  14034. const BigInteger findGreatestCommonDivisor (BigInteger other) const;
  14035. /** Performs a combined exponent and modulo operation.
  14036. This BigInteger's value becomes (this ^ exponent) % modulus.
  14037. */
  14038. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  14039. /** Performs an inverse modulo on the value.
  14040. i.e. the result is (this ^ -1) mod (modulus).
  14041. */
  14042. void inverseModulo (const BigInteger& modulus);
  14043. /** Returns true if the value is less than zero.
  14044. @see setNegative, negate
  14045. */
  14046. bool isNegative() const throw();
  14047. /** Changes the sign of the number to be positive or negative.
  14048. @see isNegative, negate
  14049. */
  14050. void setNegative (bool shouldBeNegative) throw();
  14051. /** Inverts the sign of the number.
  14052. @see isNegative, setNegative
  14053. */
  14054. void negate() throw();
  14055. /** Converts the number to a string.
  14056. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14057. If minimumNumCharacters is greater than 0, the returned string will be
  14058. padded with leading zeros to reach at least that length.
  14059. */
  14060. const String toString (int base, int minimumNumCharacters = 1) const;
  14061. /** Reads the numeric value from a string.
  14062. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  14063. Any invalid characters will be ignored.
  14064. */
  14065. void parseString (const String& text, int base);
  14066. /** Turns the number into a block of binary data.
  14067. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14068. of the number, and so on.
  14069. @see loadFromMemoryBlock
  14070. */
  14071. const MemoryBlock toMemoryBlock() const;
  14072. /** Converts a block of raw data into a number.
  14073. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  14074. of the number, and so on.
  14075. @see toMemoryBlock
  14076. */
  14077. void loadFromMemoryBlock (const MemoryBlock& data);
  14078. private:
  14079. HeapBlock <uint32> values;
  14080. int numValues, highestBit;
  14081. bool negative;
  14082. void ensureSize (int numVals);
  14083. static const BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  14084. static inline int bitToIndex (const int bit) throw() { return bit >> 5; }
  14085. static inline uint32 bitToMask (const int bit) throw() { return 1 << (bit & 31); }
  14086. JUCE_LEAK_DETECTOR (BigInteger);
  14087. };
  14088. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  14089. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  14090. #ifndef DOXYGEN
  14091. // For backwards compatibility, BitArray is defined as an alias for BigInteger.
  14092. typedef BigInteger BitArray;
  14093. #endif
  14094. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  14095. /*** End of inlined file: juce_BigInteger.h ***/
  14096. /**
  14097. Prime number creation class.
  14098. This class contains static methods for generating and testing prime numbers.
  14099. @see BigInteger
  14100. */
  14101. class JUCE_API Primes
  14102. {
  14103. public:
  14104. /** Creates a random prime number with a given bit-length.
  14105. The certainty parameter specifies how many iterations to use when testing
  14106. for primality. A safe value might be anything over about 20-30.
  14107. The randomSeeds parameter lets you optionally pass it a set of values with
  14108. which to seed the random number generation, improving the security of the
  14109. keys generated.
  14110. */
  14111. static const BigInteger createProbablePrime (int bitLength,
  14112. int certainty,
  14113. const int* randomSeeds = 0,
  14114. int numRandomSeeds = 0);
  14115. /** Tests a number to see if it's prime.
  14116. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  14117. whether the number is prime.
  14118. The certainty parameter specifies how many iterations to use when testing - a
  14119. safe value might be anything over about 20-30.
  14120. */
  14121. static bool isProbablyPrime (const BigInteger& number, int certainty);
  14122. private:
  14123. Primes();
  14124. JUCE_DECLARE_NON_COPYABLE (Primes);
  14125. };
  14126. #endif // __JUCE_PRIMES_JUCEHEADER__
  14127. /*** End of inlined file: juce_Primes.h ***/
  14128. #endif
  14129. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14130. /*** Start of inlined file: juce_RSAKey.h ***/
  14131. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  14132. #define __JUCE_RSAKEY_JUCEHEADER__
  14133. /**
  14134. RSA public/private key-pair encryption class.
  14135. An object of this type makes up one half of a public/private RSA key pair. Use the
  14136. createKeyPair() method to create a matching pair for encoding/decoding.
  14137. */
  14138. class JUCE_API RSAKey
  14139. {
  14140. public:
  14141. /** Creates a null key object.
  14142. Initialise a pair of objects for use with the createKeyPair() method.
  14143. */
  14144. RSAKey();
  14145. /** Loads a key from an encoded string representation.
  14146. This reloads a key from a string created by the toString() method.
  14147. */
  14148. explicit RSAKey (const String& stringRepresentation);
  14149. /** Destructor. */
  14150. ~RSAKey();
  14151. bool operator== (const RSAKey& other) const throw();
  14152. bool operator!= (const RSAKey& other) const throw();
  14153. /** Turns the key into a string representation.
  14154. This can be reloaded using the constructor that takes a string.
  14155. */
  14156. const String toString() const;
  14157. /** Encodes or decodes a value.
  14158. Call this on the public key object to encode some data, then use the matching
  14159. private key object to decode it.
  14160. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  14161. initialised correctly.
  14162. NOTE: This method dumbly applies this key to this data. If you encode some data
  14163. and then try to decode it with a key that doesn't match, this method will still
  14164. happily do its job and return true, but the result won't be what you were expecting.
  14165. It's your responsibility to check that the result is what you wanted.
  14166. */
  14167. bool applyToValue (BigInteger& value) const;
  14168. /** Creates a public/private key-pair.
  14169. Each key will perform one-way encryption that can only be reversed by
  14170. using the other key.
  14171. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  14172. sizes are more secure, but this method will take longer to execute.
  14173. The randomSeeds parameter lets you optionally pass it a set of values with
  14174. which to seed the random number generation, improving the security of the
  14175. keys generated. If you supply these, make sure you provide more than 2 values,
  14176. and the more your provide, the better the security.
  14177. */
  14178. static void createKeyPair (RSAKey& publicKey,
  14179. RSAKey& privateKey,
  14180. int numBits,
  14181. const int* randomSeeds = 0,
  14182. int numRandomSeeds = 0);
  14183. protected:
  14184. BigInteger part1, part2;
  14185. private:
  14186. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q);
  14187. JUCE_LEAK_DETECTOR (RSAKey);
  14188. };
  14189. #endif // __JUCE_RSAKEY_JUCEHEADER__
  14190. /*** End of inlined file: juce_RSAKey.h ***/
  14191. #endif
  14192. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14193. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  14194. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14195. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14196. /**
  14197. Searches through a the files in a directory, returning each file that is found.
  14198. A DirectoryIterator will search through a directory and its subdirectories using
  14199. a wildcard filepattern match.
  14200. If you may be finding a large number of files, this is better than
  14201. using File::findChildFiles() because it doesn't block while it finds them
  14202. all, and this is more memory-efficient.
  14203. It can also guess how far it's got using a wildly inaccurate algorithm.
  14204. */
  14205. class JUCE_API DirectoryIterator
  14206. {
  14207. public:
  14208. /** Creates a DirectoryIterator for a given directory.
  14209. After creating one of these, call its next() method to get the
  14210. first file - e.g. @code
  14211. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  14212. while (iter.next())
  14213. {
  14214. File theFileItFound (iter.getFile());
  14215. ... etc
  14216. }
  14217. @endcode
  14218. @param directory the directory to search in
  14219. @param isRecursive whether all the subdirectories should also be searched
  14220. @param wildCard the file pattern to match
  14221. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  14222. whether to look for files, directories, or both.
  14223. */
  14224. DirectoryIterator (const File& directory,
  14225. bool isRecursive,
  14226. const String& wildCard = "*",
  14227. int whatToLookFor = File::findFiles);
  14228. /** Destructor. */
  14229. ~DirectoryIterator();
  14230. /** Moves the iterator along to the next file.
  14231. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14232. false if there are no more matching files.
  14233. */
  14234. bool next();
  14235. /** Moves the iterator along to the next file, and returns various properties of that file.
  14236. If you need to find out details about the file, it's more efficient to call this method than
  14237. to call the normal next() method and then find out the details afterwards.
  14238. All the parameters are optional, so pass null pointers for any items that you're not
  14239. interested in.
  14240. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14241. false if there are no more matching files. If it returns false, then none of the
  14242. parameters will be filled-in.
  14243. */
  14244. bool next (bool* isDirectory, bool* isHidden, int64* fileSize,
  14245. Time* modTime, Time* creationTime, bool* isReadOnly);
  14246. /** Returns the file that the iterator is currently pointing at.
  14247. The result of this call is only valid after a call to next() has returned true.
  14248. */
  14249. const File getFile() const;
  14250. /** Returns a guess of how far through the search the iterator has got.
  14251. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  14252. very accurate.
  14253. */
  14254. float getEstimatedProgress() const;
  14255. private:
  14256. class NativeIterator
  14257. {
  14258. public:
  14259. NativeIterator (const File& directory, const String& wildCard);
  14260. ~NativeIterator();
  14261. bool next (String& filenameFound,
  14262. bool* isDirectory, bool* isHidden, int64* fileSize,
  14263. Time* modTime, Time* creationTime, bool* isReadOnly);
  14264. class Pimpl;
  14265. private:
  14266. friend class DirectoryIterator;
  14267. friend class ScopedPointer<Pimpl>;
  14268. ScopedPointer<Pimpl> pimpl;
  14269. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeIterator);
  14270. };
  14271. friend class ScopedPointer<NativeIterator::Pimpl>;
  14272. NativeIterator fileFinder;
  14273. String wildCard, path;
  14274. int index;
  14275. mutable int totalNumFiles;
  14276. const int whatToLookFor;
  14277. const bool isRecursive;
  14278. bool hasBeenAdvanced;
  14279. ScopedPointer <DirectoryIterator> subIterator;
  14280. File currentFile;
  14281. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryIterator);
  14282. };
  14283. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14284. /*** End of inlined file: juce_DirectoryIterator.h ***/
  14285. #endif
  14286. #ifndef __JUCE_FILE_JUCEHEADER__
  14287. #endif
  14288. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14289. /*** Start of inlined file: juce_FileInputStream.h ***/
  14290. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14291. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14292. /**
  14293. An input stream that reads from a local file.
  14294. @see InputStream, FileOutputStream, File::createInputStream
  14295. */
  14296. class JUCE_API FileInputStream : public InputStream
  14297. {
  14298. public:
  14299. /** Creates a FileInputStream.
  14300. @param fileToRead the file to read from - if the file can't be accessed for some
  14301. reason, then the stream will just contain no data
  14302. */
  14303. explicit FileInputStream (const File& fileToRead);
  14304. /** Destructor. */
  14305. ~FileInputStream();
  14306. const File& getFile() const throw() { return file; }
  14307. int64 getTotalLength();
  14308. int read (void* destBuffer, int maxBytesToRead);
  14309. bool isExhausted();
  14310. int64 getPosition();
  14311. bool setPosition (int64 pos);
  14312. private:
  14313. File file;
  14314. void* fileHandle;
  14315. int64 currentPosition, totalSize;
  14316. bool needToSeek;
  14317. void openHandle();
  14318. void closeHandle();
  14319. size_t readInternal (void* buffer, size_t numBytes);
  14320. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputStream);
  14321. };
  14322. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14323. /*** End of inlined file: juce_FileInputStream.h ***/
  14324. #endif
  14325. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14326. /*** Start of inlined file: juce_FileOutputStream.h ***/
  14327. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14328. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14329. /**
  14330. An output stream that writes into a local file.
  14331. @see OutputStream, FileInputStream, File::createOutputStream
  14332. */
  14333. class JUCE_API FileOutputStream : public OutputStream
  14334. {
  14335. public:
  14336. /** Creates a FileOutputStream.
  14337. If the file doesn't exist, it will first be created. If the file can't be
  14338. created or opened, the failedToOpen() method will return
  14339. true.
  14340. If the file already exists when opened, the stream's write-postion will
  14341. be set to the end of the file. To overwrite an existing file,
  14342. use File::deleteFile() before opening the stream, or use setPosition(0)
  14343. after it's opened (although this won't truncate the file).
  14344. It's better to use File::createOutputStream() to create one of these, rather
  14345. than using the class directly.
  14346. @see TemporaryFile
  14347. */
  14348. FileOutputStream (const File& fileToWriteTo,
  14349. int bufferSizeToUse = 16384);
  14350. /** Destructor. */
  14351. ~FileOutputStream();
  14352. /** Returns the file that this stream is writing to.
  14353. */
  14354. const File& getFile() const { return file; }
  14355. /** Returns true if the stream couldn't be opened for some reason.
  14356. */
  14357. bool failedToOpen() const { return fileHandle == 0; }
  14358. void flush();
  14359. int64 getPosition();
  14360. bool setPosition (int64 pos);
  14361. bool write (const void* data, int numBytes);
  14362. private:
  14363. File file;
  14364. void* fileHandle;
  14365. int64 currentPosition;
  14366. int bufferSize, bytesInBuffer;
  14367. HeapBlock <char> buffer;
  14368. void openHandle();
  14369. void closeHandle();
  14370. void flushInternal();
  14371. int64 setPositionInternal (int64 newPosition);
  14372. int writeInternal (const void* data, int numBytes);
  14373. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileOutputStream);
  14374. };
  14375. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14376. /*** End of inlined file: juce_FileOutputStream.h ***/
  14377. #endif
  14378. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  14379. /*** Start of inlined file: juce_FileSearchPath.h ***/
  14380. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  14381. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  14382. /**
  14383. Encapsulates a set of folders that make up a search path.
  14384. @see File
  14385. */
  14386. class JUCE_API FileSearchPath
  14387. {
  14388. public:
  14389. /** Creates an empty search path. */
  14390. FileSearchPath();
  14391. /** Creates a search path from a string of pathnames.
  14392. The path can be semicolon- or comma-separated, e.g.
  14393. "/foo/bar;/foo/moose;/fish/moose"
  14394. The separate folders are tokenised and added to the search path.
  14395. */
  14396. FileSearchPath (const String& path);
  14397. /** Creates a copy of another search path. */
  14398. FileSearchPath (const FileSearchPath& other);
  14399. /** Destructor. */
  14400. ~FileSearchPath();
  14401. /** Uses a string containing a list of pathnames to re-initialise this list.
  14402. This search path is cleared and the semicolon- or comma-separated folders
  14403. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  14404. */
  14405. FileSearchPath& operator= (const String& path);
  14406. /** Returns the number of folders in this search path.
  14407. @see operator[]
  14408. */
  14409. int getNumPaths() const;
  14410. /** Returns one of the folders in this search path.
  14411. The file returned isn't guaranteed to actually be a valid directory.
  14412. @see getNumPaths
  14413. */
  14414. const File operator[] (int index) const;
  14415. /** Returns the search path as a semicolon-separated list of directories. */
  14416. const String toString() const;
  14417. /** Adds a new directory to the search path.
  14418. The new directory is added to the end of the list if the insertIndex parameter is
  14419. less than zero, otherwise it is inserted at the given index.
  14420. */
  14421. void add (const File& directoryToAdd,
  14422. int insertIndex = -1);
  14423. /** Adds a new directory to the search path if it's not already in there. */
  14424. void addIfNotAlreadyThere (const File& directoryToAdd);
  14425. /** Removes a directory from the search path. */
  14426. void remove (int indexToRemove);
  14427. /** Merges another search path into this one.
  14428. This will remove any duplicate directories.
  14429. */
  14430. void addPath (const FileSearchPath& other);
  14431. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  14432. If the search is intended to be recursive, there's no point having nested folders in the search
  14433. path, because they'll just get searched twice and you'll get duplicate results.
  14434. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  14435. */
  14436. void removeRedundantPaths();
  14437. /** Removes any directories that don't actually exist. */
  14438. void removeNonExistentPaths();
  14439. /** Searches the path for a wildcard.
  14440. This will search all the directories in the search path in order, adding any
  14441. matching files to the results array.
  14442. @param results an array to append the results to
  14443. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  14444. return files, directories, or both.
  14445. @param searchRecursively whether to recursively search the subdirectories too
  14446. @param wildCardPattern a pattern to match against the filenames
  14447. @returns the number of files added to the array
  14448. @see File::findChildFiles
  14449. */
  14450. int findChildFiles (Array<File>& results,
  14451. int whatToLookFor,
  14452. bool searchRecursively,
  14453. const String& wildCardPattern = "*") const;
  14454. /** Finds out whether a file is inside one of the path's directories.
  14455. This will return true if the specified file is a child of one of the
  14456. directories specified by this path. Note that this doesn't actually do any
  14457. searching or check that the files exist - it just looks at the pathnames
  14458. to work out whether the file would be inside a directory.
  14459. @param fileToCheck the file to look for
  14460. @param checkRecursively if true, then this will return true if the file is inside a
  14461. subfolder of one of the path's directories (at any depth). If false
  14462. it will only return true if the file is actually a direct child
  14463. of one of the directories.
  14464. @see File::isAChildOf
  14465. */
  14466. bool isFileInPath (const File& fileToCheck,
  14467. bool checkRecursively) const;
  14468. private:
  14469. StringArray directories;
  14470. void init (const String& path);
  14471. JUCE_LEAK_DETECTOR (FileSearchPath);
  14472. };
  14473. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  14474. /*** End of inlined file: juce_FileSearchPath.h ***/
  14475. #endif
  14476. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  14477. /*** Start of inlined file: juce_NamedPipe.h ***/
  14478. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  14479. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  14480. /**
  14481. A cross-process pipe that can have data written to and read from it.
  14482. Two or more processes can use these for inter-process communication.
  14483. @see InterprocessConnection
  14484. */
  14485. class JUCE_API NamedPipe
  14486. {
  14487. public:
  14488. /** Creates a NamedPipe. */
  14489. NamedPipe();
  14490. /** Destructor. */
  14491. ~NamedPipe();
  14492. /** Tries to open a pipe that already exists.
  14493. Returns true if it succeeds.
  14494. */
  14495. bool openExisting (const String& pipeName);
  14496. /** Tries to create a new pipe.
  14497. Returns true if it succeeds.
  14498. */
  14499. bool createNewPipe (const String& pipeName);
  14500. /** Closes the pipe, if it's open. */
  14501. void close();
  14502. /** True if the pipe is currently open. */
  14503. bool isOpen() const;
  14504. /** Returns the last name that was used to try to open this pipe. */
  14505. const String getName() const;
  14506. /** Reads data from the pipe.
  14507. This will block until another thread has written enough data into the pipe to fill
  14508. the number of bytes specified, or until another thread calls the cancelPendingReads()
  14509. method.
  14510. If the operation fails, it returns -1, otherwise, it will return the number of
  14511. bytes read.
  14512. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  14513. this is a maximum timeout for reading from the pipe.
  14514. */
  14515. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  14516. /** Writes some data to the pipe.
  14517. If the operation fails, it returns -1, otherwise, it will return the number of
  14518. bytes written.
  14519. */
  14520. int write (const void* sourceBuffer, int numBytesToWrite,
  14521. int timeOutMilliseconds = 2000);
  14522. /** If any threads are currently blocked on a read operation, this tells them to abort.
  14523. */
  14524. void cancelPendingReads();
  14525. private:
  14526. void* internal;
  14527. String currentPipeName;
  14528. CriticalSection lock;
  14529. bool openInternal (const String& pipeName, const bool createPipe);
  14530. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NamedPipe);
  14531. };
  14532. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  14533. /*** End of inlined file: juce_NamedPipe.h ***/
  14534. #endif
  14535. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  14536. /*** Start of inlined file: juce_TemporaryFile.h ***/
  14537. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  14538. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  14539. /**
  14540. Manages a temporary file, which will be deleted when this object is deleted.
  14541. This object is intended to be used as a stack based object, using its scope
  14542. to make sure the temporary file isn't left lying around.
  14543. For example:
  14544. @code
  14545. {
  14546. File myTargetFile ("~/myfile.txt");
  14547. // this will choose a file called something like "~/myfile_temp239348.txt"
  14548. // which definitely doesn't exist at the time the constructor is called.
  14549. TemporaryFile temp (myTargetFile);
  14550. // create a stream to the temporary file, and write some data to it...
  14551. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  14552. if (out != 0)
  14553. {
  14554. out->write ( ...etc )
  14555. out->flush();
  14556. out = 0; // (deletes the stream)
  14557. // ..now we've finished writing, this will rename the temp file to
  14558. // make it replace the target file we specified above.
  14559. bool succeeded = temp.overwriteTargetFileWithTemporary();
  14560. }
  14561. // ..and even if something went wrong and our overwrite failed,
  14562. // as the TemporaryFile object goes out of scope here, it'll make sure
  14563. // that the temp file gets deleted.
  14564. }
  14565. @endcode
  14566. @see File, FileOutputStream
  14567. */
  14568. class JUCE_API TemporaryFile
  14569. {
  14570. public:
  14571. enum OptionFlags
  14572. {
  14573. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  14574. i.e. its name should start with a dot. */
  14575. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  14576. the file is unique, they should go in brackets rather
  14577. than just being appended (see File::getNonexistentSibling() )*/
  14578. };
  14579. /** Creates a randomly-named temporary file in the default temp directory.
  14580. @param suffix a file suffix to use for the file
  14581. @param optionFlags a combination of the values listed in the OptionFlags enum
  14582. The file will not be created until you write to it. And remember that when
  14583. this object is deleted, the file will also be deleted!
  14584. */
  14585. TemporaryFile (const String& suffix = String::empty,
  14586. int optionFlags = 0);
  14587. /** Creates a temporary file in the same directory as a specified file.
  14588. This is useful if you have a file that you want to overwrite, but don't
  14589. want to harm the original file if the write operation fails. You can
  14590. use this to create a temporary file next to the target file, then
  14591. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  14592. to replace the target file with the one you've just written.
  14593. This class won't create any files until you actually write to them. And remember
  14594. that when this object is deleted, the temporary file will also be deleted!
  14595. @param targetFile the file that you intend to overwrite - the temporary
  14596. file will be created in the same directory as this
  14597. @param optionFlags a combination of the values listed in the OptionFlags enum
  14598. */
  14599. TemporaryFile (const File& targetFile,
  14600. int optionFlags = 0);
  14601. /** Destructor.
  14602. When this object is deleted it will make sure that its temporary file is
  14603. also deleted! If the operation fails, it'll throw an assertion in debug
  14604. mode.
  14605. */
  14606. ~TemporaryFile();
  14607. /** Returns the temporary file. */
  14608. const File getFile() const { return temporaryFile; }
  14609. /** Returns the target file that was specified in the constructor. */
  14610. const File getTargetFile() const { return targetFile; }
  14611. /** Tries to move the temporary file to overwrite the target file that was
  14612. specified in the constructor.
  14613. If you used the constructor that specified a target file, this will attempt
  14614. to replace that file with the temporary one.
  14615. Before calling this, make sure:
  14616. - that you've actually written to the temporary file
  14617. - that you've closed any open streams that you were using to write to it
  14618. - and that you don't have any streams open to the target file, which would
  14619. prevent it being overwritten
  14620. If the file move succeeds, this returns false, and the temporary file will
  14621. have disappeared. If it fails, the temporary file will probably still exist,
  14622. but will be deleted when this object is destroyed.
  14623. */
  14624. bool overwriteTargetFileWithTemporary() const;
  14625. /** Attempts to delete the temporary file, if it exists.
  14626. @returns true if the file is successfully deleted (or if it didn't exist).
  14627. */
  14628. bool deleteTemporaryFile() const;
  14629. private:
  14630. File temporaryFile, targetFile;
  14631. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  14632. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryFile);
  14633. };
  14634. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  14635. /*** End of inlined file: juce_TemporaryFile.h ***/
  14636. #endif
  14637. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  14638. /*** Start of inlined file: juce_ZipFile.h ***/
  14639. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  14640. #define __JUCE_ZIPFILE_JUCEHEADER__
  14641. /*** Start of inlined file: juce_InputSource.h ***/
  14642. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  14643. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  14644. /**
  14645. A lightweight object that can create a stream to read some kind of resource.
  14646. This may be used to refer to a file, or some other kind of source, allowing a
  14647. caller to create an input stream that can read from it when required.
  14648. @see FileInputSource
  14649. */
  14650. class JUCE_API InputSource
  14651. {
  14652. public:
  14653. InputSource() throw() {}
  14654. /** Destructor. */
  14655. virtual ~InputSource() {}
  14656. /** Returns a new InputStream to read this item.
  14657. @returns an inputstream that the caller will delete, or 0 if
  14658. the filename isn't found.
  14659. */
  14660. virtual InputStream* createInputStream() = 0;
  14661. /** Returns a new InputStream to read an item, relative.
  14662. @param relatedItemPath the relative pathname of the resource that is required
  14663. @returns an inputstream that the caller will delete, or 0 if
  14664. the item isn't found.
  14665. */
  14666. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  14667. /** Returns a hash code that uniquely represents this item.
  14668. */
  14669. virtual int64 hashCode() const = 0;
  14670. private:
  14671. JUCE_LEAK_DETECTOR (InputSource);
  14672. };
  14673. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  14674. /*** End of inlined file: juce_InputSource.h ***/
  14675. /**
  14676. Decodes a ZIP file from a stream.
  14677. This can enumerate the items in a ZIP file and can create suitable stream objects
  14678. to read each one.
  14679. */
  14680. class JUCE_API ZipFile
  14681. {
  14682. public:
  14683. /** Creates a ZipFile for a given stream.
  14684. @param inputStream the stream to read from
  14685. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  14686. will be deleted when this ZipFile object is deleted
  14687. */
  14688. ZipFile (InputStream* inputStream, bool deleteStreamWhenDestroyed);
  14689. /** Creates a ZipFile based for a file. */
  14690. ZipFile (const File& file);
  14691. /** Creates a ZipFile for an input source.
  14692. The inputSource object will be owned by the zip file, which will delete
  14693. it later when not needed.
  14694. */
  14695. ZipFile (InputSource* inputSource);
  14696. /** Destructor. */
  14697. ~ZipFile();
  14698. /**
  14699. Contains information about one of the entries in a ZipFile.
  14700. @see ZipFile::getEntry
  14701. */
  14702. struct ZipEntry
  14703. {
  14704. /** The name of the file, which may also include a partial pathname. */
  14705. String filename;
  14706. /** The file's original size. */
  14707. unsigned int uncompressedSize;
  14708. /** The last time the file was modified. */
  14709. Time fileTime;
  14710. };
  14711. /** Returns the number of items in the zip file. */
  14712. int getNumEntries() const throw();
  14713. /** Returns a structure that describes one of the entries in the zip file.
  14714. This may return zero if the index is out of range.
  14715. @see ZipFile::ZipEntry
  14716. */
  14717. const ZipEntry* getEntry (int index) const throw();
  14718. /** Returns the index of the first entry with a given filename.
  14719. This uses a case-sensitive comparison to look for a filename in the
  14720. list of entries. It might return -1 if no match is found.
  14721. @see ZipFile::ZipEntry
  14722. */
  14723. int getIndexOfFileName (const String& fileName) const throw();
  14724. /** Returns a structure that describes one of the entries in the zip file.
  14725. This uses a case-sensitive comparison to look for a filename in the
  14726. list of entries. It might return 0 if no match is found.
  14727. @see ZipFile::ZipEntry
  14728. */
  14729. const ZipEntry* getEntry (const String& fileName) const throw();
  14730. /** Sorts the list of entries, based on the filename.
  14731. */
  14732. void sortEntriesByFilename();
  14733. /** Creates a stream that can read from one of the zip file's entries.
  14734. The stream that is returned must be deleted by the caller (and
  14735. zero might be returned if a stream can't be opened for some reason).
  14736. The stream must not be used after the ZipFile object that created
  14737. has been deleted.
  14738. */
  14739. InputStream* createStreamForEntry (int index);
  14740. /** Creates a stream that can read from one of the zip file's entries.
  14741. The stream that is returned must be deleted by the caller (and
  14742. zero might be returned if a stream can't be opened for some reason).
  14743. The stream must not be used after the ZipFile object that created
  14744. has been deleted.
  14745. */
  14746. InputStream* createStreamForEntry (ZipEntry& entry);
  14747. /** Uncompresses all of the files in the zip file.
  14748. This will expand all the entries into a target directory. The relative
  14749. paths of the entries are used.
  14750. @param targetDirectory the root folder to uncompress to
  14751. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  14752. @returns true if all the files are successfully unzipped
  14753. */
  14754. bool uncompressTo (const File& targetDirectory,
  14755. bool shouldOverwriteFiles = true);
  14756. /** Uncompresses one of the entries from the zip file.
  14757. This will expand the entry and write it in a target directory. The entry's path is used to
  14758. determine which subfolder of the target should contain the new file.
  14759. @param index the index of the entry to uncompress
  14760. @param targetDirectory the root folder to uncompress into
  14761. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  14762. @returns true if the files is successfully unzipped
  14763. */
  14764. bool uncompressEntry (int index,
  14765. const File& targetDirectory,
  14766. bool shouldOverwriteFiles = true);
  14767. private:
  14768. class ZipInputStream;
  14769. class ZipFilenameComparator;
  14770. class ZipEntryInfo;
  14771. friend class ZipInputStream;
  14772. friend class ZipFilenameComparator;
  14773. friend class ZipEntryInfo;
  14774. OwnedArray <ZipEntryInfo> entries;
  14775. CriticalSection lock;
  14776. InputStream* inputStream;
  14777. ScopedPointer <InputStream> streamToDelete;
  14778. ScopedPointer <InputSource> inputSource;
  14779. #if JUCE_DEBUG
  14780. int numOpenStreams;
  14781. #endif
  14782. void init();
  14783. int findEndOfZipEntryTable (InputStream& input, int& numEntries);
  14784. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  14785. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipFile);
  14786. };
  14787. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  14788. /*** End of inlined file: juce_ZipFile.h ***/
  14789. #endif
  14790. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  14791. /*** Start of inlined file: juce_MACAddress.h ***/
  14792. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  14793. #define __JUCE_MACADDRESS_JUCEHEADER__
  14794. /**
  14795. A wrapper for a streaming (TCP) socket.
  14796. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  14797. sockets, you could also try the InterprocessConnection class.
  14798. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  14799. */
  14800. class JUCE_API MACAddress
  14801. {
  14802. public:
  14803. /** Populates a list of the MAC addresses of all the available network cards. */
  14804. static void findAllAddresses (Array<MACAddress>& results);
  14805. /** Creates a null address (00-00-00-00-00-00). */
  14806. MACAddress();
  14807. /** Creates a copy of another address. */
  14808. MACAddress (const MACAddress& other);
  14809. /** Creates a copy of another address. */
  14810. MACAddress& operator= (const MACAddress& other);
  14811. /** Creates an address from 6 bytes. */
  14812. explicit MACAddress (const uint8 bytes[6]);
  14813. /** Returns a pointer to the 6 bytes that make up this address. */
  14814. const uint8* getBytes() const throw() { return asBytes; }
  14815. /** Returns a dash-separated string in the form "11-22-33-44-55-66" */
  14816. const String toString() const;
  14817. /** Returns the address in the lower 6 bytes of an int64.
  14818. This uses a little-endian arrangement, with the first byte of the address being
  14819. stored in the least-significant byte of the result value.
  14820. */
  14821. int64 toInt64() const throw();
  14822. /** Returns true if this address is null (00-00-00-00-00-00). */
  14823. bool isNull() const throw();
  14824. bool operator== (const MACAddress& other) const throw();
  14825. bool operator!= (const MACAddress& other) const throw();
  14826. private:
  14827. #ifndef DOXYGEN
  14828. union
  14829. {
  14830. uint64 asInt64;
  14831. uint8 asBytes[6];
  14832. };
  14833. #endif
  14834. };
  14835. #endif // __JUCE_MACADDRESS_JUCEHEADER__
  14836. /*** End of inlined file: juce_MACAddress.h ***/
  14837. #endif
  14838. #ifndef __JUCE_SOCKET_JUCEHEADER__
  14839. /*** Start of inlined file: juce_Socket.h ***/
  14840. #ifndef __JUCE_SOCKET_JUCEHEADER__
  14841. #define __JUCE_SOCKET_JUCEHEADER__
  14842. /**
  14843. A wrapper for a streaming (TCP) socket.
  14844. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  14845. sockets, you could also try the InterprocessConnection class.
  14846. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  14847. */
  14848. class JUCE_API StreamingSocket
  14849. {
  14850. public:
  14851. /** Creates an uninitialised socket.
  14852. To connect it, use the connect() method, after which you can read() or write()
  14853. to it.
  14854. To wait for other sockets to connect to this one, the createListener() method
  14855. enters "listener" mode, and can be used to spawn new sockets for each connection
  14856. that comes along.
  14857. */
  14858. StreamingSocket();
  14859. /** Destructor. */
  14860. ~StreamingSocket();
  14861. /** Binds the socket to the specified local port.
  14862. @returns true on success; false may indicate that another socket is already bound
  14863. on the same port
  14864. */
  14865. bool bindToPort (int localPortNumber);
  14866. /** Tries to connect the socket to hostname:port.
  14867. If timeOutMillisecs is 0, then this method will block until the operating system
  14868. rejects the connection (which could take a long time).
  14869. @returns true if it succeeds.
  14870. @see isConnected
  14871. */
  14872. bool connect (const String& remoteHostname,
  14873. int remotePortNumber,
  14874. int timeOutMillisecs = 3000);
  14875. /** True if the socket is currently connected. */
  14876. bool isConnected() const throw() { return connected; }
  14877. /** Closes the connection. */
  14878. void close();
  14879. /** Returns the name of the currently connected host. */
  14880. const String& getHostName() const throw() { return hostName; }
  14881. /** Returns the port number that's currently open. */
  14882. int getPort() const throw() { return portNumber; }
  14883. /** True if the socket is connected to this machine rather than over the network. */
  14884. bool isLocal() const throw();
  14885. /** Waits until the socket is ready for reading or writing.
  14886. If readyForReading is true, it will wait until the socket is ready for
  14887. reading; if false, it will wait until it's ready for writing.
  14888. If the timeout is < 0, it will wait forever, or else will give up after
  14889. the specified time.
  14890. If the socket is ready on return, this returns 1. If it times-out before
  14891. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  14892. */
  14893. int waitUntilReady (bool readyForReading,
  14894. int timeoutMsecs) const;
  14895. /** Reads bytes from the socket.
  14896. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  14897. maxBytesToRead bytes have been read, (or until an error occurs). If this
  14898. flag is false, the method will return as much data as is currently available
  14899. without blocking.
  14900. @returns the number of bytes read, or -1 if there was an error.
  14901. @see waitUntilReady
  14902. */
  14903. int read (void* destBuffer, int maxBytesToRead,
  14904. bool blockUntilSpecifiedAmountHasArrived);
  14905. /** Writes bytes to the socket from a buffer.
  14906. Note that this method will block unless you have checked the socket is ready
  14907. for writing before calling it (see the waitUntilReady() method).
  14908. @returns the number of bytes written, or -1 if there was an error.
  14909. */
  14910. int write (const void* sourceBuffer, int numBytesToWrite);
  14911. /** Puts this socket into "listener" mode.
  14912. When in this mode, your thread can call waitForNextConnection() repeatedly,
  14913. which will spawn new sockets for each new connection, so that these can
  14914. be handled in parallel by other threads.
  14915. @param portNumber the port number to listen on
  14916. @param localHostName the interface address to listen on - pass an empty
  14917. string to listen on all addresses
  14918. @returns true if it manages to open the socket successfully.
  14919. @see waitForNextConnection
  14920. */
  14921. bool createListener (int portNumber, const String& localHostName = String::empty);
  14922. /** When in "listener" mode, this waits for a connection and spawns it as a new
  14923. socket.
  14924. The object that gets returned will be owned by the caller.
  14925. This method can only be called after using createListener().
  14926. @see createListener
  14927. */
  14928. StreamingSocket* waitForNextConnection() const;
  14929. private:
  14930. String hostName;
  14931. int volatile portNumber, handle;
  14932. bool connected, isListener;
  14933. StreamingSocket (const String& hostname, int portNumber, int handle);
  14934. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StreamingSocket);
  14935. };
  14936. /**
  14937. A wrapper for a datagram (UDP) socket.
  14938. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  14939. sockets, you could also try the InterprocessConnection class.
  14940. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  14941. */
  14942. class JUCE_API DatagramSocket
  14943. {
  14944. public:
  14945. /**
  14946. Creates an (uninitialised) datagram socket.
  14947. The localPortNumber is the port on which to bind this socket. If this value is 0,
  14948. the port number is assigned by the operating system.
  14949. To use the socket for sending, call the connect() method. This will not immediately
  14950. make a connection, but will save the destination you've provided. After this, you can
  14951. call read() or write().
  14952. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  14953. (may require extra privileges on linux)
  14954. To wait for other sockets to connect to this one, call waitForNextConnection().
  14955. */
  14956. DatagramSocket (int localPortNumber,
  14957. bool enableBroadcasting = false);
  14958. /** Destructor. */
  14959. ~DatagramSocket();
  14960. /** Binds the socket to the specified local port.
  14961. @returns true on success; false may indicate that another socket is already bound
  14962. on the same port
  14963. */
  14964. bool bindToPort (int localPortNumber);
  14965. /** Tries to connect the socket to hostname:port.
  14966. If timeOutMillisecs is 0, then this method will block until the operating system
  14967. rejects the connection (which could take a long time).
  14968. @returns true if it succeeds.
  14969. @see isConnected
  14970. */
  14971. bool connect (const String& remoteHostname,
  14972. int remotePortNumber,
  14973. int timeOutMillisecs = 3000);
  14974. /** True if the socket is currently connected. */
  14975. bool isConnected() const throw() { return connected; }
  14976. /** Closes the connection. */
  14977. void close();
  14978. /** Returns the name of the currently connected host. */
  14979. const String& getHostName() const throw() { return hostName; }
  14980. /** Returns the port number that's currently open. */
  14981. int getPort() const throw() { return portNumber; }
  14982. /** True if the socket is connected to this machine rather than over the network. */
  14983. bool isLocal() const throw();
  14984. /** Waits until the socket is ready for reading or writing.
  14985. If readyForReading is true, it will wait until the socket is ready for
  14986. reading; if false, it will wait until it's ready for writing.
  14987. If the timeout is < 0, it will wait forever, or else will give up after
  14988. the specified time.
  14989. If the socket is ready on return, this returns 1. If it times-out before
  14990. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  14991. */
  14992. int waitUntilReady (bool readyForReading,
  14993. int timeoutMsecs) const;
  14994. /** Reads bytes from the socket.
  14995. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  14996. maxBytesToRead bytes have been read, (or until an error occurs). If this
  14997. flag is false, the method will return as much data as is currently available
  14998. without blocking.
  14999. @returns the number of bytes read, or -1 if there was an error.
  15000. @see waitUntilReady
  15001. */
  15002. int read (void* destBuffer, int maxBytesToRead,
  15003. bool blockUntilSpecifiedAmountHasArrived);
  15004. /** Writes bytes to the socket from a buffer.
  15005. Note that this method will block unless you have checked the socket is ready
  15006. for writing before calling it (see the waitUntilReady() method).
  15007. @returns the number of bytes written, or -1 if there was an error.
  15008. */
  15009. int write (const void* sourceBuffer, int numBytesToWrite);
  15010. /** This waits for incoming data to be sent, and returns a socket that can be used
  15011. to read it.
  15012. The object that gets returned is owned by the caller, and can't be used for
  15013. sending, but can be used to read the data.
  15014. */
  15015. DatagramSocket* waitForNextConnection() const;
  15016. private:
  15017. String hostName;
  15018. int volatile portNumber, handle;
  15019. bool connected, allowBroadcast;
  15020. void* serverAddress;
  15021. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  15022. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DatagramSocket);
  15023. };
  15024. #endif // __JUCE_SOCKET_JUCEHEADER__
  15025. /*** End of inlined file: juce_Socket.h ***/
  15026. #endif
  15027. #ifndef __JUCE_URL_JUCEHEADER__
  15028. /*** Start of inlined file: juce_URL.h ***/
  15029. #ifndef __JUCE_URL_JUCEHEADER__
  15030. #define __JUCE_URL_JUCEHEADER__
  15031. /**
  15032. Represents a URL and has a bunch of useful functions to manipulate it.
  15033. This class can be used to launch URLs in browsers, and also to create
  15034. InputStreams that can read from remote http or ftp sources.
  15035. */
  15036. class JUCE_API URL
  15037. {
  15038. public:
  15039. /** Creates an empty URL. */
  15040. URL();
  15041. /** Creates a URL from a string. */
  15042. URL (const String& url);
  15043. /** Creates a copy of another URL. */
  15044. URL (const URL& other);
  15045. /** Destructor. */
  15046. ~URL();
  15047. /** Copies this URL from another one. */
  15048. URL& operator= (const URL& other);
  15049. /** Returns a string version of the URL.
  15050. If includeGetParameters is true and any parameters have been set with the
  15051. withParameter() method, then the string will have these appended on the
  15052. end and url-encoded.
  15053. */
  15054. const String toString (bool includeGetParameters) const;
  15055. /** True if it seems to be valid. */
  15056. bool isWellFormed() const;
  15057. /** Returns just the domain part of the URL.
  15058. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  15059. */
  15060. const String getDomain() const;
  15061. /** Returns the path part of the URL.
  15062. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  15063. */
  15064. const String getSubPath() const;
  15065. /** Returns the scheme of the URL.
  15066. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  15067. include the colon).
  15068. */
  15069. const String getScheme() const;
  15070. /** Returns a new version of this URL that uses a different sub-path.
  15071. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  15072. "bar", it'll return "http://www.xyz.com/bar?x=1".
  15073. */
  15074. const URL withNewSubPath (const String& newPath) const;
  15075. /** Returns a copy of this URL, with a GET or POST parameter added to the end.
  15076. Any control characters in the value will be encoded.
  15077. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  15078. would produce a new url whose toString(true) method would return
  15079. "www.fish.com?amount=some+fish".
  15080. */
  15081. const URL withParameter (const String& parameterName,
  15082. const String& parameterValue) const;
  15083. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  15084. When performing a POST where one of your parameters is a binary file, this
  15085. lets you specify the file.
  15086. Note that the filename is stored, but the file itself won't actually be read
  15087. until this URL is later used to create a network input stream.
  15088. */
  15089. const URL withFileToUpload (const String& parameterName,
  15090. const File& fileToUpload,
  15091. const String& mimeType) const;
  15092. /** Returns a set of all the parameters encoded into the url.
  15093. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  15094. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  15095. The values returned will have been cleaned up to remove any escape characters.
  15096. @see getNamedParameter, withParameter
  15097. */
  15098. const StringPairArray& getParameters() const;
  15099. /** Returns the set of files that should be uploaded as part of a POST operation.
  15100. This is the set of files that were added to the URL with the withFileToUpload()
  15101. method.
  15102. */
  15103. const StringPairArray& getFilesToUpload() const;
  15104. /** Returns the set of mime types associated with each of the upload files.
  15105. */
  15106. const StringPairArray& getMimeTypesOfUploadFiles() const;
  15107. /** Returns a copy of this URL, with a block of data to send as the POST data.
  15108. If you're setting the POST data, be careful not to have any parameters set
  15109. as well, otherwise it'll all get thrown in together, and might not have the
  15110. desired effect.
  15111. If the URL already contains some POST data, this will replace it, rather
  15112. than being appended to it.
  15113. This data will only be used if you specify a post operation when you call
  15114. createInputStream().
  15115. */
  15116. const URL withPOSTData (const String& postData) const;
  15117. /** Returns the data that was set using withPOSTData().
  15118. */
  15119. const String getPostData() const { return postData; }
  15120. /** Tries to launch the system's default browser to open the URL.
  15121. Returns true if this seems to have worked.
  15122. */
  15123. bool launchInDefaultBrowser() const;
  15124. /** Takes a guess as to whether a string might be a valid website address.
  15125. This isn't foolproof!
  15126. */
  15127. static bool isProbablyAWebsiteURL (const String& possibleURL);
  15128. /** Takes a guess as to whether a string might be a valid email address.
  15129. This isn't foolproof!
  15130. */
  15131. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  15132. /** This callback function can be used by the createInputStream() method.
  15133. It allows your app to receive progress updates during a lengthy POST operation. If you
  15134. want to continue the operation, this should return true, or false to abort.
  15135. */
  15136. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  15137. /** Attempts to open a stream that can read from this URL.
  15138. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  15139. the paramters, otherwise it'll encode them into the
  15140. URL and do a 'GET'.
  15141. @param progressCallback if this is non-zero, it lets you supply a callback function
  15142. to keep track of the operation's progress. This can be useful
  15143. for lengthy POST operations, so that you can provide user feedback.
  15144. @param progressCallbackContext if a callback is specified, this value will be passed to
  15145. the function
  15146. @param extraHeaders if not empty, this string is appended onto the headers that
  15147. are used for the request. It must therefore be a valid set of HTML
  15148. header directives, separated by newlines.
  15149. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  15150. a negative number, it will be infinite. Otherwise it specifies a
  15151. time in milliseconds.
  15152. @param responseHeaders if this is non-zero, all the (key, value) pairs received as headers
  15153. in the response will be stored in this array
  15154. @returns an input stream that the caller must delete, or a null pointer if there was an
  15155. error trying to open it.
  15156. */
  15157. InputStream* createInputStream (bool usePostCommand,
  15158. OpenStreamProgressCallback* progressCallback = 0,
  15159. void* progressCallbackContext = 0,
  15160. const String& extraHeaders = String::empty,
  15161. int connectionTimeOutMs = 0,
  15162. StringPairArray* responseHeaders = 0) const;
  15163. /** Tries to download the entire contents of this URL into a binary data block.
  15164. If it succeeds, this will return true and append the data it read onto the end
  15165. of the memory block.
  15166. @param destData the memory block to append the new data to
  15167. @param usePostCommand whether to use a POST command to get the data (uses
  15168. a GET command if this is false)
  15169. @see readEntireTextStream, readEntireXmlStream
  15170. */
  15171. bool readEntireBinaryStream (MemoryBlock& destData,
  15172. bool usePostCommand = false) const;
  15173. /** Tries to download the entire contents of this URL as a string.
  15174. If it fails, this will return an empty string, otherwise it will return the
  15175. contents of the downloaded file. If you need to distinguish between a read
  15176. operation that fails and one that returns an empty string, you'll need to use
  15177. a different method, such as readEntireBinaryStream().
  15178. @param usePostCommand whether to use a POST command to get the data (uses
  15179. a GET command if this is false)
  15180. @see readEntireBinaryStream, readEntireXmlStream
  15181. */
  15182. const String readEntireTextStream (bool usePostCommand = false) const;
  15183. /** Tries to download the entire contents of this URL and parse it as XML.
  15184. If it fails, or if the text that it reads can't be parsed as XML, this will
  15185. return 0.
  15186. When it returns a valid XmlElement object, the caller is responsibile for deleting
  15187. this object when no longer needed.
  15188. @param usePostCommand whether to use a POST command to get the data (uses
  15189. a GET command if this is false)
  15190. @see readEntireBinaryStream, readEntireTextStream
  15191. */
  15192. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  15193. /** Adds escape sequences to a string to encode any characters that aren't
  15194. legal in a URL.
  15195. E.g. any spaces will be replaced with "%20".
  15196. This is the opposite of removeEscapeChars().
  15197. If isParameter is true, it means that the string is going to be used
  15198. as a parameter, so it also encodes '$' and ',' (which would otherwise
  15199. be legal in a URL.
  15200. @see removeEscapeChars
  15201. */
  15202. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  15203. bool isParameter);
  15204. /** Replaces any escape character sequences in a string with their original
  15205. character codes.
  15206. E.g. any instances of "%20" will be replaced by a space.
  15207. This is the opposite of addEscapeChars().
  15208. @see addEscapeChars
  15209. */
  15210. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  15211. private:
  15212. String url, postData;
  15213. StringPairArray parameters, filesToUpload, mimeTypes;
  15214. static InputStream* createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  15215. OpenStreamProgressCallback* progressCallback,
  15216. void* progressCallbackContext, const String& headers,
  15217. const int timeOutMs, StringPairArray* responseHeaders);
  15218. JUCE_LEAK_DETECTOR (URL);
  15219. };
  15220. #endif // __JUCE_URL_JUCEHEADER__
  15221. /*** End of inlined file: juce_URL.h ***/
  15222. #endif
  15223. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15224. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  15225. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15226. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15227. /*** Start of inlined file: juce_OptionalScopedPointer.h ***/
  15228. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15229. #define __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15230. /**
  15231. Holds a pointer to an object which can optionally be deleted when this pointer
  15232. goes out of scope.
  15233. This acts in many ways like a ScopedPointer, but allows you to specify whether or
  15234. not the object is deleted.
  15235. @see ScopedPointer
  15236. */
  15237. template <class ObjectType>
  15238. class OptionalScopedPointer
  15239. {
  15240. public:
  15241. /** Creates an empty OptionalScopedPointer. */
  15242. OptionalScopedPointer() : shouldDelete (false) {}
  15243. /** Creates an OptionalScopedPointer to point to a given object, and specifying whether
  15244. the OptionalScopedPointer will delete it.
  15245. If takeOwnership is true, then the OptionalScopedPointer will act like a ScopedPointer,
  15246. deleting the object when it is itself deleted. If this parameter is false, then the
  15247. OptionalScopedPointer just holds a normal pointer to the object, and won't delete it.
  15248. */
  15249. OptionalScopedPointer (ObjectType* objectToHold, bool takeOwnership)
  15250. : object (objectToHold), shouldDelete (takeOwnership)
  15251. {
  15252. }
  15253. /** Takes ownership of the object that another OptionalScopedPointer holds.
  15254. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  15255. as ownership of the managed object is transferred to this object.
  15256. The flag to indicate whether or not to delete the managed object is also
  15257. copied from the source object.
  15258. */
  15259. OptionalScopedPointer (OptionalScopedPointer& objectToTransferFrom)
  15260. : object (objectToTransferFrom.release()),
  15261. shouldDelete (objectToTransferFrom.shouldDelete)
  15262. {
  15263. }
  15264. /** Takes ownership of the object that another OptionalScopedPointer holds.
  15265. Like a normal ScopedPointer, the objectToTransferFrom object will become null,
  15266. as ownership of the managed object is transferred to this object.
  15267. The ownership flag that says whether or not to delete the managed object is also
  15268. copied from the source object.
  15269. */
  15270. OptionalScopedPointer& operator= (OptionalScopedPointer& objectToTransferFrom)
  15271. {
  15272. if (object != objectToTransferFrom.object)
  15273. {
  15274. clear();
  15275. object = objectToTransferFrom.object;
  15276. }
  15277. shouldDelete = objectToTransferFrom.shouldDelete;
  15278. return *this;
  15279. }
  15280. /** The destructor may or may not delete the object that is being held, depending on the
  15281. takeOwnership flag that was specified when the object was first passed into an
  15282. OptionalScopedPointer constructor.
  15283. */
  15284. ~OptionalScopedPointer()
  15285. {
  15286. clear();
  15287. }
  15288. /** Returns the object that this pointer is managing. */
  15289. inline operator ObjectType*() const throw() { return object; }
  15290. /** Returns the object that this pointer is managing. */
  15291. inline ObjectType& operator*() const throw() { return *object; }
  15292. /** Lets you access methods and properties of the object that this pointer is holding. */
  15293. inline ObjectType* operator->() const throw() { return object; }
  15294. /** Removes the current object from this OptionalScopedPointer without deleting it.
  15295. This will return the current object, and set this OptionalScopedPointer to a null pointer.
  15296. */
  15297. ObjectType* release() throw() { return object.release(); }
  15298. /** Resets this pointer to null, possibly deleting the object that it holds, if it has
  15299. ownership of it.
  15300. */
  15301. void clear()
  15302. {
  15303. if (! shouldDelete)
  15304. object.release();
  15305. }
  15306. /** Swaps this object with another OptionalScopedPointer.
  15307. The two objects simply exchange their states.
  15308. */
  15309. void swapWith (OptionalScopedPointer<ObjectType>& other) throw()
  15310. {
  15311. object.swapWith (other.object);
  15312. swapVariables (shouldDelete, other.shouldDelete);
  15313. }
  15314. private:
  15315. ScopedPointer<ObjectType> object;
  15316. bool shouldDelete;
  15317. };
  15318. #endif // __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15319. /*** End of inlined file: juce_OptionalScopedPointer.h ***/
  15320. /** Wraps another input stream, and reads from it using an intermediate buffer
  15321. If you're using an input stream such as a file input stream, and making lots of
  15322. small read accesses to it, it's probably sensible to wrap it in one of these,
  15323. so that the source stream gets accessed in larger chunk sizes, meaning less
  15324. work for the underlying stream.
  15325. */
  15326. class JUCE_API BufferedInputStream : public InputStream
  15327. {
  15328. public:
  15329. /** Creates a BufferedInputStream from an input source.
  15330. @param sourceStream the source stream to read from
  15331. @param bufferSize the size of reservoir to use to buffer the source
  15332. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  15333. deleted by this object when it is itself deleted.
  15334. */
  15335. BufferedInputStream (InputStream* sourceStream,
  15336. int bufferSize,
  15337. bool deleteSourceWhenDestroyed);
  15338. /** Creates a BufferedInputStream from an input source.
  15339. @param sourceStream the source stream to read from - the source stream must not
  15340. be deleted until this object has been destroyed.
  15341. @param bufferSize the size of reservoir to use to buffer the source
  15342. */
  15343. BufferedInputStream (InputStream& sourceStream, int bufferSize);
  15344. /** Destructor.
  15345. This may also delete the source stream, if that option was chosen when the
  15346. buffered stream was created.
  15347. */
  15348. ~BufferedInputStream();
  15349. int64 getTotalLength();
  15350. int64 getPosition();
  15351. bool setPosition (int64 newPosition);
  15352. int read (void* destBuffer, int maxBytesToRead);
  15353. const String readString();
  15354. bool isExhausted();
  15355. private:
  15356. OptionalScopedPointer<InputStream> source;
  15357. int bufferSize;
  15358. int64 position, lastReadPos, bufferStart, bufferOverlap;
  15359. HeapBlock <char> buffer;
  15360. void ensureBuffered();
  15361. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferedInputStream);
  15362. };
  15363. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15364. /*** End of inlined file: juce_BufferedInputStream.h ***/
  15365. #endif
  15366. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15367. /*** Start of inlined file: juce_FileInputSource.h ***/
  15368. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15369. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15370. /**
  15371. A type of InputSource that represents a normal file.
  15372. @see InputSource
  15373. */
  15374. class JUCE_API FileInputSource : public InputSource
  15375. {
  15376. public:
  15377. FileInputSource (const File& file, bool useFileTimeInHashGeneration = false);
  15378. ~FileInputSource();
  15379. InputStream* createInputStream();
  15380. InputStream* createInputStreamFor (const String& relatedItemPath);
  15381. int64 hashCode() const;
  15382. private:
  15383. const File file;
  15384. bool useFileTimeInHashGeneration;
  15385. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputSource);
  15386. };
  15387. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15388. /*** End of inlined file: juce_FileInputSource.h ***/
  15389. #endif
  15390. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15391. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  15392. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15393. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15394. /**
  15395. A stream which uses zlib to compress the data written into it.
  15396. @see GZIPDecompressorInputStream
  15397. */
  15398. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  15399. {
  15400. public:
  15401. /** Creates a compression stream.
  15402. @param destStream the stream into which the compressed data should
  15403. be written
  15404. @param compressionLevel how much to compress the data, between 1 and 9, where
  15405. 1 is the fastest/lowest compression, and 9 is the
  15406. slowest/highest compression. Any value outside this range
  15407. indicates that a default compression level should be used.
  15408. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  15409. this stream is destroyed
  15410. @param windowBits this is used internally to change the window size used
  15411. by zlib - leave it as 0 unless you specifically need to set
  15412. its value for some reason
  15413. */
  15414. GZIPCompressorOutputStream (OutputStream* destStream,
  15415. int compressionLevel = 0,
  15416. bool deleteDestStreamWhenDestroyed = false,
  15417. int windowBits = 0);
  15418. /** Destructor. */
  15419. ~GZIPCompressorOutputStream();
  15420. void flush();
  15421. int64 getPosition();
  15422. bool setPosition (int64 newPosition);
  15423. bool write (const void* destBuffer, int howMany);
  15424. /** These are preset values that can be used for the constructor's windowBits paramter.
  15425. For more info about this, see the zlib documentation for its windowBits parameter.
  15426. */
  15427. enum WindowBitsValues
  15428. {
  15429. windowBitsRaw = -15,
  15430. windowBitsGZIP = 15 + 16
  15431. };
  15432. private:
  15433. OptionalScopedPointer<OutputStream> destStream;
  15434. HeapBlock <uint8> buffer;
  15435. class GZIPCompressorHelper;
  15436. friend class ScopedPointer <GZIPCompressorHelper>;
  15437. ScopedPointer <GZIPCompressorHelper> helper;
  15438. bool doNextBlock();
  15439. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPCompressorOutputStream);
  15440. };
  15441. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15442. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  15443. #endif
  15444. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  15445. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  15446. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  15447. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  15448. /**
  15449. This stream will decompress a source-stream using zlib.
  15450. Tip: if you're reading lots of small items from one of these streams, you
  15451. can increase the performance enormously by passing it through a
  15452. BufferedInputStream, so that it has to read larger blocks less often.
  15453. @see GZIPCompressorOutputStream
  15454. */
  15455. class JUCE_API GZIPDecompressorInputStream : public InputStream
  15456. {
  15457. public:
  15458. /** Creates a decompressor stream.
  15459. @param sourceStream the stream to read from
  15460. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  15461. when this object is destroyed
  15462. @param noWrap this is used internally by the ZipFile class
  15463. and should be ignored by user applications
  15464. @param uncompressedStreamLength if the creator knows the length that the
  15465. uncompressed stream will be, then it can supply this
  15466. value, which will be returned by getTotalLength()
  15467. */
  15468. GZIPDecompressorInputStream (InputStream* sourceStream,
  15469. bool deleteSourceWhenDestroyed,
  15470. bool noWrap = false,
  15471. int64 uncompressedStreamLength = -1);
  15472. /** Creates a decompressor stream.
  15473. @param sourceStream the stream to read from - the source stream must not be
  15474. deleted until this object has been destroyed
  15475. */
  15476. GZIPDecompressorInputStream (InputStream& sourceStream);
  15477. /** Destructor. */
  15478. ~GZIPDecompressorInputStream();
  15479. int64 getPosition();
  15480. bool setPosition (int64 pos);
  15481. int64 getTotalLength();
  15482. bool isExhausted();
  15483. int read (void* destBuffer, int maxBytesToRead);
  15484. private:
  15485. OptionalScopedPointer<InputStream> sourceStream;
  15486. const int64 uncompressedStreamLength;
  15487. const bool noWrap;
  15488. bool isEof;
  15489. int activeBufferSize;
  15490. int64 originalSourcePos, currentPos;
  15491. HeapBlock <uint8> buffer;
  15492. class GZIPDecompressHelper;
  15493. friend class ScopedPointer <GZIPDecompressHelper>;
  15494. ScopedPointer <GZIPDecompressHelper> helper;
  15495. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPDecompressorInputStream);
  15496. };
  15497. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  15498. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  15499. #endif
  15500. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  15501. #endif
  15502. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  15503. #endif
  15504. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  15505. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  15506. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  15507. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  15508. /**
  15509. Allows a block of data and to be accessed as a stream.
  15510. This can either be used to refer to a shared block of memory, or can make its
  15511. own internal copy of the data when the MemoryInputStream is created.
  15512. */
  15513. class JUCE_API MemoryInputStream : public InputStream
  15514. {
  15515. public:
  15516. /** Creates a MemoryInputStream.
  15517. @param sourceData the block of data to use as the stream's source
  15518. @param sourceDataSize the number of bytes in the source data block
  15519. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  15520. the source data, so this data shouldn't be changed
  15521. for the lifetime of the stream; if this parameter is
  15522. true, the stream will make its own copy of the
  15523. data and use that.
  15524. */
  15525. MemoryInputStream (const void* sourceData,
  15526. size_t sourceDataSize,
  15527. bool keepInternalCopyOfData);
  15528. /** Creates a MemoryInputStream.
  15529. @param data a block of data to use as the stream's source
  15530. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  15531. the source data, so this data shouldn't be changed
  15532. for the lifetime of the stream; if this parameter is
  15533. true, the stream will make its own copy of the
  15534. data and use that.
  15535. */
  15536. MemoryInputStream (const MemoryBlock& data,
  15537. bool keepInternalCopyOfData);
  15538. /** Destructor. */
  15539. ~MemoryInputStream();
  15540. int64 getPosition();
  15541. bool setPosition (int64 pos);
  15542. int64 getTotalLength();
  15543. bool isExhausted();
  15544. int read (void* destBuffer, int maxBytesToRead);
  15545. private:
  15546. const char* data;
  15547. size_t dataSize, position;
  15548. MemoryBlock internalCopy;
  15549. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryInputStream);
  15550. };
  15551. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  15552. /*** End of inlined file: juce_MemoryInputStream.h ***/
  15553. #endif
  15554. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  15555. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  15556. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  15557. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  15558. /**
  15559. Writes data to an internal memory buffer, which grows as required.
  15560. The data that was written into the stream can then be accessed later as
  15561. a contiguous block of memory.
  15562. */
  15563. class JUCE_API MemoryOutputStream : public OutputStream
  15564. {
  15565. public:
  15566. /** Creates an empty memory stream ready for writing into.
  15567. @param initialSize the intial amount of capacity to allocate for writing into
  15568. */
  15569. MemoryOutputStream (size_t initialSize = 256);
  15570. /** Creates a memory stream for writing into into a pre-existing MemoryBlock object.
  15571. Note that the destination block will always be larger than the amount of data
  15572. that has been written to the stream, because the MemoryOutputStream keeps some
  15573. spare capactity at its end. To trim the block's size down to fit the actual
  15574. data, call flush(), or delete the MemoryOutputStream.
  15575. @param memoryBlockToWriteTo the block into which new data will be written.
  15576. @param appendToExistingBlockContent if this is true, the contents of the block will be
  15577. kept, and new data will be appended to it. If false,
  15578. the block will be cleared before use
  15579. */
  15580. MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  15581. bool appendToExistingBlockContent);
  15582. /** Destructor.
  15583. This will free any data that was written to it.
  15584. */
  15585. ~MemoryOutputStream();
  15586. /** Returns a pointer to the data that has been written to the stream.
  15587. @see getDataSize
  15588. */
  15589. const void* getData() const throw();
  15590. /** Returns the number of bytes of data that have been written to the stream.
  15591. @see getData
  15592. */
  15593. size_t getDataSize() const throw() { return size; }
  15594. /** Resets the stream, clearing any data that has been written to it so far. */
  15595. void reset() throw();
  15596. /** Increases the internal storage capacity to be able to contain at least the specified
  15597. amount of data without needing to be resized.
  15598. */
  15599. void preallocate (size_t bytesToPreallocate);
  15600. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  15601. const String toUTF8() const;
  15602. /** Attempts to detect the encoding of the data and convert it to a string.
  15603. @see String::createStringFromData
  15604. */
  15605. const String toString() const;
  15606. /** If the stream is writing to a user-supplied MemoryBlock, this will trim any excess
  15607. capacity off the block, so that its length matches the amount of actual data that
  15608. has been written so far.
  15609. */
  15610. void flush();
  15611. bool write (const void* buffer, int howMany);
  15612. int64 getPosition() { return position; }
  15613. bool setPosition (int64 newPosition);
  15614. int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  15615. private:
  15616. MemoryBlock& data;
  15617. MemoryBlock internalBlock;
  15618. size_t position, size;
  15619. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryOutputStream);
  15620. };
  15621. /** Copies all the data that has been written to a MemoryOutputStream into another stream. */
  15622. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead);
  15623. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  15624. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  15625. #endif
  15626. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  15627. #endif
  15628. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  15629. /*** Start of inlined file: juce_SubregionStream.h ***/
  15630. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  15631. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  15632. /** Wraps another input stream, and reads from a specific part of it.
  15633. This lets you take a subsection of a stream and present it as an entire
  15634. stream in its own right.
  15635. */
  15636. class JUCE_API SubregionStream : public InputStream
  15637. {
  15638. public:
  15639. /** Creates a SubregionStream from an input source.
  15640. @param sourceStream the source stream to read from
  15641. @param startPositionInSourceStream this is the position in the source stream that
  15642. corresponds to position 0 in this stream
  15643. @param lengthOfSourceStream this specifies the maximum number of bytes
  15644. from the source stream that will be passed through
  15645. by this stream. When the position of this stream
  15646. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  15647. If the length passed in here is greater than the length
  15648. of the source stream (as returned by getTotalLength()),
  15649. then the smaller value will be used.
  15650. Passing a negative value for this parameter means it
  15651. will keep reading until the source's end-of-stream.
  15652. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  15653. deleted by this object when it is itself deleted.
  15654. */
  15655. SubregionStream (InputStream* sourceStream,
  15656. int64 startPositionInSourceStream,
  15657. int64 lengthOfSourceStream,
  15658. bool deleteSourceWhenDestroyed);
  15659. /** Destructor.
  15660. This may also delete the source stream, if that option was chosen when the
  15661. buffered stream was created.
  15662. */
  15663. ~SubregionStream();
  15664. int64 getTotalLength();
  15665. int64 getPosition();
  15666. bool setPosition (int64 newPosition);
  15667. int read (void* destBuffer, int maxBytesToRead);
  15668. bool isExhausted();
  15669. private:
  15670. OptionalScopedPointer<InputStream> source;
  15671. const int64 startPositionInSourceStream, lengthOfSourceStream;
  15672. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubregionStream);
  15673. };
  15674. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  15675. /*** End of inlined file: juce_SubregionStream.h ***/
  15676. #endif
  15677. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  15678. #endif
  15679. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  15680. /*** Start of inlined file: juce_Expression.h ***/
  15681. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  15682. #define __JUCE_EXPRESSION_JUCEHEADER__
  15683. /**
  15684. A class for dynamically evaluating simple numeric expressions.
  15685. This class can parse a simple C-style string expression involving floating point
  15686. numbers, named symbols and functions. The basic arithmetic operations of +, -, *, /
  15687. are supported, as well as parentheses, and any alphanumeric identifiers are
  15688. assumed to be named symbols which will be resolved when the expression is
  15689. evaluated.
  15690. Expressions which use identifiers and functions require a subclass of
  15691. Expression::Scope to be supplied when evaluating them, and this object
  15692. is expected to be able to resolve the symbol names and perform the functions that
  15693. are used.
  15694. */
  15695. class JUCE_API Expression
  15696. {
  15697. public:
  15698. /** Creates a simple expression with a value of 0. */
  15699. Expression();
  15700. /** Destructor. */
  15701. ~Expression();
  15702. /** Creates a simple expression with a specified constant value. */
  15703. explicit Expression (double constant);
  15704. /** Creates a copy of an expression. */
  15705. Expression (const Expression& other);
  15706. /** Copies another expression. */
  15707. Expression& operator= (const Expression& other);
  15708. /** Creates an expression by parsing a string.
  15709. If there's a syntax error in the string, this will throw a ParseError exception.
  15710. @throws ParseError
  15711. */
  15712. explicit Expression (const String& stringToParse);
  15713. /** Returns a string version of the expression. */
  15714. const String toString() const;
  15715. /** Returns an expression which is an addtion operation of two existing expressions. */
  15716. const Expression operator+ (const Expression& other) const;
  15717. /** Returns an expression which is a subtraction operation of two existing expressions. */
  15718. const Expression operator- (const Expression& other) const;
  15719. /** Returns an expression which is a multiplication operation of two existing expressions. */
  15720. const Expression operator* (const Expression& other) const;
  15721. /** Returns an expression which is a division operation of two existing expressions. */
  15722. const Expression operator/ (const Expression& other) const;
  15723. /** Returns an expression which performs a negation operation on an existing expression. */
  15724. const Expression operator-() const;
  15725. /** Returns an Expression which is an identifier reference. */
  15726. static const Expression symbol (const String& symbol);
  15727. /** Returns an Expression which is a function call. */
  15728. static const Expression function (const String& functionName, const Array<Expression>& parameters);
  15729. /** Returns an Expression which parses a string from a character pointer, and updates the pointer
  15730. to indicate where it finished.
  15731. The pointer is incremented so that on return, it indicates the character that follows
  15732. the end of the expression that was parsed.
  15733. If there's a syntax error in the string, this will throw a ParseError exception.
  15734. @throws ParseError
  15735. */
  15736. static const Expression parse (String::CharPointerType& stringToParse);
  15737. /** When evaluating an Expression object, this class is used to resolve symbols and
  15738. perform functions that the expression uses.
  15739. */
  15740. class JUCE_API Scope
  15741. {
  15742. public:
  15743. Scope();
  15744. virtual ~Scope();
  15745. /** Returns some kind of globally unique ID that identifies this scope. */
  15746. virtual const String getScopeUID() const;
  15747. /** Returns the value of a symbol.
  15748. If the symbol is unknown, this can throw an Expression::EvaluationError exception.
  15749. The member value is set to the part of the symbol that followed the dot, if there is
  15750. one, e.g. for "foo.bar", symbol = "foo" and member = "bar".
  15751. @throws Expression::EvaluationError
  15752. */
  15753. virtual const Expression getSymbolValue (const String& symbol) const;
  15754. /** Executes a named function.
  15755. If the function name is unknown, this can throw an Expression::EvaluationError exception.
  15756. @throws Expression::EvaluationError
  15757. */
  15758. virtual double evaluateFunction (const String& functionName,
  15759. const double* parameters, int numParameters) const;
  15760. /** Used as a callback by the Scope::visitRelativeScope() method.
  15761. You should never create an instance of this class yourself, it's used by the
  15762. expression evaluation code.
  15763. */
  15764. class Visitor
  15765. {
  15766. public:
  15767. virtual ~Visitor() {}
  15768. virtual void visit (const Scope&) = 0;
  15769. };
  15770. /** Creates a Scope object for a named scope, and then calls a visitor
  15771. to do some kind of processing with this new scope.
  15772. If the name is valid, this method must create a suitable (temporary) Scope
  15773. object to represent it, and must call the Visitor::visit() method with this
  15774. new scope.
  15775. */
  15776. virtual void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  15777. };
  15778. /** Evaluates this expression, without using a Scope.
  15779. Without a Scope, no symbols can be used, and only basic functions such as sin, cos, tan,
  15780. min, max are available.
  15781. To find out about any errors during evaluation, use the other version of this method which
  15782. takes a String parameter.
  15783. */
  15784. double evaluate() const;
  15785. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  15786. or functions that it uses.
  15787. To find out about any errors during evaluation, use the other version of this method which
  15788. takes a String parameter.
  15789. */
  15790. double evaluate (const Scope& scope) const;
  15791. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  15792. or functions that it uses.
  15793. */
  15794. double evaluate (const Scope& scope, String& evaluationError) const;
  15795. /** Attempts to return an expression which is a copy of this one, but with a constant adjusted
  15796. to make the expression resolve to a target value.
  15797. E.g. if the expression is "x + 10" and x is 5, then asking for a target value of 8 will return
  15798. the expression "x + 3". Obviously some expressions can't be reversed in this way, in which
  15799. case they might just be adjusted by adding a constant to the original expression.
  15800. @throws Expression::EvaluationError
  15801. */
  15802. const Expression adjustedToGiveNewResult (double targetValue, const Scope& scope) const;
  15803. /** Represents a symbol that is used in an Expression. */
  15804. struct Symbol
  15805. {
  15806. Symbol (const String& scopeUID, const String& symbolName);
  15807. bool operator== (const Symbol&) const throw();
  15808. bool operator!= (const Symbol&) const throw();
  15809. String scopeUID; /**< The unique ID of the Scope that contains this symbol. */
  15810. String symbolName; /**< The name of the symbol. */
  15811. };
  15812. /** Returns a copy of this expression in which all instances of a given symbol have been renamed. */
  15813. const Expression withRenamedSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope) const;
  15814. /** Returns true if this expression makes use of the specified symbol.
  15815. If a suitable scope is supplied, the search will dereference and recursively check
  15816. all symbols, so that it can be determined whether this expression relies on the given
  15817. symbol at any level in its evaluation. If the scope parameter is null, this just checks
  15818. whether the expression contains any direct references to the symbol.
  15819. @throws Expression::EvaluationError
  15820. */
  15821. bool referencesSymbol (const Symbol& symbol, const Scope& scope) const;
  15822. /** Returns true if this expression contains any symbols. */
  15823. bool usesAnySymbols() const;
  15824. /** Returns a list of all symbols that may be needed to resolve this expression in the given scope. */
  15825. void findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const;
  15826. /** An exception that can be thrown by Expression::parse(). */
  15827. class ParseError : public std::exception
  15828. {
  15829. public:
  15830. ParseError (const String& message);
  15831. String description;
  15832. };
  15833. /** Expression type.
  15834. @see Expression::getType()
  15835. */
  15836. enum Type
  15837. {
  15838. constantType,
  15839. functionType,
  15840. operatorType,
  15841. symbolType
  15842. };
  15843. /** Returns the type of this expression. */
  15844. Type getType() const throw();
  15845. /** If this expression is a symbol, function or operator, this returns its identifier. */
  15846. const String getSymbolOrFunction() const;
  15847. /** Returns the number of inputs to this expression.
  15848. @see getInput
  15849. */
  15850. int getNumInputs() const;
  15851. /** Retrieves one of the inputs to this expression.
  15852. @see getNumInputs
  15853. */
  15854. const Expression getInput (int index) const;
  15855. private:
  15856. class Term;
  15857. class Helpers;
  15858. friend class Term;
  15859. friend class Helpers;
  15860. friend class ScopedPointer<Term>;
  15861. friend class ReferenceCountedObjectPtr<Term>;
  15862. ReferenceCountedObjectPtr<Term> term;
  15863. explicit Expression (Term* term);
  15864. };
  15865. #endif // __JUCE_EXPRESSION_JUCEHEADER__
  15866. /*** End of inlined file: juce_Expression.h ***/
  15867. #endif
  15868. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  15869. #endif
  15870. #ifndef __JUCE_RANDOM_JUCEHEADER__
  15871. /*** Start of inlined file: juce_Random.h ***/
  15872. #ifndef __JUCE_RANDOM_JUCEHEADER__
  15873. #define __JUCE_RANDOM_JUCEHEADER__
  15874. /**
  15875. A random number generator.
  15876. You can create a Random object and use it to generate a sequence of random numbers.
  15877. As a handy shortcut to avoid having to create and seed one yourself, you can call
  15878. Random::getSystemRandom() to return a global RNG that is seeded randomly when the
  15879. app launches.
  15880. */
  15881. class JUCE_API Random
  15882. {
  15883. public:
  15884. /** Creates a Random object based on a seed value.
  15885. For a given seed value, the subsequent numbers generated by this object
  15886. will be predictable, so a good idea is to set this value based
  15887. on the time, e.g.
  15888. new Random (Time::currentTimeMillis())
  15889. */
  15890. explicit Random (int64 seedValue) throw();
  15891. /** Destructor. */
  15892. ~Random() throw();
  15893. /** Returns the next random 32 bit integer.
  15894. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  15895. */
  15896. int nextInt() throw();
  15897. /** Returns the next random number, limited to a given range.
  15898. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  15899. */
  15900. int nextInt (int maxValue) throw();
  15901. /** Returns the next 64-bit random number.
  15902. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  15903. */
  15904. int64 nextInt64() throw();
  15905. /** Returns the next random floating-point number.
  15906. @returns a random value in the range 0 to 1.0
  15907. */
  15908. float nextFloat() throw();
  15909. /** Returns the next random floating-point number.
  15910. @returns a random value in the range 0 to 1.0
  15911. */
  15912. double nextDouble() throw();
  15913. /** Returns the next random boolean value.
  15914. */
  15915. bool nextBool() throw();
  15916. /** Returns a BigInteger containing a random number.
  15917. @returns a random value in the range 0 to (maximumValue - 1).
  15918. */
  15919. const BigInteger nextLargeNumber (const BigInteger& maximumValue);
  15920. /** Sets a range of bits in a BigInteger to random values. */
  15921. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  15922. /** To avoid the overhead of having to create a new Random object whenever
  15923. you need a number, this is a shared application-wide object that
  15924. can be used.
  15925. It's not thread-safe though, so threads should use their own Random object.
  15926. */
  15927. static Random& getSystemRandom() throw();
  15928. /** Resets this Random object to a given seed value. */
  15929. void setSeed (int64 newSeed) throw();
  15930. /** Merges this object's seed with another value.
  15931. This sets the seed to be a value created by combining the current seed and this
  15932. new value.
  15933. */
  15934. void combineSeed (int64 seedValue) throw();
  15935. /** Reseeds this generator using a value generated from various semi-random system
  15936. properties like the current time, etc.
  15937. Because this function convolves the time with the last seed value, calling
  15938. it repeatedly will increase the randomness of the final result.
  15939. */
  15940. void setSeedRandomly();
  15941. private:
  15942. int64 seed;
  15943. JUCE_LEAK_DETECTOR (Random);
  15944. };
  15945. #endif // __JUCE_RANDOM_JUCEHEADER__
  15946. /*** End of inlined file: juce_Random.h ***/
  15947. #endif
  15948. #ifndef __JUCE_RANGE_JUCEHEADER__
  15949. #endif
  15950. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  15951. #endif
  15952. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  15953. #endif
  15954. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  15955. #endif
  15956. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  15957. #endif
  15958. #ifndef __JUCE_MEMORY_JUCEHEADER__
  15959. #endif
  15960. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  15961. #endif
  15962. #ifndef __JUCE_OPTIONALSCOPEDPOINTER_JUCEHEADER__
  15963. #endif
  15964. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  15965. #endif
  15966. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  15967. #endif
  15968. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  15969. /*** Start of inlined file: juce_WeakReference.h ***/
  15970. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  15971. #define __JUCE_WEAKREFERENCE_JUCEHEADER__
  15972. /**
  15973. This class acts as a pointer which will automatically become null if the object
  15974. to which it points is deleted.
  15975. To accomplish this, the source object needs to cooperate by performing a couple of simple tasks.
  15976. It must provide a getWeakReference() method and embed a WeakReference::Master object, which stores
  15977. a shared pointer object. It must also clear this master pointer when it's getting deleted.
  15978. E.g.
  15979. @code
  15980. class MyObject
  15981. {
  15982. public:
  15983. MyObject()
  15984. {
  15985. // If you're planning on using your WeakReferences in a multi-threaded situation, you may choose
  15986. // to call getWeakReference() here in the constructor, which will pre-initialise it, avoiding an
  15987. // (extremely unlikely) race condition that could occur if multiple threads overlap while making
  15988. // the first call to getWeakReference().
  15989. }
  15990. ~MyObject()
  15991. {
  15992. // This will zero all the references - you need to call this in your destructor.
  15993. masterReference.clear();
  15994. }
  15995. // Your object must provide a method that looks pretty much identical to this (except
  15996. // for the templated class name, of course).
  15997. const WeakReference<MyObject>::SharedRef& getWeakReference()
  15998. {
  15999. return masterReference (this);
  16000. }
  16001. private:
  16002. // You need to embed one of these inside your object. It can be private.
  16003. WeakReference<MyObject>::Master masterReference;
  16004. };
  16005. // Here's an example of using a pointer..
  16006. MyObject* n = new MyObject();
  16007. WeakReference<MyObject> myObjectRef = n;
  16008. MyObject* pointer1 = myObjectRef; // returns a valid pointer to 'n'
  16009. delete n;
  16010. MyObject* pointer2 = myObjectRef; // returns a null pointer
  16011. @endcode
  16012. @see WeakReference::Master
  16013. */
  16014. template <class ObjectType>
  16015. class WeakReference
  16016. {
  16017. public:
  16018. /** Creates a null SafePointer. */
  16019. WeakReference() throw() {}
  16020. /** Creates a WeakReference that points at the given object. */
  16021. WeakReference (ObjectType* const object) : holder (object != 0 ? object->getWeakReference() : 0) {}
  16022. /** Creates a copy of another WeakReference. */
  16023. WeakReference (const WeakReference& other) throw() : holder (other.holder) {}
  16024. /** Copies another pointer to this one. */
  16025. WeakReference& operator= (const WeakReference& other) { holder = other.holder; return *this; }
  16026. /** Copies another pointer to this one. */
  16027. WeakReference& operator= (ObjectType* const newObject) { holder = newObject != 0 ? newObject->getWeakReference() : 0; return *this; }
  16028. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16029. ObjectType* get() const throw() { return holder != 0 ? holder->get() : 0; }
  16030. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16031. operator ObjectType*() const throw() { return get(); }
  16032. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16033. ObjectType* operator->() throw() { return get(); }
  16034. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  16035. const ObjectType* operator->() const throw() { return get(); }
  16036. /** This returns true if this reference has been pointing at an object, but that object has
  16037. since been deleted.
  16038. If this reference was only ever pointing at a null pointer, this will return false. Using
  16039. operator=() to make this refer to a different object will reset this flag to match the status
  16040. of the reference from which you're copying.
  16041. */
  16042. bool wasObjectDeleted() const throw() { return holder != 0 && holder->get() == 0; }
  16043. bool operator== (ObjectType* const object) const throw() { return get() == object; }
  16044. bool operator!= (ObjectType* const object) const throw() { return get() != object; }
  16045. /** This class is used internally by the WeakReference class - don't use it directly
  16046. in your code!
  16047. @see WeakReference
  16048. */
  16049. class SharedPointer : public ReferenceCountedObject
  16050. {
  16051. public:
  16052. explicit SharedPointer (ObjectType* const owner_) throw() : owner (owner_) {}
  16053. inline ObjectType* get() const throw() { return owner; }
  16054. void clearPointer() throw() { owner = 0; }
  16055. private:
  16056. ObjectType* volatile owner;
  16057. JUCE_DECLARE_NON_COPYABLE (SharedPointer);
  16058. };
  16059. typedef ReferenceCountedObjectPtr<SharedPointer> SharedRef;
  16060. /**
  16061. This class is embedded inside an object to which you want to attach WeakReference pointers.
  16062. See the WeakReference class notes for an example of how to use this class.
  16063. @see WeakReference
  16064. */
  16065. class Master
  16066. {
  16067. public:
  16068. Master() throw() {}
  16069. ~Master()
  16070. {
  16071. // You must remember to call clear() in your source object's destructor! See the notes
  16072. // for the WeakReference class for an example of how to do this.
  16073. jassert (sharedPointer == 0 || sharedPointer->get() == 0);
  16074. }
  16075. /** The first call to this method will create an internal object that is shared by all weak
  16076. references to the object.
  16077. You need to call this from your main object's getWeakReference() method - see the WeakReference
  16078. class notes for an example.
  16079. */
  16080. const SharedRef& operator() (ObjectType* const object)
  16081. {
  16082. if (sharedPointer == 0)
  16083. {
  16084. sharedPointer = new SharedPointer (object);
  16085. }
  16086. else
  16087. {
  16088. // You're trying to create a weak reference to an object that has already been deleted!!
  16089. jassert (sharedPointer->get() != 0);
  16090. }
  16091. return sharedPointer;
  16092. }
  16093. /** The object that owns this master pointer should call this before it gets destroyed,
  16094. to zero all the references to this object that may be out there. See the WeakReference
  16095. class notes for an example of how to do this.
  16096. */
  16097. void clear()
  16098. {
  16099. if (sharedPointer != 0)
  16100. sharedPointer->clearPointer();
  16101. }
  16102. private:
  16103. SharedRef sharedPointer;
  16104. JUCE_DECLARE_NON_COPYABLE (Master);
  16105. };
  16106. private:
  16107. SharedRef holder;
  16108. };
  16109. #endif // __JUCE_WEAKREFERENCE_JUCEHEADER__
  16110. /*** End of inlined file: juce_WeakReference.h ***/
  16111. #endif
  16112. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  16113. #endif
  16114. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  16115. #endif
  16116. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  16117. #endif
  16118. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  16119. #endif
  16120. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  16121. #endif
  16122. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  16123. #endif
  16124. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16125. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  16126. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16127. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16128. /** Used in the same way as the T(text) macro, this will attempt to translate a
  16129. string into a localised version using the LocalisedStrings class.
  16130. @see LocalisedStrings
  16131. */
  16132. #define TRANS(stringLiteral) \
  16133. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  16134. /**
  16135. Used to convert strings to localised foreign-language versions.
  16136. This is basically a look-up table of strings and their translated equivalents.
  16137. It can be loaded from a text file, so that you can supply a set of localised
  16138. versions of strings that you use in your app.
  16139. To use it in your code, simply call the translate() method on each string that
  16140. might have foreign versions, and if none is found, the method will just return
  16141. the original string.
  16142. The translation file should start with some lines specifying a description of
  16143. the language it contains, and also a list of ISO country codes where it might
  16144. be appropriate to use the file. After that, each line of the file should contain
  16145. a pair of quoted strings with an '=' sign.
  16146. E.g. for a french translation, the file might be:
  16147. @code
  16148. language: French
  16149. countries: fr be mc ch lu
  16150. "hello" = "bonjour"
  16151. "goodbye" = "au revoir"
  16152. @endcode
  16153. If the strings need to contain a quote character, they can use '\"' instead, and
  16154. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  16155. (you can use this to add comments).
  16156. Note that this is a singleton class, so don't create or destroy the object directly.
  16157. There's also a TRANS(text) macro defined to make it easy to use the this.
  16158. E.g. @code
  16159. printSomething (TRANS("hello"));
  16160. @endcode
  16161. This macro is used in the Juce classes themselves, so your application has a chance to
  16162. intercept and translate any internal Juce text strings that might be shown. (You can easily
  16163. get a list of all the messages by searching for the TRANS() macro in the Juce source
  16164. code).
  16165. */
  16166. class JUCE_API LocalisedStrings
  16167. {
  16168. public:
  16169. /** Creates a set of translations from the text of a translation file.
  16170. When you create one of these, you can call setCurrentMappings() to make it
  16171. the set of mappings that the system's using.
  16172. */
  16173. LocalisedStrings (const String& fileContents);
  16174. /** Creates a set of translations from a file.
  16175. When you create one of these, you can call setCurrentMappings() to make it
  16176. the set of mappings that the system's using.
  16177. */
  16178. LocalisedStrings (const File& fileToLoad);
  16179. /** Destructor. */
  16180. ~LocalisedStrings();
  16181. /** Selects the current set of mappings to be used by the system.
  16182. The object you pass in will be automatically deleted when no longer needed, so
  16183. don't keep a pointer to it. You can also pass in zero to remove the current
  16184. mappings.
  16185. See also the TRANS() macro, which uses the current set to do its translation.
  16186. @see translateWithCurrentMappings
  16187. */
  16188. static void setCurrentMappings (LocalisedStrings* newTranslations);
  16189. /** Returns the currently selected set of mappings.
  16190. This is the object that was last passed to setCurrentMappings(). It may
  16191. be 0 if none has been created.
  16192. */
  16193. static LocalisedStrings* getCurrentMappings();
  16194. /** Tries to translate a string using the currently selected set of mappings.
  16195. If no mapping has been set, or if the mapping doesn't contain a translation
  16196. for the string, this will just return the original string.
  16197. See also the TRANS() macro, which uses this method to do its translation.
  16198. @see setCurrentMappings, getCurrentMappings
  16199. */
  16200. static const String translateWithCurrentMappings (const String& text);
  16201. /** Tries to translate a string using the currently selected set of mappings.
  16202. If no mapping has been set, or if the mapping doesn't contain a translation
  16203. for the string, this will just return the original string.
  16204. See also the TRANS() macro, which uses this method to do its translation.
  16205. @see setCurrentMappings, getCurrentMappings
  16206. */
  16207. static const String translateWithCurrentMappings (const char* text);
  16208. /** Attempts to look up a string and return its localised version.
  16209. If the string isn't found in the list, the original string will be returned.
  16210. */
  16211. const String translate (const String& text) const;
  16212. /** Returns the name of the language specified in the translation file.
  16213. This is specified in the file using a line starting with "language:", e.g.
  16214. @code
  16215. language: german
  16216. @endcode
  16217. */
  16218. const String getLanguageName() const { return languageName; }
  16219. /** Returns the list of suitable country codes listed in the translation file.
  16220. These is specified in the file using a line starting with "countries:", e.g.
  16221. @code
  16222. countries: fr be mc ch lu
  16223. @endcode
  16224. The country codes are supposed to be 2-character ISO complient codes.
  16225. */
  16226. const StringArray getCountryCodes() const { return countryCodes; }
  16227. /** Indicates whether to use a case-insensitive search when looking up a string.
  16228. This defaults to true.
  16229. */
  16230. void setIgnoresCase (bool shouldIgnoreCase);
  16231. private:
  16232. String languageName;
  16233. StringArray countryCodes;
  16234. StringPairArray translations;
  16235. void loadFromText (const String& fileContents);
  16236. JUCE_LEAK_DETECTOR (LocalisedStrings);
  16237. };
  16238. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  16239. /*** End of inlined file: juce_LocalisedStrings.h ***/
  16240. #endif
  16241. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  16242. #endif
  16243. #ifndef __JUCE_STRING_JUCEHEADER__
  16244. #endif
  16245. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  16246. #endif
  16247. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  16248. #endif
  16249. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  16250. #endif
  16251. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  16252. /*** Start of inlined file: juce_XmlDocument.h ***/
  16253. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  16254. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  16255. /**
  16256. Parses a text-based XML document and creates an XmlElement object from it.
  16257. The parser will parse DTDs to load external entities but won't
  16258. check the document for validity against the DTD.
  16259. e.g.
  16260. @code
  16261. XmlDocument myDocument (File ("myfile.xml"));
  16262. XmlElement* mainElement = myDocument.getDocumentElement();
  16263. if (mainElement == 0)
  16264. {
  16265. String error = myDocument.getLastParseError();
  16266. }
  16267. else
  16268. {
  16269. ..use the element
  16270. }
  16271. @endcode
  16272. Or you can use the static helper methods for quick parsing..
  16273. @code
  16274. XmlElement* xml = XmlDocument::parse (myXmlFile);
  16275. if (xml != 0 && xml->hasTagName ("foobar"))
  16276. {
  16277. ...etc
  16278. @endcode
  16279. @see XmlElement
  16280. */
  16281. class JUCE_API XmlDocument
  16282. {
  16283. public:
  16284. /** Creates an XmlDocument from the xml text.
  16285. The text doesn't actually get parsed until the getDocumentElement() method is called.
  16286. */
  16287. XmlDocument (const String& documentText);
  16288. /** Creates an XmlDocument from a file.
  16289. The text doesn't actually get parsed until the getDocumentElement() method is called.
  16290. */
  16291. XmlDocument (const File& file);
  16292. /** Destructor. */
  16293. ~XmlDocument();
  16294. /** Creates an XmlElement object to represent the main document node.
  16295. This method will do the actual parsing of the text, and if there's a
  16296. parse error, it may returns 0 (and you can find out the error using
  16297. the getLastParseError() method).
  16298. See also the parse() methods, which provide a shorthand way to quickly
  16299. parse a file or string.
  16300. @param onlyReadOuterDocumentElement if true, the parser will only read the
  16301. first section of the file, and will only
  16302. return the outer document element - this
  16303. allows quick checking of large files to
  16304. see if they contain the correct type of
  16305. tag, without having to parse the entire file
  16306. @returns a new XmlElement which the caller will need to delete, or null if
  16307. there was an error.
  16308. @see getLastParseError
  16309. */
  16310. XmlElement* getDocumentElement (bool onlyReadOuterDocumentElement = false);
  16311. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  16312. @returns the error, or an empty string if there was no error.
  16313. */
  16314. const String& getLastParseError() const throw();
  16315. /** Sets an input source object to use for parsing documents that reference external entities.
  16316. If the document has been created from a file, this probably won't be needed, but
  16317. if you're parsing some text and there might be a DTD that references external
  16318. files, you may need to create a custom input source that can retrieve the
  16319. other files it needs.
  16320. The object that is passed-in will be deleted automatically when no longer needed.
  16321. @see InputSource
  16322. */
  16323. void setInputSource (InputSource* newSource) throw();
  16324. /** Sets a flag to change the treatment of empty text elements.
  16325. If this is true (the default state), then any text elements that contain only
  16326. whitespace characters will be ingored during parsing. If you need to catch
  16327. whitespace-only text, then you should set this to false before calling the
  16328. getDocumentElement() method.
  16329. */
  16330. void setEmptyTextElementsIgnored (bool shouldBeIgnored) throw();
  16331. /** A handy static method that parses a file.
  16332. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  16333. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  16334. */
  16335. static XmlElement* parse (const File& file);
  16336. /** A handy static method that parses some XML data.
  16337. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  16338. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  16339. */
  16340. static XmlElement* parse (const String& xmlData);
  16341. private:
  16342. String originalText;
  16343. String::CharPointerType input;
  16344. bool outOfData, errorOccurred;
  16345. String lastError, dtdText;
  16346. StringArray tokenisedDTD;
  16347. bool needToLoadDTD, ignoreEmptyTextElements;
  16348. ScopedPointer <InputSource> inputSource;
  16349. void setLastError (const String& desc, bool carryOn);
  16350. void skipHeader();
  16351. void skipNextWhiteSpace();
  16352. juce_wchar readNextChar() throw();
  16353. XmlElement* readNextElement (bool alsoParseSubElements);
  16354. void readChildElements (XmlElement* parent);
  16355. int findNextTokenLength() throw();
  16356. void readQuotedString (String& result);
  16357. void readEntity (String& result);
  16358. const String getFileContents (const String& filename) const;
  16359. const String expandEntity (const String& entity);
  16360. const String expandExternalEntity (const String& entity);
  16361. const String getParameterEntity (const String& entity);
  16362. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XmlDocument);
  16363. };
  16364. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  16365. /*** End of inlined file: juce_XmlDocument.h ***/
  16366. #endif
  16367. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  16368. #endif
  16369. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  16370. #endif
  16371. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16372. /*** Start of inlined file: juce_InterProcessLock.h ***/
  16373. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16374. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16375. /**
  16376. Acts as a critical section which processes can use to block each other.
  16377. @see CriticalSection
  16378. */
  16379. class JUCE_API InterProcessLock
  16380. {
  16381. public:
  16382. /** Creates a lock object.
  16383. @param name a name that processes will use to identify this lock object
  16384. */
  16385. explicit InterProcessLock (const String& name);
  16386. /** Destructor.
  16387. This will also release the lock if it's currently held by this process.
  16388. */
  16389. ~InterProcessLock();
  16390. /** Attempts to lock the critical section.
  16391. @param timeOutMillisecs how many milliseconds to wait if the lock
  16392. is already held by another process - a value of
  16393. 0 will return immediately, negative values will wait
  16394. forever
  16395. @returns true if the lock could be gained within the timeout period, or
  16396. false if the timeout expired.
  16397. */
  16398. bool enter (int timeOutMillisecs = -1);
  16399. /** Releases the lock if it's currently held by this process.
  16400. */
  16401. void exit();
  16402. /**
  16403. Automatically locks and unlocks an InterProcessLock object.
  16404. This works like a ScopedLock, but using an InterprocessLock rather than
  16405. a CriticalSection.
  16406. @see ScopedLock
  16407. */
  16408. class ScopedLockType
  16409. {
  16410. public:
  16411. /** Creates a scoped lock.
  16412. As soon as it is created, this will lock the InterProcessLock, and
  16413. when the ScopedLockType object is deleted, the InterProcessLock will
  16414. be unlocked.
  16415. Note that since an InterprocessLock can fail due to errors, you should check
  16416. isLocked() to make sure that the lock was successful before using it.
  16417. Make sure this object is created and deleted by the same thread,
  16418. otherwise there are no guarantees what will happen! Best just to use it
  16419. as a local stack object, rather than creating one with the new() operator.
  16420. */
  16421. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  16422. /** Destructor.
  16423. The InterProcessLock will be unlocked when the destructor is called.
  16424. Make sure this object is created and deleted by the same thread,
  16425. otherwise there are no guarantees what will happen!
  16426. */
  16427. inline ~ScopedLockType() { lock_.exit(); }
  16428. /** Returns true if the InterProcessLock was successfully locked. */
  16429. bool isLocked() const throw() { return lockWasSuccessful; }
  16430. private:
  16431. InterProcessLock& lock_;
  16432. bool lockWasSuccessful;
  16433. JUCE_DECLARE_NON_COPYABLE (ScopedLockType);
  16434. };
  16435. private:
  16436. class Pimpl;
  16437. friend class ScopedPointer <Pimpl>;
  16438. ScopedPointer <Pimpl> pimpl;
  16439. CriticalSection lock;
  16440. String name;
  16441. JUCE_DECLARE_NON_COPYABLE (InterProcessLock);
  16442. };
  16443. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16444. /*** End of inlined file: juce_InterProcessLock.h ***/
  16445. #endif
  16446. #ifndef __JUCE_PROCESS_JUCEHEADER__
  16447. /*** Start of inlined file: juce_Process.h ***/
  16448. #ifndef __JUCE_PROCESS_JUCEHEADER__
  16449. #define __JUCE_PROCESS_JUCEHEADER__
  16450. /** Represents the current executable's process.
  16451. This contains methods for controlling the current application at the
  16452. process-level.
  16453. @see Thread, JUCEApplication
  16454. */
  16455. class JUCE_API Process
  16456. {
  16457. public:
  16458. enum ProcessPriority
  16459. {
  16460. LowPriority = 0,
  16461. NormalPriority = 1,
  16462. HighPriority = 2,
  16463. RealtimePriority = 3
  16464. };
  16465. /** Changes the current process's priority.
  16466. @param priority the process priority, where
  16467. 0=low, 1=normal, 2=high, 3=realtime
  16468. */
  16469. static void setPriority (const ProcessPriority priority);
  16470. /** Kills the current process immediately.
  16471. This is an emergency process terminator that kills the application
  16472. immediately - it's intended only for use only when something goes
  16473. horribly wrong.
  16474. @see JUCEApplication::quit
  16475. */
  16476. static void terminate();
  16477. /** Returns true if this application process is the one that the user is
  16478. currently using.
  16479. */
  16480. static bool isForegroundProcess();
  16481. /** Raises the current process's privilege level.
  16482. Does nothing if this isn't supported by the current OS, or if process
  16483. privilege level is fixed.
  16484. */
  16485. static void raisePrivilege();
  16486. /** Lowers the current process's privilege level.
  16487. Does nothing if this isn't supported by the current OS, or if process
  16488. privilege level is fixed.
  16489. */
  16490. static void lowerPrivilege();
  16491. /** Returns true if this process is being hosted by a debugger.
  16492. */
  16493. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  16494. private:
  16495. Process();
  16496. JUCE_DECLARE_NON_COPYABLE (Process);
  16497. };
  16498. #endif // __JUCE_PROCESS_JUCEHEADER__
  16499. /*** End of inlined file: juce_Process.h ***/
  16500. #endif
  16501. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  16502. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  16503. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  16504. #define __JUCE_READWRITELOCK_JUCEHEADER__
  16505. /*** Start of inlined file: juce_WaitableEvent.h ***/
  16506. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  16507. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  16508. /**
  16509. Allows threads to wait for events triggered by other threads.
  16510. A thread can call wait() on a WaitableObject, and this will suspend the
  16511. calling thread until another thread wakes it up by calling the signal()
  16512. method.
  16513. */
  16514. class JUCE_API WaitableEvent
  16515. {
  16516. public:
  16517. /** Creates a WaitableEvent object.
  16518. @param manualReset If this is false, the event will be reset automatically when the wait()
  16519. method is called. If manualReset is true, then once the event is signalled,
  16520. the only way to reset it will be by calling the reset() method.
  16521. */
  16522. WaitableEvent (bool manualReset = false) throw();
  16523. /** Destructor.
  16524. If other threads are waiting on this object when it gets deleted, this
  16525. can cause nasty errors, so be careful!
  16526. */
  16527. ~WaitableEvent() throw();
  16528. /** Suspends the calling thread until the event has been signalled.
  16529. This will wait until the object's signal() method is called by another thread,
  16530. or until the timeout expires.
  16531. After the event has been signalled, this method will return true and if manualReset
  16532. was set to false in the WaitableEvent's constructor, then the event will be reset.
  16533. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  16534. value will cause it to wait forever.
  16535. @returns true if the object has been signalled, false if the timeout expires first.
  16536. @see signal, reset
  16537. */
  16538. bool wait (int timeOutMilliseconds = -1) const throw();
  16539. /** Wakes up any threads that are currently waiting on this object.
  16540. If signal() is called when nothing is waiting, the next thread to call wait()
  16541. will return immediately and reset the signal.
  16542. @see wait, reset
  16543. */
  16544. void signal() const throw();
  16545. /** Resets the event to an unsignalled state.
  16546. If it's not already signalled, this does nothing.
  16547. */
  16548. void reset() const throw();
  16549. private:
  16550. void* internal;
  16551. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WaitableEvent);
  16552. };
  16553. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  16554. /*** End of inlined file: juce_WaitableEvent.h ***/
  16555. /*** Start of inlined file: juce_Thread.h ***/
  16556. #ifndef __JUCE_THREAD_JUCEHEADER__
  16557. #define __JUCE_THREAD_JUCEHEADER__
  16558. /**
  16559. Encapsulates a thread.
  16560. Subclasses derive from Thread and implement the run() method, in which they
  16561. do their business. The thread can then be started with the startThread() method
  16562. and controlled with various other methods.
  16563. This class also contains some thread-related static methods, such
  16564. as sleep(), yield(), getCurrentThreadId() etc.
  16565. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  16566. MessageManagerLock
  16567. */
  16568. class JUCE_API Thread
  16569. {
  16570. public:
  16571. /**
  16572. Creates a thread.
  16573. When first created, the thread is not running. Use the startThread()
  16574. method to start it.
  16575. */
  16576. explicit Thread (const String& threadName);
  16577. /** Destructor.
  16578. Deleting a Thread object that is running will only give the thread a
  16579. brief opportunity to stop itself cleanly, so it's recommended that you
  16580. should always call stopThread() with a decent timeout before deleting,
  16581. to avoid the thread being forcibly killed (which is a Bad Thing).
  16582. */
  16583. virtual ~Thread();
  16584. /** Must be implemented to perform the thread's actual code.
  16585. Remember that the thread must regularly check the threadShouldExit()
  16586. method whilst running, and if this returns true it should return from
  16587. the run() method as soon as possible to avoid being forcibly killed.
  16588. @see threadShouldExit, startThread
  16589. */
  16590. virtual void run() = 0;
  16591. // Thread control functions..
  16592. /** Starts the thread running.
  16593. This will start the thread's run() method.
  16594. (if it's already started, startThread() won't do anything).
  16595. @see stopThread
  16596. */
  16597. void startThread();
  16598. /** Starts the thread with a given priority.
  16599. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  16600. If the thread is already running, its priority will be changed.
  16601. @see startThread, setPriority
  16602. */
  16603. void startThread (int priority);
  16604. /** Attempts to stop the thread running.
  16605. This method will cause the threadShouldExit() method to return true
  16606. and call notify() in case the thread is currently waiting.
  16607. Hopefully the thread will then respond to this by exiting cleanly, and
  16608. the stopThread method will wait for a given time-period for this to
  16609. happen.
  16610. If the thread is stuck and fails to respond after the time-out, it gets
  16611. forcibly killed, which is a very bad thing to happen, as it could still
  16612. be holding locks, etc. which are needed by other parts of your program.
  16613. @param timeOutMilliseconds The number of milliseconds to wait for the
  16614. thread to finish before killing it by force. A negative
  16615. value in here will wait forever.
  16616. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  16617. */
  16618. void stopThread (int timeOutMilliseconds);
  16619. /** Returns true if the thread is currently active */
  16620. bool isThreadRunning() const;
  16621. /** Sets a flag to tell the thread it should stop.
  16622. Calling this means that the threadShouldExit() method will then return true.
  16623. The thread should be regularly checking this to see whether it should exit.
  16624. If your thread makes use of wait(), you might want to call notify() after calling
  16625. this method, to interrupt any waits that might be in progress, and allow it
  16626. to reach a point where it can exit.
  16627. @see threadShouldExit
  16628. @see waitForThreadToExit
  16629. */
  16630. void signalThreadShouldExit();
  16631. /** Checks whether the thread has been told to stop running.
  16632. Threads need to check this regularly, and if it returns true, they should
  16633. return from their run() method at the first possible opportunity.
  16634. @see signalThreadShouldExit
  16635. */
  16636. inline bool threadShouldExit() const { return threadShouldExit_; }
  16637. /** Waits for the thread to stop.
  16638. This will waits until isThreadRunning() is false or until a timeout expires.
  16639. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  16640. is less than zero, it will wait forever.
  16641. @returns true if the thread exits, or false if the timeout expires first.
  16642. */
  16643. bool waitForThreadToExit (int timeOutMilliseconds) const;
  16644. /** Changes the thread's priority.
  16645. May return false if for some reason the priority can't be changed.
  16646. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  16647. of 5 is normal.
  16648. */
  16649. bool setPriority (int priority);
  16650. /** Changes the priority of the caller thread.
  16651. Similar to setPriority(), but this static method acts on the caller thread.
  16652. May return false if for some reason the priority can't be changed.
  16653. @see setPriority
  16654. */
  16655. static bool setCurrentThreadPriority (int priority);
  16656. /** Sets the affinity mask for the thread.
  16657. This will only have an effect next time the thread is started - i.e. if the
  16658. thread is already running when called, it'll have no effect.
  16659. @see setCurrentThreadAffinityMask
  16660. */
  16661. void setAffinityMask (uint32 affinityMask);
  16662. /** Changes the affinity mask for the caller thread.
  16663. This will change the affinity mask for the thread that calls this static method.
  16664. @see setAffinityMask
  16665. */
  16666. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  16667. // this can be called from any thread that needs to pause..
  16668. static void JUCE_CALLTYPE sleep (int milliseconds);
  16669. /** Yields the calling thread's current time-slot. */
  16670. static void JUCE_CALLTYPE yield();
  16671. /** Makes the thread wait for a notification.
  16672. This puts the thread to sleep until either the timeout period expires, or
  16673. another thread calls the notify() method to wake it up.
  16674. A negative time-out value means that the method will wait indefinitely.
  16675. @returns true if the event has been signalled, false if the timeout expires.
  16676. */
  16677. bool wait (int timeOutMilliseconds) const;
  16678. /** Wakes up the thread.
  16679. If the thread has called the wait() method, this will wake it up.
  16680. @see wait
  16681. */
  16682. void notify() const;
  16683. /** A value type used for thread IDs.
  16684. @see getCurrentThreadId(), getThreadId()
  16685. */
  16686. typedef void* ThreadID;
  16687. /** Returns an id that identifies the caller thread.
  16688. To find the ID of a particular thread object, use getThreadId().
  16689. @returns a unique identifier that identifies the calling thread.
  16690. @see getThreadId
  16691. */
  16692. static ThreadID getCurrentThreadId();
  16693. /** Finds the thread object that is currently running.
  16694. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  16695. object associated with them, so this will return 0.
  16696. */
  16697. static Thread* getCurrentThread();
  16698. /** Returns the ID of this thread.
  16699. That means the ID of this thread object - not of the thread that's calling the method.
  16700. This can change when the thread is started and stopped, and will be invalid if the
  16701. thread's not actually running.
  16702. @see getCurrentThreadId
  16703. */
  16704. ThreadID getThreadId() const throw() { return threadId_; }
  16705. /** Returns the name of the thread.
  16706. This is the name that gets set in the constructor.
  16707. */
  16708. const String getThreadName() const { return threadName_; }
  16709. /** Returns the number of currently-running threads.
  16710. @returns the number of Thread objects known to be currently running.
  16711. @see stopAllThreads
  16712. */
  16713. static int getNumRunningThreads();
  16714. /** Tries to stop all currently-running threads.
  16715. This will attempt to stop all the threads known to be running at the moment.
  16716. */
  16717. static void stopAllThreads (int timeoutInMillisecs);
  16718. private:
  16719. const String threadName_;
  16720. void* volatile threadHandle_;
  16721. ThreadID threadId_;
  16722. CriticalSection startStopLock;
  16723. WaitableEvent startSuspensionEvent_, defaultEvent_;
  16724. int threadPriority_;
  16725. uint32 affinityMask_;
  16726. bool volatile threadShouldExit_;
  16727. #ifndef DOXYGEN
  16728. friend class MessageManager;
  16729. friend void JUCE_API juce_threadEntryPoint (void*);
  16730. #endif
  16731. void launchThread();
  16732. void closeThreadHandle();
  16733. void killThread();
  16734. void threadEntryPoint();
  16735. static void setCurrentThreadName (const String& name);
  16736. static bool setThreadPriority (void* handle, int priority);
  16737. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread);
  16738. };
  16739. #endif // __JUCE_THREAD_JUCEHEADER__
  16740. /*** End of inlined file: juce_Thread.h ***/
  16741. /**
  16742. A critical section that allows multiple simultaneous readers.
  16743. Features of this type of lock are:
  16744. - Multiple readers can hold the lock at the same time, but only one writer
  16745. can hold it at once.
  16746. - Writers trying to gain the lock will be blocked until all readers and writers
  16747. have released it
  16748. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  16749. blocked until the writer has obtained and released it
  16750. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  16751. there are no other readers
  16752. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  16753. - Recursive locking is supported.
  16754. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  16755. */
  16756. class JUCE_API ReadWriteLock
  16757. {
  16758. public:
  16759. /**
  16760. Creates a ReadWriteLock object.
  16761. */
  16762. ReadWriteLock() throw();
  16763. /** Destructor.
  16764. If the object is deleted whilst locked, any subsequent behaviour
  16765. is unpredictable.
  16766. */
  16767. ~ReadWriteLock() throw();
  16768. /** Locks this object for reading.
  16769. Multiple threads can simulaneously lock the object for reading, but if another
  16770. thread has it locked for writing, then this will block until it releases the
  16771. lock.
  16772. @see exitRead, ScopedReadLock
  16773. */
  16774. void enterRead() const throw();
  16775. /** Releases the read-lock.
  16776. If the caller thread hasn't got the lock, this can have unpredictable results.
  16777. If the enterRead() method has been called multiple times by the thread, each
  16778. call must be matched by a call to exitRead() before other threads will be allowed
  16779. to take over the lock.
  16780. @see enterRead, ScopedReadLock
  16781. */
  16782. void exitRead() const throw();
  16783. /** Locks this object for writing.
  16784. This will block until any other threads that have it locked for reading or
  16785. writing have released their lock.
  16786. @see exitWrite, ScopedWriteLock
  16787. */
  16788. void enterWrite() const throw();
  16789. /** Tries to lock this object for writing.
  16790. This is like enterWrite(), but doesn't block - it returns true if it manages
  16791. to obtain the lock.
  16792. @see enterWrite
  16793. */
  16794. bool tryEnterWrite() const throw();
  16795. /** Releases the write-lock.
  16796. If the caller thread hasn't got the lock, this can have unpredictable results.
  16797. If the enterWrite() method has been called multiple times by the thread, each
  16798. call must be matched by a call to exit() before other threads will be allowed
  16799. to take over the lock.
  16800. @see enterWrite, ScopedWriteLock
  16801. */
  16802. void exitWrite() const throw();
  16803. private:
  16804. CriticalSection accessLock;
  16805. WaitableEvent waitEvent;
  16806. mutable int numWaitingWriters, numWriters;
  16807. mutable Thread::ThreadID writerThreadId;
  16808. mutable Array <Thread::ThreadID> readerThreads;
  16809. JUCE_DECLARE_NON_COPYABLE (ReadWriteLock);
  16810. };
  16811. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  16812. /*** End of inlined file: juce_ReadWriteLock.h ***/
  16813. #endif
  16814. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  16815. #endif
  16816. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  16817. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  16818. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  16819. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  16820. /**
  16821. Automatically locks and unlocks a ReadWriteLock object.
  16822. Use one of these as a local variable to control access to a ReadWriteLock.
  16823. e.g. @code
  16824. ReadWriteLock myLock;
  16825. for (;;)
  16826. {
  16827. const ScopedReadLock myScopedLock (myLock);
  16828. // myLock is now locked
  16829. ...do some stuff...
  16830. // myLock gets unlocked here.
  16831. }
  16832. @endcode
  16833. @see ReadWriteLock, ScopedWriteLock
  16834. */
  16835. class JUCE_API ScopedReadLock
  16836. {
  16837. public:
  16838. /** Creates a ScopedReadLock.
  16839. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  16840. when the ScopedReadLock object is deleted, the ReadWriteLock will
  16841. be unlocked.
  16842. Make sure this object is created and deleted by the same thread,
  16843. otherwise there are no guarantees what will happen! Best just to use it
  16844. as a local stack object, rather than creating one with the new() operator.
  16845. */
  16846. inline explicit ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  16847. /** Destructor.
  16848. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  16849. Make sure this object is created and deleted by the same thread,
  16850. otherwise there are no guarantees what will happen!
  16851. */
  16852. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  16853. private:
  16854. const ReadWriteLock& lock_;
  16855. JUCE_DECLARE_NON_COPYABLE (ScopedReadLock);
  16856. };
  16857. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  16858. /*** End of inlined file: juce_ScopedReadLock.h ***/
  16859. #endif
  16860. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  16861. /*** Start of inlined file: juce_ScopedTryLock.h ***/
  16862. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  16863. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  16864. /**
  16865. Automatically tries to lock and unlock a CriticalSection object.
  16866. Use one of these as a local variable to control access to a CriticalSection.
  16867. e.g. @code
  16868. CriticalSection myCriticalSection;
  16869. for (;;)
  16870. {
  16871. const ScopedTryLock myScopedTryLock (myCriticalSection);
  16872. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  16873. // should test this with the isLocked() method before doing your thread-unsafe
  16874. // action..
  16875. if (myScopedTryLock.isLocked())
  16876. {
  16877. ...do some stuff...
  16878. }
  16879. else
  16880. {
  16881. ..our attempt at locking failed because another thread had already locked it..
  16882. }
  16883. // myCriticalSection gets unlocked here (if it was locked)
  16884. }
  16885. @endcode
  16886. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  16887. */
  16888. class JUCE_API ScopedTryLock
  16889. {
  16890. public:
  16891. /** Creates a ScopedTryLock.
  16892. As soon as it is created, this will try to lock the CriticalSection, and
  16893. when the ScopedTryLock object is deleted, the CriticalSection will
  16894. be unlocked if the lock was successful.
  16895. Make sure this object is created and deleted by the same thread,
  16896. otherwise there are no guarantees what will happen! Best just to use it
  16897. as a local stack object, rather than creating one with the new() operator.
  16898. */
  16899. inline explicit ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  16900. /** Destructor.
  16901. The CriticalSection will be unlocked (if locked) when the destructor is called.
  16902. Make sure this object is created and deleted by the same thread,
  16903. otherwise there are no guarantees what will happen!
  16904. */
  16905. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  16906. /** Returns true if the CriticalSection was successfully locked. */
  16907. bool isLocked() const throw() { return lockWasSuccessful; }
  16908. private:
  16909. const CriticalSection& lock_;
  16910. const bool lockWasSuccessful;
  16911. JUCE_DECLARE_NON_COPYABLE (ScopedTryLock);
  16912. };
  16913. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  16914. /*** End of inlined file: juce_ScopedTryLock.h ***/
  16915. #endif
  16916. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  16917. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  16918. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  16919. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  16920. /**
  16921. Automatically locks and unlocks a ReadWriteLock object.
  16922. Use one of these as a local variable to control access to a ReadWriteLock.
  16923. e.g. @code
  16924. ReadWriteLock myLock;
  16925. for (;;)
  16926. {
  16927. const ScopedWriteLock myScopedLock (myLock);
  16928. // myLock is now locked
  16929. ...do some stuff...
  16930. // myLock gets unlocked here.
  16931. }
  16932. @endcode
  16933. @see ReadWriteLock, ScopedReadLock
  16934. */
  16935. class JUCE_API ScopedWriteLock
  16936. {
  16937. public:
  16938. /** Creates a ScopedWriteLock.
  16939. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  16940. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  16941. be unlocked.
  16942. Make sure this object is created and deleted by the same thread,
  16943. otherwise there are no guarantees what will happen! Best just to use it
  16944. as a local stack object, rather than creating one with the new() operator.
  16945. */
  16946. inline explicit ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  16947. /** Destructor.
  16948. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  16949. Make sure this object is created and deleted by the same thread,
  16950. otherwise there are no guarantees what will happen!
  16951. */
  16952. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  16953. private:
  16954. const ReadWriteLock& lock_;
  16955. JUCE_DECLARE_NON_COPYABLE (ScopedWriteLock);
  16956. };
  16957. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  16958. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  16959. #endif
  16960. #ifndef __JUCE_THREAD_JUCEHEADER__
  16961. #endif
  16962. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  16963. /*** Start of inlined file: juce_ThreadPool.h ***/
  16964. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  16965. #define __JUCE_THREADPOOL_JUCEHEADER__
  16966. class ThreadPool;
  16967. class ThreadPoolThread;
  16968. /**
  16969. A task that is executed by a ThreadPool object.
  16970. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  16971. its threads.
  16972. The runJob() method needs to be implemented to do the task, and if the code that
  16973. does the work takes a significant time to run, it must keep checking the shouldExit()
  16974. method to see if something is trying to interrupt the job. If shouldExit() returns
  16975. true, the runJob() method must return immediately.
  16976. @see ThreadPool, Thread
  16977. */
  16978. class JUCE_API ThreadPoolJob
  16979. {
  16980. public:
  16981. /** Creates a thread pool job object.
  16982. After creating your job, add it to a thread pool with ThreadPool::addJob().
  16983. */
  16984. explicit ThreadPoolJob (const String& name);
  16985. /** Destructor. */
  16986. virtual ~ThreadPoolJob();
  16987. /** Returns the name of this job.
  16988. @see setJobName
  16989. */
  16990. const String getJobName() const;
  16991. /** Changes the job's name.
  16992. @see getJobName
  16993. */
  16994. void setJobName (const String& newName);
  16995. /** These are the values that can be returned by the runJob() method.
  16996. */
  16997. enum JobStatus
  16998. {
  16999. jobHasFinished = 0, /**< indicates that the job has finished and can be
  17000. removed from the pool. */
  17001. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  17002. should be automatically deleted by the pool. */
  17003. jobNeedsRunningAgain /**< indicates that the job would like to be called
  17004. again when a thread is free. */
  17005. };
  17006. /** Peforms the actual work that this job needs to do.
  17007. Your subclass must implement this method, in which is does its work.
  17008. If the code in this method takes a significant time to run, it must repeatedly check
  17009. the shouldExit() method to see if something is trying to interrupt the job.
  17010. If shouldExit() ever returns true, the runJob() method must return immediately.
  17011. If this method returns jobHasFinished, then the job will be removed from the pool
  17012. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  17013. pool and will get a chance to run again as soon as a thread is free.
  17014. @see shouldExit()
  17015. */
  17016. virtual JobStatus runJob() = 0;
  17017. /** Returns true if this job is currently running its runJob() method. */
  17018. bool isRunning() const { return isActive; }
  17019. /** Returns true if something is trying to interrupt this job and make it stop.
  17020. Your runJob() method must call this whenever it gets a chance, and if it ever
  17021. returns true, the runJob() method must return immediately.
  17022. @see signalJobShouldExit()
  17023. */
  17024. bool shouldExit() const { return shouldStop; }
  17025. /** Calling this will cause the shouldExit() method to return true, and the job
  17026. should (if it's been implemented correctly) stop as soon as possible.
  17027. @see shouldExit()
  17028. */
  17029. void signalJobShouldExit();
  17030. private:
  17031. friend class ThreadPool;
  17032. friend class ThreadPoolThread;
  17033. String jobName;
  17034. ThreadPool* pool;
  17035. bool shouldStop, isActive, shouldBeDeleted;
  17036. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob);
  17037. };
  17038. /**
  17039. A set of threads that will run a list of jobs.
  17040. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  17041. will be called by the next pooled thread that becomes free.
  17042. @see ThreadPoolJob, Thread
  17043. */
  17044. class JUCE_API ThreadPool
  17045. {
  17046. public:
  17047. /** Creates a thread pool.
  17048. Once you've created a pool, you can give it some things to do with the addJob()
  17049. method.
  17050. @param numberOfThreads the maximum number of actual threads to run.
  17051. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  17052. until there are some jobs to run. If false, then
  17053. all the threads will be fired-up immediately so that
  17054. they're ready for action
  17055. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  17056. inactive for this length of time, they will automatically
  17057. be stopped until more jobs come along and they're needed
  17058. */
  17059. ThreadPool (int numberOfThreads,
  17060. bool startThreadsOnlyWhenNeeded = true,
  17061. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  17062. /** Destructor.
  17063. This will attempt to remove all the jobs before deleting, but if you want to
  17064. specify a timeout, you should call removeAllJobs() explicitly before deleting
  17065. the pool.
  17066. */
  17067. ~ThreadPool();
  17068. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  17069. for some kind of operation.
  17070. @see ThreadPool::removeAllJobs
  17071. */
  17072. class JUCE_API JobSelector
  17073. {
  17074. public:
  17075. virtual ~JobSelector() {}
  17076. /** Should return true if the specified thread matches your criteria for whatever
  17077. operation that this object is being used for.
  17078. Any implementation of this method must be extremely fast and thread-safe!
  17079. */
  17080. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  17081. };
  17082. /** Adds a job to the queue.
  17083. Once a job has been added, then the next time a thread is free, it will run
  17084. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  17085. runJob() method, the pool will either remove the job from the pool or add it to
  17086. the back of the queue to be run again.
  17087. */
  17088. void addJob (ThreadPoolJob* job);
  17089. /** Tries to remove a job from the pool.
  17090. If the job isn't yet running, this will simply remove it. If it is running, it
  17091. will wait for it to finish.
  17092. If the timeout period expires before the job finishes running, then the job will be
  17093. left in the pool and this will return false. It returns true if the job is sucessfully
  17094. stopped and removed.
  17095. @param job the job to remove
  17096. @param interruptIfRunning if true, then if the job is currently busy, its
  17097. ThreadPoolJob::signalJobShouldExit() method will be called to try
  17098. to interrupt it. If false, then if the job will be allowed to run
  17099. until it stops normally (or the timeout expires)
  17100. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  17101. before giving up and returning false
  17102. */
  17103. bool removeJob (ThreadPoolJob* job,
  17104. bool interruptIfRunning,
  17105. int timeOutMilliseconds);
  17106. /** Tries to remove all jobs from the pool.
  17107. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  17108. methods called to try to interrupt them
  17109. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  17110. before giving up and returning false
  17111. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  17112. they will simply be removed from the pool. Jobs that are already running when
  17113. this method is called can choose whether they should be deleted by
  17114. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  17115. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  17116. jobs should be removed. If it is zero, all jobs are removed
  17117. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  17118. expires while waiting for one or more jobs to stop
  17119. */
  17120. bool removeAllJobs (bool interruptRunningJobs,
  17121. int timeOutMilliseconds,
  17122. bool deleteInactiveJobs = false,
  17123. JobSelector* selectedJobsToRemove = 0);
  17124. /** Returns the number of jobs currently running or queued.
  17125. */
  17126. int getNumJobs() const;
  17127. /** Returns one of the jobs in the queue.
  17128. Note that this can be a very volatile list as jobs might be continuously getting shifted
  17129. around in the list, and this method may return 0 if the index is currently out-of-range.
  17130. */
  17131. ThreadPoolJob* getJob (int index) const;
  17132. /** Returns true if the given job is currently queued or running.
  17133. @see isJobRunning()
  17134. */
  17135. bool contains (const ThreadPoolJob* job) const;
  17136. /** Returns true if the given job is currently being run by a thread.
  17137. */
  17138. bool isJobRunning (const ThreadPoolJob* job) const;
  17139. /** Waits until a job has finished running and has been removed from the pool.
  17140. This will wait until the job is no longer in the pool - i.e. until its
  17141. runJob() method returns ThreadPoolJob::jobHasFinished.
  17142. If the timeout period expires before the job finishes, this will return false;
  17143. it returns true if the job has finished successfully.
  17144. */
  17145. bool waitForJobToFinish (const ThreadPoolJob* job,
  17146. int timeOutMilliseconds) const;
  17147. /** Returns a list of the names of all the jobs currently running or queued.
  17148. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  17149. */
  17150. const StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  17151. /** Changes the priority of all the threads.
  17152. This will call Thread::setPriority() for each thread in the pool.
  17153. May return false if for some reason the priority can't be changed.
  17154. */
  17155. bool setThreadPriorities (int newPriority);
  17156. private:
  17157. const int threadStopTimeout;
  17158. int priority;
  17159. class ThreadPoolThread;
  17160. friend class OwnedArray <ThreadPoolThread>;
  17161. OwnedArray <ThreadPoolThread> threads;
  17162. Array <ThreadPoolJob*> jobs;
  17163. CriticalSection lock;
  17164. uint32 lastJobEndTime;
  17165. WaitableEvent jobFinishedSignal;
  17166. friend class ThreadPoolThread;
  17167. bool runNextJob();
  17168. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool);
  17169. };
  17170. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  17171. /*** End of inlined file: juce_ThreadPool.h ***/
  17172. #endif
  17173. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17174. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  17175. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17176. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17177. class TimeSliceThread;
  17178. /**
  17179. Used by the TimeSliceThread class.
  17180. To register your class with a TimeSliceThread, derive from this class and
  17181. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  17182. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  17183. deleting your client!
  17184. @see TimeSliceThread
  17185. */
  17186. class JUCE_API TimeSliceClient
  17187. {
  17188. public:
  17189. /** Destructor. */
  17190. virtual ~TimeSliceClient() {}
  17191. /** Called back by a TimeSliceThread.
  17192. When you register this class with it, a TimeSliceThread will repeatedly call
  17193. this method.
  17194. The implementation of this method should use its time-slice to do something that's
  17195. quick - never block for longer than absolutely necessary.
  17196. @returns Your method should return the number of milliseconds which it would like to wait before being called
  17197. again. Returning 0 will make the thread call again as soon as possible (after possibly servicing
  17198. other busy clients). If you return a value below zero, your client will be removed from the list of clients,
  17199. and won't be called again. The value you specify isn't a guaranteee, and is only used as a hint by the
  17200. thread - the actual time before the next callback may be more or less than specified.
  17201. You can force the TimeSliceThread to wake up and poll again immediately by calling its notify() method.
  17202. */
  17203. virtual int useTimeSlice() = 0;
  17204. private:
  17205. friend class TimeSliceThread;
  17206. Time nextCallTime;
  17207. };
  17208. /**
  17209. A thread that keeps a list of clients, and calls each one in turn, giving them
  17210. all a chance to run some sort of short task.
  17211. @see TimeSliceClient, Thread
  17212. */
  17213. class JUCE_API TimeSliceThread : public Thread
  17214. {
  17215. public:
  17216. /**
  17217. Creates a TimeSliceThread.
  17218. When first created, the thread is not running. Use the startThread()
  17219. method to start it.
  17220. */
  17221. explicit TimeSliceThread (const String& threadName);
  17222. /** Destructor.
  17223. Deleting a Thread object that is running will only give the thread a
  17224. brief opportunity to stop itself cleanly, so it's recommended that you
  17225. should always call stopThread() with a decent timeout before deleting,
  17226. to avoid the thread being forcibly killed (which is a Bad Thing).
  17227. */
  17228. ~TimeSliceThread();
  17229. /** Adds a client to the list.
  17230. The client's callbacks will start after the number of milliseconds specified
  17231. by millisecondsBeforeStarting (and this may happen before this method has returned).
  17232. */
  17233. void addTimeSliceClient (TimeSliceClient* client, int millisecondsBeforeStarting = 0);
  17234. /** Removes a client from the list.
  17235. This method will make sure that all callbacks to the client have completely
  17236. finished before the method returns.
  17237. */
  17238. void removeTimeSliceClient (TimeSliceClient* client);
  17239. /** Returns the number of registered clients. */
  17240. int getNumClients() const;
  17241. /** Returns one of the registered clients. */
  17242. TimeSliceClient* getClient (int index) const;
  17243. /** @internal */
  17244. void run();
  17245. private:
  17246. CriticalSection callbackLock, listLock;
  17247. Array <TimeSliceClient*> clients;
  17248. TimeSliceClient* clientBeingCalled;
  17249. TimeSliceClient* getNextClient (int index) const;
  17250. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimeSliceThread);
  17251. };
  17252. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17253. /*** End of inlined file: juce_TimeSliceThread.h ***/
  17254. #endif
  17255. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  17256. #endif
  17257. #endif
  17258. /*** End of inlined file: juce_core_includes.h ***/
  17259. // if you're compiling a command-line app, you might want to just include the core headers,
  17260. // so you can set this macro before including juce.h
  17261. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  17262. /*** Start of inlined file: juce_app_includes.h ***/
  17263. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  17264. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  17265. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  17266. /*** Start of inlined file: juce_Application.h ***/
  17267. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  17268. #define __JUCE_APPLICATION_JUCEHEADER__
  17269. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  17270. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17271. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17272. /*** Start of inlined file: juce_Component.h ***/
  17273. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  17274. #define __JUCE_COMPONENT_JUCEHEADER__
  17275. /*** Start of inlined file: juce_MouseCursor.h ***/
  17276. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  17277. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  17278. class Image;
  17279. class ComponentPeer;
  17280. class Component;
  17281. /**
  17282. Represents a mouse cursor image.
  17283. This object can either be used to represent one of the standard mouse
  17284. cursor shapes, or a custom one generated from an image.
  17285. */
  17286. class JUCE_API MouseCursor
  17287. {
  17288. public:
  17289. /** The set of available standard mouse cursors. */
  17290. enum StandardCursorType
  17291. {
  17292. NoCursor = 0, /**< An invisible cursor. */
  17293. NormalCursor, /**< The stardard arrow cursor. */
  17294. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  17295. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  17296. CrosshairCursor, /**< A pair of crosshairs. */
  17297. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  17298. that you're dragging a copy of something. */
  17299. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  17300. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  17301. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  17302. UpDownResizeCursor, /**< an arrow pointing up and down. */
  17303. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  17304. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  17305. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  17306. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  17307. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  17308. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  17309. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  17310. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  17311. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  17312. };
  17313. /** Creates the standard arrow cursor. */
  17314. MouseCursor();
  17315. /** Creates one of the standard mouse cursor */
  17316. MouseCursor (StandardCursorType type);
  17317. /** Creates a custom cursor from an image.
  17318. @param image the image to use for the cursor - if this is bigger than the
  17319. system can manage, it might get scaled down first, and might
  17320. also have to be turned to black-and-white if it can't do colour
  17321. cursors.
  17322. @param hotSpotX the x position of the cursor's hotspot within the image
  17323. @param hotSpotY the y position of the cursor's hotspot within the image
  17324. */
  17325. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  17326. /** Creates a copy of another cursor object. */
  17327. MouseCursor (const MouseCursor& other);
  17328. /** Copies this cursor from another object. */
  17329. MouseCursor& operator= (const MouseCursor& other);
  17330. /** Destructor. */
  17331. ~MouseCursor();
  17332. /** Checks whether two mouse cursors are the same.
  17333. For custom cursors, two cursors created from the same image won't be
  17334. recognised as the same, only MouseCursor objects that have been
  17335. copied from the same object.
  17336. */
  17337. bool operator== (const MouseCursor& other) const throw();
  17338. /** Checks whether two mouse cursors are the same.
  17339. For custom cursors, two cursors created from the same image won't be
  17340. recognised as the same, only MouseCursor objects that have been
  17341. copied from the same object.
  17342. */
  17343. bool operator!= (const MouseCursor& other) const throw();
  17344. /** Makes the system show its default 'busy' cursor.
  17345. This will turn the system cursor to an hourglass or spinning beachball
  17346. until the next time the mouse is moved, or hideWaitCursor() is called.
  17347. This is handy if the message loop is about to block for a couple of
  17348. seconds while busy and you want to give the user feedback about this.
  17349. @see MessageManager::setTimeBeforeShowingWaitCursor
  17350. */
  17351. static void showWaitCursor();
  17352. /** If showWaitCursor has been called, this will return the mouse to its
  17353. normal state.
  17354. This will look at what component is under the mouse, and update the
  17355. cursor to be the correct one for that component.
  17356. @see showWaitCursor
  17357. */
  17358. static void hideWaitCursor();
  17359. private:
  17360. class SharedCursorHandle;
  17361. friend class SharedCursorHandle;
  17362. SharedCursorHandle* cursorHandle;
  17363. friend class MouseInputSourceInternal;
  17364. void showInWindow (ComponentPeer* window) const;
  17365. void showInAllWindows() const;
  17366. void* getHandle() const throw();
  17367. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  17368. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  17369. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  17370. JUCE_LEAK_DETECTOR (MouseCursor);
  17371. };
  17372. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  17373. /*** End of inlined file: juce_MouseCursor.h ***/
  17374. /*** Start of inlined file: juce_MouseListener.h ***/
  17375. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  17376. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  17377. class MouseEvent;
  17378. /**
  17379. A MouseListener can be registered with a component to receive callbacks
  17380. about mouse events that happen to that component.
  17381. @see Component::addMouseListener, Component::removeMouseListener
  17382. */
  17383. class JUCE_API MouseListener
  17384. {
  17385. public:
  17386. /** Destructor. */
  17387. virtual ~MouseListener() {}
  17388. /** Called when the mouse moves inside a component.
  17389. If the mouse button isn't pressed and the mouse moves over a component,
  17390. this will be called to let the component react to this.
  17391. A component will always get a mouseEnter callback before a mouseMove.
  17392. @param e details about the position and status of the mouse event, including
  17393. the source component in which it occurred
  17394. @see mouseEnter, mouseExit, mouseDrag, contains
  17395. */
  17396. virtual void mouseMove (const MouseEvent& e);
  17397. /** Called when the mouse first enters a component.
  17398. If the mouse button isn't pressed and the mouse moves into a component,
  17399. this will be called to let the component react to this.
  17400. When the mouse button is pressed and held down while being moved in
  17401. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  17402. mouseDrag messages are sent to the component that the mouse was originally
  17403. clicked on, until the button is released.
  17404. @param e details about the position and status of the mouse event, including
  17405. the source component in which it occurred
  17406. @see mouseExit, mouseDrag, mouseMove, contains
  17407. */
  17408. virtual void mouseEnter (const MouseEvent& e);
  17409. /** Called when the mouse moves out of a component.
  17410. This will be called when the mouse moves off the edge of this
  17411. component.
  17412. If the mouse button was pressed, and it was then dragged off the
  17413. edge of the component and released, then this callback will happen
  17414. when the button is released, after the mouseUp callback.
  17415. @param e details about the position and status of the mouse event, including
  17416. the source component in which it occurred
  17417. @see mouseEnter, mouseDrag, mouseMove, contains
  17418. */
  17419. virtual void mouseExit (const MouseEvent& e);
  17420. /** Called when a mouse button is pressed.
  17421. The MouseEvent object passed in contains lots of methods for finding out
  17422. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  17423. were held down at the time.
  17424. Once a button is held down, the mouseDrag method will be called when the
  17425. mouse moves, until the button is released.
  17426. @param e details about the position and status of the mouse event, including
  17427. the source component in which it occurred
  17428. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  17429. */
  17430. virtual void mouseDown (const MouseEvent& e);
  17431. /** Called when the mouse is moved while a button is held down.
  17432. When a mouse button is pressed inside a component, that component
  17433. receives mouseDrag callbacks each time the mouse moves, even if the
  17434. mouse strays outside the component's bounds.
  17435. @param e details about the position and status of the mouse event, including
  17436. the source component in which it occurred
  17437. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  17438. */
  17439. virtual void mouseDrag (const MouseEvent& e);
  17440. /** Called when a mouse button is released.
  17441. A mouseUp callback is sent to the component in which a button was pressed
  17442. even if the mouse is actually over a different component when the
  17443. button is released.
  17444. The MouseEvent object passed in contains lots of methods for finding out
  17445. which buttons were down just before they were released.
  17446. @param e details about the position and status of the mouse event, including
  17447. the source component in which it occurred
  17448. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  17449. */
  17450. virtual void mouseUp (const MouseEvent& e);
  17451. /** Called when a mouse button has been double-clicked on a component.
  17452. The MouseEvent object passed in contains lots of methods for finding out
  17453. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  17454. were held down at the time.
  17455. @param e details about the position and status of the mouse event, including
  17456. the source component in which it occurred
  17457. @see mouseDown, mouseUp
  17458. */
  17459. virtual void mouseDoubleClick (const MouseEvent& e);
  17460. /** Called when the mouse-wheel is moved.
  17461. This callback is sent to the component that the mouse is over when the
  17462. wheel is moved.
  17463. If not overridden, the component will forward this message to its parent, so
  17464. that parent components can collect mouse-wheel messages that happen to
  17465. child components which aren't interested in them.
  17466. @param e details about the position and status of the mouse event, including
  17467. the source component in which it occurred
  17468. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  17469. value means the wheel has been pushed to the right, negative means it
  17470. was pushed to the left
  17471. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  17472. value means the wheel has been pushed upwards, negative means it
  17473. was pushed downwards
  17474. */
  17475. virtual void mouseWheelMove (const MouseEvent& e,
  17476. float wheelIncrementX,
  17477. float wheelIncrementY);
  17478. };
  17479. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  17480. /*** End of inlined file: juce_MouseListener.h ***/
  17481. /*** Start of inlined file: juce_MouseEvent.h ***/
  17482. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  17483. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  17484. class Component;
  17485. class MouseInputSource;
  17486. /*** Start of inlined file: juce_ModifierKeys.h ***/
  17487. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  17488. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  17489. /**
  17490. Represents the state of the mouse buttons and modifier keys.
  17491. This is used both by mouse events and by KeyPress objects to describe
  17492. the state of keys such as shift, control, alt, etc.
  17493. @see KeyPress, MouseEvent::mods
  17494. */
  17495. class JUCE_API ModifierKeys
  17496. {
  17497. public:
  17498. /** Creates a ModifierKeys object from a raw set of flags.
  17499. @param flags to represent the keys that are down
  17500. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  17501. rightButtonModifier, commandModifier, popupMenuClickModifier
  17502. */
  17503. ModifierKeys (int flags = 0) throw();
  17504. /** Creates a copy of another object. */
  17505. ModifierKeys (const ModifierKeys& other) throw();
  17506. /** Copies this object from another one. */
  17507. ModifierKeys& operator= (const ModifierKeys& other) throw();
  17508. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  17509. This is a platform-agnostic way of checking for the operating system's
  17510. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  17511. Windows/Linux, it's actually checking for the CTRL key.
  17512. */
  17513. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  17514. /** Checks whether the user is trying to launch a pop-up menu.
  17515. This checks for platform-specific modifiers that might indicate that the user
  17516. is following the operating system's normal method of showing a pop-up menu.
  17517. So on Windows/Linux, this method is really testing for a right-click.
  17518. On the Mac, it tests for either the CTRL key being down, or a right-click.
  17519. */
  17520. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  17521. /** Checks whether the flag is set for the left mouse-button. */
  17522. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  17523. /** Checks whether the flag is set for the right mouse-button.
  17524. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  17525. this is platform-independent (and makes your code more explanatory too).
  17526. */
  17527. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  17528. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  17529. /** Tests for any of the mouse-button flags. */
  17530. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  17531. /** Tests for any of the modifier key flags. */
  17532. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  17533. /** Checks whether the shift key's flag is set. */
  17534. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  17535. /** Checks whether the CTRL key's flag is set.
  17536. Remember that it's better to use the platform-agnostic routines to test for command-key and
  17537. popup-menu modifiers.
  17538. @see isCommandDown, isPopupMenu
  17539. */
  17540. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  17541. /** Checks whether the shift key's flag is set. */
  17542. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  17543. /** Flags that represent the different keys. */
  17544. enum Flags
  17545. {
  17546. /** Shift key flag. */
  17547. shiftModifier = 1,
  17548. /** CTRL key flag. */
  17549. ctrlModifier = 2,
  17550. /** ALT key flag. */
  17551. altModifier = 4,
  17552. /** Left mouse button flag. */
  17553. leftButtonModifier = 16,
  17554. /** Right mouse button flag. */
  17555. rightButtonModifier = 32,
  17556. /** Middle mouse button flag. */
  17557. middleButtonModifier = 64,
  17558. #if JUCE_MAC
  17559. /** Command key flag - on windows this is the same as the CTRL key flag. */
  17560. commandModifier = 8,
  17561. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  17562. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  17563. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  17564. #else
  17565. /** Command key flag - on windows this is the same as the CTRL key flag. */
  17566. commandModifier = ctrlModifier,
  17567. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  17568. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  17569. popupMenuClickModifier = rightButtonModifier,
  17570. #endif
  17571. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  17572. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  17573. /** Represents a combination of all the mouse buttons at once. */
  17574. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  17575. };
  17576. /** Returns a copy of only the mouse-button flags */
  17577. const ModifierKeys withOnlyMouseButtons() const throw() { return ModifierKeys (flags & allMouseButtonModifiers); }
  17578. /** Returns a copy of only the non-mouse flags */
  17579. const ModifierKeys withoutMouseButtons() const throw() { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  17580. bool operator== (const ModifierKeys& other) const throw() { return flags == other.flags; }
  17581. bool operator!= (const ModifierKeys& other) const throw() { return flags != other.flags; }
  17582. /** Returns the raw flags for direct testing. */
  17583. inline int getRawFlags() const throw() { return flags; }
  17584. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const throw() { return ModifierKeys (flags & ~rawFlagsToClear); }
  17585. inline const ModifierKeys withFlags (int rawFlagsToSet) const throw() { return ModifierKeys (flags | rawFlagsToSet); }
  17586. /** Tests a combination of flags and returns true if any of them are set. */
  17587. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  17588. /** Returns the total number of mouse buttons that are down. */
  17589. int getNumMouseButtonsDown() const throw();
  17590. /** Creates a ModifierKeys object to represent the last-known state of the
  17591. keyboard and mouse buttons.
  17592. @see getCurrentModifiersRealtime
  17593. */
  17594. static const ModifierKeys getCurrentModifiers() throw();
  17595. /** Creates a ModifierKeys object to represent the current state of the
  17596. keyboard and mouse buttons.
  17597. This isn't often needed and isn't recommended, but will actively check all the
  17598. mouse and key states rather than just returning their last-known state like
  17599. getCurrentModifiers() does.
  17600. This is only needed in special circumstances for up-to-date modifier information
  17601. at times when the app's event loop isn't running normally.
  17602. Another reason to avoid this method is that it's not stateless, and calling it may
  17603. update the value returned by getCurrentModifiers(), which could cause subtle changes
  17604. in the behaviour of some components.
  17605. */
  17606. static const ModifierKeys getCurrentModifiersRealtime() throw();
  17607. private:
  17608. int flags;
  17609. static ModifierKeys currentModifiers;
  17610. friend class ComponentPeer;
  17611. friend class MouseInputSource;
  17612. friend class MouseInputSourceInternal;
  17613. static void updateCurrentModifiers() throw();
  17614. };
  17615. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  17616. /*** End of inlined file: juce_ModifierKeys.h ***/
  17617. /*** Start of inlined file: juce_Point.h ***/
  17618. #ifndef __JUCE_POINT_JUCEHEADER__
  17619. #define __JUCE_POINT_JUCEHEADER__
  17620. /*** Start of inlined file: juce_AffineTransform.h ***/
  17621. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  17622. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  17623. /**
  17624. Represents a 2D affine-transformation matrix.
  17625. An affine transformation is a transformation such as a rotation, scale, shear,
  17626. resize or translation.
  17627. These are used for various 2D transformation tasks, e.g. with Path objects.
  17628. @see Path, Point, Line
  17629. */
  17630. class JUCE_API AffineTransform
  17631. {
  17632. public:
  17633. /** Creates an identity transform. */
  17634. AffineTransform() throw();
  17635. /** Creates a copy of another transform. */
  17636. AffineTransform (const AffineTransform& other) throw();
  17637. /** Creates a transform from a set of raw matrix values.
  17638. The resulting matrix is:
  17639. (mat00 mat01 mat02)
  17640. (mat10 mat11 mat12)
  17641. ( 0 0 1 )
  17642. */
  17643. AffineTransform (float mat00, float mat01, float mat02,
  17644. float mat10, float mat11, float mat12) throw();
  17645. /** Copies from another AffineTransform object */
  17646. AffineTransform& operator= (const AffineTransform& other) throw();
  17647. /** Compares two transforms. */
  17648. bool operator== (const AffineTransform& other) const throw();
  17649. /** Compares two transforms. */
  17650. bool operator!= (const AffineTransform& other) const throw();
  17651. /** A ready-to-use identity transform, which you can use to append other
  17652. transformations to.
  17653. e.g. @code
  17654. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  17655. .scaled (2.0f);
  17656. @endcode
  17657. */
  17658. static const AffineTransform identity;
  17659. /** Transforms a 2D co-ordinate using this matrix. */
  17660. template <typename ValueType>
  17661. void transformPoint (ValueType& x, ValueType& y) const throw()
  17662. {
  17663. const ValueType oldX = x;
  17664. x = static_cast <ValueType> (mat00 * oldX + mat01 * y + mat02);
  17665. y = static_cast <ValueType> (mat10 * oldX + mat11 * y + mat12);
  17666. }
  17667. /** Transforms two 2D co-ordinates using this matrix.
  17668. This is just a shortcut for calling transformPoint() on each of these pairs of
  17669. coordinates in turn. (And putting all the calculations into one function hopefully
  17670. also gives the compiler a bit more scope for pipelining it).
  17671. */
  17672. template <typename ValueType>
  17673. void transformPoints (ValueType& x1, ValueType& y1,
  17674. ValueType& x2, ValueType& y2) const throw()
  17675. {
  17676. const ValueType oldX1 = x1, oldX2 = x2;
  17677. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  17678. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  17679. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  17680. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  17681. }
  17682. /** Transforms three 2D co-ordinates using this matrix.
  17683. This is just a shortcut for calling transformPoint() on each of these pairs of
  17684. coordinates in turn. (And putting all the calculations into one function hopefully
  17685. also gives the compiler a bit more scope for pipelining it).
  17686. */
  17687. template <typename ValueType>
  17688. void transformPoints (ValueType& x1, ValueType& y1,
  17689. ValueType& x2, ValueType& y2,
  17690. ValueType& x3, ValueType& y3) const throw()
  17691. {
  17692. const ValueType oldX1 = x1, oldX2 = x2, oldX3 = x3;
  17693. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  17694. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  17695. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  17696. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  17697. x3 = static_cast <ValueType> (mat00 * oldX3 + mat01 * y3 + mat02);
  17698. y3 = static_cast <ValueType> (mat10 * oldX3 + mat11 * y3 + mat12);
  17699. }
  17700. /** Returns a new transform which is the same as this one followed by a translation. */
  17701. const AffineTransform translated (float deltaX,
  17702. float deltaY) const throw();
  17703. /** Returns a new transform which is a translation. */
  17704. static const AffineTransform translation (float deltaX,
  17705. float deltaY) throw();
  17706. /** Returns a transform which is the same as this one followed by a rotation.
  17707. The rotation is specified by a number of radians to rotate clockwise, centred around
  17708. the origin (0, 0).
  17709. */
  17710. const AffineTransform rotated (float angleInRadians) const throw();
  17711. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  17712. The rotation is specified by a number of radians to rotate clockwise, centred around
  17713. the co-ordinates passed in.
  17714. */
  17715. const AffineTransform rotated (float angleInRadians,
  17716. float pivotX,
  17717. float pivotY) const throw();
  17718. /** Returns a new transform which is a rotation about (0, 0). */
  17719. static const AffineTransform rotation (float angleInRadians) throw();
  17720. /** Returns a new transform which is a rotation about a given point. */
  17721. static const AffineTransform rotation (float angleInRadians,
  17722. float pivotX,
  17723. float pivotY) throw();
  17724. /** Returns a transform which is the same as this one followed by a re-scaling.
  17725. The scaling is centred around the origin (0, 0).
  17726. */
  17727. const AffineTransform scaled (float factorX,
  17728. float factorY) const throw();
  17729. /** Returns a transform which is the same as this one followed by a re-scaling.
  17730. The scaling is centred around the origin provided.
  17731. */
  17732. const AffineTransform scaled (float factorX, float factorY,
  17733. float pivotX, float pivotY) const throw();
  17734. /** Returns a new transform which is a re-scale about the origin. */
  17735. static const AffineTransform scale (float factorX,
  17736. float factorY) throw();
  17737. /** Returns a new transform which is a re-scale centred around the point provided. */
  17738. static const AffineTransform scale (float factorX, float factorY,
  17739. float pivotX, float pivotY) throw();
  17740. /** Returns a transform which is the same as this one followed by a shear.
  17741. The shear is centred around the origin (0, 0).
  17742. */
  17743. const AffineTransform sheared (float shearX, float shearY) const throw();
  17744. /** Returns a shear transform, centred around the origin (0, 0). */
  17745. static const AffineTransform shear (float shearX, float shearY) throw();
  17746. /** Returns a matrix which is the inverse operation of this one.
  17747. Some matrices don't have an inverse - in this case, the method will just return
  17748. an identity transform.
  17749. */
  17750. const AffineTransform inverted() const throw();
  17751. /** Returns the transform that will map three known points onto three coordinates
  17752. that are supplied.
  17753. This returns the transform that will transform (0, 0) into (x00, y00),
  17754. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  17755. */
  17756. static const AffineTransform fromTargetPoints (float x00, float y00,
  17757. float x10, float y10,
  17758. float x01, float y01) throw();
  17759. /** Returns the transform that will map three specified points onto three target points.
  17760. */
  17761. static const AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
  17762. float sourceX2, float sourceY2, float targetX2, float targetY2,
  17763. float sourceX3, float sourceY3, float targetX3, float targetY3) throw();
  17764. /** Returns the result of concatenating another transformation after this one. */
  17765. const AffineTransform followedBy (const AffineTransform& other) const throw();
  17766. /** Returns true if this transform has no effect on points. */
  17767. bool isIdentity() const throw();
  17768. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  17769. bool isSingularity() const throw();
  17770. /** Returns true if the transform only translates, and doesn't scale or rotate the
  17771. points. */
  17772. bool isOnlyTranslation() const throw();
  17773. /** If this transform is only a translation, this returns the X offset.
  17774. @see isOnlyTranslation
  17775. */
  17776. float getTranslationX() const throw() { return mat02; }
  17777. /** If this transform is only a translation, this returns the X offset.
  17778. @see isOnlyTranslation
  17779. */
  17780. float getTranslationY() const throw() { return mat12; }
  17781. /** Returns the approximate scale factor by which lengths will be transformed.
  17782. Obviously a length may be scaled by entirely different amounts depending on its
  17783. direction, so this is only appropriate as a rough guide.
  17784. */
  17785. float getScaleFactor() const throw();
  17786. /* The transform matrix is:
  17787. (mat00 mat01 mat02)
  17788. (mat10 mat11 mat12)
  17789. ( 0 0 1 )
  17790. */
  17791. float mat00, mat01, mat02;
  17792. float mat10, mat11, mat12;
  17793. private:
  17794. JUCE_LEAK_DETECTOR (AffineTransform);
  17795. };
  17796. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  17797. /*** End of inlined file: juce_AffineTransform.h ***/
  17798. /**
  17799. A pair of (x, y) co-ordinates.
  17800. The ValueType template should be a primitive type such as int, float, double,
  17801. rather than a class.
  17802. @see Line, Path, AffineTransform
  17803. */
  17804. template <typename ValueType>
  17805. class Point
  17806. {
  17807. public:
  17808. /** Creates a point with co-ordinates (0, 0). */
  17809. Point() throw() : x(), y() {}
  17810. /** Creates a copy of another point. */
  17811. Point (const Point& other) throw() : x (other.x), y (other.y) {}
  17812. /** Creates a point from an (x, y) position. */
  17813. Point (const ValueType initialX, const ValueType initialY) throw() : x (initialX), y (initialY) {}
  17814. /** Destructor. */
  17815. ~Point() throw() {}
  17816. /** Copies this point from another one. */
  17817. Point& operator= (const Point& other) throw() { x = other.x; y = other.y; return *this; }
  17818. inline bool operator== (const Point& other) const throw() { return x == other.x && y == other.y; }
  17819. inline bool operator!= (const Point& other) const throw() { return x != other.x || y != other.y; }
  17820. /** Returns true if the point is (0, 0). */
  17821. bool isOrigin() const throw() { return x == ValueType() && y == ValueType(); }
  17822. /** Returns the point's x co-ordinate. */
  17823. inline ValueType getX() const throw() { return x; }
  17824. /** Returns the point's y co-ordinate. */
  17825. inline ValueType getY() const throw() { return y; }
  17826. /** Sets the point's x co-ordinate. */
  17827. inline void setX (const ValueType newX) throw() { x = newX; }
  17828. /** Sets the point's y co-ordinate. */
  17829. inline void setY (const ValueType newY) throw() { y = newY; }
  17830. /** Returns a point which has the same Y position as this one, but a new X. */
  17831. const Point withX (const ValueType newX) const throw() { return Point (newX, y); }
  17832. /** Returns a point which has the same X position as this one, but a new Y. */
  17833. const Point withY (const ValueType newY) const throw() { return Point (x, newY); }
  17834. /** Changes the point's x and y co-ordinates. */
  17835. void setXY (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  17836. /** Adds a pair of co-ordinates to this value. */
  17837. void addXY (const ValueType xToAdd, const ValueType yToAdd) throw() { x += xToAdd; y += yToAdd; }
  17838. /** Returns a point with a given offset from this one. */
  17839. const Point translated (const ValueType xDelta, const ValueType yDelta) const throw() { return Point (x + xDelta, y + yDelta); }
  17840. /** Adds two points together. */
  17841. const Point operator+ (const Point& other) const throw() { return Point (x + other.x, y + other.y); }
  17842. /** Adds another point's co-ordinates to this one. */
  17843. Point& operator+= (const Point& other) throw() { x += other.x; y += other.y; return *this; }
  17844. /** Subtracts one points from another. */
  17845. const Point operator- (const Point& other) const throw() { return Point (x - other.x, y - other.y); }
  17846. /** Subtracts another point's co-ordinates to this one. */
  17847. Point& operator-= (const Point& other) throw() { x -= other.x; y -= other.y; return *this; }
  17848. /** Returns a point whose coordinates are multiplied by a given value. */
  17849. const Point operator* (const ValueType multiplier) const throw() { return Point (x * multiplier, y * multiplier); }
  17850. /** Multiplies the point's co-ordinates by a value. */
  17851. Point& operator*= (const ValueType multiplier) throw() { x *= multiplier; y *= multiplier; return *this; }
  17852. /** Returns a point whose coordinates are divided by a given value. */
  17853. const Point operator/ (const ValueType divisor) const throw() { return Point (x / divisor, y / divisor); }
  17854. /** Divides the point's co-ordinates by a value. */
  17855. Point& operator/= (const ValueType divisor) throw() { x /= divisor; y /= divisor; return *this; }
  17856. /** Returns the inverse of this point. */
  17857. const Point operator-() const throw() { return Point (-x, -y); }
  17858. /** Returns the straight-line distance between this point and another one. */
  17859. ValueType getDistanceFromOrigin() const throw() { return juce_hypot (x, y); }
  17860. /** Returns the straight-line distance between this point and another one. */
  17861. ValueType getDistanceFrom (const Point& other) const throw() { return juce_hypot (x - other.x, y - other.y); }
  17862. /** Returns the angle from this point to another one.
  17863. The return value is the number of radians clockwise from the 3 o'clock direction,
  17864. where this point is the centre and the other point is on the circumference.
  17865. */
  17866. ValueType getAngleToPoint (const Point& other) const throw() { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  17867. /** Taking this point to be the centre of a circle, this returns a point on its circumference.
  17868. @param radius the radius of the circle.
  17869. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  17870. */
  17871. const Point getPointOnCircumference (const float radius, const float angle) const throw() { return Point<float> (x + radius * std::sin (angle),
  17872. y - radius * std::cos (angle)); }
  17873. /** Taking this point to be the centre of an ellipse, this returns a point on its circumference.
  17874. @param radiusX the horizontal radius of the circle.
  17875. @param radiusY the vertical radius of the circle.
  17876. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  17877. */
  17878. const Point getPointOnCircumference (const float radiusX, const float radiusY, const float angle) const throw() { return Point<float> (x + radiusX * std::sin (angle),
  17879. y - radiusY * std::cos (angle)); }
  17880. /** Uses a transform to change the point's co-ordinates.
  17881. This will only compile if ValueType = float!
  17882. @see AffineTransform::transformPoint
  17883. */
  17884. void applyTransform (const AffineTransform& transform) throw() { transform.transformPoint (x, y); }
  17885. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  17886. const Point transformedBy (const AffineTransform& transform) const throw() { return Point (transform.mat00 * x + transform.mat01 * y + transform.mat02,
  17887. transform.mat10 * x + transform.mat11 * y + transform.mat12); }
  17888. /** Casts this point to a Point<int> object. */
  17889. const Point<int> toInt() const throw() { return Point<int> (static_cast <int> (x), static_cast<int> (y)); }
  17890. /** Casts this point to a Point<float> object. */
  17891. const Point<float> toFloat() const throw() { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  17892. /** Casts this point to a Point<double> object. */
  17893. const Point<double> toDouble() const throw() { return Point<double> (static_cast <double> (x), static_cast<double> (y)); }
  17894. /** Returns the point as a string in the form "x, y". */
  17895. const String toString() const { return String (x) + ", " + String (y); }
  17896. private:
  17897. ValueType x, y;
  17898. };
  17899. #endif // __JUCE_POINT_JUCEHEADER__
  17900. /*** End of inlined file: juce_Point.h ***/
  17901. /**
  17902. Contains position and status information about a mouse event.
  17903. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  17904. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  17905. */
  17906. class JUCE_API MouseEvent
  17907. {
  17908. public:
  17909. /** Creates a MouseEvent.
  17910. Normally an application will never need to use this.
  17911. @param source the source that's invoking the event
  17912. @param position the position of the mouse, relative to the component that is passed-in
  17913. @param modifiers the key modifiers at the time of the event
  17914. @param eventComponent the component that the mouse event applies to
  17915. @param originator the component that originally received the event
  17916. @param eventTime the time the event happened
  17917. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  17918. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  17919. the same as the current mouse-x position.
  17920. @param mouseDownTime the time at which the corresponding mouse-down event happened
  17921. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  17922. the same as the current mouse-event time.
  17923. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  17924. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  17925. */
  17926. MouseEvent (MouseInputSource& source,
  17927. const Point<int>& position,
  17928. const ModifierKeys& modifiers,
  17929. Component* eventComponent,
  17930. Component* originator,
  17931. const Time& eventTime,
  17932. const Point<int> mouseDownPos,
  17933. const Time& mouseDownTime,
  17934. int numberOfClicks,
  17935. bool mouseWasDragged) throw();
  17936. /** Destructor. */
  17937. ~MouseEvent() throw();
  17938. /** The x-position of the mouse when the event occurred.
  17939. This value is relative to the top-left of the component to which the
  17940. event applies (as indicated by the MouseEvent::eventComponent field).
  17941. */
  17942. const int x;
  17943. /** The y-position of the mouse when the event occurred.
  17944. This value is relative to the top-left of the component to which the
  17945. event applies (as indicated by the MouseEvent::eventComponent field).
  17946. */
  17947. const int y;
  17948. /** The key modifiers associated with the event.
  17949. This will let you find out which mouse buttons were down, as well as which
  17950. modifier keys were held down.
  17951. When used for mouse-up events, this will indicate the state of the mouse buttons
  17952. just before they were released, so that you can tell which button they let go of.
  17953. */
  17954. const ModifierKeys mods;
  17955. /** The component that this event applies to.
  17956. This is usually the component that the mouse was over at the time, but for mouse-drag
  17957. events the mouse could actually be over a different component and the events are
  17958. still sent to the component that the button was originally pressed on.
  17959. The x and y member variables are relative to this component's position.
  17960. If you use getEventRelativeTo() to retarget this object to be relative to a different
  17961. component, this pointer will be updated, but originalComponent remains unchanged.
  17962. @see originalComponent
  17963. */
  17964. Component* const eventComponent;
  17965. /** The component that the event first occurred on.
  17966. If you use getEventRelativeTo() to retarget this object to be relative to a different
  17967. component, this value remains unchanged to indicate the first component that received it.
  17968. @see eventComponent
  17969. */
  17970. Component* const originalComponent;
  17971. /** The time that this mouse-event occurred.
  17972. */
  17973. const Time eventTime;
  17974. /** The source device that generated this event.
  17975. */
  17976. MouseInputSource& source;
  17977. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  17978. The co-ordinate is relative to the component specified in MouseEvent::component.
  17979. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  17980. */
  17981. int getMouseDownX() const throw();
  17982. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  17983. The co-ordinate is relative to the component specified in MouseEvent::component.
  17984. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  17985. */
  17986. int getMouseDownY() const throw();
  17987. /** Returns the co-ordinates of the last place that a mouse was pressed.
  17988. The co-ordinates are relative to the component specified in MouseEvent::component.
  17989. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  17990. */
  17991. const Point<int> getMouseDownPosition() const throw();
  17992. /** Returns the straight-line distance between where the mouse is now and where it
  17993. was the last time the button was pressed.
  17994. This is quite handy for things like deciding whether the user has moved far enough
  17995. for it to be considered a drag operation.
  17996. @see getDistanceFromDragStartX
  17997. */
  17998. int getDistanceFromDragStart() const throw();
  17999. /** Returns the difference between the mouse's current x postion and where it was
  18000. when the button was last pressed.
  18001. @see getDistanceFromDragStart
  18002. */
  18003. int getDistanceFromDragStartX() const throw();
  18004. /** Returns the difference between the mouse's current y postion and where it was
  18005. when the button was last pressed.
  18006. @see getDistanceFromDragStart
  18007. */
  18008. int getDistanceFromDragStartY() const throw();
  18009. /** Returns the difference between the mouse's current postion and where it was
  18010. when the button was last pressed.
  18011. @see getDistanceFromDragStart
  18012. */
  18013. const Point<int> getOffsetFromDragStart() const throw();
  18014. /** Returns true if the mouse has just been clicked.
  18015. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  18016. the user has dragged the mouse more than a few pixels from the place where the
  18017. mouse-down occurred.
  18018. Once they have dragged it far enough for this method to return false, it will continue
  18019. to return false until the mouse-up, even if they move the mouse back to the same
  18020. position where they originally pressed it. This means that it's very handy for
  18021. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  18022. callback to ignore any small movements they might make while clicking.
  18023. @returns true if the mouse wasn't dragged by more than a few pixels between
  18024. the last time the button was pressed and released.
  18025. */
  18026. bool mouseWasClicked() const throw();
  18027. /** For a click event, the number of times the mouse was clicked in succession.
  18028. So for example a double-click event will return 2, a triple-click 3, etc.
  18029. */
  18030. int getNumberOfClicks() const throw() { return numberOfClicks; }
  18031. /** Returns the time that the mouse button has been held down for.
  18032. If called from a mouseDrag or mouseUp callback, this will return the
  18033. number of milliseconds since the corresponding mouseDown event occurred.
  18034. If called in other contexts, e.g. a mouseMove, then the returned value
  18035. may be 0 or an undefined value.
  18036. */
  18037. int getLengthOfMousePress() const throw();
  18038. /** The position of the mouse when the event occurred.
  18039. This position is relative to the top-left of the component to which the
  18040. event applies (as indicated by the MouseEvent::eventComponent field).
  18041. */
  18042. const Point<int> getPosition() const throw();
  18043. /** Returns the mouse x position of this event, in global screen co-ordinates.
  18044. The co-ordinates are relative to the top-left of the main monitor.
  18045. @see getScreenPosition
  18046. */
  18047. int getScreenX() const;
  18048. /** Returns the mouse y position of this event, in global screen co-ordinates.
  18049. The co-ordinates are relative to the top-left of the main monitor.
  18050. @see getScreenPosition
  18051. */
  18052. int getScreenY() const;
  18053. /** Returns the mouse position of this event, in global screen co-ordinates.
  18054. The co-ordinates are relative to the top-left of the main monitor.
  18055. @see getMouseDownScreenPosition
  18056. */
  18057. const Point<int> getScreenPosition() const;
  18058. /** Returns the x co-ordinate at which the mouse button was last pressed.
  18059. The co-ordinates are relative to the top-left of the main monitor.
  18060. @see getMouseDownScreenPosition
  18061. */
  18062. int getMouseDownScreenX() const;
  18063. /** Returns the y co-ordinate at which the mouse button was last pressed.
  18064. The co-ordinates are relative to the top-left of the main monitor.
  18065. @see getMouseDownScreenPosition
  18066. */
  18067. int getMouseDownScreenY() const;
  18068. /** Returns the co-ordinates at which the mouse button was last pressed.
  18069. The co-ordinates are relative to the top-left of the main monitor.
  18070. @see getScreenPosition
  18071. */
  18072. const Point<int> getMouseDownScreenPosition() const;
  18073. /** Creates a version of this event that is relative to a different component.
  18074. The x and y positions of the event that is returned will have been
  18075. adjusted to be relative to the new component.
  18076. */
  18077. const MouseEvent getEventRelativeTo (Component* otherComponent) const throw();
  18078. /** Creates a copy of this event with a different position.
  18079. All other members of the event object are the same, but the x and y are
  18080. replaced with these new values.
  18081. */
  18082. const MouseEvent withNewPosition (const Point<int>& newPosition) const throw();
  18083. /** Changes the application-wide setting for the double-click time limit.
  18084. This is the maximum length of time between mouse-clicks for it to be
  18085. considered a double-click. It's used by the Component class.
  18086. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  18087. */
  18088. static void setDoubleClickTimeout (int timeOutMilliseconds) throw();
  18089. /** Returns the application-wide setting for the double-click time limit.
  18090. This is the maximum length of time between mouse-clicks for it to be
  18091. considered a double-click. It's used by the Component class.
  18092. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  18093. */
  18094. static int getDoubleClickTimeout() throw();
  18095. private:
  18096. const Point<int> mouseDownPos;
  18097. const Time mouseDownTime;
  18098. const int numberOfClicks;
  18099. const bool wasMovedSinceMouseDown;
  18100. static int doubleClickTimeOutMs;
  18101. MouseEvent& operator= (const MouseEvent&);
  18102. };
  18103. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  18104. /*** End of inlined file: juce_MouseEvent.h ***/
  18105. /*** Start of inlined file: juce_ComponentListener.h ***/
  18106. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18107. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18108. class Component;
  18109. /**
  18110. Gets informed about changes to a component's hierarchy or position.
  18111. To monitor a component for changes, register a subclass of ComponentListener
  18112. with the component using Component::addComponentListener().
  18113. Be sure to deregister listeners before you delete them!
  18114. @see Component::addComponentListener, Component::removeComponentListener
  18115. */
  18116. class JUCE_API ComponentListener
  18117. {
  18118. public:
  18119. /** Destructor. */
  18120. virtual ~ComponentListener() {}
  18121. /** Called when the component's position or size changes.
  18122. @param component the component that was moved or resized
  18123. @param wasMoved true if the component's top-left corner has just moved
  18124. @param wasResized true if the component's width or height has just changed
  18125. @see Component::setBounds, Component::resized, Component::moved
  18126. */
  18127. virtual void componentMovedOrResized (Component& component,
  18128. bool wasMoved,
  18129. bool wasResized);
  18130. /** Called when the component is brought to the top of the z-order.
  18131. @param component the component that was moved
  18132. @see Component::toFront, Component::broughtToFront
  18133. */
  18134. virtual void componentBroughtToFront (Component& component);
  18135. /** Called when the component is made visible or invisible.
  18136. @param component the component that changed
  18137. @see Component::setVisible
  18138. */
  18139. virtual void componentVisibilityChanged (Component& component);
  18140. /** Called when the component has children added or removed.
  18141. @param component the component whose children were changed
  18142. @see Component::childrenChanged, Component::addChildComponent,
  18143. Component::removeChildComponent
  18144. */
  18145. virtual void componentChildrenChanged (Component& component);
  18146. /** Called to indicate that the component's parents have changed.
  18147. When a component is added or removed from its parent, all of its children
  18148. will produce this notification (recursively - so all children of its
  18149. children will also be called as well).
  18150. @param component the component that this listener is registered with
  18151. @see Component::parentHierarchyChanged
  18152. */
  18153. virtual void componentParentHierarchyChanged (Component& component);
  18154. /** Called when the component's name is changed.
  18155. @see Component::setName, Component::getName
  18156. */
  18157. virtual void componentNameChanged (Component& component);
  18158. /** Called when the component is in the process of being deleted.
  18159. This callback is made from inside the destructor, so be very, very cautious
  18160. about what you do in here.
  18161. In particular, bear in mind that it's the Component base class's destructor that calls
  18162. this - so if the object that's being deleted is a subclass of Component, then the
  18163. subclass layers of the object will already have been destructed when it gets to this
  18164. point!
  18165. */
  18166. virtual void componentBeingDeleted (Component& component);
  18167. };
  18168. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  18169. /*** End of inlined file: juce_ComponentListener.h ***/
  18170. /*** Start of inlined file: juce_KeyListener.h ***/
  18171. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  18172. #define __JUCE_KEYLISTENER_JUCEHEADER__
  18173. /*** Start of inlined file: juce_KeyPress.h ***/
  18174. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  18175. #define __JUCE_KEYPRESS_JUCEHEADER__
  18176. /**
  18177. Represents a key press, including any modifier keys that are needed.
  18178. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  18179. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  18180. */
  18181. class JUCE_API KeyPress
  18182. {
  18183. public:
  18184. /** Creates an (invalid) KeyPress.
  18185. @see isValid
  18186. */
  18187. KeyPress() throw();
  18188. /** Creates a KeyPress for a key and some modifiers.
  18189. e.g.
  18190. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  18191. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  18192. @param keyCode a code that represents the key - this value must be
  18193. one of special constants listed in this class, or an
  18194. 8-bit character code such as a letter (case is ignored),
  18195. digit or a simple key like "," or ".". Note that this
  18196. isn't the same as the textCharacter parameter, so for example
  18197. a keyCode of 'a' and a shift-key modifier should have a
  18198. textCharacter value of 'A'.
  18199. @param modifiers the modifiers to associate with the keystroke
  18200. @param textCharacter the character that would be printed if someone typed
  18201. this keypress into a text editor. This value may be
  18202. null if the keypress is a non-printing character
  18203. @see getKeyCode, isKeyCode, getModifiers
  18204. */
  18205. KeyPress (int keyCode,
  18206. const ModifierKeys& modifiers,
  18207. juce_wchar textCharacter) throw();
  18208. /** Creates a keypress with a keyCode but no modifiers or text character.
  18209. */
  18210. KeyPress (int keyCode) throw();
  18211. /** Creates a copy of another KeyPress. */
  18212. KeyPress (const KeyPress& other) throw();
  18213. /** Copies this KeyPress from another one. */
  18214. KeyPress& operator= (const KeyPress& other) throw();
  18215. /** Compares two KeyPress objects. */
  18216. bool operator== (const KeyPress& other) const throw();
  18217. /** Compares two KeyPress objects. */
  18218. bool operator!= (const KeyPress& other) const throw();
  18219. /** Returns true if this is a valid KeyPress.
  18220. A null keypress can be created by the default constructor, in case it's
  18221. needed.
  18222. */
  18223. bool isValid() const throw() { return keyCode != 0; }
  18224. /** Returns the key code itself.
  18225. This will either be one of the special constants defined in this class,
  18226. or an 8-bit character code.
  18227. */
  18228. int getKeyCode() const throw() { return keyCode; }
  18229. /** Returns the key modifiers.
  18230. @see ModifierKeys
  18231. */
  18232. const ModifierKeys getModifiers() const throw() { return mods; }
  18233. /** Returns the character that is associated with this keypress.
  18234. This is the character that you'd expect to see printed if you press this
  18235. keypress in a text editor or similar component.
  18236. */
  18237. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  18238. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  18239. the modifiers.
  18240. The values for key codes can either be one of the special constants defined in
  18241. this class, or an 8-bit character code.
  18242. @see getKeyCode
  18243. */
  18244. bool isKeyCode (int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  18245. /** Converts a textual key description to a KeyPress.
  18246. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  18247. This isn't designed to cope with any kind of input, but should be given the
  18248. strings that are created by the getTextDescription() method.
  18249. If the string can't be parsed, the object returned will be invalid.
  18250. @see getTextDescription
  18251. */
  18252. static const KeyPress createFromDescription (const String& textVersion);
  18253. /** Creates a textual description of the key combination.
  18254. e.g. "CTRL + C" or "DELETE".
  18255. To store a keypress in a file, use this method, along with createFromDescription()
  18256. to retrieve it later.
  18257. */
  18258. const String getTextDescription() const;
  18259. /** Creates a textual description of the key combination, using unicode icon symbols if possible.
  18260. On OSX, this uses the Apple symbols for command, option, shift, etc, instead of the textual
  18261. modifier key descriptions that are returned by getTextDescription()
  18262. */
  18263. const String getTextDescriptionWithIcons() const;
  18264. /** Checks whether the user is currently holding down the keys that make up this
  18265. KeyPress.
  18266. Note that this will return false if any extra modifier keys are
  18267. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  18268. then it will be false.
  18269. */
  18270. bool isCurrentlyDown() const;
  18271. /** Checks whether a particular key is held down, irrespective of modifiers.
  18272. The values for key codes can either be one of the special constants defined in
  18273. this class, or an 8-bit character code.
  18274. */
  18275. static bool isKeyCurrentlyDown (int keyCode);
  18276. // Key codes
  18277. //
  18278. // Note that the actual values of these are platform-specific and may change
  18279. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  18280. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  18281. //
  18282. static const int spaceKey; /**< key-code for the space bar */
  18283. static const int escapeKey; /**< key-code for the escape key */
  18284. static const int returnKey; /**< key-code for the return key*/
  18285. static const int tabKey; /**< key-code for the tab key*/
  18286. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  18287. static const int backspaceKey; /**< key-code for the backspace key */
  18288. static const int insertKey; /**< key-code for the insert key */
  18289. static const int upKey; /**< key-code for the cursor-up key */
  18290. static const int downKey; /**< key-code for the cursor-down key */
  18291. static const int leftKey; /**< key-code for the cursor-left key */
  18292. static const int rightKey; /**< key-code for the cursor-right key */
  18293. static const int pageUpKey; /**< key-code for the page-up key */
  18294. static const int pageDownKey; /**< key-code for the page-down key */
  18295. static const int homeKey; /**< key-code for the home key */
  18296. static const int endKey; /**< key-code for the end key */
  18297. static const int F1Key; /**< key-code for the F1 key */
  18298. static const int F2Key; /**< key-code for the F2 key */
  18299. static const int F3Key; /**< key-code for the F3 key */
  18300. static const int F4Key; /**< key-code for the F4 key */
  18301. static const int F5Key; /**< key-code for the F5 key */
  18302. static const int F6Key; /**< key-code for the F6 key */
  18303. static const int F7Key; /**< key-code for the F7 key */
  18304. static const int F8Key; /**< key-code for the F8 key */
  18305. static const int F9Key; /**< key-code for the F9 key */
  18306. static const int F10Key; /**< key-code for the F10 key */
  18307. static const int F11Key; /**< key-code for the F11 key */
  18308. static const int F12Key; /**< key-code for the F12 key */
  18309. static const int F13Key; /**< key-code for the F13 key */
  18310. static const int F14Key; /**< key-code for the F14 key */
  18311. static const int F15Key; /**< key-code for the F15 key */
  18312. static const int F16Key; /**< key-code for the F16 key */
  18313. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  18314. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  18315. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  18316. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  18317. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  18318. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  18319. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  18320. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  18321. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  18322. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  18323. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  18324. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  18325. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  18326. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  18327. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  18328. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  18329. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  18330. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  18331. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  18332. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  18333. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  18334. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  18335. private:
  18336. int keyCode;
  18337. ModifierKeys mods;
  18338. juce_wchar textCharacter;
  18339. JUCE_LEAK_DETECTOR (KeyPress);
  18340. };
  18341. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  18342. /*** End of inlined file: juce_KeyPress.h ***/
  18343. class Component;
  18344. /**
  18345. Receives callbacks when keys are pressed.
  18346. You can add a key listener to a component to be informed when that component
  18347. gets key events. See the Component::addListener method for more details.
  18348. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  18349. */
  18350. class JUCE_API KeyListener
  18351. {
  18352. public:
  18353. /** Destructor. */
  18354. virtual ~KeyListener() {}
  18355. /** Called to indicate that a key has been pressed.
  18356. If your implementation returns true, then the key event is considered to have
  18357. been consumed, and will not be passed on to any other components. If it returns
  18358. false, then the key will be passed to other components that might want to use it.
  18359. @param key the keystroke, including modifier keys
  18360. @param originatingComponent the component that received the key event
  18361. @see keyStateChanged, Component::keyPressed
  18362. */
  18363. virtual bool keyPressed (const KeyPress& key,
  18364. Component* originatingComponent) = 0;
  18365. /** Called when any key is pressed or released.
  18366. When this is called, classes that might be interested in
  18367. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  18368. check whether their key has changed.
  18369. If your implementation returns true, then the key event is considered to have
  18370. been consumed, and will not be passed on to any other components. If it returns
  18371. false, then the key will be passed to other components that might want to use it.
  18372. @param originatingComponent the component that received the key event
  18373. @param isKeyDown true if a key is being pressed, false if one is being released
  18374. @see KeyPress, Component::keyStateChanged
  18375. */
  18376. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  18377. };
  18378. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  18379. /*** End of inlined file: juce_KeyListener.h ***/
  18380. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  18381. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  18382. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  18383. class Component;
  18384. /**
  18385. Controls the order in which focus moves between components.
  18386. The default algorithm used by this class to work out the order of traversal
  18387. is as follows:
  18388. - if two components both have an explicit focus order specified, then the
  18389. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  18390. method).
  18391. - any component with an explicit focus order greater than 0 comes before ones
  18392. that don't have an order specified.
  18393. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  18394. order.
  18395. If you need traversal in a more customised way, you can create a subclass
  18396. of KeyboardFocusTraverser that uses your own algorithm, and use
  18397. Component::createFocusTraverser() to create it.
  18398. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  18399. */
  18400. class JUCE_API KeyboardFocusTraverser
  18401. {
  18402. public:
  18403. KeyboardFocusTraverser();
  18404. /** Destructor. */
  18405. virtual ~KeyboardFocusTraverser();
  18406. /** Returns the component that should be given focus after the specified one
  18407. when moving "forwards".
  18408. The default implementation will return the next component which is to the
  18409. right of or below this one.
  18410. This may return 0 if there's no suitable candidate.
  18411. */
  18412. virtual Component* getNextComponent (Component* current);
  18413. /** Returns the component that should be given focus after the specified one
  18414. when moving "backwards".
  18415. The default implementation will return the next component which is to the
  18416. left of or above this one.
  18417. This may return 0 if there's no suitable candidate.
  18418. */
  18419. virtual Component* getPreviousComponent (Component* current);
  18420. /** Returns the component that should receive focus be default within the given
  18421. parent component.
  18422. The default implementation will just return the foremost child component that
  18423. wants focus.
  18424. This may return 0 if there's no suitable candidate.
  18425. */
  18426. virtual Component* getDefaultComponent (Component* parentComponent);
  18427. };
  18428. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  18429. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  18430. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  18431. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  18432. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  18433. /*** Start of inlined file: juce_Graphics.h ***/
  18434. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  18435. #define __JUCE_GRAPHICS_JUCEHEADER__
  18436. /*** Start of inlined file: juce_Font.h ***/
  18437. #ifndef __JUCE_FONT_JUCEHEADER__
  18438. #define __JUCE_FONT_JUCEHEADER__
  18439. /*** Start of inlined file: juce_Typeface.h ***/
  18440. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  18441. #define __JUCE_TYPEFACE_JUCEHEADER__
  18442. /*** Start of inlined file: juce_Path.h ***/
  18443. #ifndef __JUCE_PATH_JUCEHEADER__
  18444. #define __JUCE_PATH_JUCEHEADER__
  18445. /*** Start of inlined file: juce_Line.h ***/
  18446. #ifndef __JUCE_LINE_JUCEHEADER__
  18447. #define __JUCE_LINE_JUCEHEADER__
  18448. /**
  18449. Represents a line.
  18450. This class contains a bunch of useful methods for various geometric
  18451. tasks.
  18452. The ValueType template parameter should be a primitive type - float or double
  18453. are what it's designed for. Integer types will work in a basic way, but some methods
  18454. that perform mathematical operations may not compile, or they may not produce
  18455. sensible results.
  18456. @see Point, Rectangle, Path, Graphics::drawLine
  18457. */
  18458. template <typename ValueType>
  18459. class Line
  18460. {
  18461. public:
  18462. /** Creates a line, using (0, 0) as its start and end points. */
  18463. Line() throw() {}
  18464. /** Creates a copy of another line. */
  18465. Line (const Line& other) throw()
  18466. : start (other.start),
  18467. end (other.end)
  18468. {
  18469. }
  18470. /** Creates a line based on the co-ordinates of its start and end points. */
  18471. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) throw()
  18472. : start (startX, startY),
  18473. end (endX, endY)
  18474. {
  18475. }
  18476. /** Creates a line from its start and end points. */
  18477. Line (const Point<ValueType>& startPoint,
  18478. const Point<ValueType>& endPoint) throw()
  18479. : start (startPoint),
  18480. end (endPoint)
  18481. {
  18482. }
  18483. /** Copies a line from another one. */
  18484. Line& operator= (const Line& other) throw()
  18485. {
  18486. start = other.start;
  18487. end = other.end;
  18488. return *this;
  18489. }
  18490. /** Destructor. */
  18491. ~Line() throw() {}
  18492. /** Returns the x co-ordinate of the line's start point. */
  18493. inline ValueType getStartX() const throw() { return start.getX(); }
  18494. /** Returns the y co-ordinate of the line's start point. */
  18495. inline ValueType getStartY() const throw() { return start.getY(); }
  18496. /** Returns the x co-ordinate of the line's end point. */
  18497. inline ValueType getEndX() const throw() { return end.getX(); }
  18498. /** Returns the y co-ordinate of the line's end point. */
  18499. inline ValueType getEndY() const throw() { return end.getY(); }
  18500. /** Returns the line's start point. */
  18501. inline const Point<ValueType>& getStart() const throw() { return start; }
  18502. /** Returns the line's end point. */
  18503. inline const Point<ValueType>& getEnd() const throw() { return end; }
  18504. /** Changes this line's start point */
  18505. void setStart (ValueType newStartX, ValueType newStartY) throw() { start.setXY (newStartX, newStartY); }
  18506. /** Changes this line's end point */
  18507. void setEnd (ValueType newEndX, ValueType newEndY) throw() { end.setXY (newEndX, newEndY); }
  18508. /** Changes this line's start point */
  18509. void setStart (const Point<ValueType>& newStart) throw() { start = newStart; }
  18510. /** Changes this line's end point */
  18511. void setEnd (const Point<ValueType>& newEnd) throw() { end = newEnd; }
  18512. /** Returns a line that is the same as this one, but with the start and end reversed, */
  18513. const Line reversed() const throw() { return Line (end, start); }
  18514. /** Applies an affine transform to the line's start and end points. */
  18515. void applyTransform (const AffineTransform& transform) throw()
  18516. {
  18517. start.applyTransform (transform);
  18518. end.applyTransform (transform);
  18519. }
  18520. /** Returns the length of the line. */
  18521. ValueType getLength() const throw() { return start.getDistanceFrom (end); }
  18522. /** Returns true if the line's start and end x co-ordinates are the same. */
  18523. bool isVertical() const throw() { return start.getX() == end.getX(); }
  18524. /** Returns true if the line's start and end y co-ordinates are the same. */
  18525. bool isHorizontal() const throw() { return start.getY() == end.getY(); }
  18526. /** Returns the line's angle.
  18527. This value is the number of radians clockwise from the 3 o'clock direction,
  18528. where the line's start point is considered to be at the centre.
  18529. */
  18530. ValueType getAngle() const throw() { return start.getAngleToPoint (end); }
  18531. /** Compares two lines. */
  18532. bool operator== (const Line& other) const throw() { return start == other.start && end == other.end; }
  18533. /** Compares two lines. */
  18534. bool operator!= (const Line& other) const throw() { return start != other.start || end != other.end; }
  18535. /** Finds the intersection between two lines.
  18536. @param line the other line
  18537. @param intersection the position of the point where the lines meet (or
  18538. where they would meet if they were infinitely long)
  18539. the intersection (if the lines intersect). If the lines
  18540. are parallel, this will just be set to the position
  18541. of one of the line's endpoints.
  18542. @returns true if the line segments intersect; false if they dont. Even if they
  18543. don't intersect, the intersection co-ordinates returned will still
  18544. be valid
  18545. */
  18546. bool intersects (const Line& line, Point<ValueType>& intersection) const throw()
  18547. {
  18548. return findIntersection (start, end, line.start, line.end, intersection);
  18549. }
  18550. /** Finds the intersection between two lines.
  18551. @param line the line to intersect with
  18552. @returns the point at which the lines intersect, even if this lies beyond the end of the lines
  18553. */
  18554. const Point<ValueType> getIntersection (const Line& line) const throw()
  18555. {
  18556. Point<ValueType> p;
  18557. findIntersection (start, end, line.start, line.end, p);
  18558. return p;
  18559. }
  18560. /** Returns the location of the point which is a given distance along this line.
  18561. @param distanceFromStart the distance to move along the line from its
  18562. start point. This value can be negative or longer
  18563. than the line itself
  18564. @see getPointAlongLineProportionally
  18565. */
  18566. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const throw()
  18567. {
  18568. return start + (end - start) * (distanceFromStart / getLength());
  18569. }
  18570. /** Returns a point which is a certain distance along and to the side of this line.
  18571. This effectively moves a given distance along the line, then another distance
  18572. perpendicularly to this, and returns the resulting position.
  18573. @param distanceFromStart the distance to move along the line from its
  18574. start point. This value can be negative or longer
  18575. than the line itself
  18576. @param perpendicularDistance how far to move sideways from the line. If you're
  18577. looking along the line from its start towards its
  18578. end, then a positive value here will move to the
  18579. right, negative value move to the left.
  18580. */
  18581. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  18582. ValueType perpendicularDistance) const throw()
  18583. {
  18584. const Point<ValueType> delta (end - start);
  18585. const double length = juce_hypot ((double) delta.getX(),
  18586. (double) delta.getY());
  18587. if (length <= 0)
  18588. return start;
  18589. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  18590. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  18591. }
  18592. /** Returns the location of the point which is a given distance along this line
  18593. proportional to the line's length.
  18594. @param proportionOfLength the distance to move along the line from its
  18595. start point, in multiples of the line's length.
  18596. So a value of 0.0 will return the line's start point
  18597. and a value of 1.0 will return its end point. (This value
  18598. can be negative or greater than 1.0).
  18599. @see getPointAlongLine
  18600. */
  18601. const Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const throw()
  18602. {
  18603. return start + (end - start) * proportionOfLength;
  18604. }
  18605. /** Returns the smallest distance between this line segment and a given point.
  18606. So if the point is close to the line, this will return the perpendicular
  18607. distance from the line; if the point is a long way beyond one of the line's
  18608. end-point's, it'll return the straight-line distance to the nearest end-point.
  18609. pointOnLine receives the position of the point that is found.
  18610. @returns the point's distance from the line
  18611. @see getPositionAlongLineOfNearestPoint
  18612. */
  18613. ValueType getDistanceFromPoint (const Point<ValueType>& targetPoint,
  18614. Point<ValueType>& pointOnLine) const throw()
  18615. {
  18616. const Point<ValueType> delta (end - start);
  18617. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  18618. if (length > 0)
  18619. {
  18620. const double prop = ((targetPoint.getX() - start.getX()) * delta.getX()
  18621. + (targetPoint.getY() - start.getY()) * delta.getY()) / length;
  18622. if (prop >= 0 && prop <= 1.0)
  18623. {
  18624. pointOnLine = start + delta * (ValueType) prop;
  18625. return targetPoint.getDistanceFrom (pointOnLine);
  18626. }
  18627. }
  18628. const float fromStart = targetPoint.getDistanceFrom (start);
  18629. const float fromEnd = targetPoint.getDistanceFrom (end);
  18630. if (fromStart < fromEnd)
  18631. {
  18632. pointOnLine = start;
  18633. return fromStart;
  18634. }
  18635. else
  18636. {
  18637. pointOnLine = end;
  18638. return fromEnd;
  18639. }
  18640. }
  18641. /** Finds the point on this line which is nearest to a given point, and
  18642. returns its position as a proportional position along the line.
  18643. @returns a value 0 to 1.0 which is the distance along this line from the
  18644. line's start to the point which is nearest to the point passed-in. To
  18645. turn this number into a position, use getPointAlongLineProportionally().
  18646. @see getDistanceFromPoint, getPointAlongLineProportionally
  18647. */
  18648. ValueType findNearestProportionalPositionTo (const Point<ValueType>& point) const throw()
  18649. {
  18650. const Point<ValueType> delta (end - start);
  18651. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  18652. return length <= 0 ? 0
  18653. : jlimit ((ValueType) 0, (ValueType) 1,
  18654. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  18655. + (point.getY() - start.getY()) * delta.getY()) / length));
  18656. }
  18657. /** Finds the point on this line which is nearest to a given point.
  18658. @see getDistanceFromPoint, findNearestProportionalPositionTo
  18659. */
  18660. const Point<ValueType> findNearestPointTo (const Point<ValueType>& point) const throw()
  18661. {
  18662. return getPointAlongLineProportionally (findNearestProportionalPositionTo (point));
  18663. }
  18664. /** Returns true if the given point lies above this line.
  18665. The return value is true if the point's y coordinate is less than the y
  18666. coordinate of this line at the given x (assuming the line extends infinitely
  18667. in both directions).
  18668. */
  18669. bool isPointAbove (const Point<ValueType>& point) const throw()
  18670. {
  18671. return start.getX() != end.getX()
  18672. && point.getY() < ((end.getY() - start.getY())
  18673. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  18674. }
  18675. /** Returns a shortened copy of this line.
  18676. This will chop off part of the start of this line by a certain amount, (leaving the
  18677. end-point the same), and return the new line.
  18678. */
  18679. const Line withShortenedStart (ValueType distanceToShortenBy) const throw()
  18680. {
  18681. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  18682. }
  18683. /** Returns a shortened copy of this line.
  18684. This will chop off part of the end of this line by a certain amount, (leaving the
  18685. start-point the same), and return the new line.
  18686. */
  18687. const Line withShortenedEnd (ValueType distanceToShortenBy) const throw()
  18688. {
  18689. const ValueType length = getLength();
  18690. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  18691. }
  18692. private:
  18693. Point<ValueType> start, end;
  18694. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  18695. const Point<ValueType>& p3, const Point<ValueType>& p4,
  18696. Point<ValueType>& intersection) throw()
  18697. {
  18698. if (p2 == p3)
  18699. {
  18700. intersection = p2;
  18701. return true;
  18702. }
  18703. const Point<ValueType> d1 (p2 - p1);
  18704. const Point<ValueType> d2 (p4 - p3);
  18705. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  18706. if (divisor == 0)
  18707. {
  18708. if (! (d1.isOrigin() || d2.isOrigin()))
  18709. {
  18710. if (d1.getY() == 0 && d2.getY() != 0)
  18711. {
  18712. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  18713. intersection = p1.withX (p3.getX() + along * d2.getX());
  18714. return along >= 0 && along <= (ValueType) 1;
  18715. }
  18716. else if (d2.getY() == 0 && d1.getY() != 0)
  18717. {
  18718. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  18719. intersection = p3.withX (p1.getX() + along * d1.getX());
  18720. return along >= 0 && along <= (ValueType) 1;
  18721. }
  18722. else if (d1.getX() == 0 && d2.getX() != 0)
  18723. {
  18724. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  18725. intersection = p1.withY (p3.getY() + along * d2.getY());
  18726. return along >= 0 && along <= (ValueType) 1;
  18727. }
  18728. else if (d2.getX() == 0 && d1.getX() != 0)
  18729. {
  18730. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  18731. intersection = p3.withY (p1.getY() + along * d1.getY());
  18732. return along >= 0 && along <= (ValueType) 1;
  18733. }
  18734. }
  18735. intersection = (p2 + p3) / (ValueType) 2;
  18736. return false;
  18737. }
  18738. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  18739. intersection = p1 + d1 * along1;
  18740. if (along1 < 0 || along1 > (ValueType) 1)
  18741. return false;
  18742. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  18743. return along2 >= 0 && along2 <= (ValueType) 1;
  18744. }
  18745. };
  18746. #endif // __JUCE_LINE_JUCEHEADER__
  18747. /*** End of inlined file: juce_Line.h ***/
  18748. /*** Start of inlined file: juce_Rectangle.h ***/
  18749. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  18750. #define __JUCE_RECTANGLE_JUCEHEADER__
  18751. class RectangleList;
  18752. /**
  18753. Manages a rectangle and allows geometric operations to be performed on it.
  18754. @see RectangleList, Path, Line, Point
  18755. */
  18756. template <typename ValueType>
  18757. class Rectangle
  18758. {
  18759. public:
  18760. /** Creates a rectangle of zero size.
  18761. The default co-ordinates will be (0, 0, 0, 0).
  18762. */
  18763. Rectangle() throw()
  18764. : x(), y(), w(), h()
  18765. {
  18766. }
  18767. /** Creates a copy of another rectangle. */
  18768. Rectangle (const Rectangle& other) throw()
  18769. : x (other.x), y (other.y),
  18770. w (other.w), h (other.h)
  18771. {
  18772. }
  18773. /** Creates a rectangle with a given position and size. */
  18774. Rectangle (const ValueType initialX, const ValueType initialY,
  18775. const ValueType width, const ValueType height) throw()
  18776. : x (initialX), y (initialY),
  18777. w (width), h (height)
  18778. {
  18779. }
  18780. /** Creates a rectangle with a given size, and a position of (0, 0). */
  18781. Rectangle (const ValueType width, const ValueType height) throw()
  18782. : x(), y(), w (width), h (height)
  18783. {
  18784. }
  18785. /** Creates a Rectangle from the positions of two opposite corners. */
  18786. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) throw()
  18787. : x (jmin (corner1.getX(), corner2.getX())),
  18788. y (jmin (corner1.getY(), corner2.getY())),
  18789. w (corner1.getX() - corner2.getX()),
  18790. h (corner1.getY() - corner2.getY())
  18791. {
  18792. if (w < ValueType()) w = -w;
  18793. if (h < ValueType()) h = -h;
  18794. }
  18795. /** Creates a Rectangle from a set of left, right, top, bottom coordinates.
  18796. The right and bottom values must be larger than the left and top ones, or the resulting
  18797. rectangle will have a negative size.
  18798. */
  18799. static const Rectangle leftTopRightBottom (const ValueType left, const ValueType top,
  18800. const ValueType right, const ValueType bottom) throw()
  18801. {
  18802. return Rectangle (left, top, right - left, bottom - top);
  18803. }
  18804. Rectangle& operator= (const Rectangle& other) throw()
  18805. {
  18806. x = other.x; y = other.y;
  18807. w = other.w; h = other.h;
  18808. return *this;
  18809. }
  18810. /** Destructor. */
  18811. ~Rectangle() throw() {}
  18812. /** Returns true if the rectangle's width and height are both zero or less */
  18813. bool isEmpty() const throw() { return w <= ValueType() || h <= ValueType(); }
  18814. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  18815. inline ValueType getX() const throw() { return x; }
  18816. /** Returns the y co-ordinate of the rectangle's top edge. */
  18817. inline ValueType getY() const throw() { return y; }
  18818. /** Returns the width of the rectangle. */
  18819. inline ValueType getWidth() const throw() { return w; }
  18820. /** Returns the height of the rectangle. */
  18821. inline ValueType getHeight() const throw() { return h; }
  18822. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  18823. inline ValueType getRight() const throw() { return x + w; }
  18824. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  18825. inline ValueType getBottom() const throw() { return y + h; }
  18826. /** Returns the x co-ordinate of the rectangle's centre. */
  18827. ValueType getCentreX() const throw() { return x + w / (ValueType) 2; }
  18828. /** Returns the y co-ordinate of the rectangle's centre. */
  18829. ValueType getCentreY() const throw() { return y + h / (ValueType) 2; }
  18830. /** Returns the centre point of the rectangle. */
  18831. const Point<ValueType> getCentre() const throw() { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  18832. /** Returns the aspect ratio of the rectangle's width / height.
  18833. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  18834. it returns height / width. */
  18835. ValueType getAspectRatio (const bool widthOverHeight = true) const throw() { return widthOverHeight ? w / h : h / w; }
  18836. /** Returns the rectangle's top-left position as a Point. */
  18837. const Point<ValueType> getPosition() const throw() { return Point<ValueType> (x, y); }
  18838. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  18839. void setPosition (const Point<ValueType>& newPos) throw() { x = newPos.getX(); y = newPos.getY(); }
  18840. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  18841. void setPosition (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  18842. /** Returns a rectangle with the same size as this one, but a new position. */
  18843. const Rectangle withPosition (const ValueType newX, const ValueType newY) const throw() { return Rectangle (newX, newY, w, h); }
  18844. /** Returns a rectangle with the same size as this one, but a new position. */
  18845. const Rectangle withPosition (const Point<ValueType>& newPos) const throw() { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  18846. /** Returns the rectangle's top-left position as a Point. */
  18847. const Point<ValueType> getTopLeft() const throw() { return getPosition(); }
  18848. /** Returns the rectangle's top-right position as a Point. */
  18849. const Point<ValueType> getTopRight() const throw() { return Point<ValueType> (x + w, y); }
  18850. /** Returns the rectangle's bottom-left position as a Point. */
  18851. const Point<ValueType> getBottomLeft() const throw() { return Point<ValueType> (x, y + h); }
  18852. /** Returns the rectangle's bottom-right position as a Point. */
  18853. const Point<ValueType> getBottomRight() const throw() { return Point<ValueType> (x + w, y + h); }
  18854. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  18855. void setSize (const ValueType newWidth, const ValueType newHeight) throw() { w = newWidth; h = newHeight; }
  18856. /** Returns a rectangle with the same position as this one, but a new size. */
  18857. const Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const throw() { return Rectangle (x, y, newWidth, newHeight); }
  18858. /** Changes all the rectangle's co-ordinates. */
  18859. void setBounds (const ValueType newX, const ValueType newY,
  18860. const ValueType newWidth, const ValueType newHeight) throw()
  18861. {
  18862. x = newX; y = newY; w = newWidth; h = newHeight;
  18863. }
  18864. /** Changes the rectangle's X coordinate */
  18865. void setX (const ValueType newX) throw() { x = newX; }
  18866. /** Changes the rectangle's Y coordinate */
  18867. void setY (const ValueType newY) throw() { y = newY; }
  18868. /** Changes the rectangle's width */
  18869. void setWidth (const ValueType newWidth) throw() { w = newWidth; }
  18870. /** Changes the rectangle's height */
  18871. void setHeight (const ValueType newHeight) throw() { h = newHeight; }
  18872. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  18873. const Rectangle withX (const ValueType newX) const throw() { return Rectangle (newX, y, w, h); }
  18874. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  18875. const Rectangle withY (const ValueType newY) const throw() { return Rectangle (x, newY, w, h); }
  18876. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  18877. const Rectangle withWidth (const ValueType newWidth) const throw() { return Rectangle (x, y, newWidth, h); }
  18878. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  18879. const Rectangle withHeight (const ValueType newHeight) const throw() { return Rectangle (x, y, w, newHeight); }
  18880. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  18881. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  18882. @see withLeft
  18883. */
  18884. void setLeft (const ValueType newLeft) throw()
  18885. {
  18886. w = jmax (ValueType(), x + w - newLeft);
  18887. x = newLeft;
  18888. }
  18889. /** Returns a new rectangle with a different x position, but the same right-hand edge as this one.
  18890. If the new x is beyond the right of the current right-hand edge, the width will be set to zero.
  18891. @see setLeft
  18892. */
  18893. const Rectangle withLeft (const ValueType newLeft) const throw() { return Rectangle (newLeft, y, jmax (ValueType(), x + w - newLeft), h); }
  18894. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  18895. If the y is moved to be below the current bottom edge, the height will be set to zero.
  18896. @see withTop
  18897. */
  18898. void setTop (const ValueType newTop) throw()
  18899. {
  18900. h = jmax (ValueType(), y + h - newTop);
  18901. y = newTop;
  18902. }
  18903. /** Returns a new rectangle with a different y position, but the same bottom edge as this one.
  18904. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  18905. @see setTop
  18906. */
  18907. const Rectangle withTop (const ValueType newTop) const throw() { return Rectangle (x, newTop, w, jmax (ValueType(), y + h - newTop)); }
  18908. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  18909. If the new right is below the current X value, the X will be pushed down to match it.
  18910. @see getRight, withRight
  18911. */
  18912. void setRight (const ValueType newRight) throw()
  18913. {
  18914. x = jmin (x, newRight);
  18915. w = newRight - x;
  18916. }
  18917. /** Returns a new rectangle with a different right-hand edge position, but the same left-hand edge as this one.
  18918. If the new right edge is below the current left-hand edge, the width will be set to zero.
  18919. @see setRight
  18920. */
  18921. const Rectangle withRight (const ValueType newRight) const throw() { return Rectangle (jmin (x, newRight), y, jmax (ValueType(), newRight - x), h); }
  18922. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  18923. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  18924. @see getBottom, withBottom
  18925. */
  18926. void setBottom (const ValueType newBottom) throw()
  18927. {
  18928. y = jmin (y, newBottom);
  18929. h = newBottom - y;
  18930. }
  18931. /** Returns a new rectangle with a different bottom edge position, but the same top edge as this one.
  18932. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  18933. @see setBottom
  18934. */
  18935. const Rectangle withBottom (const ValueType newBottom) const throw() { return Rectangle (x, jmin (y, newBottom), w, jmax (ValueType(), newBottom - y)); }
  18936. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  18937. void translate (const ValueType deltaX,
  18938. const ValueType deltaY) throw()
  18939. {
  18940. x += deltaX;
  18941. y += deltaY;
  18942. }
  18943. /** Returns a rectangle which is the same as this one moved by a given amount. */
  18944. const Rectangle translated (const ValueType deltaX,
  18945. const ValueType deltaY) const throw()
  18946. {
  18947. return Rectangle (x + deltaX, y + deltaY, w, h);
  18948. }
  18949. /** Returns a rectangle which is the same as this one moved by a given amount. */
  18950. const Rectangle operator+ (const Point<ValueType>& deltaPosition) const throw()
  18951. {
  18952. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  18953. }
  18954. /** Moves this rectangle by a given amount. */
  18955. Rectangle& operator+= (const Point<ValueType>& deltaPosition) throw()
  18956. {
  18957. x += deltaPosition.getX(); y += deltaPosition.getY();
  18958. return *this;
  18959. }
  18960. /** Returns a rectangle which is the same as this one moved by a given amount. */
  18961. const Rectangle operator- (const Point<ValueType>& deltaPosition) const throw()
  18962. {
  18963. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  18964. }
  18965. /** Moves this rectangle by a given amount. */
  18966. Rectangle& operator-= (const Point<ValueType>& deltaPosition) throw()
  18967. {
  18968. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  18969. return *this;
  18970. }
  18971. /** Expands the rectangle by a given amount.
  18972. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  18973. @see expanded, reduce, reduced
  18974. */
  18975. void expand (const ValueType deltaX,
  18976. const ValueType deltaY) throw()
  18977. {
  18978. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  18979. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  18980. setBounds (x - deltaX, y - deltaY, nw, nh);
  18981. }
  18982. /** Returns a rectangle that is larger than this one by a given amount.
  18983. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  18984. @see expand, reduce, reduced
  18985. */
  18986. const Rectangle expanded (const ValueType deltaX,
  18987. const ValueType deltaY) const throw()
  18988. {
  18989. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  18990. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  18991. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  18992. }
  18993. /** Shrinks the rectangle by a given amount.
  18994. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  18995. @see reduced, expand, expanded
  18996. */
  18997. void reduce (const ValueType deltaX,
  18998. const ValueType deltaY) throw()
  18999. {
  19000. expand (-deltaX, -deltaY);
  19001. }
  19002. /** Returns a rectangle that is smaller than this one by a given amount.
  19003. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  19004. @see reduce, expand, expanded
  19005. */
  19006. const Rectangle reduced (const ValueType deltaX,
  19007. const ValueType deltaY) const throw()
  19008. {
  19009. return expanded (-deltaX, -deltaY);
  19010. }
  19011. /** Removes a strip from the top of this rectangle, reducing this rectangle
  19012. by the specified amount and returning the section that was removed.
  19013. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19014. return (100, 100, 300, 50) and leave this rectangle as (100, 150, 300, 250).
  19015. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  19016. that value.
  19017. */
  19018. const Rectangle removeFromTop (const ValueType amountToRemove) throw()
  19019. {
  19020. const Rectangle r (x, y, w, jmin (amountToRemove, h));
  19021. y += r.h; h -= r.h;
  19022. return r;
  19023. }
  19024. /** Removes a strip from the left-hand edge of this rectangle, reducing this rectangle
  19025. by the specified amount and returning the section that was removed.
  19026. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19027. return (100, 100, 50, 300) and leave this rectangle as (150, 100, 250, 300).
  19028. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19029. that value.
  19030. */
  19031. const Rectangle removeFromLeft (const ValueType amountToRemove) throw()
  19032. {
  19033. const Rectangle r (x, y, jmin (amountToRemove, w), h);
  19034. x += r.w; w -= r.w;
  19035. return r;
  19036. }
  19037. /** Removes a strip from the right-hand edge of this rectangle, reducing this rectangle
  19038. by the specified amount and returning the section that was removed.
  19039. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19040. return (250, 100, 50, 300) and leave this rectangle as (100, 100, 250, 300).
  19041. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  19042. that value.
  19043. */
  19044. const Rectangle removeFromRight (ValueType amountToRemove) throw()
  19045. {
  19046. amountToRemove = jmin (amountToRemove, w);
  19047. const Rectangle r (x + w - amountToRemove, y, amountToRemove, h);
  19048. w -= amountToRemove;
  19049. return r;
  19050. }
  19051. /** Removes a strip from the bottom of this rectangle, reducing this rectangle
  19052. by the specified amount and returning the section that was removed.
  19053. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  19054. return (100, 250, 300, 50) and leave this rectangle as (100, 100, 300, 250).
  19055. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  19056. that value.
  19057. */
  19058. const Rectangle removeFromBottom (ValueType amountToRemove) throw()
  19059. {
  19060. amountToRemove = jmin (amountToRemove, h);
  19061. const Rectangle r (x, y + h - amountToRemove, w, amountToRemove);
  19062. h -= amountToRemove;
  19063. return r;
  19064. }
  19065. /** Returns true if the two rectangles are identical. */
  19066. bool operator== (const Rectangle& other) const throw()
  19067. {
  19068. return x == other.x && y == other.y
  19069. && w == other.w && h == other.h;
  19070. }
  19071. /** Returns true if the two rectangles are not identical. */
  19072. bool operator!= (const Rectangle& other) const throw()
  19073. {
  19074. return x != other.x || y != other.y
  19075. || w != other.w || h != other.h;
  19076. }
  19077. /** Returns true if this co-ordinate is inside the rectangle. */
  19078. bool contains (const ValueType xCoord, const ValueType yCoord) const throw()
  19079. {
  19080. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  19081. }
  19082. /** Returns true if this co-ordinate is inside the rectangle. */
  19083. bool contains (const Point<ValueType>& point) const throw()
  19084. {
  19085. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  19086. }
  19087. /** Returns true if this other rectangle is completely inside this one. */
  19088. bool contains (const Rectangle& other) const throw()
  19089. {
  19090. return x <= other.x && y <= other.y
  19091. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  19092. }
  19093. /** Returns the nearest point to the specified point that lies within this rectangle. */
  19094. const Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const throw()
  19095. {
  19096. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  19097. jlimit (y, y + h, point.getY()));
  19098. }
  19099. /** Returns true if any part of another rectangle overlaps this one. */
  19100. bool intersects (const Rectangle& other) const throw()
  19101. {
  19102. return x + w > other.x
  19103. && y + h > other.y
  19104. && x < other.x + other.w
  19105. && y < other.y + other.h
  19106. && w > ValueType() && h > ValueType();
  19107. }
  19108. /** Returns the region that is the overlap between this and another rectangle.
  19109. If the two rectangles don't overlap, the rectangle returned will be empty.
  19110. */
  19111. const Rectangle getIntersection (const Rectangle& other) const throw()
  19112. {
  19113. const ValueType nx = jmax (x, other.x);
  19114. const ValueType ny = jmax (y, other.y);
  19115. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  19116. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  19117. if (nw >= ValueType() && nh >= ValueType())
  19118. return Rectangle (nx, ny, nw, nh);
  19119. return Rectangle();
  19120. }
  19121. /** Clips a rectangle so that it lies only within this one.
  19122. This is a non-static version of intersectRectangles().
  19123. Returns false if the two regions didn't overlap.
  19124. */
  19125. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const throw()
  19126. {
  19127. const int maxX = jmax (otherX, x);
  19128. otherW = jmin (otherX + otherW, x + w) - maxX;
  19129. if (otherW > ValueType())
  19130. {
  19131. const int maxY = jmax (otherY, y);
  19132. otherH = jmin (otherY + otherH, y + h) - maxY;
  19133. if (otherH > ValueType())
  19134. {
  19135. otherX = maxX; otherY = maxY;
  19136. return true;
  19137. }
  19138. }
  19139. return false;
  19140. }
  19141. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  19142. If either this or the other rectangle are empty, they will not be counted as
  19143. part of the resulting region.
  19144. */
  19145. const Rectangle getUnion (const Rectangle& other) const throw()
  19146. {
  19147. if (other.isEmpty()) return *this;
  19148. if (isEmpty()) return other;
  19149. const ValueType newX = jmin (x, other.x);
  19150. const ValueType newY = jmin (y, other.y);
  19151. return Rectangle (newX, newY,
  19152. jmax (x + w, other.x + other.w) - newX,
  19153. jmax (y + h, other.y + other.h) - newY);
  19154. }
  19155. /** If this rectangle merged with another one results in a simple rectangle, this
  19156. will set this rectangle to the result, and return true.
  19157. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  19158. or if they form a complex region.
  19159. */
  19160. bool enlargeIfAdjacent (const Rectangle& other) throw()
  19161. {
  19162. if (x == other.x && getRight() == other.getRight()
  19163. && (other.getBottom() >= y && other.y <= getBottom()))
  19164. {
  19165. const ValueType newY = jmin (y, other.y);
  19166. h = jmax (getBottom(), other.getBottom()) - newY;
  19167. y = newY;
  19168. return true;
  19169. }
  19170. else if (y == other.y && getBottom() == other.getBottom()
  19171. && (other.getRight() >= x && other.x <= getRight()))
  19172. {
  19173. const ValueType newX = jmin (x, other.x);
  19174. w = jmax (getRight(), other.getRight()) - newX;
  19175. x = newX;
  19176. return true;
  19177. }
  19178. return false;
  19179. }
  19180. /** If after removing another rectangle from this one the result is a simple rectangle,
  19181. this will set this object's bounds to be the result, and return true.
  19182. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  19183. or if removing the other one would form a complex region.
  19184. */
  19185. bool reduceIfPartlyContainedIn (const Rectangle& other) throw()
  19186. {
  19187. int inside = 0;
  19188. const int otherR = other.getRight();
  19189. if (x >= other.x && x < otherR) inside = 1;
  19190. const int otherB = other.getBottom();
  19191. if (y >= other.y && y < otherB) inside |= 2;
  19192. const int r = x + w;
  19193. if (r >= other.x && r < otherR) inside |= 4;
  19194. const int b = y + h;
  19195. if (b >= other.y && b < otherB) inside |= 8;
  19196. switch (inside)
  19197. {
  19198. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  19199. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  19200. case 2 + 4 + 8: w = other.x - x; return true;
  19201. case 1 + 4 + 8: h = other.y - y; return true;
  19202. }
  19203. return false;
  19204. }
  19205. /** Returns the smallest rectangle that can contain the shape created by applying
  19206. a transform to this rectangle.
  19207. This should only be used on floating point rectangles.
  19208. */
  19209. const Rectangle transformed (const AffineTransform& transform) const throw()
  19210. {
  19211. float x1 = x, y1 = y;
  19212. float x2 = x + w, y2 = y;
  19213. float x3 = x, y3 = y + h;
  19214. float x4 = x2, y4 = y3;
  19215. transform.transformPoints (x1, y1, x2, y2);
  19216. transform.transformPoints (x3, y3, x4, y4);
  19217. const float rx = jmin (x1, x2, x3, x4);
  19218. const float ry = jmin (y1, y2, y3, y4);
  19219. return Rectangle (rx, ry,
  19220. jmax (x1, x2, x3, x4) - rx,
  19221. jmax (y1, y2, y3, y4) - ry);
  19222. }
  19223. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  19224. This is only relevent for floating-point rectangles, of course.
  19225. @see toFloat()
  19226. */
  19227. const Rectangle<int> getSmallestIntegerContainer() const throw()
  19228. {
  19229. const int x1 = (int) std::floor (static_cast<float> (x));
  19230. const int y1 = (int) std::floor (static_cast<float> (y));
  19231. const int x2 = (int) std::ceil (static_cast<float> (x + w));
  19232. const int y2 = (int) std::ceil (static_cast<float> (y + h));
  19233. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  19234. }
  19235. /** Returns the smallest Rectangle that can contain a set of points. */
  19236. static const Rectangle findAreaContainingPoints (const Point<ValueType>* const points, const int numPoints) throw()
  19237. {
  19238. if (numPoints == 0)
  19239. return Rectangle();
  19240. ValueType minX (points[0].getX());
  19241. ValueType maxX (minX);
  19242. ValueType minY (points[0].getY());
  19243. ValueType maxY (minY);
  19244. for (int i = 1; i < numPoints; ++i)
  19245. {
  19246. minX = jmin (minX, points[i].getX());
  19247. maxX = jmax (maxX, points[i].getX());
  19248. minY = jmin (minY, points[i].getY());
  19249. maxY = jmax (maxY, points[i].getY());
  19250. }
  19251. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  19252. }
  19253. /** Casts this rectangle to a Rectangle<float>.
  19254. Obviously this is mainly useful for rectangles that use integer types.
  19255. @see getSmallestIntegerContainer
  19256. */
  19257. const Rectangle<float> toFloat() const throw()
  19258. {
  19259. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  19260. static_cast<float> (w), static_cast<float> (h));
  19261. }
  19262. /** Static utility to intersect two sets of rectangular co-ordinates.
  19263. Returns false if the two regions didn't overlap.
  19264. @see intersectRectangle
  19265. */
  19266. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  19267. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) throw()
  19268. {
  19269. const ValueType x = jmax (x1, x2);
  19270. w1 = jmin (x1 + w1, x2 + w2) - x;
  19271. if (w1 > ValueType())
  19272. {
  19273. const ValueType y = jmax (y1, y2);
  19274. h1 = jmin (y1 + h1, y2 + h2) - y;
  19275. if (h1 > ValueType())
  19276. {
  19277. x1 = x; y1 = y;
  19278. return true;
  19279. }
  19280. }
  19281. return false;
  19282. }
  19283. /** Creates a string describing this rectangle.
  19284. The string will be of the form "x y width height", e.g. "100 100 400 200".
  19285. Coupled with the fromString() method, this is very handy for things like
  19286. storing rectangles (particularly component positions) in XML attributes.
  19287. @see fromString
  19288. */
  19289. const String toString() const
  19290. {
  19291. String s;
  19292. s.preallocateBytes (32);
  19293. s << x << ' ' << y << ' ' << w << ' ' << h;
  19294. return s;
  19295. }
  19296. /** Parses a string containing a rectangle's details.
  19297. The string should contain 4 integer tokens, in the form "x y width height". They
  19298. can be comma or whitespace separated.
  19299. This method is intended to go with the toString() method, to form an easy way
  19300. of saving/loading rectangles as strings.
  19301. @see toString
  19302. */
  19303. static const Rectangle fromString (const String& stringVersion)
  19304. {
  19305. StringArray toks;
  19306. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  19307. return Rectangle (toks[0].trim().getIntValue(),
  19308. toks[1].trim().getIntValue(),
  19309. toks[2].trim().getIntValue(),
  19310. toks[3].trim().getIntValue());
  19311. }
  19312. private:
  19313. friend class RectangleList;
  19314. ValueType x, y, w, h;
  19315. };
  19316. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  19317. /*** End of inlined file: juce_Rectangle.h ***/
  19318. /*** Start of inlined file: juce_Justification.h ***/
  19319. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  19320. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  19321. /**
  19322. Represents a type of justification to be used when positioning graphical items.
  19323. e.g. it indicates whether something should be placed top-left, top-right,
  19324. centred, etc.
  19325. It is used in various places wherever this kind of information is needed.
  19326. */
  19327. class JUCE_API Justification
  19328. {
  19329. public:
  19330. /** Creates a Justification object using a combination of flags. */
  19331. inline Justification (int flags_) throw() : flags (flags_) {}
  19332. /** Creates a copy of another Justification object. */
  19333. Justification (const Justification& other) throw();
  19334. /** Copies another Justification object. */
  19335. Justification& operator= (const Justification& other) throw();
  19336. bool operator== (const Justification& other) const throw() { return flags == other.flags; }
  19337. bool operator!= (const Justification& other) const throw() { return flags != other.flags; }
  19338. /** Returns the raw flags that are set for this Justification object. */
  19339. inline int getFlags() const throw() { return flags; }
  19340. /** Tests a set of flags for this object.
  19341. @returns true if any of the flags passed in are set on this object.
  19342. */
  19343. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  19344. /** Returns just the flags from this object that deal with vertical layout. */
  19345. int getOnlyVerticalFlags() const throw();
  19346. /** Returns just the flags from this object that deal with horizontal layout. */
  19347. int getOnlyHorizontalFlags() const throw();
  19348. /** Adjusts the position of a rectangle to fit it into a space.
  19349. The (x, y) position of the rectangle will be updated to position it inside the
  19350. given space according to the justification flags.
  19351. */
  19352. template <typename ValueType>
  19353. void applyToRectangle (ValueType& x, ValueType& y, ValueType w, ValueType h,
  19354. ValueType spaceX, ValueType spaceY, ValueType spaceW, ValueType spaceH) const throw()
  19355. {
  19356. x = spaceX;
  19357. if ((flags & horizontallyCentred) != 0) x += (spaceW - w) / (ValueType) 2;
  19358. else if ((flags & right) != 0) x += spaceW - w;
  19359. y = spaceY;
  19360. if ((flags & verticallyCentred) != 0) y += (spaceH - h) / (ValueType) 2;
  19361. else if ((flags & bottom) != 0) y += spaceH - h;
  19362. }
  19363. /** Returns the new position of a rectangle that has been justified to fit within a given space.
  19364. */
  19365. template <typename ValueType>
  19366. const Rectangle<ValueType> appliedToRectangle (const Rectangle<ValueType>& areaToAdjust,
  19367. const Rectangle<ValueType>& targetSpace) const throw()
  19368. {
  19369. ValueType x = areaToAdjust.getX(), y = areaToAdjust.getY();
  19370. applyToRectangle (x, y, areaToAdjust.getWidth(), areaToAdjust.getHeight(),
  19371. targetSpace.getX(), targetSpace.getY(), targetSpace.getWidth(), targetSpace.getHeight());
  19372. return areaToAdjust.withPosition (x, y);
  19373. }
  19374. /** Flag values that can be combined and used in the constructor. */
  19375. enum
  19376. {
  19377. /** Indicates that the item should be aligned against the left edge of the available space. */
  19378. left = 1,
  19379. /** Indicates that the item should be aligned against the right edge of the available space. */
  19380. right = 2,
  19381. /** Indicates that the item should be placed in the centre between the left and right
  19382. sides of the available space. */
  19383. horizontallyCentred = 4,
  19384. /** Indicates that the item should be aligned against the top edge of the available space. */
  19385. top = 8,
  19386. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  19387. bottom = 16,
  19388. /** Indicates that the item should be placed in the centre between the top and bottom
  19389. sides of the available space. */
  19390. verticallyCentred = 32,
  19391. /** Indicates that lines of text should be spread out to fill the maximum width
  19392. available, so that both margins are aligned vertically.
  19393. */
  19394. horizontallyJustified = 64,
  19395. /** Indicates that the item should be centred vertically and horizontally.
  19396. This is equivalent to (horizontallyCentred | verticallyCentred)
  19397. */
  19398. centred = 36,
  19399. /** Indicates that the item should be centred vertically but placed on the left hand side.
  19400. This is equivalent to (left | verticallyCentred)
  19401. */
  19402. centredLeft = 33,
  19403. /** Indicates that the item should be centred vertically but placed on the right hand side.
  19404. This is equivalent to (right | verticallyCentred)
  19405. */
  19406. centredRight = 34,
  19407. /** Indicates that the item should be centred horizontally and placed at the top.
  19408. This is equivalent to (horizontallyCentred | top)
  19409. */
  19410. centredTop = 12,
  19411. /** Indicates that the item should be centred horizontally and placed at the bottom.
  19412. This is equivalent to (horizontallyCentred | bottom)
  19413. */
  19414. centredBottom = 20,
  19415. /** Indicates that the item should be placed in the top-left corner.
  19416. This is equivalent to (left | top)
  19417. */
  19418. topLeft = 9,
  19419. /** Indicates that the item should be placed in the top-right corner.
  19420. This is equivalent to (right | top)
  19421. */
  19422. topRight = 10,
  19423. /** Indicates that the item should be placed in the bottom-left corner.
  19424. This is equivalent to (left | bottom)
  19425. */
  19426. bottomLeft = 17,
  19427. /** Indicates that the item should be placed in the bottom-left corner.
  19428. This is equivalent to (right | bottom)
  19429. */
  19430. bottomRight = 18
  19431. };
  19432. private:
  19433. int flags;
  19434. };
  19435. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  19436. /*** End of inlined file: juce_Justification.h ***/
  19437. class Image;
  19438. /**
  19439. A path is a sequence of lines and curves that may either form a closed shape
  19440. or be open-ended.
  19441. To use a path, you can create an empty one, then add lines and curves to it
  19442. to create shapes, then it can be rendered by a Graphics context or used
  19443. for geometric operations.
  19444. e.g. @code
  19445. Path myPath;
  19446. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  19447. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  19448. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  19449. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  19450. // add an ellipse as well, which will form a second sub-path within the path..
  19451. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  19452. // double the width of the whole thing..
  19453. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  19454. // and draw it to a graphics context with a 5-pixel thick outline.
  19455. g.strokePath (myPath, PathStrokeType (5.0f));
  19456. @endcode
  19457. A path object can actually contain multiple sub-paths, which may themselves
  19458. be open or closed.
  19459. @see PathFlatteningIterator, PathStrokeType, Graphics
  19460. */
  19461. class JUCE_API Path
  19462. {
  19463. public:
  19464. /** Creates an empty path. */
  19465. Path();
  19466. /** Creates a copy of another path. */
  19467. Path (const Path& other);
  19468. /** Destructor. */
  19469. ~Path();
  19470. /** Copies this path from another one. */
  19471. Path& operator= (const Path& other);
  19472. bool operator== (const Path& other) const throw();
  19473. bool operator!= (const Path& other) const throw();
  19474. /** Returns true if the path doesn't contain any lines or curves. */
  19475. bool isEmpty() const throw();
  19476. /** Returns the smallest rectangle that contains all points within the path.
  19477. */
  19478. const Rectangle<float> getBounds() const throw();
  19479. /** Returns the smallest rectangle that contains all points within the path
  19480. after it's been transformed with the given tranasform matrix.
  19481. */
  19482. const Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const throw();
  19483. /** Checks whether a point lies within the path.
  19484. This is only relevent for closed paths (see closeSubPath()), and
  19485. may produce false results if used on a path which has open sub-paths.
  19486. The path's winding rule is taken into account by this method.
  19487. The tolerance parameter is the maximum error allowed when flattening the path,
  19488. so this method could return a false positive when your point is up to this distance
  19489. outside the path's boundary.
  19490. @see closeSubPath, setUsingNonZeroWinding
  19491. */
  19492. bool contains (float x, float y,
  19493. float tolerance = 1.0f) const;
  19494. /** Checks whether a point lies within the path.
  19495. This is only relevent for closed paths (see closeSubPath()), and
  19496. may produce false results if used on a path which has open sub-paths.
  19497. The path's winding rule is taken into account by this method.
  19498. The tolerance parameter is the maximum error allowed when flattening the path,
  19499. so this method could return a false positive when your point is up to this distance
  19500. outside the path's boundary.
  19501. @see closeSubPath, setUsingNonZeroWinding
  19502. */
  19503. bool contains (const Point<float>& point,
  19504. float tolerance = 1.0f) const;
  19505. /** Checks whether a line crosses the path.
  19506. This will return positive if the line crosses any of the paths constituent
  19507. lines or curves. It doesn't take into account whether the line is inside
  19508. or outside the path, or whether the path is open or closed.
  19509. The tolerance parameter is the maximum error allowed when flattening the path,
  19510. so this method could return a false positive when your point is up to this distance
  19511. outside the path's boundary.
  19512. */
  19513. bool intersectsLine (const Line<float>& line,
  19514. float tolerance = 1.0f);
  19515. /** Cuts off parts of a line to keep the parts that are either inside or
  19516. outside this path.
  19517. Note that this isn't smart enough to cope with situations where the
  19518. line would need to be cut into multiple pieces to correctly clip against
  19519. a re-entrant shape.
  19520. @param line the line to clip
  19521. @param keepSectionOutsidePath if true, it's the section outside the path
  19522. that will be kept; if false its the section inside
  19523. the path
  19524. */
  19525. const Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  19526. /** Returns the length of the path.
  19527. @see getPointAlongPath
  19528. */
  19529. float getLength (const AffineTransform& transform = AffineTransform::identity) const;
  19530. /** Returns a point that is the specified distance along the path.
  19531. If the distance is greater than the total length of the path, this will return the
  19532. end point.
  19533. @see getLength
  19534. */
  19535. const Point<float> getPointAlongPath (float distanceFromStart,
  19536. const AffineTransform& transform = AffineTransform::identity) const;
  19537. /** Finds the point along the path which is nearest to a given position.
  19538. This sets pointOnPath to the nearest point, and returns the distance of this point from the start
  19539. of the path.
  19540. */
  19541. float getNearestPoint (const Point<float>& targetPoint,
  19542. Point<float>& pointOnPath,
  19543. const AffineTransform& transform = AffineTransform::identity) const;
  19544. /** Removes all lines and curves, resetting the path completely. */
  19545. void clear() throw();
  19546. /** Begins a new subpath with a given starting position.
  19547. This will move the path's current position to the co-ordinates passed in and
  19548. make it ready to draw lines or curves starting from this position.
  19549. After adding whatever lines and curves are needed, you can either
  19550. close the current sub-path using closeSubPath() or call startNewSubPath()
  19551. to move to a new sub-path, leaving the old one open-ended.
  19552. @see lineTo, quadraticTo, cubicTo, closeSubPath
  19553. */
  19554. void startNewSubPath (float startX, float startY);
  19555. /** Begins a new subpath with a given starting position.
  19556. This will move the path's current position to the co-ordinates passed in and
  19557. make it ready to draw lines or curves starting from this position.
  19558. After adding whatever lines and curves are needed, you can either
  19559. close the current sub-path using closeSubPath() or call startNewSubPath()
  19560. to move to a new sub-path, leaving the old one open-ended.
  19561. @see lineTo, quadraticTo, cubicTo, closeSubPath
  19562. */
  19563. void startNewSubPath (const Point<float>& start);
  19564. /** Closes a the current sub-path with a line back to its start-point.
  19565. When creating a closed shape such as a triangle, don't use 3 lineTo()
  19566. calls - instead use two lineTo() calls, followed by a closeSubPath()
  19567. to join the final point back to the start.
  19568. This ensures that closes shapes are recognised as such, and this is
  19569. important for tasks like drawing strokes, which needs to know whether to
  19570. draw end-caps or not.
  19571. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  19572. */
  19573. void closeSubPath();
  19574. /** Adds a line from the shape's last position to a new end-point.
  19575. This will connect the end-point of the last line or curve that was added
  19576. to a new point, using a straight line.
  19577. See the class description for an example of how to add lines and curves to a path.
  19578. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  19579. */
  19580. void lineTo (float endX, float endY);
  19581. /** Adds a line from the shape's last position to a new end-point.
  19582. This will connect the end-point of the last line or curve that was added
  19583. to a new point, using a straight line.
  19584. See the class description for an example of how to add lines and curves to a path.
  19585. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  19586. */
  19587. void lineTo (const Point<float>& end);
  19588. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  19589. This will connect the end-point of the last line or curve that was added
  19590. to a new point, using a quadratic spline with one control-point.
  19591. See the class description for an example of how to add lines and curves to a path.
  19592. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  19593. */
  19594. void quadraticTo (float controlPointX,
  19595. float controlPointY,
  19596. float endPointX,
  19597. float endPointY);
  19598. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  19599. This will connect the end-point of the last line or curve that was added
  19600. to a new point, using a quadratic spline with one control-point.
  19601. See the class description for an example of how to add lines and curves to a path.
  19602. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  19603. */
  19604. void quadraticTo (const Point<float>& controlPoint,
  19605. const Point<float>& endPoint);
  19606. /** Adds a cubic bezier curve from the shape's last position to a new position.
  19607. This will connect the end-point of the last line or curve that was added
  19608. to a new point, using a cubic spline with two control-points.
  19609. See the class description for an example of how to add lines and curves to a path.
  19610. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  19611. */
  19612. void cubicTo (float controlPoint1X,
  19613. float controlPoint1Y,
  19614. float controlPoint2X,
  19615. float controlPoint2Y,
  19616. float endPointX,
  19617. float endPointY);
  19618. /** Adds a cubic bezier curve from the shape's last position to a new position.
  19619. This will connect the end-point of the last line or curve that was added
  19620. to a new point, using a cubic spline with two control-points.
  19621. See the class description for an example of how to add lines and curves to a path.
  19622. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  19623. */
  19624. void cubicTo (const Point<float>& controlPoint1,
  19625. const Point<float>& controlPoint2,
  19626. const Point<float>& endPoint);
  19627. /** Returns the last point that was added to the path by one of the drawing methods.
  19628. */
  19629. const Point<float> getCurrentPosition() const;
  19630. /** Adds a rectangle to the path.
  19631. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19632. @see addRoundedRectangle, addTriangle
  19633. */
  19634. void addRectangle (float x, float y, float width, float height);
  19635. /** Adds a rectangle to the path.
  19636. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19637. @see addRoundedRectangle, addTriangle
  19638. */
  19639. template <typename ValueType>
  19640. void addRectangle (const Rectangle<ValueType>& rectangle)
  19641. {
  19642. addRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  19643. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()));
  19644. }
  19645. /** Adds a rectangle with rounded corners to the path.
  19646. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19647. @see addRectangle, addTriangle
  19648. */
  19649. void addRoundedRectangle (float x, float y, float width, float height,
  19650. float cornerSize);
  19651. /** Adds a rectangle with rounded corners to the path.
  19652. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19653. @see addRectangle, addTriangle
  19654. */
  19655. void addRoundedRectangle (float x, float y, float width, float height,
  19656. float cornerSizeX,
  19657. float cornerSizeY);
  19658. /** Adds a rectangle with rounded corners to the path.
  19659. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19660. @see addRectangle, addTriangle
  19661. */
  19662. template <typename ValueType>
  19663. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSizeX, float cornerSizeY)
  19664. {
  19665. addRoundedRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  19666. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()),
  19667. cornerSizeX, cornerSizeY);
  19668. }
  19669. /** Adds a rectangle with rounded corners to the path.
  19670. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19671. @see addRectangle, addTriangle
  19672. */
  19673. template <typename ValueType>
  19674. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSize)
  19675. {
  19676. addRoundedRectangle (rectangle, cornerSize, cornerSize);
  19677. }
  19678. /** Adds a triangle to the path.
  19679. The triangle is added as a new closed sub-path. (Any currently open paths will be left open).
  19680. Note that whether the vertices are specified in clockwise or anticlockwise
  19681. order will affect how the triangle is filled when it overlaps other
  19682. shapes (the winding order setting will affect this of course).
  19683. */
  19684. void addTriangle (float x1, float y1,
  19685. float x2, float y2,
  19686. float x3, float y3);
  19687. /** Adds a quadrilateral to the path.
  19688. The quad is added as a new closed sub-path. (Any currently open paths will be left open).
  19689. Note that whether the vertices are specified in clockwise or anticlockwise
  19690. order will affect how the quad is filled when it overlaps other
  19691. shapes (the winding order setting will affect this of course).
  19692. */
  19693. void addQuadrilateral (float x1, float y1,
  19694. float x2, float y2,
  19695. float x3, float y3,
  19696. float x4, float y4);
  19697. /** Adds an ellipse to the path.
  19698. The shape is added as a new sub-path. (Any currently open paths will be left open).
  19699. @see addArc
  19700. */
  19701. void addEllipse (float x, float y, float width, float height);
  19702. /** Adds an elliptical arc to the current path.
  19703. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  19704. or anti-clockwise according to whether the end angle is greater than the start. This means
  19705. that sometimes you may need to use values greater than 2*Pi for the end angle.
  19706. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  19707. @param y the top edge of the rectangle in which the elliptical outline fits
  19708. @param width the width of the rectangle in which the elliptical outline fits
  19709. @param height the height of the rectangle in which the elliptical outline fits
  19710. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  19711. top-centre of the ellipse)
  19712. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  19713. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  19714. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  19715. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  19716. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  19717. it will be added to the current sub-path, continuing from the current postition
  19718. @see addCentredArc, arcTo, addPieSegment, addEllipse
  19719. */
  19720. void addArc (float x, float y, float width, float height,
  19721. float fromRadians,
  19722. float toRadians,
  19723. bool startAsNewSubPath = false);
  19724. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  19725. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  19726. or anti-clockwise according to whether the end angle is greater than the start. This means
  19727. that sometimes you may need to use values greater than 2*Pi for the end angle.
  19728. @param centreX the centre x of the ellipse
  19729. @param centreY the centre y of the ellipse
  19730. @param radiusX the horizontal radius of the ellipse
  19731. @param radiusY the vertical radius of the ellipse
  19732. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  19733. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  19734. top-centre of the ellipse)
  19735. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  19736. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  19737. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  19738. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  19739. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  19740. it will be added to the current sub-path, continuing from the current postition
  19741. @see addArc, arcTo
  19742. */
  19743. void addCentredArc (float centreX, float centreY,
  19744. float radiusX, float radiusY,
  19745. float rotationOfEllipse,
  19746. float fromRadians,
  19747. float toRadians,
  19748. bool startAsNewSubPath = false);
  19749. /** Adds a "pie-chart" shape to the path.
  19750. The shape is added as a new sub-path. (Any currently open paths will be
  19751. left open).
  19752. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  19753. or anti-clockwise according to whether the end angle is greater than the start. This means
  19754. that sometimes you may need to use values greater than 2*Pi for the end angle.
  19755. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  19756. @param y the top edge of the rectangle in which the elliptical outline fits
  19757. @param width the width of the rectangle in which the elliptical outline fits
  19758. @param height the height of the rectangle in which the elliptical outline fits
  19759. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  19760. top-centre of the ellipse)
  19761. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  19762. top-centre of the ellipse)
  19763. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  19764. ellipse at its centre, where this value indicates the inner ellipse's size with
  19765. respect to the outer one.
  19766. @see addArc
  19767. */
  19768. void addPieSegment (float x, float y,
  19769. float width, float height,
  19770. float fromRadians,
  19771. float toRadians,
  19772. float innerCircleProportionalSize);
  19773. /** Adds a line with a specified thickness.
  19774. The line is added as a new closed sub-path. (Any currently open paths will be
  19775. left open).
  19776. @see addArrow
  19777. */
  19778. void addLineSegment (const Line<float>& line, float lineThickness);
  19779. /** Adds a line with an arrowhead on the end.
  19780. The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
  19781. @see PathStrokeType::createStrokeWithArrowheads
  19782. */
  19783. void addArrow (const Line<float>& line,
  19784. float lineThickness,
  19785. float arrowheadWidth,
  19786. float arrowheadLength);
  19787. /** Adds a polygon shape to the path.
  19788. @see addStar
  19789. */
  19790. void addPolygon (const Point<float>& centre,
  19791. int numberOfSides,
  19792. float radius,
  19793. float startAngle = 0.0f);
  19794. /** Adds a star shape to the path.
  19795. @see addPolygon
  19796. */
  19797. void addStar (const Point<float>& centre,
  19798. int numberOfPoints,
  19799. float innerRadius,
  19800. float outerRadius,
  19801. float startAngle = 0.0f);
  19802. /** Adds a speech-bubble shape to the path.
  19803. @param bodyX the left of the main body area of the bubble
  19804. @param bodyY the top of the main body area of the bubble
  19805. @param bodyW the width of the main body area of the bubble
  19806. @param bodyH the height of the main body area of the bubble
  19807. @param cornerSize the amount by which to round off the corners of the main body rectangle
  19808. @param arrowTipX the x position that the tip of the arrow should connect to
  19809. @param arrowTipY the y position that the tip of the arrow should connect to
  19810. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  19811. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  19812. arrow's base should be - this is a proportional distance between 0 and 1.0
  19813. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  19814. */
  19815. void addBubble (float bodyX, float bodyY,
  19816. float bodyW, float bodyH,
  19817. float cornerSize,
  19818. float arrowTipX,
  19819. float arrowTipY,
  19820. int whichSide,
  19821. float arrowPositionAlongEdgeProportional,
  19822. float arrowWidth);
  19823. /** Adds another path to this one.
  19824. The new path is added as a new sub-path. (Any currently open paths in this
  19825. path will be left open).
  19826. @param pathToAppend the path to add
  19827. */
  19828. void addPath (const Path& pathToAppend);
  19829. /** Adds another path to this one, transforming it on the way in.
  19830. The new path is added as a new sub-path, its points being transformed by the given
  19831. matrix before being added.
  19832. @param pathToAppend the path to add
  19833. @param transformToApply an optional transform to apply to the incoming vertices
  19834. */
  19835. void addPath (const Path& pathToAppend,
  19836. const AffineTransform& transformToApply);
  19837. /** Swaps the contents of this path with another one.
  19838. The internal data of the two paths is swapped over, so this is much faster than
  19839. copying it to a temp variable and back.
  19840. */
  19841. void swapWithPath (Path& other) throw();
  19842. /** Applies a 2D transform to all the vertices in the path.
  19843. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  19844. */
  19845. void applyTransform (const AffineTransform& transform) throw();
  19846. /** Rescales this path to make it fit neatly into a given space.
  19847. This is effectively a quick way of calling
  19848. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  19849. @param x the x position of the rectangle to fit the path inside
  19850. @param y the y position of the rectangle to fit the path inside
  19851. @param width the width of the rectangle to fit the path inside
  19852. @param height the height of the rectangle to fit the path inside
  19853. @param preserveProportions if true, it will fit the path into the space without altering its
  19854. horizontal/vertical scale ratio; if false, it will distort the
  19855. path to fill the specified ratio both horizontally and vertically
  19856. @see applyTransform, getTransformToScaleToFit
  19857. */
  19858. void scaleToFit (float x, float y, float width, float height,
  19859. bool preserveProportions) throw();
  19860. /** Returns a transform that can be used to rescale the path to fit into a given space.
  19861. @param x the x position of the rectangle to fit the path inside
  19862. @param y the y position of the rectangle to fit the path inside
  19863. @param width the width of the rectangle to fit the path inside
  19864. @param height the height of the rectangle to fit the path inside
  19865. @param preserveProportions if true, it will fit the path into the space without altering its
  19866. horizontal/vertical scale ratio; if false, it will distort the
  19867. path to fill the specified ratio both horizontally and vertically
  19868. @param justificationType if the proportions are preseved, the resultant path may be smaller
  19869. than the available rectangle, so this describes how it should be
  19870. positioned within the space.
  19871. @returns an appropriate transformation
  19872. @see applyTransform, scaleToFit
  19873. */
  19874. const AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  19875. bool preserveProportions,
  19876. const Justification& justificationType = Justification::centred) const;
  19877. /** Creates a version of this path where all sharp corners have been replaced by curves.
  19878. Wherever two lines meet at an angle, this will replace the corner with a curve
  19879. of the given radius.
  19880. */
  19881. const Path createPathWithRoundedCorners (float cornerRadius) const;
  19882. /** Changes the winding-rule to be used when filling the path.
  19883. If set to true (which is the default), then the path uses a non-zero-winding rule
  19884. to determine which points are inside the path. If set to false, it uses an
  19885. alternate-winding rule.
  19886. The winding-rule comes into play when areas of the shape overlap other
  19887. areas, and determines whether the overlapping regions are considered to be
  19888. inside or outside.
  19889. Changing this value just sets a flag - it doesn't affect the contents of the
  19890. path.
  19891. @see isUsingNonZeroWinding
  19892. */
  19893. void setUsingNonZeroWinding (bool isNonZeroWinding) throw();
  19894. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  19895. The default for a new path is true.
  19896. @see setUsingNonZeroWinding
  19897. */
  19898. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  19899. /** Iterates the lines and curves that a path contains.
  19900. @see Path, PathFlatteningIterator
  19901. */
  19902. class JUCE_API Iterator
  19903. {
  19904. public:
  19905. Iterator (const Path& path);
  19906. ~Iterator();
  19907. /** Moves onto the next element in the path.
  19908. If this returns false, there are no more elements. If it returns true,
  19909. the elementType variable will be set to the type of the current element,
  19910. and some of the x and y variables will be filled in with values.
  19911. */
  19912. bool next();
  19913. enum PathElementType
  19914. {
  19915. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  19916. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  19917. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  19918. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  19919. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  19920. };
  19921. PathElementType elementType;
  19922. float x1, y1, x2, y2, x3, y3;
  19923. private:
  19924. const Path& path;
  19925. size_t index;
  19926. JUCE_DECLARE_NON_COPYABLE (Iterator);
  19927. };
  19928. /** Loads a stored path from a data stream.
  19929. The data in the stream must have been written using writePathToStream().
  19930. Note that this will append the stored path to whatever is currently in
  19931. this path, so you might need to call clear() beforehand.
  19932. @see loadPathFromData, writePathToStream
  19933. */
  19934. void loadPathFromStream (InputStream& source);
  19935. /** Loads a stored path from a block of data.
  19936. This is similar to loadPathFromStream(), but just reads from a block
  19937. of data. Useful if you're including stored shapes in your code as a
  19938. block of static data.
  19939. @see loadPathFromStream, writePathToStream
  19940. */
  19941. void loadPathFromData (const void* data, int numberOfBytes);
  19942. /** Stores the path by writing it out to a stream.
  19943. After writing out a path, you can reload it using loadPathFromStream().
  19944. @see loadPathFromStream, loadPathFromData
  19945. */
  19946. void writePathToStream (OutputStream& destination) const;
  19947. /** Creates a string containing a textual representation of this path.
  19948. @see restoreFromString
  19949. */
  19950. const String toString() const;
  19951. /** Restores this path from a string that was created with the toString() method.
  19952. @see toString()
  19953. */
  19954. void restoreFromString (const String& stringVersion);
  19955. private:
  19956. friend class PathFlatteningIterator;
  19957. friend class Path::Iterator;
  19958. ArrayAllocationBase <float, DummyCriticalSection> data;
  19959. size_t numElements;
  19960. float pathXMin, pathXMax, pathYMin, pathYMax;
  19961. bool useNonZeroWinding;
  19962. static const float lineMarker;
  19963. static const float moveMarker;
  19964. static const float quadMarker;
  19965. static const float cubicMarker;
  19966. static const float closeSubPathMarker;
  19967. JUCE_LEAK_DETECTOR (Path);
  19968. };
  19969. #endif // __JUCE_PATH_JUCEHEADER__
  19970. /*** End of inlined file: juce_Path.h ***/
  19971. class Font;
  19972. class EdgeTable;
  19973. /** A typeface represents a size-independent font.
  19974. This base class is abstract, but calling createSystemTypefaceFor() will return
  19975. a platform-specific subclass that can be used.
  19976. The CustomTypeface subclass allow you to build your own typeface, and to
  19977. load and save it in the Juce typeface format.
  19978. Normally you should never need to deal directly with Typeface objects - the Font
  19979. class does everything you typically need for rendering text.
  19980. @see CustomTypeface, Font
  19981. */
  19982. class JUCE_API Typeface : public ReferenceCountedObject
  19983. {
  19984. public:
  19985. /** A handy typedef for a pointer to a typeface. */
  19986. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  19987. /** Returns the name of the typeface.
  19988. @see Font::getTypefaceName
  19989. */
  19990. const String getName() const throw() { return name; }
  19991. /** Creates a new system typeface. */
  19992. static const Ptr createSystemTypefaceFor (const Font& font);
  19993. /** Destructor. */
  19994. virtual ~Typeface();
  19995. /** Returns true if this typeface can be used to render the specified font.
  19996. When called, the font will already have been checked to make sure that its name and
  19997. style flags match the typeface.
  19998. */
  19999. virtual bool isSuitableForFont (const Font&) const { return true; }
  20000. /** Returns the ascent of the font, as a proportion of its height.
  20001. The height is considered to always be normalised as 1.0, so this will be a
  20002. value less that 1.0, indicating the proportion of the font that lies above
  20003. its baseline.
  20004. */
  20005. virtual float getAscent() const = 0;
  20006. /** Returns the descent of the font, as a proportion of its height.
  20007. The height is considered to always be normalised as 1.0, so this will be a
  20008. value less that 1.0, indicating the proportion of the font that lies below
  20009. its baseline.
  20010. */
  20011. virtual float getDescent() const = 0;
  20012. /** Measures the width of a line of text.
  20013. The distance returned is based on the font having an normalised height of 1.0.
  20014. You should never need to call this directly! Use Font::getStringWidth() instead!
  20015. */
  20016. virtual float getStringWidth (const String& text) = 0;
  20017. /** Converts a line of text into its glyph numbers and their positions.
  20018. The distances returned are based on the font having an normalised height of 1.0.
  20019. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  20020. */
  20021. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  20022. /** Returns the outline for a glyph.
  20023. The path returned will be normalised to a font height of 1.0.
  20024. */
  20025. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  20026. /** Returns a new EdgeTable that contains the path for the givem glyph, with the specified transform applied. */
  20027. virtual EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  20028. /** Returns true if the typeface uses hinting. */
  20029. virtual bool isHinted() const { return false; }
  20030. /** Changes the number of fonts that are cached in memory. */
  20031. static void setTypefaceCacheSize (int numFontsToCache);
  20032. protected:
  20033. String name;
  20034. bool isFallbackFont;
  20035. explicit Typeface (const String& name) throw();
  20036. static const Ptr getFallbackTypeface();
  20037. private:
  20038. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Typeface);
  20039. };
  20040. /** A typeface that can be populated with custom glyphs.
  20041. You can create a CustomTypeface if you need one that contains your own glyphs,
  20042. or if you need to load a typeface from a Juce-formatted binary stream.
  20043. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  20044. to copy glyphs into this face.
  20045. @see Typeface, Font
  20046. */
  20047. class JUCE_API CustomTypeface : public Typeface
  20048. {
  20049. public:
  20050. /** Creates a new, empty typeface. */
  20051. CustomTypeface();
  20052. /** Loads a typeface from a previously saved stream.
  20053. The stream must have been created by writeToStream().
  20054. @see writeToStream
  20055. */
  20056. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  20057. /** Destructor. */
  20058. ~CustomTypeface();
  20059. /** Resets this typeface, deleting all its glyphs and settings. */
  20060. void clear();
  20061. /** Sets the vital statistics for the typeface.
  20062. @param name the typeface's name
  20063. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  20064. the value that will be returned by Typeface::getAscent(). The
  20065. descent is assumed to be (1.0 - ascent)
  20066. @param isBold should be true if the typeface is bold
  20067. @param isItalic should be true if the typeface is italic
  20068. @param defaultCharacter the character to be used as a replacement if there's
  20069. no glyph available for the character that's being drawn
  20070. */
  20071. void setCharacteristics (const String& name, float ascent,
  20072. bool isBold, bool isItalic,
  20073. juce_wchar defaultCharacter) throw();
  20074. /** Adds a glyph to the typeface.
  20075. The path that is passed in is normalised so that the font height is 1.0, and its
  20076. origin is the anchor point of the character on its baseline.
  20077. The width is the nominal width of the character, and any extra kerning values that
  20078. are specified will be added to this width.
  20079. */
  20080. void addGlyph (juce_wchar character, const Path& path, float width) throw();
  20081. /** Specifies an extra kerning amount to be used between a pair of characters.
  20082. The amount will be added to the nominal width of the first character when laying out a string.
  20083. */
  20084. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) throw();
  20085. /** Adds a range of glyphs from another typeface.
  20086. This will attempt to pull in the paths and kerning information from another typeface and
  20087. add it to this one.
  20088. */
  20089. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw();
  20090. /** Saves this typeface as a Juce-formatted font file.
  20091. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  20092. constructor.
  20093. */
  20094. bool writeToStream (OutputStream& outputStream);
  20095. // The following methods implement the basic Typeface behaviour.
  20096. float getAscent() const;
  20097. float getDescent() const;
  20098. float getStringWidth (const String& text);
  20099. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  20100. bool getOutlineForGlyph (int glyphNumber, Path& path);
  20101. EdgeTable* getEdgeTableForGlyph (int glyphNumber, const AffineTransform& transform);
  20102. int getGlyphForCharacter (juce_wchar character);
  20103. protected:
  20104. juce_wchar defaultCharacter;
  20105. float ascent;
  20106. bool isBold, isItalic;
  20107. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  20108. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  20109. particular character and there's no corresponding glyph, they'll call this
  20110. method so that a subclass can try to add that glyph, returning true if it
  20111. manages to do so.
  20112. */
  20113. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  20114. private:
  20115. class GlyphInfo;
  20116. friend class OwnedArray<GlyphInfo>;
  20117. OwnedArray <GlyphInfo> glyphs;
  20118. short lookupTable [128];
  20119. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) throw();
  20120. GlyphInfo* findGlyphSubstituting (juce_wchar character) throw();
  20121. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomTypeface);
  20122. };
  20123. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  20124. /*** End of inlined file: juce_Typeface.h ***/
  20125. class LowLevelGraphicsContext;
  20126. /**
  20127. Represents a particular font, including its size, style, etc.
  20128. Apart from the typeface to be used, a Font object also dictates whether
  20129. the font is bold, italic, underlined, how big it is, and its kerning and
  20130. horizontal scale factor.
  20131. @see Typeface
  20132. */
  20133. class JUCE_API Font
  20134. {
  20135. public:
  20136. /** A combination of these values is used by the constructor to specify the
  20137. style of font to use.
  20138. */
  20139. enum FontStyleFlags
  20140. {
  20141. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  20142. bold = 1, /**< boldens the font. @see setStyleFlags */
  20143. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  20144. underlined = 4 /**< underlines the font. @see setStyleFlags */
  20145. };
  20146. /** Creates a sans-serif font in a given size.
  20147. @param fontHeight the height in pixels (can be fractional)
  20148. @param styleFlags the style to use - this can be a combination of the
  20149. Font::bold, Font::italic and Font::underlined, or
  20150. just Font::plain for the normal style.
  20151. @see FontStyleFlags, getDefaultSansSerifFontName
  20152. */
  20153. Font (float fontHeight, int styleFlags = plain);
  20154. /** Creates a font with a given typeface and parameters.
  20155. @param typefaceName the name of the typeface to use
  20156. @param fontHeight the height in pixels (can be fractional)
  20157. @param styleFlags the style to use - this can be a combination of the
  20158. Font::bold, Font::italic and Font::underlined, or
  20159. just Font::plain for the normal style.
  20160. @see FontStyleFlags, getDefaultSansSerifFontName
  20161. */
  20162. Font (const String& typefaceName, float fontHeight, int styleFlags);
  20163. /** Creates a copy of another Font object. */
  20164. Font (const Font& other) throw();
  20165. /** Creates a font for a typeface. */
  20166. Font (const Typeface::Ptr& typeface);
  20167. /** Creates a basic sans-serif font at a default height.
  20168. You should use one of the other constructors for creating a font that you're planning
  20169. on drawing with - this constructor is here to help initialise objects before changing
  20170. the font's settings later.
  20171. */
  20172. Font();
  20173. /** Copies this font from another one. */
  20174. Font& operator= (const Font& other) throw();
  20175. bool operator== (const Font& other) const throw();
  20176. bool operator!= (const Font& other) const throw();
  20177. /** Destructor. */
  20178. ~Font() throw();
  20179. /** Changes the name of the typeface family.
  20180. e.g. "Arial", "Courier", etc.
  20181. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  20182. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  20183. but are generic names that are used to represent the various default fonts.
  20184. If you need to know the exact typeface name being used, you can call
  20185. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  20186. If a suitable font isn't found on the machine, it'll just use a default instead.
  20187. */
  20188. void setTypefaceName (const String& faceName);
  20189. /** Returns the name of the typeface family that this font uses.
  20190. e.g. "Arial", "Courier", etc.
  20191. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  20192. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  20193. but are generic names that are used to represent the various default fonts.
  20194. If you need to know the exact typeface name being used, you can call
  20195. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  20196. */
  20197. const String& getTypefaceName() const throw() { return font->typefaceName; }
  20198. /** Returns a typeface name that represents the default sans-serif font.
  20199. This is also the typeface that will be used when a font is created without
  20200. specifying any typeface details.
  20201. Note that this method just returns a generic placeholder string that means "the default
  20202. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  20203. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  20204. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  20205. */
  20206. static const String getDefaultSansSerifFontName();
  20207. /** Returns a typeface name that represents the default sans-serif font.
  20208. Note that this method just returns a generic placeholder string that means "the default
  20209. serif font" - it's not the actual name of this font. To get the actual name, use
  20210. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  20211. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  20212. */
  20213. static const String getDefaultSerifFontName();
  20214. /** Returns a typeface name that represents the default sans-serif font.
  20215. Note that this method just returns a generic placeholder string that means "the default
  20216. monospaced font" - it's not the actual name of this font. To get the actual name, use
  20217. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  20218. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  20219. */
  20220. static const String getDefaultMonospacedFontName();
  20221. /** Returns the typeface names of the default fonts on the current platform. */
  20222. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback);
  20223. /** Returns the total height of this font.
  20224. This is the maximum height, from the top of the ascent to the bottom of the
  20225. descenders.
  20226. @see setHeight, setHeightWithoutChangingWidth, getAscent
  20227. */
  20228. float getHeight() const throw() { return font->height; }
  20229. /** Changes the font's height.
  20230. @see getHeight, setHeightWithoutChangingWidth
  20231. */
  20232. void setHeight (float newHeight);
  20233. /** Changes the font's height without changing its width.
  20234. This alters the horizontal scale to compensate for the change in height.
  20235. */
  20236. void setHeightWithoutChangingWidth (float newHeight);
  20237. /** Returns the height of the font above its baseline.
  20238. This is the maximum height from the baseline to the top.
  20239. @see getHeight, getDescent
  20240. */
  20241. float getAscent() const;
  20242. /** Returns the amount that the font descends below its baseline.
  20243. This is calculated as (getHeight() - getAscent()).
  20244. @see getAscent, getHeight
  20245. */
  20246. float getDescent() const;
  20247. /** Returns the font's style flags.
  20248. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  20249. enum, to describe whether the font is bold, italic, etc.
  20250. @see FontStyleFlags
  20251. */
  20252. int getStyleFlags() const throw() { return font->styleFlags; }
  20253. /** Changes the font's style.
  20254. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  20255. enum, to set the font's properties
  20256. @see FontStyleFlags
  20257. */
  20258. void setStyleFlags (int newFlags);
  20259. /** Makes the font bold or non-bold. */
  20260. void setBold (bool shouldBeBold);
  20261. /** Returns a copy of this font with the bold attribute set. */
  20262. const Font boldened() const;
  20263. /** Returns true if the font is bold. */
  20264. bool isBold() const throw();
  20265. /** Makes the font italic or non-italic. */
  20266. void setItalic (bool shouldBeItalic);
  20267. /** Returns a copy of this font with the italic attribute set. */
  20268. const Font italicised() const;
  20269. /** Returns true if the font is italic. */
  20270. bool isItalic() const throw();
  20271. /** Makes the font underlined or non-underlined. */
  20272. void setUnderline (bool shouldBeUnderlined);
  20273. /** Returns true if the font is underlined. */
  20274. bool isUnderlined() const throw();
  20275. /** Changes the font's horizontal scale factor.
  20276. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  20277. narrower, greater than 1.0 will be stretched out.
  20278. */
  20279. void setHorizontalScale (float scaleFactor);
  20280. /** Returns the font's horizontal scale.
  20281. A value of 1.0 is the normal scale, less than this will be narrower, greater
  20282. than 1.0 will be stretched out.
  20283. @see setHorizontalScale
  20284. */
  20285. float getHorizontalScale() const throw() { return font->horizontalScale; }
  20286. /** Changes the font's kerning.
  20287. @param extraKerning a multiple of the font's height that will be added
  20288. to space between the characters. So a value of zero is
  20289. normal spacing, positive values spread the letters out,
  20290. negative values make them closer together.
  20291. */
  20292. void setExtraKerningFactor (float extraKerning);
  20293. /** Returns the font's kerning.
  20294. This is the extra space added between adjacent characters, as a proportion
  20295. of the font's height.
  20296. A value of zero is normal spacing, positive values will spread the letters
  20297. out more, and negative values make them closer together.
  20298. */
  20299. float getExtraKerningFactor() const throw() { return font->kerning; }
  20300. /** Changes all the font's characteristics with one call. */
  20301. void setSizeAndStyle (float newHeight,
  20302. int newStyleFlags,
  20303. float newHorizontalScale,
  20304. float newKerningAmount);
  20305. /** Returns the total width of a string as it would be drawn using this font.
  20306. For a more accurate floating-point result, use getStringWidthFloat().
  20307. */
  20308. int getStringWidth (const String& text) const;
  20309. /** Returns the total width of a string as it would be drawn using this font.
  20310. @see getStringWidth
  20311. */
  20312. float getStringWidthFloat (const String& text) const;
  20313. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  20314. An extra x offset is added at the end of the run, to indicate where the right hand
  20315. edge of the last character is.
  20316. */
  20317. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const;
  20318. /** Returns the typeface used by this font.
  20319. Note that the object returned may go out of scope if this font is deleted
  20320. or has its style changed.
  20321. */
  20322. Typeface* getTypeface() const;
  20323. /** Creates an array of Font objects to represent all the fonts on the system.
  20324. If you just need the names of the typefaces, you can also use
  20325. findAllTypefaceNames() instead.
  20326. @param results the array to which new Font objects will be added.
  20327. */
  20328. static void findFonts (Array<Font>& results);
  20329. /** Returns a list of all the available typeface names.
  20330. The names returned can be passed into setTypefaceName().
  20331. You can use this instead of findFonts() if you only need their names, and not
  20332. font objects.
  20333. */
  20334. static const StringArray findAllTypefaceNames();
  20335. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  20336. in the requested typeface.
  20337. */
  20338. static const String getFallbackFontName();
  20339. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  20340. available in whatever font you're trying to use.
  20341. */
  20342. static void setFallbackFontName (const String& name);
  20343. /** Creates a string to describe this font.
  20344. The string will contain information to describe the font's typeface, size, and
  20345. style. To recreate the font from this string, use fromString().
  20346. */
  20347. const String toString() const;
  20348. /** Recreates a font from its stringified encoding.
  20349. This method takes a string that was created by toString(), and recreates the
  20350. original font.
  20351. */
  20352. static const Font fromString (const String& fontDescription);
  20353. private:
  20354. friend class FontGlyphAlphaMap;
  20355. friend class TypefaceCache;
  20356. class SharedFontInternal : public ReferenceCountedObject
  20357. {
  20358. public:
  20359. SharedFontInternal (float height, int styleFlags) throw();
  20360. SharedFontInternal (const String& typefaceName, float height, int styleFlags) throw();
  20361. SharedFontInternal (const Typeface::Ptr& typeface) throw();
  20362. SharedFontInternal (const SharedFontInternal& other) throw();
  20363. bool operator== (const SharedFontInternal&) const throw();
  20364. String typefaceName;
  20365. float height, horizontalScale, kerning, ascent;
  20366. int styleFlags;
  20367. Typeface::Ptr typeface;
  20368. };
  20369. ReferenceCountedObjectPtr <SharedFontInternal> font;
  20370. void dupeInternalIfShared();
  20371. JUCE_LEAK_DETECTOR (Font);
  20372. };
  20373. #endif // __JUCE_FONT_JUCEHEADER__
  20374. /*** End of inlined file: juce_Font.h ***/
  20375. /*** Start of inlined file: juce_PathStrokeType.h ***/
  20376. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20377. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20378. /**
  20379. Describes a type of stroke used to render a solid outline along a path.
  20380. A PathStrokeType object can be used directly to create the shape of an outline
  20381. around a path, and is used by Graphics::strokePath to specify the type of
  20382. stroke to draw.
  20383. @see Path, Graphics::strokePath
  20384. */
  20385. class JUCE_API PathStrokeType
  20386. {
  20387. public:
  20388. /** The type of shape to use for the corners between two adjacent line segments. */
  20389. enum JointStyle
  20390. {
  20391. mitered, /**< Indicates that corners should be drawn with sharp joints.
  20392. Note that for angles that curve back on themselves, drawing a
  20393. mitre could require extending the point too far away from the
  20394. path, so a mitre limit is imposed and any corners that exceed it
  20395. are drawn as bevelled instead. */
  20396. curved, /**< Indicates that corners should be drawn as rounded-off. */
  20397. beveled /**< Indicates that corners should be drawn with a line flattening their
  20398. outside edge. */
  20399. };
  20400. /** The type shape to use for the ends of lines. */
  20401. enum EndCapStyle
  20402. {
  20403. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  20404. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  20405. the thickness of the stroke. */
  20406. rounded /**< Ends of lines are rounded-off with a circular shape. */
  20407. };
  20408. /** Creates a stroke type.
  20409. @param strokeThickness the width of the line to use
  20410. @param jointStyle the type of joints to use for corners
  20411. @param endStyle the type of end-caps to use for the ends of open paths.
  20412. */
  20413. PathStrokeType (float strokeThickness,
  20414. JointStyle jointStyle = mitered,
  20415. EndCapStyle endStyle = butt) throw();
  20416. /** Createes a copy of another stroke type. */
  20417. PathStrokeType (const PathStrokeType& other) throw();
  20418. /** Copies another stroke onto this one. */
  20419. PathStrokeType& operator= (const PathStrokeType& other) throw();
  20420. /** Destructor. */
  20421. ~PathStrokeType() throw();
  20422. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  20423. @param destPath the resultant stroked outline shape will be copied into this path.
  20424. Note that it's ok for the source and destination Paths to be
  20425. the same object, so you can easily turn a path into a stroked version
  20426. of itself.
  20427. @param sourcePath the path to use as the source
  20428. @param transform an optional transform to apply to the points from the source path
  20429. as they are being used
  20430. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  20431. a higher resolution, which improves the quality if you'll later want
  20432. to enlarge the stroked path. So for example, if you're planning on drawing
  20433. the stroke at 3x the size that you're creating it, you should set this to 3.
  20434. @see createDashedStroke
  20435. */
  20436. void createStrokedPath (Path& destPath,
  20437. const Path& sourcePath,
  20438. const AffineTransform& transform = AffineTransform::identity,
  20439. float extraAccuracy = 1.0f) const;
  20440. /** Applies this stroke type to a path, creating a dashed line.
  20441. This is similar to createStrokedPath, but uses the array passed in to
  20442. break the stroke up into a series of dashes.
  20443. @param destPath the resultant stroked outline shape will be copied into this path.
  20444. Note that it's ok for the source and destination Paths to be
  20445. the same object, so you can easily turn a path into a stroked version
  20446. of itself.
  20447. @param sourcePath the path to use as the source
  20448. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  20449. a line of length 2, then skip a length of 3, then add a line of length 4,
  20450. skip 5, and keep repeating this pattern.
  20451. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  20452. an even number, otherwise the pattern will get out of step as it
  20453. repeats.
  20454. @param transform an optional transform to apply to the points from the source path
  20455. as they are being used
  20456. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  20457. a higher resolution, which improves the quality if you'll later want
  20458. to enlarge the stroked path. So for example, if you're planning on drawing
  20459. the stroke at 3x the size that you're creating it, you should set this to 3.
  20460. */
  20461. void createDashedStroke (Path& destPath,
  20462. const Path& sourcePath,
  20463. const float* dashLengths,
  20464. int numDashLengths,
  20465. const AffineTransform& transform = AffineTransform::identity,
  20466. float extraAccuracy = 1.0f) const;
  20467. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  20468. @param destPath the resultant stroked outline shape will be copied into this path.
  20469. Note that it's ok for the source and destination Paths to be
  20470. the same object, so you can easily turn a path into a stroked version
  20471. of itself.
  20472. @param sourcePath the path to use as the source
  20473. @param arrowheadStartWidth the width of the arrowhead at the start of the path
  20474. @param arrowheadStartLength the length of the arrowhead at the start of the path
  20475. @param arrowheadEndWidth the width of the arrowhead at the end of the path
  20476. @param arrowheadEndLength the length of the arrowhead at the end of the path
  20477. @param transform an optional transform to apply to the points from the source path
  20478. as they are being used
  20479. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  20480. a higher resolution, which improves the quality if you'll later want
  20481. to enlarge the stroked path. So for example, if you're planning on drawing
  20482. the stroke at 3x the size that you're creating it, you should set this to 3.
  20483. @see createDashedStroke
  20484. */
  20485. void createStrokeWithArrowheads (Path& destPath,
  20486. const Path& sourcePath,
  20487. float arrowheadStartWidth, float arrowheadStartLength,
  20488. float arrowheadEndWidth, float arrowheadEndLength,
  20489. const AffineTransform& transform = AffineTransform::identity,
  20490. float extraAccuracy = 1.0f) const;
  20491. /** Returns the stroke thickness. */
  20492. float getStrokeThickness() const throw() { return thickness; }
  20493. /** Sets the stroke thickness. */
  20494. void setStrokeThickness (float newThickness) throw() { thickness = newThickness; }
  20495. /** Returns the joint style. */
  20496. JointStyle getJointStyle() const throw() { return jointStyle; }
  20497. /** Sets the joint style. */
  20498. void setJointStyle (JointStyle newStyle) throw() { jointStyle = newStyle; }
  20499. /** Returns the end-cap style. */
  20500. EndCapStyle getEndStyle() const throw() { return endStyle; }
  20501. /** Sets the end-cap style. */
  20502. void setEndStyle (EndCapStyle newStyle) throw() { endStyle = newStyle; }
  20503. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  20504. bool operator== (const PathStrokeType& other) const throw();
  20505. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  20506. bool operator!= (const PathStrokeType& other) const throw();
  20507. private:
  20508. float thickness;
  20509. JointStyle jointStyle;
  20510. EndCapStyle endStyle;
  20511. JUCE_LEAK_DETECTOR (PathStrokeType);
  20512. };
  20513. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20514. /*** End of inlined file: juce_PathStrokeType.h ***/
  20515. /*** Start of inlined file: juce_Colours.h ***/
  20516. #ifndef __JUCE_COLOURS_JUCEHEADER__
  20517. #define __JUCE_COLOURS_JUCEHEADER__
  20518. /*** Start of inlined file: juce_Colour.h ***/
  20519. #ifndef __JUCE_COLOUR_JUCEHEADER__
  20520. #define __JUCE_COLOUR_JUCEHEADER__
  20521. /*** Start of inlined file: juce_PixelFormats.h ***/
  20522. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  20523. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  20524. #ifndef DOXYGEN
  20525. #if JUCE_MSVC
  20526. #pragma pack (push, 1)
  20527. #define PACKED
  20528. #elif JUCE_GCC
  20529. #define PACKED __attribute__((packed))
  20530. #else
  20531. #define PACKED
  20532. #endif
  20533. #endif
  20534. class PixelRGB;
  20535. class PixelAlpha;
  20536. /**
  20537. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  20538. operations with it.
  20539. This is used internally by the imaging classes.
  20540. @see PixelRGB
  20541. */
  20542. class JUCE_API PixelARGB
  20543. {
  20544. public:
  20545. /** Creates a pixel without defining its colour. */
  20546. PixelARGB() throw() {}
  20547. ~PixelARGB() throw() {}
  20548. /** Creates a pixel from a 32-bit argb value.
  20549. */
  20550. PixelARGB (const uint32 argb_) throw()
  20551. : argb (argb_)
  20552. {
  20553. }
  20554. forcedinline uint32 getARGB() const throw() { return argb; }
  20555. forcedinline uint32 getUnpremultipliedARGB() const throw() { PixelARGB p (argb); p.unpremultiply(); return p.getARGB(); }
  20556. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  20557. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  20558. forcedinline uint8 getAlpha() const throw() { return components.a; }
  20559. forcedinline uint8 getRed() const throw() { return components.r; }
  20560. forcedinline uint8 getGreen() const throw() { return components.g; }
  20561. forcedinline uint8 getBlue() const throw() { return components.b; }
  20562. /** Blends another pixel onto this one.
  20563. This takes into account the opacity of the pixel being overlaid, and blends
  20564. it accordingly.
  20565. */
  20566. forcedinline void blend (const PixelARGB& src) throw()
  20567. {
  20568. uint32 sargb = src.getARGB();
  20569. const uint32 alpha = 0x100 - (sargb >> 24);
  20570. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  20571. sargb += 0xff00ff00 & (getAG() * alpha);
  20572. argb = sargb;
  20573. }
  20574. /** Blends another pixel onto this one.
  20575. This takes into account the opacity of the pixel being overlaid, and blends
  20576. it accordingly.
  20577. */
  20578. forcedinline void blend (const PixelAlpha& src) throw();
  20579. /** Blends another pixel onto this one.
  20580. This takes into account the opacity of the pixel being overlaid, and blends
  20581. it accordingly.
  20582. */
  20583. forcedinline void blend (const PixelRGB& src) throw();
  20584. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  20585. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  20586. being used, so this can blend semi-transparently from a PixelRGB argument.
  20587. */
  20588. template <class Pixel>
  20589. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  20590. {
  20591. ++extraAlpha;
  20592. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  20593. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  20594. const uint32 alpha = 0x100 - (sargb >> 24);
  20595. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  20596. sargb += 0xff00ff00 & (getAG() * alpha);
  20597. argb = sargb;
  20598. }
  20599. /** Blends another pixel with this one, creating a colour that is somewhere
  20600. between the two, as specified by the amount.
  20601. */
  20602. template <class Pixel>
  20603. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  20604. {
  20605. uint32 drb = getRB();
  20606. drb += (((src.getRB() - drb) * amount) >> 8);
  20607. drb &= 0x00ff00ff;
  20608. uint32 dag = getAG();
  20609. dag += (((src.getAG() - dag) * amount) >> 8);
  20610. dag &= 0x00ff00ff;
  20611. dag <<= 8;
  20612. dag |= drb;
  20613. argb = dag;
  20614. }
  20615. /** Copies another pixel colour over this one.
  20616. This doesn't blend it - this colour is simply replaced by the other one.
  20617. */
  20618. template <class Pixel>
  20619. forcedinline void set (const Pixel& src) throw()
  20620. {
  20621. argb = src.getARGB();
  20622. }
  20623. /** Replaces the colour's alpha value with another one. */
  20624. forcedinline void setAlpha (const uint8 newAlpha) throw()
  20625. {
  20626. components.a = newAlpha;
  20627. }
  20628. /** Multiplies the colour's alpha value with another one. */
  20629. forcedinline void multiplyAlpha (int multiplier) throw()
  20630. {
  20631. ++multiplier;
  20632. argb = ((multiplier * getAG()) & 0xff00ff00)
  20633. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  20634. }
  20635. forcedinline void multiplyAlpha (const float multiplier) throw()
  20636. {
  20637. multiplyAlpha ((int) (multiplier * 256.0f));
  20638. }
  20639. /** Sets the pixel's colour from individual components. */
  20640. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  20641. {
  20642. components.b = b;
  20643. components.g = g;
  20644. components.r = r;
  20645. components.a = a;
  20646. }
  20647. /** Premultiplies the pixel's RGB values by its alpha. */
  20648. forcedinline void premultiply() throw()
  20649. {
  20650. const uint32 alpha = components.a;
  20651. if (alpha < 0xff)
  20652. {
  20653. if (alpha == 0)
  20654. {
  20655. components.b = 0;
  20656. components.g = 0;
  20657. components.r = 0;
  20658. }
  20659. else
  20660. {
  20661. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  20662. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  20663. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  20664. }
  20665. }
  20666. }
  20667. /** Unpremultiplies the pixel's RGB values. */
  20668. forcedinline void unpremultiply() throw()
  20669. {
  20670. const uint32 alpha = components.a;
  20671. if (alpha < 0xff)
  20672. {
  20673. if (alpha == 0)
  20674. {
  20675. components.b = 0;
  20676. components.g = 0;
  20677. components.r = 0;
  20678. }
  20679. else
  20680. {
  20681. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  20682. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  20683. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  20684. }
  20685. }
  20686. }
  20687. forcedinline void desaturate() throw()
  20688. {
  20689. if (components.a < 0xff && components.a > 0)
  20690. {
  20691. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  20692. components.r = components.g = components.b
  20693. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  20694. }
  20695. else
  20696. {
  20697. components.r = components.g = components.b
  20698. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  20699. }
  20700. }
  20701. /** The indexes of the different components in the byte layout of this type of colour. */
  20702. #if JUCE_BIG_ENDIAN
  20703. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  20704. #else
  20705. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  20706. #endif
  20707. private:
  20708. union
  20709. {
  20710. uint32 argb;
  20711. struct
  20712. {
  20713. #if JUCE_BIG_ENDIAN
  20714. uint8 a : 8, r : 8, g : 8, b : 8;
  20715. #else
  20716. uint8 b, g, r, a;
  20717. #endif
  20718. } PACKED components;
  20719. };
  20720. }
  20721. #ifndef DOXYGEN
  20722. PACKED
  20723. #endif
  20724. ;
  20725. /**
  20726. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  20727. This is used internally by the imaging classes.
  20728. @see PixelARGB
  20729. */
  20730. class JUCE_API PixelRGB
  20731. {
  20732. public:
  20733. /** Creates a pixel without defining its colour. */
  20734. PixelRGB() throw() {}
  20735. ~PixelRGB() throw() {}
  20736. /** Creates a pixel from a 32-bit argb value.
  20737. (The argb format is that used by PixelARGB)
  20738. */
  20739. PixelRGB (const uint32 argb) throw()
  20740. {
  20741. r = (uint8) (argb >> 16);
  20742. g = (uint8) (argb >> 8);
  20743. b = (uint8) (argb);
  20744. }
  20745. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  20746. forcedinline uint32 getUnpremultipliedARGB() const throw() { return getARGB(); }
  20747. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  20748. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  20749. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  20750. forcedinline uint8 getRed() const throw() { return r; }
  20751. forcedinline uint8 getGreen() const throw() { return g; }
  20752. forcedinline uint8 getBlue() const throw() { return b; }
  20753. /** Blends another pixel onto this one.
  20754. This takes into account the opacity of the pixel being overlaid, and blends
  20755. it accordingly.
  20756. */
  20757. forcedinline void blend (const PixelARGB& src) throw()
  20758. {
  20759. uint32 sargb = src.getARGB();
  20760. const uint32 alpha = 0x100 - (sargb >> 24);
  20761. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  20762. sargb += 0x0000ff00 & (g * alpha);
  20763. r = (uint8) (sargb >> 16);
  20764. g = (uint8) (sargb >> 8);
  20765. b = (uint8) sargb;
  20766. }
  20767. forcedinline void blend (const PixelRGB& src) throw()
  20768. {
  20769. set (src);
  20770. }
  20771. forcedinline void blend (const PixelAlpha& src) throw();
  20772. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  20773. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  20774. being used, so this can blend semi-transparently from a PixelRGB argument.
  20775. */
  20776. template <class Pixel>
  20777. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  20778. {
  20779. ++extraAlpha;
  20780. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  20781. const uint32 sag = extraAlpha * src.getAG();
  20782. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  20783. const uint32 alpha = 0x100 - (sargb >> 24);
  20784. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  20785. sargb += 0x0000ff00 & (g * alpha);
  20786. b = (uint8) sargb;
  20787. g = (uint8) (sargb >> 8);
  20788. r = (uint8) (sargb >> 16);
  20789. }
  20790. /** Blends another pixel with this one, creating a colour that is somewhere
  20791. between the two, as specified by the amount.
  20792. */
  20793. template <class Pixel>
  20794. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  20795. {
  20796. uint32 drb = getRB();
  20797. drb += (((src.getRB() - drb) * amount) >> 8);
  20798. uint32 dag = getAG();
  20799. dag += (((src.getAG() - dag) * amount) >> 8);
  20800. b = (uint8) drb;
  20801. g = (uint8) dag;
  20802. r = (uint8) (drb >> 16);
  20803. }
  20804. /** Copies another pixel colour over this one.
  20805. This doesn't blend it - this colour is simply replaced by the other one.
  20806. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  20807. is thrown away.
  20808. */
  20809. template <class Pixel>
  20810. forcedinline void set (const Pixel& src) throw()
  20811. {
  20812. b = src.getBlue();
  20813. g = src.getGreen();
  20814. r = src.getRed();
  20815. }
  20816. /** This method is included for compatibility with the PixelARGB class. */
  20817. forcedinline void setAlpha (const uint8) throw() {}
  20818. /** Multiplies the colour's alpha value with another one. */
  20819. forcedinline void multiplyAlpha (int) throw() {}
  20820. /** Sets the pixel's colour from individual components. */
  20821. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  20822. {
  20823. r = r_;
  20824. g = g_;
  20825. b = b_;
  20826. }
  20827. /** Premultiplies the pixel's RGB values by its alpha. */
  20828. forcedinline void premultiply() throw() {}
  20829. /** Unpremultiplies the pixel's RGB values. */
  20830. forcedinline void unpremultiply() throw() {}
  20831. forcedinline void desaturate() throw()
  20832. {
  20833. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  20834. }
  20835. /** The indexes of the different components in the byte layout of this type of colour. */
  20836. #if JUCE_MAC
  20837. enum { indexR = 0, indexG = 1, indexB = 2 };
  20838. #else
  20839. enum { indexR = 2, indexG = 1, indexB = 0 };
  20840. #endif
  20841. private:
  20842. #if JUCE_MAC
  20843. uint8 r, g, b;
  20844. #else
  20845. uint8 b, g, r;
  20846. #endif
  20847. }
  20848. #ifndef DOXYGEN
  20849. PACKED
  20850. #endif
  20851. ;
  20852. forcedinline void PixelARGB::blend (const PixelRGB& src) throw()
  20853. {
  20854. set (src);
  20855. }
  20856. /**
  20857. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  20858. This is used internally by the imaging classes.
  20859. @see PixelARGB, PixelRGB
  20860. */
  20861. class JUCE_API PixelAlpha
  20862. {
  20863. public:
  20864. /** Creates a pixel without defining its colour. */
  20865. PixelAlpha() throw() {}
  20866. ~PixelAlpha() throw() {}
  20867. /** Creates a pixel from a 32-bit argb value.
  20868. (The argb format is that used by PixelARGB)
  20869. */
  20870. PixelAlpha (const uint32 argb) throw()
  20871. {
  20872. a = (uint8) (argb >> 24);
  20873. }
  20874. forcedinline uint32 getARGB() const throw() { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  20875. forcedinline uint32 getUnpremultipliedARGB() const throw() { return (((uint32) a) << 24) | 0xffffff; }
  20876. forcedinline uint32 getRB() const throw() { return (((uint32) a) << 16) | a; }
  20877. forcedinline uint32 getAG() const throw() { return (((uint32) a) << 16) | a; }
  20878. forcedinline uint8 getAlpha() const throw() { return a; }
  20879. forcedinline uint8 getRed() const throw() { return 0; }
  20880. forcedinline uint8 getGreen() const throw() { return 0; }
  20881. forcedinline uint8 getBlue() const throw() { return 0; }
  20882. /** Blends another pixel onto this one.
  20883. This takes into account the opacity of the pixel being overlaid, and blends
  20884. it accordingly.
  20885. */
  20886. template <class Pixel>
  20887. forcedinline void blend (const Pixel& src) throw()
  20888. {
  20889. const int srcA = src.getAlpha();
  20890. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  20891. }
  20892. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  20893. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  20894. being used, so this can blend semi-transparently from a PixelRGB argument.
  20895. */
  20896. template <class Pixel>
  20897. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  20898. {
  20899. ++extraAlpha;
  20900. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  20901. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  20902. }
  20903. /** Blends another pixel with this one, creating a colour that is somewhere
  20904. between the two, as specified by the amount.
  20905. */
  20906. template <class Pixel>
  20907. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  20908. {
  20909. a += ((src,getAlpha() - a) * amount) >> 8;
  20910. }
  20911. /** Copies another pixel colour over this one.
  20912. This doesn't blend it - this colour is simply replaced by the other one.
  20913. */
  20914. template <class Pixel>
  20915. forcedinline void set (const Pixel& src) throw()
  20916. {
  20917. a = src.getAlpha();
  20918. }
  20919. /** Replaces the colour's alpha value with another one. */
  20920. forcedinline void setAlpha (const uint8 newAlpha) throw()
  20921. {
  20922. a = newAlpha;
  20923. }
  20924. /** Multiplies the colour's alpha value with another one. */
  20925. forcedinline void multiplyAlpha (int multiplier) throw()
  20926. {
  20927. ++multiplier;
  20928. a = (uint8) ((a * multiplier) >> 8);
  20929. }
  20930. forcedinline void multiplyAlpha (const float multiplier) throw()
  20931. {
  20932. a = (uint8) (a * multiplier);
  20933. }
  20934. /** Sets the pixel's colour from individual components. */
  20935. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) throw()
  20936. {
  20937. a = a_;
  20938. }
  20939. /** Premultiplies the pixel's RGB values by its alpha. */
  20940. forcedinline void premultiply() throw()
  20941. {
  20942. }
  20943. /** Unpremultiplies the pixel's RGB values. */
  20944. forcedinline void unpremultiply() throw()
  20945. {
  20946. }
  20947. forcedinline void desaturate() throw()
  20948. {
  20949. }
  20950. /** The indexes of the different components in the byte layout of this type of colour. */
  20951. enum { indexA = 0 };
  20952. private:
  20953. uint8 a : 8;
  20954. }
  20955. #ifndef DOXYGEN
  20956. PACKED
  20957. #endif
  20958. ;
  20959. forcedinline void PixelRGB::blend (const PixelAlpha& src) throw()
  20960. {
  20961. blend (PixelARGB (src.getARGB()));
  20962. }
  20963. forcedinline void PixelARGB::blend (const PixelAlpha& src) throw()
  20964. {
  20965. uint32 sargb = src.getARGB();
  20966. const uint32 alpha = 0x100 - (sargb >> 24);
  20967. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  20968. sargb += 0xff00ff00 & (getAG() * alpha);
  20969. argb = sargb;
  20970. }
  20971. #if JUCE_MSVC
  20972. #pragma pack (pop)
  20973. #endif
  20974. #undef PACKED
  20975. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  20976. /*** End of inlined file: juce_PixelFormats.h ***/
  20977. /**
  20978. Represents a colour, also including a transparency value.
  20979. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  20980. */
  20981. class JUCE_API Colour
  20982. {
  20983. public:
  20984. /** Creates a transparent black colour. */
  20985. Colour() throw();
  20986. /** Creates a copy of another Colour object. */
  20987. Colour (const Colour& other) throw();
  20988. /** Creates a colour from a 32-bit ARGB value.
  20989. The format of this number is:
  20990. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  20991. All components in the range 0x00 to 0xff.
  20992. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  20993. @see getPixelARGB
  20994. */
  20995. explicit Colour (uint32 argb) throw();
  20996. /** Creates an opaque colour using 8-bit red, green and blue values */
  20997. Colour (uint8 red,
  20998. uint8 green,
  20999. uint8 blue) throw();
  21000. /** Creates an opaque colour using 8-bit red, green and blue values */
  21001. static const Colour fromRGB (uint8 red,
  21002. uint8 green,
  21003. uint8 blue) throw();
  21004. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21005. Colour (uint8 red,
  21006. uint8 green,
  21007. uint8 blue,
  21008. uint8 alpha) throw();
  21009. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  21010. static const Colour fromRGBA (uint8 red,
  21011. uint8 green,
  21012. uint8 blue,
  21013. uint8 alpha) throw();
  21014. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  21015. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  21016. Values outside the valid range will be clipped.
  21017. */
  21018. Colour (uint8 red,
  21019. uint8 green,
  21020. uint8 blue,
  21021. float alpha) throw();
  21022. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  21023. static const Colour fromRGBAFloat (uint8 red,
  21024. uint8 green,
  21025. uint8 blue,
  21026. float alpha) throw();
  21027. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21028. The floating point values must be between 0.0 and 1.0.
  21029. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21030. Values outside the valid range will be clipped.
  21031. */
  21032. Colour (float hue,
  21033. float saturation,
  21034. float brightness,
  21035. uint8 alpha) throw();
  21036. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  21037. All values must be between 0.0 and 1.0.
  21038. Numbers outside the valid range will be clipped.
  21039. */
  21040. Colour (float hue,
  21041. float saturation,
  21042. float brightness,
  21043. float alpha) throw();
  21044. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  21045. The floating point values must be between 0.0 and 1.0.
  21046. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  21047. Values outside the valid range will be clipped.
  21048. */
  21049. static const Colour fromHSV (float hue,
  21050. float saturation,
  21051. float brightness,
  21052. float alpha) throw();
  21053. /** Destructor. */
  21054. ~Colour() throw();
  21055. /** Copies another Colour object. */
  21056. Colour& operator= (const Colour& other) throw();
  21057. /** Compares two colours. */
  21058. bool operator== (const Colour& other) const throw();
  21059. /** Compares two colours. */
  21060. bool operator!= (const Colour& other) const throw();
  21061. /** Returns the red component of this colour.
  21062. @returns a value between 0x00 and 0xff.
  21063. */
  21064. uint8 getRed() const throw() { return argb.getRed(); }
  21065. /** Returns the green component of this colour.
  21066. @returns a value between 0x00 and 0xff.
  21067. */
  21068. uint8 getGreen() const throw() { return argb.getGreen(); }
  21069. /** Returns the blue component of this colour.
  21070. @returns a value between 0x00 and 0xff.
  21071. */
  21072. uint8 getBlue() const throw() { return argb.getBlue(); }
  21073. /** Returns the red component of this colour as a floating point value.
  21074. @returns a value between 0.0 and 1.0
  21075. */
  21076. float getFloatRed() const throw();
  21077. /** Returns the green component of this colour as a floating point value.
  21078. @returns a value between 0.0 and 1.0
  21079. */
  21080. float getFloatGreen() const throw();
  21081. /** Returns the blue component of this colour as a floating point value.
  21082. @returns a value between 0.0 and 1.0
  21083. */
  21084. float getFloatBlue() const throw();
  21085. /** Returns a premultiplied ARGB pixel object that represents this colour.
  21086. */
  21087. const PixelARGB getPixelARGB() const throw();
  21088. /** Returns a 32-bit integer that represents this colour.
  21089. The format of this number is:
  21090. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  21091. */
  21092. uint32 getARGB() const throw();
  21093. /** Returns the colour's alpha (opacity).
  21094. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  21095. */
  21096. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  21097. /** Returns the colour's alpha (opacity) as a floating point value.
  21098. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  21099. */
  21100. float getFloatAlpha() const throw();
  21101. /** Returns true if this colour is completely opaque.
  21102. Equivalent to (getAlpha() == 0xff).
  21103. */
  21104. bool isOpaque() const throw();
  21105. /** Returns true if this colour is completely transparent.
  21106. Equivalent to (getAlpha() == 0x00).
  21107. */
  21108. bool isTransparent() const throw();
  21109. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21110. const Colour withAlpha (uint8 newAlpha) const throw();
  21111. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  21112. const Colour withAlpha (float newAlpha) const throw();
  21113. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  21114. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  21115. */
  21116. const Colour withMultipliedAlpha (float alphaMultiplier) const throw();
  21117. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  21118. If the foreground colour is semi-transparent, it is blended onto this colour
  21119. accordingly.
  21120. */
  21121. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  21122. /** Returns a colour that lies somewhere between this one and another.
  21123. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  21124. is 1.0, the result is 100% of the other colour.
  21125. */
  21126. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const throw();
  21127. /** Returns the colour's hue component.
  21128. The value returned is in the range 0.0 to 1.0
  21129. */
  21130. float getHue() const throw();
  21131. /** Returns the colour's saturation component.
  21132. The value returned is in the range 0.0 to 1.0
  21133. */
  21134. float getSaturation() const throw();
  21135. /** Returns the colour's brightness component.
  21136. The value returned is in the range 0.0 to 1.0
  21137. */
  21138. float getBrightness() const throw();
  21139. /** Returns the colour's hue, saturation and brightness components all at once.
  21140. The values returned are in the range 0.0 to 1.0
  21141. */
  21142. void getHSB (float& hue,
  21143. float& saturation,
  21144. float& brightness) const throw();
  21145. /** Returns a copy of this colour with a different hue. */
  21146. const Colour withHue (float newHue) const throw();
  21147. /** Returns a copy of this colour with a different saturation. */
  21148. const Colour withSaturation (float newSaturation) const throw();
  21149. /** Returns a copy of this colour with a different brightness.
  21150. @see brighter, darker, withMultipliedBrightness
  21151. */
  21152. const Colour withBrightness (float newBrightness) const throw();
  21153. /** Returns a copy of this colour with it hue rotated.
  21154. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  21155. @see brighter, darker, withMultipliedBrightness
  21156. */
  21157. const Colour withRotatedHue (float amountToRotate) const throw();
  21158. /** Returns a copy of this colour with its saturation multiplied by the given value.
  21159. The new colour's saturation is (this->getSaturation() * multiplier)
  21160. (the result is clipped to legal limits).
  21161. */
  21162. const Colour withMultipliedSaturation (float multiplier) const throw();
  21163. /** Returns a copy of this colour with its brightness multiplied by the given value.
  21164. The new colour's saturation is (this->getBrightness() * multiplier)
  21165. (the result is clipped to legal limits).
  21166. */
  21167. const Colour withMultipliedBrightness (float amount) const throw();
  21168. /** Returns a brighter version of this colour.
  21169. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  21170. unchanged, and higher values make it brighter
  21171. @see withMultipliedBrightness
  21172. */
  21173. const Colour brighter (float amountBrighter = 0.4f) const throw();
  21174. /** Returns a darker version of this colour.
  21175. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  21176. unchanged, and higher values make it darker
  21177. @see withMultipliedBrightness
  21178. */
  21179. const Colour darker (float amountDarker = 0.4f) const throw();
  21180. /** Returns a colour that will be clearly visible against this colour.
  21181. The amount parameter indicates how contrasting the new colour should
  21182. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  21183. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  21184. return white; Colours::white.contrasting (1.0f) will return black, etc.
  21185. */
  21186. const Colour contrasting (float amount = 1.0f) const throw();
  21187. /** Returns a colour that contrasts against two colours.
  21188. Looks for a colour that contrasts with both of the colours passed-in.
  21189. Handy for things like choosing a highlight colour in text editors, etc.
  21190. */
  21191. static const Colour contrasting (const Colour& colour1,
  21192. const Colour& colour2) throw();
  21193. /** Returns an opaque shade of grey.
  21194. @param brightness the level of grey to return - 0 is black, 1.0 is white
  21195. */
  21196. static const Colour greyLevel (float brightness) throw();
  21197. /** Returns a stringified version of this colour.
  21198. The string can be turned back into a colour using the fromString() method.
  21199. */
  21200. const String toString() const;
  21201. /** Reads the colour from a string that was created with toString().
  21202. */
  21203. static const Colour fromString (const String& encodedColourString);
  21204. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  21205. const String toDisplayString (bool includeAlphaValue) const;
  21206. private:
  21207. PixelARGB argb;
  21208. };
  21209. #endif // __JUCE_COLOUR_JUCEHEADER__
  21210. /*** End of inlined file: juce_Colour.h ***/
  21211. /**
  21212. Contains a set of predefined named colours (mostly standard HTML colours)
  21213. @see Colour, Colours::greyLevel
  21214. */
  21215. class Colours
  21216. {
  21217. public:
  21218. static JUCE_API const Colour
  21219. transparentBlack, /**< ARGB = 0x00000000 */
  21220. transparentWhite, /**< ARGB = 0x00ffffff */
  21221. black, /**< ARGB = 0xff000000 */
  21222. white, /**< ARGB = 0xffffffff */
  21223. blue, /**< ARGB = 0xff0000ff */
  21224. grey, /**< ARGB = 0xff808080 */
  21225. green, /**< ARGB = 0xff008000 */
  21226. red, /**< ARGB = 0xffff0000 */
  21227. yellow, /**< ARGB = 0xffffff00 */
  21228. aliceblue, antiquewhite, aqua, aquamarine,
  21229. azure, beige, bisque, blanchedalmond,
  21230. blueviolet, brown, burlywood, cadetblue,
  21231. chartreuse, chocolate, coral, cornflowerblue,
  21232. cornsilk, crimson, cyan, darkblue,
  21233. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  21234. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  21235. darkorchid, darkred, darksalmon, darkseagreen,
  21236. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  21237. deeppink, deepskyblue, dimgrey, dodgerblue,
  21238. firebrick, floralwhite, forestgreen, fuchsia,
  21239. gainsboro, gold, goldenrod, greenyellow,
  21240. honeydew, hotpink, indianred, indigo,
  21241. ivory, khaki, lavender, lavenderblush,
  21242. lemonchiffon, lightblue, lightcoral, lightcyan,
  21243. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  21244. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  21245. lightsteelblue, lightyellow, lime, limegreen,
  21246. linen, magenta, maroon, mediumaquamarine,
  21247. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  21248. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  21249. midnightblue, mintcream, mistyrose, navajowhite,
  21250. navy, oldlace, olive, olivedrab,
  21251. orange, orangered, orchid, palegoldenrod,
  21252. palegreen, paleturquoise, palevioletred, papayawhip,
  21253. peachpuff, peru, pink, plum,
  21254. powderblue, purple, rosybrown, royalblue,
  21255. saddlebrown, salmon, sandybrown, seagreen,
  21256. seashell, sienna, silver, skyblue,
  21257. slateblue, slategrey, snow, springgreen,
  21258. steelblue, tan, teal, thistle,
  21259. tomato, turquoise, violet, wheat,
  21260. whitesmoke, yellowgreen;
  21261. /** Attempts to look up a string in the list of known colour names, and return
  21262. the appropriate colour.
  21263. A non-case-sensitive search is made of the list of predefined colours, and
  21264. if a match is found, that colour is returned. If no match is found, the
  21265. colour passed in as the defaultColour parameter is returned.
  21266. */
  21267. static JUCE_API const Colour findColourForName (const String& colourName,
  21268. const Colour& defaultColour);
  21269. private:
  21270. // this isn't a class you should ever instantiate - it's just here for the
  21271. // static values in it.
  21272. Colours();
  21273. JUCE_DECLARE_NON_COPYABLE (Colours);
  21274. };
  21275. #endif // __JUCE_COLOURS_JUCEHEADER__
  21276. /*** End of inlined file: juce_Colours.h ***/
  21277. /*** Start of inlined file: juce_ColourGradient.h ***/
  21278. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  21279. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  21280. /**
  21281. Describes the layout and colours that should be used to paint a colour gradient.
  21282. @see Graphics::setGradientFill
  21283. */
  21284. class JUCE_API ColourGradient
  21285. {
  21286. public:
  21287. /** Creates a gradient object.
  21288. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  21289. colour2 should be. In between them there's a gradient.
  21290. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  21291. its centre.
  21292. The alpha transparencies of the colours are used, so note that
  21293. if you blend from transparent to a solid colour, the RGB of the transparent
  21294. colour will become visible in parts of the gradient. e.g. blending
  21295. from Colour::transparentBlack to Colours::white will produce a
  21296. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  21297. will be white all the way across.
  21298. @see ColourGradient
  21299. */
  21300. ColourGradient (const Colour& colour1, float x1, float y1,
  21301. const Colour& colour2, float x2, float y2,
  21302. bool isRadial);
  21303. /** Creates an uninitialised gradient.
  21304. If you use this constructor instead of the other one, be sure to set all the
  21305. object's public member variables before using it!
  21306. */
  21307. ColourGradient() throw();
  21308. /** Destructor */
  21309. ~ColourGradient();
  21310. /** Removes any colours that have been added.
  21311. This will also remove any start and end colours, so the gradient won't work. You'll
  21312. need to add more colours with addColour().
  21313. */
  21314. void clearColours();
  21315. /** Adds a colour at a point along the length of the gradient.
  21316. This allows the gradient to go through a spectrum of colours, instead of just a
  21317. start and end colour.
  21318. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  21319. of the distance along the line between the two points
  21320. at which the colour should occur.
  21321. @param colour the colour that should be used at this point
  21322. @returns the index at which the new point was added
  21323. */
  21324. int addColour (double proportionAlongGradient,
  21325. const Colour& colour);
  21326. /** Removes one of the colours from the gradient. */
  21327. void removeColour (int index);
  21328. /** Multiplies the alpha value of all the colours by the given scale factor */
  21329. void multiplyOpacity (float multiplier) throw();
  21330. /** Returns the number of colour-stops that have been added. */
  21331. int getNumColours() const throw();
  21332. /** Returns the position along the length of the gradient of the colour with this index.
  21333. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  21334. */
  21335. double getColourPosition (int index) const throw();
  21336. /** Returns the colour that was added with a given index.
  21337. The index is from 0 to getNumColours() - 1.
  21338. */
  21339. const Colour getColour (int index) const throw();
  21340. /** Changes the colour at a given index.
  21341. The index is from 0 to getNumColours() - 1.
  21342. */
  21343. void setColour (int index, const Colour& newColour) throw();
  21344. /** Returns the an interpolated colour at any position along the gradient.
  21345. @param position the position along the gradient, between 0 and 1
  21346. */
  21347. const Colour getColourAtPosition (double position) const throw();
  21348. /** Creates a set of interpolated premultiplied ARGB values.
  21349. This will resize the HeapBlock, fill it with the colours, and will return the number of
  21350. colours that it added.
  21351. */
  21352. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  21353. /** Returns true if all colours are opaque. */
  21354. bool isOpaque() const throw();
  21355. /** Returns true if all colours are completely transparent. */
  21356. bool isInvisible() const throw();
  21357. Point<float> point1, point2;
  21358. /** If true, the gradient should be filled circularly, centred around
  21359. point1, with point2 defining a point on the circumference.
  21360. If false, the gradient is linear between the two points.
  21361. */
  21362. bool isRadial;
  21363. bool operator== (const ColourGradient& other) const throw();
  21364. bool operator!= (const ColourGradient& other) const throw();
  21365. private:
  21366. struct ColourPoint
  21367. {
  21368. ColourPoint() throw() {}
  21369. ColourPoint (const double position_, const Colour& colour_) throw()
  21370. : position (position_), colour (colour_)
  21371. {}
  21372. bool operator== (const ColourPoint& other) const throw();
  21373. bool operator!= (const ColourPoint& other) const throw();
  21374. double position;
  21375. Colour colour;
  21376. };
  21377. Array <ColourPoint> colours;
  21378. JUCE_LEAK_DETECTOR (ColourGradient);
  21379. };
  21380. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  21381. /*** End of inlined file: juce_ColourGradient.h ***/
  21382. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  21383. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  21384. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  21385. /**
  21386. Defines the method used to postion some kind of rectangular object within
  21387. a rectangular viewport.
  21388. Although similar to Justification, this is more specific, and has some extra
  21389. options.
  21390. */
  21391. class JUCE_API RectanglePlacement
  21392. {
  21393. public:
  21394. /** Creates a RectanglePlacement object using a combination of flags. */
  21395. inline RectanglePlacement (int flags_) throw() : flags (flags_) {}
  21396. /** Creates a copy of another RectanglePlacement object. */
  21397. RectanglePlacement (const RectanglePlacement& other) throw();
  21398. /** Copies another RectanglePlacement object. */
  21399. RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  21400. /** Flag values that can be combined and used in the constructor. */
  21401. enum
  21402. {
  21403. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  21404. xLeft = 1,
  21405. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  21406. xRight = 2,
  21407. /** Indicates that the source should be placed in the centre between the left and right
  21408. sides of the available space. */
  21409. xMid = 4,
  21410. /** Indicates that the source's top edge should be aligned with the top edge of the
  21411. destination rectangle. */
  21412. yTop = 8,
  21413. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  21414. destination rectangle. */
  21415. yBottom = 16,
  21416. /** Indicates that the source should be placed in the centre between the top and bottom
  21417. sides of the available space. */
  21418. yMid = 32,
  21419. /** If this flag is set, then the source rectangle will be resized to completely fill
  21420. the destination rectangle, and all other flags are ignored.
  21421. */
  21422. stretchToFit = 64,
  21423. /** If this flag is set, then the source rectangle will be resized so that it is the
  21424. minimum size to completely fill the destination rectangle, without changing its
  21425. aspect ratio. This means that some of the source rectangle may fall outside
  21426. the destination.
  21427. If this flag is not set, the source will be given the maximum size at which none
  21428. of it falls outside the destination rectangle.
  21429. */
  21430. fillDestination = 128,
  21431. /** Indicates that the source rectangle can be reduced in size if required, but should
  21432. never be made larger than its original size.
  21433. */
  21434. onlyReduceInSize = 256,
  21435. /** Indicates that the source rectangle can be enlarged if required, but should
  21436. never be made smaller than its original size.
  21437. */
  21438. onlyIncreaseInSize = 512,
  21439. /** Indicates that the source rectangle's size should be left unchanged.
  21440. */
  21441. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  21442. /** A shorthand value that is equivalent to (xMid | yMid). */
  21443. centred = 4 + 32
  21444. };
  21445. /** Returns the raw flags that are set for this object. */
  21446. inline int getFlags() const throw() { return flags; }
  21447. /** Tests a set of flags for this object.
  21448. @returns true if any of the flags passed in are set on this object.
  21449. */
  21450. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  21451. /** Adjusts the position and size of a rectangle to fit it into a space.
  21452. The source rectangle co-ordinates will be adjusted so that they fit into
  21453. the destination rectangle based on this object's flags.
  21454. */
  21455. void applyTo (double& sourceX,
  21456. double& sourceY,
  21457. double& sourceW,
  21458. double& sourceH,
  21459. double destinationX,
  21460. double destinationY,
  21461. double destinationW,
  21462. double destinationH) const throw();
  21463. /** Returns the transform that should be applied to these source co-ordinates to fit them
  21464. into the destination rectangle using the current flags.
  21465. */
  21466. template <typename ValueType>
  21467. const Rectangle<ValueType> appliedTo (const Rectangle<ValueType>& source,
  21468. const Rectangle<ValueType>& destination) const throw()
  21469. {
  21470. double x = source.getX(), y = source.getY(), w = source.getWidth(), h = source.getHeight();
  21471. applyTo (x, y, w, h, static_cast <double> (destination.getX()), static_cast <double> (destination.getY()),
  21472. static_cast <double> (destination.getWidth()), static_cast <double> (destination.getHeight()));
  21473. return Rectangle<ValueType> (static_cast <ValueType> (x), static_cast <ValueType> (y),
  21474. static_cast <ValueType> (w), static_cast <ValueType> (h));
  21475. }
  21476. /** Returns the transform that should be applied to these source co-ordinates to fit them
  21477. into the destination rectangle using the current flags.
  21478. */
  21479. const AffineTransform getTransformToFit (const Rectangle<float>& source,
  21480. const Rectangle<float>& destination) const throw();
  21481. private:
  21482. int flags;
  21483. };
  21484. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  21485. /*** End of inlined file: juce_RectanglePlacement.h ***/
  21486. class LowLevelGraphicsContext;
  21487. class Image;
  21488. class FillType;
  21489. class RectangleList;
  21490. /**
  21491. A graphics context, used for drawing a component or image.
  21492. When a Component needs painting, a Graphics context is passed to its
  21493. Component::paint() method, and this you then call methods within this
  21494. object to actually draw the component's content.
  21495. A Graphics can also be created from an image, to allow drawing directly onto
  21496. that image.
  21497. @see Component::paint
  21498. */
  21499. class JUCE_API Graphics
  21500. {
  21501. public:
  21502. /** Creates a Graphics object to draw directly onto the given image.
  21503. The graphics object that is created will be set up to draw onto the image,
  21504. with the context's clipping area being the entire size of the image, and its
  21505. origin being the image's origin. To draw into a subsection of an image, use the
  21506. reduceClipRegion() and setOrigin() methods.
  21507. Obviously you shouldn't delete the image before this context is deleted.
  21508. */
  21509. explicit Graphics (const Image& imageToDrawOnto);
  21510. /** Destructor. */
  21511. ~Graphics();
  21512. /** Changes the current drawing colour.
  21513. This sets the colour that will now be used for drawing operations - it also
  21514. sets the opacity to that of the colour passed-in.
  21515. If a brush is being used when this method is called, the brush will be deselected,
  21516. and any subsequent drawing will be done with a solid colour brush instead.
  21517. @see setOpacity
  21518. */
  21519. void setColour (const Colour& newColour);
  21520. /** Changes the opacity to use with the current colour.
  21521. If a solid colour is being used for drawing, this changes its opacity
  21522. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  21523. If a gradient is being used, this will have no effect on it.
  21524. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  21525. */
  21526. void setOpacity (float newOpacity);
  21527. /** Sets the context to use a gradient for its fill pattern.
  21528. */
  21529. void setGradientFill (const ColourGradient& gradient);
  21530. /** Sets the context to use a tiled image pattern for filling.
  21531. Make sure that you don't delete this image while it's still being used by
  21532. this context!
  21533. */
  21534. void setTiledImageFill (const Image& imageToUse,
  21535. int anchorX, int anchorY,
  21536. float opacity);
  21537. /** Changes the current fill settings.
  21538. @see setColour, setGradientFill, setTiledImageFill
  21539. */
  21540. void setFillType (const FillType& newFill);
  21541. /** Changes the font to use for subsequent text-drawing functions.
  21542. Note there's also a setFont (float, int) method to quickly change the size and
  21543. style of the current font.
  21544. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  21545. */
  21546. void setFont (const Font& newFont);
  21547. /** Changes the size and style of the currently-selected font.
  21548. This is a convenient shortcut that changes the context's current font to a
  21549. different size or style. The typeface won't be changed.
  21550. @see Font
  21551. */
  21552. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  21553. /** Returns the currently selected font. */
  21554. const Font getCurrentFont() const;
  21555. /** Draws a one-line text string.
  21556. This will use the current colour (or brush) to fill the text. The font is the last
  21557. one specified by setFont().
  21558. @param text the string to draw
  21559. @param startX the position to draw the left-hand edge of the text
  21560. @param baselineY the position of the text's baseline
  21561. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  21562. */
  21563. void drawSingleLineText (const String& text,
  21564. int startX, int baselineY) const;
  21565. /** Draws text across multiple lines.
  21566. This will break the text onto a new line where there's a new-line or
  21567. carriage-return character, or at a word-boundary when the text becomes wider
  21568. than the size specified by the maximumLineWidth parameter.
  21569. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  21570. */
  21571. void drawMultiLineText (const String& text,
  21572. int startX, int baselineY,
  21573. int maximumLineWidth) const;
  21574. /** Renders a string of text as a vector path.
  21575. This allows a string to be transformed with an arbitrary AffineTransform and
  21576. rendered using the current colour/brush. It's much slower than the normal text methods
  21577. but more accurate.
  21578. @see setFont
  21579. */
  21580. void drawTextAsPath (const String& text,
  21581. const AffineTransform& transform) const;
  21582. /** Draws a line of text within a specified rectangle.
  21583. The text will be positioned within the rectangle based on the justification
  21584. flags passed-in. If the string is too long to fit inside the rectangle, it will
  21585. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  21586. flag is true).
  21587. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  21588. */
  21589. void drawText (const String& text,
  21590. int x, int y, int width, int height,
  21591. const Justification& justificationType,
  21592. bool useEllipsesIfTooBig) const;
  21593. /** Tries to draw a text string inside a given space.
  21594. This does its best to make the given text readable within the specified rectangle,
  21595. so it useful for labelling things.
  21596. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  21597. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  21598. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  21599. it's been truncated.
  21600. A Justification parameter lets you specify how the text is laid out within the rectangle,
  21601. both horizontally and vertically.
  21602. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  21603. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  21604. can set this value to 1.0f.
  21605. @see GlyphArrangement::addFittedText
  21606. */
  21607. void drawFittedText (const String& text,
  21608. int x, int y, int width, int height,
  21609. const Justification& justificationFlags,
  21610. int maximumNumberOfLines,
  21611. float minimumHorizontalScale = 0.7f) const;
  21612. /** Fills the context's entire clip region with the current colour or brush.
  21613. (See also the fillAll (const Colour&) method which is a quick way of filling
  21614. it with a given colour).
  21615. */
  21616. void fillAll() const;
  21617. /** Fills the context's entire clip region with a given colour.
  21618. This leaves the context's current colour and brush unchanged, it just
  21619. uses the specified colour temporarily.
  21620. */
  21621. void fillAll (const Colour& colourToUse) const;
  21622. /** Fills a rectangle with the current colour or brush.
  21623. @see drawRect, fillRoundedRectangle
  21624. */
  21625. void fillRect (int x, int y, int width, int height) const;
  21626. /** Fills a rectangle with the current colour or brush. */
  21627. void fillRect (const Rectangle<int>& rectangle) const;
  21628. /** Fills a rectangle with the current colour or brush.
  21629. This uses sub-pixel positioning so is slower than the fillRect method which
  21630. takes integer co-ordinates.
  21631. */
  21632. void fillRect (float x, float y, float width, float height) const;
  21633. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  21634. @see drawRoundedRectangle, Path::addRoundedRectangle
  21635. */
  21636. void fillRoundedRectangle (float x, float y, float width, float height,
  21637. float cornerSize) const;
  21638. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  21639. @see drawRoundedRectangle, Path::addRoundedRectangle
  21640. */
  21641. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  21642. float cornerSize) const;
  21643. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  21644. */
  21645. void fillCheckerBoard (const Rectangle<int>& area,
  21646. int checkWidth, int checkHeight,
  21647. const Colour& colour1, const Colour& colour2) const;
  21648. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  21649. The lines are drawn inside the given rectangle, and greater line thicknesses
  21650. extend inwards.
  21651. @see fillRect
  21652. */
  21653. void drawRect (int x, int y, int width, int height,
  21654. int lineThickness = 1) const;
  21655. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  21656. The lines are drawn inside the given rectangle, and greater line thicknesses
  21657. extend inwards.
  21658. @see fillRect
  21659. */
  21660. void drawRect (float x, float y, float width, float height,
  21661. float lineThickness = 1.0f) const;
  21662. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  21663. The lines are drawn inside the given rectangle, and greater line thicknesses
  21664. extend inwards.
  21665. @see fillRect
  21666. */
  21667. void drawRect (const Rectangle<int>& rectangle,
  21668. int lineThickness = 1) const;
  21669. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  21670. @see fillRoundedRectangle, Path::addRoundedRectangle
  21671. */
  21672. void drawRoundedRectangle (float x, float y, float width, float height,
  21673. float cornerSize, float lineThickness) const;
  21674. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  21675. @see fillRoundedRectangle, Path::addRoundedRectangle
  21676. */
  21677. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  21678. float cornerSize, float lineThickness) const;
  21679. /** Draws a 3D raised (or indented) bevel using two colours.
  21680. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  21681. extend inwards.
  21682. The top-left colour is used for the top- and left-hand edges of the
  21683. bevel; the bottom-right colour is used for the bottom- and right-hand
  21684. edges.
  21685. If useGradient is true, then the bevel fades out to make it look more curved
  21686. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  21687. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  21688. the centre edges are sharp and it fades towards the outside.
  21689. */
  21690. void drawBevel (int x, int y, int width, int height,
  21691. int bevelThickness,
  21692. const Colour& topLeftColour = Colours::white,
  21693. const Colour& bottomRightColour = Colours::black,
  21694. bool useGradient = true,
  21695. bool sharpEdgeOnOutside = true) const;
  21696. /** Draws a pixel using the current colour or brush.
  21697. */
  21698. void setPixel (int x, int y) const;
  21699. /** Fills an ellipse with the current colour or brush.
  21700. The ellipse is drawn to fit inside the given rectangle.
  21701. @see drawEllipse, Path::addEllipse
  21702. */
  21703. void fillEllipse (float x, float y, float width, float height) const;
  21704. /** Draws an elliptical stroke using the current colour or brush.
  21705. @see fillEllipse, Path::addEllipse
  21706. */
  21707. void drawEllipse (float x, float y, float width, float height,
  21708. float lineThickness) const;
  21709. /** Draws a line between two points.
  21710. The line is 1 pixel wide and drawn with the current colour or brush.
  21711. */
  21712. void drawLine (float startX, float startY, float endX, float endY) const;
  21713. /** Draws a line between two points with a given thickness.
  21714. @see Path::addLineSegment
  21715. */
  21716. void drawLine (float startX, float startY, float endX, float endY,
  21717. float lineThickness) const;
  21718. /** Draws a line between two points.
  21719. The line is 1 pixel wide and drawn with the current colour or brush.
  21720. */
  21721. void drawLine (const Line<float>& line) const;
  21722. /** Draws a line between two points with a given thickness.
  21723. @see Path::addLineSegment
  21724. */
  21725. void drawLine (const Line<float>& line, float lineThickness) const;
  21726. /** Draws a dashed line using a custom set of dash-lengths.
  21727. @param line the line to draw
  21728. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  21729. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  21730. draw 6 pixels, skip 7 pixels, and then repeat.
  21731. @param numDashLengths the number of elements in the array (this must be an even number).
  21732. @param lineThickness the thickness of the line to draw
  21733. @param dashIndexToStartFrom the index in the dash-length array to use for the first segment
  21734. @see PathStrokeType::createDashedStroke
  21735. */
  21736. void drawDashedLine (const Line<float>& line,
  21737. const float* dashLengths, int numDashLengths,
  21738. float lineThickness = 1.0f,
  21739. int dashIndexToStartFrom = 0) const;
  21740. /** Draws a vertical line of pixels at a given x position.
  21741. The x position is an integer, but the top and bottom of the line can be sub-pixel
  21742. positions, and these will be anti-aliased if necessary.
  21743. */
  21744. void drawVerticalLine (int x, float top, float bottom) const;
  21745. /** Draws a horizontal line of pixels at a given y position.
  21746. The y position is an integer, but the left and right ends of the line can be sub-pixel
  21747. positions, and these will be anti-aliased if necessary.
  21748. */
  21749. void drawHorizontalLine (int y, float left, float right) const;
  21750. /** Fills a path using the currently selected colour or brush.
  21751. */
  21752. void fillPath (const Path& path,
  21753. const AffineTransform& transform = AffineTransform::identity) const;
  21754. /** Draws a path's outline using the currently selected colour or brush.
  21755. */
  21756. void strokePath (const Path& path,
  21757. const PathStrokeType& strokeType,
  21758. const AffineTransform& transform = AffineTransform::identity) const;
  21759. /** Draws a line with an arrowhead at its end.
  21760. @param line the line to draw
  21761. @param lineThickness the thickness of the line
  21762. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  21763. @param arrowheadLength the length of the arrow head (along the length of the line)
  21764. */
  21765. void drawArrow (const Line<float>& line,
  21766. float lineThickness,
  21767. float arrowheadWidth,
  21768. float arrowheadLength) const;
  21769. /** Types of rendering quality that can be specified when drawing images.
  21770. @see blendImage, Graphics::setImageResamplingQuality
  21771. */
  21772. enum ResamplingQuality
  21773. {
  21774. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  21775. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  21776. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  21777. };
  21778. /** Changes the quality that will be used when resampling images.
  21779. By default a Graphics object will be set to mediumRenderingQuality.
  21780. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  21781. */
  21782. void setImageResamplingQuality (const ResamplingQuality newQuality);
  21783. /** Draws an image.
  21784. This will draw the whole of an image, positioning its top-left corner at the
  21785. given co-ordinates, and keeping its size the same. This is the simplest image
  21786. drawing method - the others give more control over the scaling and clipping
  21787. of the images.
  21788. Images are composited using the context's current opacity, so if you
  21789. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  21790. (or setColour() with an opaque colour) before drawing images.
  21791. */
  21792. void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
  21793. bool fillAlphaChannelWithCurrentBrush = false) const;
  21794. /** Draws part of an image, rescaling it to fit in a given target region.
  21795. The specified area of the source image is rescaled and drawn to fill the
  21796. specifed destination rectangle.
  21797. Images are composited using the context's current opacity, so if you
  21798. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  21799. (or setColour() with an opaque colour) before drawing images.
  21800. @param imageToDraw the image to overlay
  21801. @param destX the left of the destination rectangle
  21802. @param destY the top of the destination rectangle
  21803. @param destWidth the width of the destination rectangle
  21804. @param destHeight the height of the destination rectangle
  21805. @param sourceX the left of the rectangle to copy from the source image
  21806. @param sourceY the top of the rectangle to copy from the source image
  21807. @param sourceWidth the width of the rectangle to copy from the source image
  21808. @param sourceHeight the height of the rectangle to copy from the source image
  21809. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  21810. the source image's alpha channel is used as a mask with
  21811. which to fill the destination using the current colour
  21812. or brush. (If the source is has no alpha channel, then
  21813. it will just fill the target with a solid rectangle)
  21814. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  21815. */
  21816. void drawImage (const Image& imageToDraw,
  21817. int destX, int destY, int destWidth, int destHeight,
  21818. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  21819. bool fillAlphaChannelWithCurrentBrush = false) const;
  21820. /** Draws an image, having applied an affine transform to it.
  21821. This lets you throw the image around in some wacky ways, rotate it, shear,
  21822. scale it, etc.
  21823. Images are composited using the context's current opacity, so if you
  21824. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  21825. (or setColour() with an opaque colour) before drawing images.
  21826. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  21827. are ignored and it is filled with the current brush, masked by its alpha channel.
  21828. If you want to render only a subsection of an image, use Image::getClippedImage() to
  21829. create the section that you need.
  21830. @see setImageResamplingQuality, drawImage
  21831. */
  21832. void drawImageTransformed (const Image& imageToDraw,
  21833. const AffineTransform& transform,
  21834. bool fillAlphaChannelWithCurrentBrush = false) const;
  21835. /** Draws an image to fit within a designated rectangle.
  21836. If the image is too big or too small for the space, it will be rescaled
  21837. to fit as nicely as it can do without affecting its aspect ratio. It will
  21838. then be placed within the target rectangle according to the justification flags
  21839. specified.
  21840. @param imageToDraw the source image to draw
  21841. @param destX top-left of the target rectangle to fit it into
  21842. @param destY top-left of the target rectangle to fit it into
  21843. @param destWidth size of the target rectangle to fit the image into
  21844. @param destHeight size of the target rectangle to fit the image into
  21845. @param placementWithinTarget this specifies how the image should be positioned
  21846. within the target rectangle - see the RectanglePlacement
  21847. class for more details about this.
  21848. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  21849. alpha channel will be used as a mask with which to
  21850. draw with the current brush or colour. This is
  21851. similar to fillAlphaMap(), and see also drawImage()
  21852. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  21853. */
  21854. void drawImageWithin (const Image& imageToDraw,
  21855. int destX, int destY, int destWidth, int destHeight,
  21856. const RectanglePlacement& placementWithinTarget,
  21857. bool fillAlphaChannelWithCurrentBrush = false) const;
  21858. /** Returns the position of the bounding box for the current clipping region.
  21859. @see getClipRegion, clipRegionIntersects
  21860. */
  21861. const Rectangle<int> getClipBounds() const;
  21862. /** Checks whether a rectangle overlaps the context's clipping region.
  21863. If this returns false, no part of the given area can be drawn onto, so this
  21864. method can be used to optimise a component's paint() method, by letting it
  21865. avoid drawing complex objects that aren't within the region being repainted.
  21866. */
  21867. bool clipRegionIntersects (const Rectangle<int>& area) const;
  21868. /** Intersects the current clipping region with another region.
  21869. @returns true if the resulting clipping region is non-zero in size
  21870. @see setOrigin, clipRegionIntersects
  21871. */
  21872. bool reduceClipRegion (int x, int y, int width, int height);
  21873. /** Intersects the current clipping region with another region.
  21874. @returns true if the resulting clipping region is non-zero in size
  21875. @see setOrigin, clipRegionIntersects
  21876. */
  21877. bool reduceClipRegion (const Rectangle<int>& area);
  21878. /** Intersects the current clipping region with a rectangle list region.
  21879. @returns true if the resulting clipping region is non-zero in size
  21880. @see setOrigin, clipRegionIntersects
  21881. */
  21882. bool reduceClipRegion (const RectangleList& clipRegion);
  21883. /** Intersects the current clipping region with a path.
  21884. @returns true if the resulting clipping region is non-zero in size
  21885. @see reduceClipRegion
  21886. */
  21887. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  21888. /** Intersects the current clipping region with an image's alpha-channel.
  21889. The current clipping path is intersected with the area covered by this image's
  21890. alpha-channel, after the image has been transformed by the specified matrix.
  21891. @param image the image whose alpha-channel should be used. If the image doesn't
  21892. have an alpha-channel, it is treated as entirely opaque.
  21893. @param transform a matrix to apply to the image
  21894. @returns true if the resulting clipping region is non-zero in size
  21895. @see reduceClipRegion
  21896. */
  21897. bool reduceClipRegion (const Image& image, const AffineTransform& transform);
  21898. /** Excludes a rectangle to stop it being drawn into. */
  21899. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  21900. /** Returns true if no drawing can be done because the clip region is zero. */
  21901. bool isClipEmpty() const;
  21902. /** Saves the current graphics state on an internal stack.
  21903. To restore the state, use restoreState().
  21904. @see ScopedSaveState
  21905. */
  21906. void saveState();
  21907. /** Restores a graphics state that was previously saved with saveState().
  21908. @see ScopedSaveState
  21909. */
  21910. void restoreState();
  21911. /** Uses RAII to save and restore the state of a graphics context.
  21912. On construction, this calls Graphics::saveState(), and on destruction it calls
  21913. Graphics::restoreState() on the Graphics object that you supply.
  21914. */
  21915. class ScopedSaveState
  21916. {
  21917. public:
  21918. ScopedSaveState (Graphics& g);
  21919. ~ScopedSaveState();
  21920. private:
  21921. Graphics& context;
  21922. JUCE_DECLARE_NON_COPYABLE (ScopedSaveState);
  21923. };
  21924. /** Begins rendering to an off-screen bitmap which will later be flattened onto the current
  21925. context with the given opacity.
  21926. The context uses an internal stack of temporary image layers to do this. When you've
  21927. finished drawing to the layer, call endTransparencyLayer() to complete the operation and
  21928. composite the finished layer. Every call to beginTransparencyLayer() MUST be matched
  21929. by a corresponding call to endTransparencyLayer()!
  21930. This call also saves the current state, and endTransparencyLayer() restores it.
  21931. */
  21932. void beginTransparencyLayer (float layerOpacity);
  21933. /** Completes a drawing operation to a temporary semi-transparent buffer.
  21934. See beginTransparencyLayer() for more details.
  21935. */
  21936. void endTransparencyLayer();
  21937. /** Moves the position of the context's origin.
  21938. This changes the position that the context considers to be (0, 0) to
  21939. the specified position.
  21940. So if you call setOrigin (100, 100), then the position that was previously
  21941. referred to as (100, 100) will subsequently be considered to be (0, 0).
  21942. @see reduceClipRegion, addTransform
  21943. */
  21944. void setOrigin (int newOriginX, int newOriginY);
  21945. /** Adds a transformation which will be performed on all the graphics operations that
  21946. the context subsequently performs.
  21947. After calling this, all the coordinates that are passed into the context will be
  21948. transformed by this matrix.
  21949. @see setOrigin
  21950. */
  21951. void addTransform (const AffineTransform& transform);
  21952. /** Resets the current colour, brush, and font to default settings. */
  21953. void resetToDefaultState();
  21954. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  21955. bool isVectorDevice() const;
  21956. /** Create a graphics that uses a given low-level renderer.
  21957. For internal use only.
  21958. NB. The context will NOT be deleted by this object when it is deleted.
  21959. */
  21960. Graphics (LowLevelGraphicsContext* internalContext) throw();
  21961. /** @internal */
  21962. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  21963. private:
  21964. LowLevelGraphicsContext* const context;
  21965. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  21966. bool saveStatePending;
  21967. void saveStateIfPending();
  21968. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Graphics);
  21969. };
  21970. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  21971. /*** End of inlined file: juce_Graphics.h ***/
  21972. /**
  21973. A graphical effect filter that can be applied to components.
  21974. An ImageEffectFilter can be applied to the image that a component
  21975. paints before it hits the screen.
  21976. This is used for adding effects like shadows, blurs, etc.
  21977. @see Component::setComponentEffect
  21978. */
  21979. class JUCE_API ImageEffectFilter
  21980. {
  21981. public:
  21982. /** Overridden to render the effect.
  21983. The implementation of this method must use the image that is passed in
  21984. as its source, and should render its output to the graphics context passed in.
  21985. @param sourceImage the image that the source component has just rendered with
  21986. its paint() method. The image may or may not have an alpha
  21987. channel, depending on whether the component is opaque.
  21988. @param destContext the graphics context to use to draw the resultant image.
  21989. @param alpha the alpha with which to draw the resultant image to the
  21990. target context
  21991. */
  21992. virtual void applyEffect (Image& sourceImage,
  21993. Graphics& destContext,
  21994. float alpha) = 0;
  21995. /** Destructor. */
  21996. virtual ~ImageEffectFilter() {}
  21997. };
  21998. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  21999. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  22000. /*** Start of inlined file: juce_Image.h ***/
  22001. #ifndef __JUCE_IMAGE_JUCEHEADER__
  22002. #define __JUCE_IMAGE_JUCEHEADER__
  22003. /**
  22004. Holds a fixed-size bitmap.
  22005. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  22006. To draw into an image, create a Graphics object for it.
  22007. e.g. @code
  22008. // create a transparent 500x500 image..
  22009. Image myImage (Image::RGB, 500, 500, true);
  22010. Graphics g (myImage);
  22011. g.setColour (Colours::red);
  22012. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  22013. @endcode
  22014. Other useful ways to create an image are with the ImageCache class, or the
  22015. ImageFileFormat, which provides a way to load common image files.
  22016. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  22017. */
  22018. class JUCE_API Image
  22019. {
  22020. public:
  22021. /**
  22022. */
  22023. enum PixelFormat
  22024. {
  22025. UnknownFormat,
  22026. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  22027. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  22028. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  22029. };
  22030. /**
  22031. */
  22032. enum ImageType
  22033. {
  22034. SoftwareImage = 0,
  22035. NativeImage
  22036. };
  22037. /** Creates a null image. */
  22038. Image();
  22039. /** Creates an image with a specified size and format.
  22040. @param format the number of colour channels in the image
  22041. @param imageWidth the desired width of the image, in pixels - this value must be
  22042. greater than zero (otherwise a width of 1 will be used)
  22043. @param imageHeight the desired width of the image, in pixels - this value must be
  22044. greater than zero (otherwise a height of 1 will be used)
  22045. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  22046. or transparent black (if it's ARGB). If false, the image may contain
  22047. junk initially, so you need to make sure you overwrite it thoroughly.
  22048. @param type the type of image - this lets you specify whether you want a purely
  22049. memory-based image, or one that may be managed by the OS if possible.
  22050. */
  22051. Image (PixelFormat format,
  22052. int imageWidth,
  22053. int imageHeight,
  22054. bool clearImage,
  22055. ImageType type = NativeImage);
  22056. /** Creates a shared reference to another image.
  22057. This won't create a duplicate of the image - when Image objects are copied, they simply
  22058. point to the same shared image data. To make sure that an Image object has its own unique,
  22059. unshared internal data, call duplicateIfShared().
  22060. */
  22061. Image (const Image& other);
  22062. /** Makes this image refer to the same underlying image as another object.
  22063. This won't create a duplicate of the image - when Image objects are copied, they simply
  22064. point to the same shared image data. To make sure that an Image object has its own unique,
  22065. unshared internal data, call duplicateIfShared().
  22066. */
  22067. Image& operator= (const Image&);
  22068. /** Destructor. */
  22069. ~Image();
  22070. /** Returns true if the two images are referring to the same internal, shared image. */
  22071. bool operator== (const Image& other) const throw() { return image == other.image; }
  22072. /** Returns true if the two images are not referring to the same internal, shared image. */
  22073. bool operator!= (const Image& other) const throw() { return image != other.image; }
  22074. /** Returns true if this image isn't null.
  22075. If you create an Image with the default constructor, it has no size or content, and is null
  22076. until you reassign it to an Image which contains some actual data.
  22077. The isNull() method is the opposite of isValid().
  22078. @see isNull
  22079. */
  22080. inline bool isValid() const throw() { return image != 0; }
  22081. /** Returns true if this image is not valid.
  22082. If you create an Image with the default constructor, it has no size or content, and is null
  22083. until you reassign it to an Image which contains some actual data.
  22084. The isNull() method is the opposite of isValid().
  22085. @see isValid
  22086. */
  22087. inline bool isNull() const throw() { return image == 0; }
  22088. /** A null Image object that can be used when you need to return an invalid image.
  22089. This object is the equivalient to an Image created with the default constructor.
  22090. */
  22091. static const Image null;
  22092. /** Returns the image's width (in pixels). */
  22093. int getWidth() const throw() { return image == 0 ? 0 : image->width; }
  22094. /** Returns the image's height (in pixels). */
  22095. int getHeight() const throw() { return image == 0 ? 0 : image->height; }
  22096. /** Returns a rectangle with the same size as this image.
  22097. The rectangle's origin is always (0, 0).
  22098. */
  22099. const Rectangle<int> getBounds() const throw() { return image == 0 ? Rectangle<int>() : Rectangle<int> (image->width, image->height); }
  22100. /** Returns the image's pixel format. */
  22101. PixelFormat getFormat() const throw() { return image == 0 ? UnknownFormat : image->format; }
  22102. /** True if the image's format is ARGB. */
  22103. bool isARGB() const throw() { return getFormat() == ARGB; }
  22104. /** True if the image's format is RGB. */
  22105. bool isRGB() const throw() { return getFormat() == RGB; }
  22106. /** True if the image's format is a single-channel alpha map. */
  22107. bool isSingleChannel() const throw() { return getFormat() == SingleChannel; }
  22108. /** True if the image contains an alpha-channel. */
  22109. bool hasAlphaChannel() const throw() { return getFormat() != RGB; }
  22110. /** Clears a section of the image with a given colour.
  22111. This won't do any alpha-blending - it just sets all pixels in the image to
  22112. the given colour (which may be non-opaque if the image has an alpha channel).
  22113. */
  22114. void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  22115. /** Returns a rescaled version of this image.
  22116. A new image is returned which is a copy of this one, rescaled to the given size.
  22117. Note that if the new size is identical to the existing image, this will just return
  22118. a reference to the original image, and won't actually create a duplicate.
  22119. */
  22120. const Image rescaled (int newWidth, int newHeight,
  22121. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  22122. /** Returns a version of this image with a different image format.
  22123. A new image is returned which has been converted to the specified format.
  22124. Note that if the new format is no different to the current one, this will just return
  22125. a reference to the original image, and won't actually create a copy.
  22126. */
  22127. const Image convertedToFormat (PixelFormat newFormat) const;
  22128. /** Makes sure that no other Image objects share the same underlying data as this one.
  22129. If no other Image objects refer to the same shared data as this one, this method has no
  22130. effect. But if there are other references to the data, this will create a new copy of
  22131. the data internally.
  22132. Call this if you want to draw onto the image, but want to make sure that this doesn't
  22133. affect any other code that may be sharing the same data.
  22134. @see getReferenceCount
  22135. */
  22136. void duplicateIfShared();
  22137. /** Returns an image which refers to a subsection of this image.
  22138. This will not make a copy of the original - the new image will keep a reference to it, so that
  22139. if the original image is changed, the contents of the subsection will also change. Likewise if you
  22140. draw into the subimage, you'll also be drawing onto that area of the original image. Note that if
  22141. you use operator= to make the original Image object refer to something else, the subsection image
  22142. won't pick up this change, it'll remain pointing at the original.
  22143. The area passed-in will be clipped to the bounds of this image, so this may return a smaller
  22144. image than the area you asked for, or even a null image if the area was out-of-bounds.
  22145. */
  22146. const Image getClippedImage (const Rectangle<int>& area) const;
  22147. /** Returns the colour of one of the pixels in the image.
  22148. If the co-ordinates given are beyond the image's boundaries, this will
  22149. return Colours::transparentBlack.
  22150. @see setPixelAt, Image::BitmapData::getPixelColour
  22151. */
  22152. const Colour getPixelAt (int x, int y) const;
  22153. /** Sets the colour of one of the image's pixels.
  22154. If the co-ordinates are beyond the image's boundaries, then nothing will happen.
  22155. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  22156. with the given one. The colour's opacity will be ignored if this image doesn't have
  22157. an alpha-channel.
  22158. @see getPixelAt, Image::BitmapData::setPixelColour
  22159. */
  22160. void setPixelAt (int x, int y, const Colour& colour);
  22161. /** Changes the opacity of a pixel.
  22162. This only has an effect if the image has an alpha channel and if the
  22163. given co-ordinates are inside the image's boundary.
  22164. The multiplier must be in the range 0 to 1.0, and the current alpha
  22165. at the given co-ordinates will be multiplied by this value.
  22166. @see setPixelAt
  22167. */
  22168. void multiplyAlphaAt (int x, int y, float multiplier);
  22169. /** Changes the overall opacity of the image.
  22170. This will multiply the alpha value of each pixel in the image by the given
  22171. amount (limiting the resulting alpha values between 0 and 255). This allows
  22172. you to make an image more or less transparent.
  22173. If the image doesn't have an alpha channel, this won't have any effect.
  22174. */
  22175. void multiplyAllAlphas (float amountToMultiplyBy);
  22176. /** Changes all the colours to be shades of grey, based on their current luminosity.
  22177. */
  22178. void desaturate();
  22179. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  22180. You should only use this class as a last resort - messing about with the internals of
  22181. an image is only recommended for people who really know what they're doing!
  22182. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  22183. hanging around while the image is being used elsewhere.
  22184. Depending on the way the image class is implemented, this may create a temporary buffer
  22185. which is copied back to the image when the object is deleted, or it may just get a pointer
  22186. directly into the image's raw data.
  22187. You can use the stride and data values in this class directly, but don't alter them!
  22188. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  22189. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  22190. */
  22191. class BitmapData
  22192. {
  22193. public:
  22194. enum ReadWriteMode
  22195. {
  22196. readOnly,
  22197. writeOnly,
  22198. readWrite
  22199. };
  22200. BitmapData (Image& image, int x, int y, int w, int h, ReadWriteMode mode);
  22201. BitmapData (const Image& image, int x, int y, int w, int h);
  22202. BitmapData (const Image& image, ReadWriteMode mode);
  22203. ~BitmapData();
  22204. /** Returns a pointer to the start of a line in the image.
  22205. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  22206. sure it's not out-of-range.
  22207. */
  22208. inline uint8* getLinePointer (int y) const throw() { return data + y * lineStride; }
  22209. /** Returns a pointer to a pixel in the image.
  22210. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  22211. not out-of-range.
  22212. */
  22213. inline uint8* getPixelPointer (int x, int y) const throw() { return data + y * lineStride + x * pixelStride; }
  22214. /** Returns the colour of a given pixel.
  22215. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  22216. repsonsibility to make sure they're within the image's size.
  22217. */
  22218. const Colour getPixelColour (int x, int y) const throw();
  22219. /** Sets the colour of a given pixel.
  22220. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  22221. repsonsibility to make sure they're within the image's size.
  22222. */
  22223. void setPixelColour (int x, int y, const Colour& colour) const throw();
  22224. uint8* data;
  22225. PixelFormat pixelFormat;
  22226. int lineStride, pixelStride, width, height;
  22227. /** Used internally by custom image types to manage pixel data lifetime. */
  22228. class BitmapDataReleaser
  22229. {
  22230. protected:
  22231. BitmapDataReleaser() {}
  22232. public:
  22233. virtual ~BitmapDataReleaser() {}
  22234. };
  22235. ScopedPointer<BitmapDataReleaser> dataReleaser;
  22236. private:
  22237. JUCE_DECLARE_NON_COPYABLE (BitmapData);
  22238. };
  22239. /** Copies some pixel values to a rectangle of the image.
  22240. The format of the pixel data must match that of the image itself, and the
  22241. rectangle supplied must be within the image's bounds.
  22242. */
  22243. void setPixelData (int destX, int destY, int destW, int destH,
  22244. const uint8* sourcePixelData, int sourceLineStride);
  22245. /** Copies a section of the image to somewhere else within itself. */
  22246. void moveImageSection (int destX, int destY,
  22247. int sourceX, int sourceY,
  22248. int width, int height);
  22249. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  22250. of the image.
  22251. @param result the list that will have the area added to it
  22252. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  22253. above this level will be considered opaque
  22254. */
  22255. void createSolidAreaMask (RectangleList& result,
  22256. float alphaThreshold = 0.5f) const;
  22257. /** Returns a NamedValueSet that is attached to the image and which can be used for
  22258. associating custom values with it.
  22259. If this is a null image, this will return a null pointer.
  22260. */
  22261. NamedValueSet* getProperties() const;
  22262. /** Creates a context suitable for drawing onto this image.
  22263. Don't call this method directly! It's used internally by the Graphics class.
  22264. */
  22265. LowLevelGraphicsContext* createLowLevelContext() const;
  22266. /** Returns the number of Image objects which are currently referring to the same internal
  22267. shared image data.
  22268. @see duplicateIfShared
  22269. */
  22270. int getReferenceCount() const throw() { return image == 0 ? 0 : image->getReferenceCount(); }
  22271. /** This is a base class for task-specific types of image.
  22272. Don't use this class directly! It's used internally by the Image class.
  22273. */
  22274. class SharedImage : public ReferenceCountedObject
  22275. {
  22276. public:
  22277. SharedImage (PixelFormat format, int width, int height);
  22278. ~SharedImage();
  22279. virtual LowLevelGraphicsContext* createLowLevelContext() = 0;
  22280. virtual SharedImage* clone() = 0;
  22281. virtual ImageType getType() const = 0;
  22282. virtual void initialiseBitmapData (BitmapData& bitmapData, int x, int y, BitmapData::ReadWriteMode mode) = 0;
  22283. static SharedImage* createNativeImage (PixelFormat format, int width, int height, bool clearImage);
  22284. static SharedImage* createSoftwareImage (PixelFormat format, int width, int height, bool clearImage);
  22285. const PixelFormat getPixelFormat() const throw() { return format; }
  22286. int getWidth() const throw() { return width; }
  22287. int getHeight() const throw() { return height; }
  22288. protected:
  22289. friend class Image;
  22290. friend class BitmapData;
  22291. const PixelFormat format;
  22292. const int width, height;
  22293. NamedValueSet userData;
  22294. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedImage);
  22295. };
  22296. /** @internal */
  22297. SharedImage* getSharedImage() const throw() { return image; }
  22298. /** @internal */
  22299. explicit Image (SharedImage* instance);
  22300. private:
  22301. friend class SharedImage;
  22302. friend class BitmapData;
  22303. ReferenceCountedObjectPtr<SharedImage> image;
  22304. JUCE_LEAK_DETECTOR (Image);
  22305. };
  22306. #endif // __JUCE_IMAGE_JUCEHEADER__
  22307. /*** End of inlined file: juce_Image.h ***/
  22308. /*** Start of inlined file: juce_RectangleList.h ***/
  22309. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  22310. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  22311. /**
  22312. Maintains a set of rectangles as a complex region.
  22313. This class allows a set of rectangles to be treated as a solid shape, and can
  22314. add and remove rectangular sections of it, and simplify overlapping or
  22315. adjacent rectangles.
  22316. @see Rectangle
  22317. */
  22318. class JUCE_API RectangleList
  22319. {
  22320. public:
  22321. /** Creates an empty RectangleList */
  22322. RectangleList() throw();
  22323. /** Creates a copy of another list */
  22324. RectangleList (const RectangleList& other);
  22325. /** Creates a list containing just one rectangle. */
  22326. RectangleList (const Rectangle<int>& rect);
  22327. /** Copies this list from another one. */
  22328. RectangleList& operator= (const RectangleList& other);
  22329. /** Destructor. */
  22330. ~RectangleList();
  22331. /** Returns true if the region is empty. */
  22332. bool isEmpty() const throw();
  22333. /** Returns the number of rectangles in the list. */
  22334. int getNumRectangles() const throw() { return rects.size(); }
  22335. /** Returns one of the rectangles at a particular index.
  22336. @returns the rectangle at the index, or an empty rectangle if the
  22337. index is out-of-range.
  22338. */
  22339. const Rectangle<int> getRectangle (int index) const throw();
  22340. /** Removes all rectangles to leave an empty region. */
  22341. void clear();
  22342. /** Merges a new rectangle into the list.
  22343. The rectangle being added will first be clipped to remove any parts of it
  22344. that overlap existing rectangles in the list.
  22345. */
  22346. void add (int x, int y, int width, int height);
  22347. /** Merges a new rectangle into the list.
  22348. The rectangle being added will first be clipped to remove any parts of it
  22349. that overlap existing rectangles in the list, and adjacent rectangles will be
  22350. merged into it.
  22351. */
  22352. void add (const Rectangle<int>& rect);
  22353. /** Dumbly adds a rectangle to the list without checking for overlaps.
  22354. This simply adds the rectangle to the end, it doesn't merge it or remove
  22355. any overlapping bits.
  22356. */
  22357. void addWithoutMerging (const Rectangle<int>& rect);
  22358. /** Merges another rectangle list into this one.
  22359. Any overlaps between the two lists will be clipped, so that the result is
  22360. the union of both lists.
  22361. */
  22362. void add (const RectangleList& other);
  22363. /** Removes a rectangular region from the list.
  22364. Any rectangles in the list which overlap this will be clipped and subdivided
  22365. if necessary.
  22366. */
  22367. void subtract (const Rectangle<int>& rect);
  22368. /** Removes all areas in another RectangleList from this one.
  22369. Any rectangles in the list which overlap this will be clipped and subdivided
  22370. if necessary.
  22371. @returns true if the resulting list is non-empty.
  22372. */
  22373. bool subtract (const RectangleList& otherList);
  22374. /** Removes any areas of the region that lie outside a given rectangle.
  22375. Any rectangles in the list which overlap this will be clipped and subdivided
  22376. if necessary.
  22377. Returns true if the resulting region is not empty, false if it is empty.
  22378. @see getIntersectionWith
  22379. */
  22380. bool clipTo (const Rectangle<int>& rect);
  22381. /** Removes any areas of the region that lie outside a given rectangle list.
  22382. Any rectangles in this object which overlap the specified list will be clipped
  22383. and subdivided if necessary.
  22384. Returns true if the resulting region is not empty, false if it is empty.
  22385. @see getIntersectionWith
  22386. */
  22387. bool clipTo (const RectangleList& other);
  22388. /** Creates a region which is the result of clipping this one to a given rectangle.
  22389. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  22390. resulting region into the list whose reference is passed-in.
  22391. Returns true if the resulting region is not empty, false if it is empty.
  22392. @see clipTo
  22393. */
  22394. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  22395. /** Swaps the contents of this and another list.
  22396. This swaps their internal pointers, so is hugely faster than using copy-by-value
  22397. to swap them.
  22398. */
  22399. void swapWith (RectangleList& otherList) throw();
  22400. /** Checks whether the region contains a given point.
  22401. @returns true if the point lies within one of the rectangles in the list
  22402. */
  22403. bool containsPoint (int x, int y) const throw();
  22404. /** Checks whether the region contains the whole of a given rectangle.
  22405. @returns true all parts of the rectangle passed in lie within the region
  22406. defined by this object
  22407. @see intersectsRectangle, containsPoint
  22408. */
  22409. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  22410. /** Checks whether the region contains any part of a given rectangle.
  22411. @returns true if any part of the rectangle passed in lies within the region
  22412. defined by this object
  22413. @see containsRectangle
  22414. */
  22415. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw();
  22416. /** Checks whether this region intersects any part of another one.
  22417. @see intersectsRectangle
  22418. */
  22419. bool intersects (const RectangleList& other) const throw();
  22420. /** Returns the smallest rectangle that can enclose the whole of this region. */
  22421. const Rectangle<int> getBounds() const throw();
  22422. /** Optimises the list into a minimum number of constituent rectangles.
  22423. This will try to combine any adjacent rectangles into larger ones where
  22424. possible, to simplify lists that might have been fragmented by repeated
  22425. add/subtract calls.
  22426. */
  22427. void consolidate();
  22428. /** Adds an x and y value to all the co-ordinates. */
  22429. void offsetAll (int dx, int dy) throw();
  22430. /** Creates a Path object to represent this region. */
  22431. const Path toPath() const;
  22432. /** An iterator for accessing all the rectangles in a RectangleList. */
  22433. class JUCE_API Iterator
  22434. {
  22435. public:
  22436. Iterator (const RectangleList& list) throw();
  22437. ~Iterator();
  22438. /** Advances to the next rectangle, and returns true if it's not finished.
  22439. Call this before using getRectangle() to find the rectangle that was returned.
  22440. */
  22441. bool next() throw();
  22442. /** Returns the current rectangle. */
  22443. const Rectangle<int>* getRectangle() const throw() { return current; }
  22444. private:
  22445. const Rectangle<int>* current;
  22446. const RectangleList& owner;
  22447. int index;
  22448. JUCE_DECLARE_NON_COPYABLE (Iterator);
  22449. };
  22450. private:
  22451. friend class Iterator;
  22452. Array <Rectangle<int> > rects;
  22453. JUCE_LEAK_DETECTOR (RectangleList);
  22454. };
  22455. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  22456. /*** End of inlined file: juce_RectangleList.h ***/
  22457. /*** Start of inlined file: juce_BorderSize.h ***/
  22458. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  22459. #define __JUCE_BORDERSIZE_JUCEHEADER__
  22460. /**
  22461. Specifies a set of gaps to be left around the sides of a rectangle.
  22462. This is basically the size of the spaces at the top, bottom, left and right of
  22463. a rectangle. It's used by various component classes to specify borders.
  22464. @see Rectangle
  22465. */
  22466. template <typename ValueType>
  22467. class BorderSize
  22468. {
  22469. public:
  22470. /** Creates a null border.
  22471. All sizes are left as 0.
  22472. */
  22473. BorderSize() throw()
  22474. : top(), left(), bottom(), right()
  22475. {
  22476. }
  22477. /** Creates a copy of another border. */
  22478. BorderSize (const BorderSize& other) throw()
  22479. : top (other.top), left (other.left), bottom (other.bottom), right (other.right)
  22480. {
  22481. }
  22482. /** Creates a border with the given gaps. */
  22483. BorderSize (ValueType topGap, ValueType leftGap, ValueType bottomGap, ValueType rightGap) throw()
  22484. : top (topGap), left (leftGap), bottom (bottomGap), right (rightGap)
  22485. {
  22486. }
  22487. /** Creates a border with the given gap on all sides. */
  22488. explicit BorderSize (ValueType allGaps) throw()
  22489. : top (allGaps), left (allGaps), bottom (allGaps), right (allGaps)
  22490. {
  22491. }
  22492. /** Returns the gap that should be left at the top of the region. */
  22493. ValueType getTop() const throw() { return top; }
  22494. /** Returns the gap that should be left at the top of the region. */
  22495. ValueType getLeft() const throw() { return left; }
  22496. /** Returns the gap that should be left at the top of the region. */
  22497. ValueType getBottom() const throw() { return bottom; }
  22498. /** Returns the gap that should be left at the top of the region. */
  22499. ValueType getRight() const throw() { return right; }
  22500. /** Returns the sum of the top and bottom gaps. */
  22501. ValueType getTopAndBottom() const throw() { return top + bottom; }
  22502. /** Returns the sum of the left and right gaps. */
  22503. ValueType getLeftAndRight() const throw() { return left + right; }
  22504. /** Returns true if this border has no thickness along any edge. */
  22505. bool isEmpty() const throw() { return left + right + top + bottom == ValueType(); }
  22506. /** Changes the top gap. */
  22507. void setTop (ValueType newTopGap) throw() { top = newTopGap; }
  22508. /** Changes the left gap. */
  22509. void setLeft (ValueType newLeftGap) throw() { left = newLeftGap; }
  22510. /** Changes the bottom gap. */
  22511. void setBottom (ValueType newBottomGap) throw() { bottom = newBottomGap; }
  22512. /** Changes the right gap. */
  22513. void setRight (ValueType newRightGap) throw() { right = newRightGap; }
  22514. /** Returns a rectangle with these borders removed from it. */
  22515. const Rectangle<ValueType> subtractedFrom (const Rectangle<ValueType>& original) const throw()
  22516. {
  22517. return Rectangle<ValueType> (original.getX() + left,
  22518. original.getY() + top,
  22519. original.getWidth() - (left + right),
  22520. original.getHeight() - (top + bottom));
  22521. }
  22522. /** Removes this border from a given rectangle. */
  22523. void subtractFrom (Rectangle<ValueType>& rectangle) const throw()
  22524. {
  22525. rectangle = subtractedFrom (rectangle);
  22526. }
  22527. /** Returns a rectangle with these borders added around it. */
  22528. const Rectangle<ValueType> addedTo (const Rectangle<ValueType>& original) const throw()
  22529. {
  22530. return Rectangle<ValueType> (original.getX() - left,
  22531. original.getY() - top,
  22532. original.getWidth() + (left + right),
  22533. original.getHeight() + (top + bottom));
  22534. }
  22535. /** Adds this border around a given rectangle. */
  22536. void addTo (Rectangle<ValueType>& rectangle) const throw()
  22537. {
  22538. rectangle = addedTo (rectangle);
  22539. }
  22540. bool operator== (const BorderSize& other) const throw()
  22541. {
  22542. return top == other.top && left == other.left && bottom == other.bottom && right == other.right;
  22543. }
  22544. bool operator!= (const BorderSize& other) const throw()
  22545. {
  22546. return ! operator== (other);
  22547. }
  22548. private:
  22549. ValueType top, left, bottom, right;
  22550. JUCE_LEAK_DETECTOR (BorderSize);
  22551. };
  22552. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  22553. /*** End of inlined file: juce_BorderSize.h ***/
  22554. /*** Start of inlined file: juce_ModalComponentManager.h ***/
  22555. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  22556. #define __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  22557. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  22558. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  22559. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  22560. /**
  22561. Classes derived from this will be automatically deleted when the application exits.
  22562. After JUCEApplication::shutdown() has been called, any objects derived from
  22563. DeletedAtShutdown which are still in existence will be deleted in the reverse
  22564. order to that in which they were created.
  22565. So if you've got a singleton and don't want to have to explicitly delete it, just
  22566. inherit from this and it'll be taken care of.
  22567. */
  22568. class JUCE_API DeletedAtShutdown
  22569. {
  22570. protected:
  22571. /** Creates a DeletedAtShutdown object. */
  22572. DeletedAtShutdown();
  22573. /** Destructor.
  22574. It's ok to delete these objects explicitly - it's only the ones left
  22575. dangling at the end that will be deleted automatically.
  22576. */
  22577. virtual ~DeletedAtShutdown();
  22578. public:
  22579. /** Deletes all extant objects.
  22580. This shouldn't be used by applications, as it's called automatically
  22581. in the shutdown code of the JUCEApplication class.
  22582. */
  22583. static void deleteAll();
  22584. private:
  22585. static CriticalSection& getLock();
  22586. static Array <DeletedAtShutdown*>& getObjects();
  22587. JUCE_DECLARE_NON_COPYABLE (DeletedAtShutdown);
  22588. };
  22589. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  22590. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  22591. /**
  22592. Manages the system's stack of modal components.
  22593. Normally you'll just use the Component methods to invoke modal states in components,
  22594. and won't have to deal with this class directly, but this is the singleton object that's
  22595. used internally to manage the stack.
  22596. @see Component::enterModalState, Component::exitModalState, Component::isCurrentlyModal,
  22597. Component::getCurrentlyModalComponent, Component::isCurrentlyBlockedByAnotherModalComponent
  22598. */
  22599. class JUCE_API ModalComponentManager : public AsyncUpdater,
  22600. public DeletedAtShutdown
  22601. {
  22602. public:
  22603. /** Receives callbacks when a modal component is dismissed.
  22604. You can register a callback using Component::enterModalState() or
  22605. ModalComponentManager::attachCallback().
  22606. For some quick ways of creating callback objects, see the ModalCallbackFunction class.
  22607. @see ModalCallbackFunction
  22608. */
  22609. class Callback
  22610. {
  22611. public:
  22612. /** */
  22613. Callback() {}
  22614. /** Destructor. */
  22615. virtual ~Callback() {}
  22616. /** Called to indicate that a modal component has been dismissed.
  22617. You can register a callback using Component::enterModalState() or
  22618. ModalComponentManager::attachCallback().
  22619. The returnValue parameter is the value that was passed to Component::exitModalState()
  22620. when the component was dismissed.
  22621. The callback object will be deleted shortly after this method is called.
  22622. */
  22623. virtual void modalStateFinished (int returnValue) = 0;
  22624. };
  22625. /** Returns the number of components currently being shown modally.
  22626. @see getModalComponent
  22627. */
  22628. int getNumModalComponents() const;
  22629. /** Returns one of the components being shown modally.
  22630. An index of 0 is the most recently-shown, topmost component.
  22631. */
  22632. Component* getModalComponent (int index) const;
  22633. /** Returns true if the specified component is in a modal state. */
  22634. bool isModal (Component* component) const;
  22635. /** Returns true if the specified component is currently the topmost modal component. */
  22636. bool isFrontModalComponent (Component* component) const;
  22637. /** Adds a new callback that will be called when the specified modal component is dismissed.
  22638. If the component is modal, then when it is dismissed, either by being hidden, or by calling
  22639. Component::exitModalState(), then the Callback::modalStateFinished() method will be
  22640. called.
  22641. Each component can have any number of callbacks associated with it, and this one is added
  22642. to that list.
  22643. The object that is passed in will be deleted by the manager when it's no longer needed. If
  22644. the given component is not currently modal, the callback object is deleted immediately and
  22645. no action is taken.
  22646. */
  22647. void attachCallback (Component* component, Callback* callback);
  22648. /** Brings any modal components to the front. */
  22649. void bringModalComponentsToFront();
  22650. #if JUCE_MODAL_LOOPS_PERMITTED
  22651. /** Runs the event loop until the currently topmost modal component is dismissed, and
  22652. returns the exit code for that component.
  22653. */
  22654. int runEventLoopForCurrentComponent();
  22655. #endif
  22656. juce_DeclareSingleton_SingleThreaded_Minimal (ModalComponentManager);
  22657. protected:
  22658. /** Creates a ModalComponentManager.
  22659. You shouldn't ever call the constructor - it's a singleton, so use ModalComponentManager::getInstance()
  22660. */
  22661. ModalComponentManager();
  22662. /** Destructor. */
  22663. ~ModalComponentManager();
  22664. /** @internal */
  22665. void handleAsyncUpdate();
  22666. private:
  22667. class ModalItem;
  22668. class ReturnValueRetriever;
  22669. friend class Component;
  22670. friend class OwnedArray <ModalItem>;
  22671. OwnedArray <ModalItem> stack;
  22672. void startModal (Component* component);
  22673. void endModal (Component* component, int returnValue);
  22674. void endModal (Component* component);
  22675. JUCE_DECLARE_NON_COPYABLE (ModalComponentManager);
  22676. };
  22677. /**
  22678. This class provides some handy utility methods for creating ModalComponentManager::Callback
  22679. objects that will invoke a static function with some parameters when a modal component is dismissed.
  22680. */
  22681. class ModalCallbackFunction
  22682. {
  22683. public:
  22684. /** This is a utility function to create a ModalComponentManager::Callback that will
  22685. call a static function with a parameter.
  22686. The function that you supply must take two parameters - the first being an int, which is
  22687. the result code that was used when the modal component was dismissed, and the second
  22688. can be a custom type. Note that this custom value will be copied and stored, so it must
  22689. be a primitive type or a class that provides copy-by-value semantics.
  22690. E.g. @code
  22691. static void myCallbackFunction (int modalResult, double customValue)
  22692. {
  22693. if (modalResult == 1)
  22694. doSomethingWith (customValue);
  22695. }
  22696. Component* someKindOfComp;
  22697. ...
  22698. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0));
  22699. @endcode
  22700. @see ModalComponentManager::Callback
  22701. */
  22702. template <typename ParamType>
  22703. static ModalComponentManager::Callback* create (void (*functionToCall) (int, ParamType),
  22704. ParamType parameterValue)
  22705. {
  22706. return new FunctionCaller1 <ParamType> (functionToCall, parameterValue);
  22707. }
  22708. /** This is a utility function to create a ModalComponentManager::Callback that will
  22709. call a static function with two custom parameters.
  22710. The function that you supply must take three parameters - the first being an int, which is
  22711. the result code that was used when the modal component was dismissed, and the next two are
  22712. your custom types. Note that these custom values will be copied and stored, so they must
  22713. be primitive types or classes that provide copy-by-value semantics.
  22714. E.g. @code
  22715. static void myCallbackFunction (int modalResult, double customValue1, String customValue2)
  22716. {
  22717. if (modalResult == 1)
  22718. doSomethingWith (customValue1, customValue2);
  22719. }
  22720. Component* someKindOfComp;
  22721. ...
  22722. someKindOfComp->enterModalState (ModalCallbackFunction::create (myCallbackFunction, 3.0, String ("xyz")));
  22723. @endcode
  22724. @see ModalComponentManager::Callback
  22725. */
  22726. template <typename ParamType1, typename ParamType2>
  22727. static ModalComponentManager::Callback* withParam (void (*functionToCall) (int, ParamType1, ParamType2),
  22728. ParamType1 parameterValue1,
  22729. ParamType2 parameterValue2)
  22730. {
  22731. return new FunctionCaller2 <ParamType1, ParamType2> (functionToCall, parameterValue1, parameterValue2);
  22732. }
  22733. /** This is a utility function to create a ModalComponentManager::Callback that will
  22734. call a static function with a component.
  22735. The function that you supply must take two parameters - the first being an int, which is
  22736. the result code that was used when the modal component was dismissed, and the second
  22737. can be a Component class. The component will be stored as a WeakReference, so that if it gets
  22738. deleted before this callback is invoked, the pointer that is passed to the function will be null.
  22739. E.g. @code
  22740. static void myCallbackFunction (int modalResult, Slider* mySlider)
  22741. {
  22742. if (modalResult == 1 && mySlider != 0) // (must check that mySlider isn't null in case it was deleted..)
  22743. mySlider->setValue (0.0);
  22744. }
  22745. Component* someKindOfComp;
  22746. Slider* mySlider;
  22747. ...
  22748. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider));
  22749. @endcode
  22750. @see ModalComponentManager::Callback
  22751. */
  22752. template <class ComponentType>
  22753. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*),
  22754. ComponentType* component)
  22755. {
  22756. return new ComponentCaller1 <ComponentType> (functionToCall, component);
  22757. }
  22758. /** Creates a ModalComponentManager::Callback that will call a static function with a component.
  22759. The function that you supply must take three parameters - the first being an int, which is
  22760. the result code that was used when the modal component was dismissed, the second being a Component
  22761. class, and the third being a custom type (which must be a primitive type or have copy-by-value semantics).
  22762. The component will be stored as a WeakReference, so that if it gets deleted before this callback is
  22763. invoked, the pointer that is passed into the function will be null.
  22764. E.g. @code
  22765. static void myCallbackFunction (int modalResult, Slider* mySlider, String customParam)
  22766. {
  22767. if (modalResult == 1 && mySlider != 0) // (must check that mySlider isn't null in case it was deleted..)
  22768. mySlider->setName (customParam);
  22769. }
  22770. Component* someKindOfComp;
  22771. Slider* mySlider;
  22772. ...
  22773. someKindOfComp->enterModalState (ModalCallbackFunction::forComponent (myCallbackFunction, mySlider, String ("hello")));
  22774. @endcode
  22775. @see ModalComponentManager::Callback
  22776. */
  22777. template <class ComponentType, typename ParamType>
  22778. static ModalComponentManager::Callback* forComponent (void (*functionToCall) (int, ComponentType*, ParamType),
  22779. ComponentType* component,
  22780. ParamType param)
  22781. {
  22782. return new ComponentCaller2 <ComponentType, ParamType> (functionToCall, component, param);
  22783. }
  22784. private:
  22785. template <typename ParamType>
  22786. class FunctionCaller1 : public ModalComponentManager::Callback
  22787. {
  22788. public:
  22789. typedef void (*FunctionType) (int, ParamType);
  22790. FunctionCaller1 (FunctionType& function_, ParamType& param_)
  22791. : function (function_), param (param_) {}
  22792. void modalStateFinished (int returnValue) { function (returnValue, param); }
  22793. private:
  22794. const FunctionType function;
  22795. ParamType param;
  22796. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller1);
  22797. };
  22798. template <typename ParamType1, typename ParamType2>
  22799. class FunctionCaller2 : public ModalComponentManager::Callback
  22800. {
  22801. public:
  22802. typedef void (*FunctionType) (int, ParamType1, ParamType2);
  22803. FunctionCaller2 (FunctionType& function_, ParamType1& param1_, ParamType2& param2_)
  22804. : function (function_), param1 (param1_), param2 (param2_) {}
  22805. void modalStateFinished (int returnValue) { function (returnValue, param1, param2); }
  22806. private:
  22807. const FunctionType function;
  22808. ParamType1 param1;
  22809. ParamType2 param2;
  22810. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FunctionCaller2);
  22811. };
  22812. template <typename ComponentType>
  22813. class ComponentCaller1 : public ModalComponentManager::Callback
  22814. {
  22815. public:
  22816. typedef void (*FunctionType) (int, ComponentType*);
  22817. ComponentCaller1 (FunctionType& function_, ComponentType* comp_)
  22818. : function (function_), comp (comp_) {}
  22819. void modalStateFinished (int returnValue)
  22820. {
  22821. function (returnValue, static_cast <ComponentType*> (comp.get()));
  22822. }
  22823. private:
  22824. const FunctionType function;
  22825. WeakReference<Component> comp;
  22826. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller1);
  22827. };
  22828. template <typename ComponentType, typename ParamType1>
  22829. class ComponentCaller2 : public ModalComponentManager::Callback
  22830. {
  22831. public:
  22832. typedef void (*FunctionType) (int, ComponentType*, ParamType1);
  22833. ComponentCaller2 (FunctionType& function_, ComponentType* comp_, ParamType1 param1_)
  22834. : function (function_), comp (comp_), param1 (param1_) {}
  22835. void modalStateFinished (int returnValue)
  22836. {
  22837. function (returnValue, static_cast <ComponentType*> (comp.get()), param1);
  22838. }
  22839. private:
  22840. const FunctionType function;
  22841. WeakReference<Component> comp;
  22842. ParamType1 param1;
  22843. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentCaller2);
  22844. };
  22845. ModalCallbackFunction();
  22846. ~ModalCallbackFunction();
  22847. JUCE_DECLARE_NON_COPYABLE (ModalCallbackFunction);
  22848. };
  22849. #endif // __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  22850. /*** End of inlined file: juce_ModalComponentManager.h ***/
  22851. class LookAndFeel;
  22852. class MouseInputSource;
  22853. class MouseInputSourceInternal;
  22854. class ComponentPeer;
  22855. class MarkerList;
  22856. class RelativeRectangle;
  22857. /**
  22858. The base class for all JUCE user-interface objects.
  22859. */
  22860. class JUCE_API Component : public MouseListener
  22861. {
  22862. public:
  22863. /** Creates a component.
  22864. To get it to actually appear, you'll also need to:
  22865. - Either add it to a parent component or use the addToDesktop() method to
  22866. make it a desktop window
  22867. - Set its size and position to something sensible
  22868. - Use setVisible() to make it visible
  22869. And for it to serve any useful purpose, you'll need to write a
  22870. subclass of Component or use one of the other types of component from
  22871. the library.
  22872. */
  22873. Component();
  22874. /** Destructor.
  22875. Note that when a component is deleted, any child components it contains are NOT
  22876. automatically deleted. It's your responsibilty to manage their lifespan - you
  22877. may want to use helper methods like deleteAllChildren(), or less haphazard
  22878. approaches like using ScopedPointers or normal object aggregation to manage them.
  22879. If the component being deleted is currently the child of another one, then during
  22880. deletion, it will be removed from its parent, and the parent will receive a childrenChanged()
  22881. callback. Any ComponentListener objects that have registered with it will also have their
  22882. ComponentListener::componentBeingDeleted() methods called.
  22883. */
  22884. virtual ~Component();
  22885. /** Creates a component, setting its name at the same time.
  22886. @see getName, setName
  22887. */
  22888. explicit Component (const String& componentName);
  22889. /** Returns the name of this component.
  22890. @see setName
  22891. */
  22892. const String& getName() const throw() { return componentName; }
  22893. /** Sets the name of this component.
  22894. When the name changes, all registered ComponentListeners will receive a
  22895. ComponentListener::componentNameChanged() callback.
  22896. @see getName
  22897. */
  22898. virtual void setName (const String& newName);
  22899. /** Returns the ID string that was set by setComponentID().
  22900. @see setComponentID
  22901. */
  22902. const String& getComponentID() const throw() { return componentID; }
  22903. /** Sets the component's ID string.
  22904. You can retrieve the ID using getComponentID().
  22905. @see getComponentID
  22906. */
  22907. void setComponentID (const String& newID);
  22908. /** Makes the component visible or invisible.
  22909. This method will show or hide the component.
  22910. Note that components default to being non-visible when first created.
  22911. Also note that visible components won't be seen unless all their parent components
  22912. are also visible.
  22913. This method will call visibilityChanged() and also componentVisibilityChanged()
  22914. for any component listeners that are interested in this component.
  22915. @param shouldBeVisible whether to show or hide the component
  22916. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  22917. */
  22918. virtual void setVisible (bool shouldBeVisible);
  22919. /** Tests whether the component is visible or not.
  22920. this doesn't necessarily tell you whether this comp is actually on the screen
  22921. because this depends on whether all the parent components are also visible - use
  22922. isShowing() to find this out.
  22923. @see isShowing, setVisible
  22924. */
  22925. bool isVisible() const throw() { return flags.visibleFlag; }
  22926. /** Called when this component's visiblility changes.
  22927. @see setVisible, isVisible
  22928. */
  22929. virtual void visibilityChanged();
  22930. /** Tests whether this component and all its parents are visible.
  22931. @returns true only if this component and all its parents are visible.
  22932. @see isVisible
  22933. */
  22934. bool isShowing() const;
  22935. /** Makes this component appear as a window on the desktop.
  22936. Note that before calling this, you should make sure that the component's opacity is
  22937. set correctly using setOpaque(). If the component is non-opaque, the windowing
  22938. system will try to create a special transparent window for it, which will generally take
  22939. a lot more CPU to operate (and might not even be possible on some platforms).
  22940. If the component is inside a parent component at the time this method is called, it
  22941. will be first be removed from that parent. Likewise if a component on the desktop
  22942. is subsequently added to another component, it'll be removed from the desktop.
  22943. @param windowStyleFlags a combination of the flags specified in the
  22944. ComponentPeer::StyleFlags enum, which define the
  22945. window's characteristics.
  22946. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  22947. in which the juce component should place itself. On Windows,
  22948. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  22949. supported on all platforms, and best left as 0 unless you know
  22950. what you're doing
  22951. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  22952. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  22953. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  22954. */
  22955. virtual void addToDesktop (int windowStyleFlags,
  22956. void* nativeWindowToAttachTo = 0);
  22957. /** If the component is currently showing on the desktop, this will hide it.
  22958. You can also use setVisible() to hide a desktop window temporarily, but
  22959. removeFromDesktop() will free any system resources that are being used up.
  22960. @see addToDesktop, isOnDesktop
  22961. */
  22962. void removeFromDesktop();
  22963. /** Returns true if this component is currently showing on the desktop.
  22964. @see addToDesktop, removeFromDesktop
  22965. */
  22966. bool isOnDesktop() const throw();
  22967. /** Returns the heavyweight window that contains this component.
  22968. If this component is itself on the desktop, this will return the window
  22969. object that it is using. Otherwise, it will return the window of
  22970. its top-level parent component.
  22971. This may return 0 if there isn't a desktop component.
  22972. @see addToDesktop, isOnDesktop
  22973. */
  22974. ComponentPeer* getPeer() const;
  22975. /** For components on the desktop, this is called if the system wants to close the window.
  22976. This is a signal that either the user or the system wants the window to close. The
  22977. default implementation of this method will trigger an assertion to warn you that your
  22978. component should do something about it, but you can override this to ignore the event
  22979. if you want.
  22980. */
  22981. virtual void userTriedToCloseWindow();
  22982. /** Called for a desktop component which has just been minimised or un-minimised.
  22983. This will only be called for components on the desktop.
  22984. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  22985. */
  22986. virtual void minimisationStateChanged (bool isNowMinimised);
  22987. /** Brings the component to the front of its siblings.
  22988. If some of the component's siblings have had their 'always-on-top' flag set,
  22989. then they will still be kept in front of this one (unless of course this
  22990. one is also 'always-on-top').
  22991. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  22992. to the component (see grabKeyboardFocus() for more details)
  22993. @see toBack, toBehind, setAlwaysOnTop
  22994. */
  22995. void toFront (bool shouldAlsoGainFocus);
  22996. /** Changes this component's z-order to be at the back of all its siblings.
  22997. If the component is set to be 'always-on-top', it will only be moved to the
  22998. back of the other other 'always-on-top' components.
  22999. @see toFront, toBehind, setAlwaysOnTop
  23000. */
  23001. void toBack();
  23002. /** Changes this component's z-order so that it's just behind another component.
  23003. @see toFront, toBack
  23004. */
  23005. void toBehind (Component* other);
  23006. /** Sets whether the component should always be kept at the front of its siblings.
  23007. @see isAlwaysOnTop
  23008. */
  23009. void setAlwaysOnTop (bool shouldStayOnTop);
  23010. /** Returns true if this component is set to always stay in front of its siblings.
  23011. @see setAlwaysOnTop
  23012. */
  23013. bool isAlwaysOnTop() const throw();
  23014. /** Returns the x coordinate of the component's left edge.
  23015. This is a distance in pixels from the left edge of the component's parent.
  23016. Note that if you've used setTransform() to apply a transform, then the component's
  23017. bounds will no longer be a direct reflection of the position at which it appears within
  23018. its parent, as the transform will be applied to its bounding box.
  23019. */
  23020. inline int getX() const throw() { return bounds.getX(); }
  23021. /** Returns the y coordinate of the top of this component.
  23022. This is a distance in pixels from the top edge of the component's parent.
  23023. Note that if you've used setTransform() to apply a transform, then the component's
  23024. bounds will no longer be a direct reflection of the position at which it appears within
  23025. its parent, as the transform will be applied to its bounding box.
  23026. */
  23027. inline int getY() const throw() { return bounds.getY(); }
  23028. /** Returns the component's width in pixels. */
  23029. inline int getWidth() const throw() { return bounds.getWidth(); }
  23030. /** Returns the component's height in pixels. */
  23031. inline int getHeight() const throw() { return bounds.getHeight(); }
  23032. /** Returns the x coordinate of the component's right-hand edge.
  23033. This is a distance in pixels from the left edge of the component's parent.
  23034. Note that if you've used setTransform() to apply a transform, then the component's
  23035. bounds will no longer be a direct reflection of the position at which it appears within
  23036. its parent, as the transform will be applied to its bounding box.
  23037. */
  23038. int getRight() const throw() { return bounds.getRight(); }
  23039. /** Returns the component's top-left position as a Point. */
  23040. const Point<int> getPosition() const throw() { return bounds.getPosition(); }
  23041. /** Returns the y coordinate of the bottom edge of this component.
  23042. This is a distance in pixels from the top edge of the component's parent.
  23043. Note that if you've used setTransform() to apply a transform, then the component's
  23044. bounds will no longer be a direct reflection of the position at which it appears within
  23045. its parent, as the transform will be applied to its bounding box.
  23046. */
  23047. int getBottom() const throw() { return bounds.getBottom(); }
  23048. /** Returns this component's bounding box.
  23049. The rectangle returned is relative to the top-left of the component's parent.
  23050. Note that if you've used setTransform() to apply a transform, then the component's
  23051. bounds will no longer be a direct reflection of the position at which it appears within
  23052. its parent, as the transform will be applied to its bounding box.
  23053. */
  23054. const Rectangle<int>& getBounds() const throw() { return bounds; }
  23055. /** Returns the component's bounds, relative to its own origin.
  23056. This is like getBounds(), but returns the rectangle in local coordinates, In practice, it'll
  23057. return a rectangle with position (0, 0), and the same size as this component.
  23058. */
  23059. const Rectangle<int> getLocalBounds() const throw();
  23060. /** Returns the area of this component's parent which this component covers.
  23061. The returned area is relative to the parent's coordinate space.
  23062. If the component has an affine transform specified, then the resulting area will be
  23063. the smallest rectangle that fully covers the component's transformed bounding box.
  23064. If this component has no parent, the return value will simply be the same as getBounds().
  23065. */
  23066. const Rectangle<int> getBoundsInParent() const throw();
  23067. /** Returns the region of this component that's not obscured by other, opaque components.
  23068. The RectangleList that is returned represents the area of this component
  23069. which isn't covered by opaque child components.
  23070. If includeSiblings is true, it will also take into account any siblings
  23071. that may be overlapping the component.
  23072. */
  23073. void getVisibleArea (RectangleList& result,
  23074. bool includeSiblings) const;
  23075. /** Returns this component's x coordinate relative the the screen's top-left origin.
  23076. @see getX, localPointToGlobal
  23077. */
  23078. int getScreenX() const;
  23079. /** Returns this component's y coordinate relative the the screen's top-left origin.
  23080. @see getY, localPointToGlobal
  23081. */
  23082. int getScreenY() const;
  23083. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  23084. @see getScreenBounds
  23085. */
  23086. const Point<int> getScreenPosition() const;
  23087. /** Returns the bounds of this component, relative to the screen's top-left.
  23088. @see getScreenPosition
  23089. */
  23090. const Rectangle<int> getScreenBounds() const;
  23091. /** Converts a point to be relative to this component's coordinate space.
  23092. This takes a point relative to a different component, and returns its position relative to this
  23093. component. If the sourceComponent parameter is null, the source point is assumed to be a global
  23094. screen coordinate.
  23095. */
  23096. const Point<int> getLocalPoint (const Component* sourceComponent,
  23097. const Point<int>& pointRelativeToSourceComponent) const;
  23098. /** Converts a rectangle to be relative to this component's coordinate space.
  23099. This takes a rectangle that is relative to a different component, and returns its position relative
  23100. to this component. If the sourceComponent parameter is null, the source rectangle is assumed to be
  23101. a screen coordinate.
  23102. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23103. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23104. the smallest rectangle that fully contains the transformed area.
  23105. */
  23106. const Rectangle<int> getLocalArea (const Component* sourceComponent,
  23107. const Rectangle<int>& areaRelativeToSourceComponent) const;
  23108. /** Converts a point relative to this component's top-left into a screen coordinate.
  23109. @see getLocalPoint, localAreaToGlobal
  23110. */
  23111. const Point<int> localPointToGlobal (const Point<int>& localPoint) const;
  23112. /** Converts a rectangle from this component's coordinate space to a screen coordinate.
  23113. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  23114. may not actually be rectanglular when converted to the target space, so in that situation this will return
  23115. the smallest rectangle that fully contains the transformed area.
  23116. @see getLocalPoint, localPointToGlobal
  23117. */
  23118. const Rectangle<int> localAreaToGlobal (const Rectangle<int>& localArea) const;
  23119. /** Moves the component to a new position.
  23120. Changes the component's top-left position (without changing its size).
  23121. The position is relative to the top-left of the component's parent.
  23122. If the component actually moves, this method will make a synchronous call to moved().
  23123. Note that if you've used setTransform() to apply a transform, then the component's
  23124. bounds will no longer be a direct reflection of the position at which it appears within
  23125. its parent, as the transform will be applied to whatever bounds you set for it.
  23126. @see setBounds, ComponentListener::componentMovedOrResized
  23127. */
  23128. void setTopLeftPosition (int x, int y);
  23129. /** Moves the component to a new position.
  23130. Changes the position of the component's top-right corner (keeping it the same size).
  23131. The position is relative to the top-left of the component's parent.
  23132. If the component actually moves, this method will make a synchronous call to moved().
  23133. Note that if you've used setTransform() to apply a transform, then the component's
  23134. bounds will no longer be a direct reflection of the position at which it appears within
  23135. its parent, as the transform will be applied to whatever bounds you set for it.
  23136. */
  23137. void setTopRightPosition (int x, int y);
  23138. /** Changes the size of the component.
  23139. A synchronous call to resized() will be occur if the size actually changes.
  23140. Note that if you've used setTransform() to apply a transform, then the component's
  23141. bounds will no longer be a direct reflection of the position at which it appears within
  23142. its parent, as the transform will be applied to whatever bounds you set for it.
  23143. */
  23144. void setSize (int newWidth, int newHeight);
  23145. /** Changes the component's position and size.
  23146. The coordinates are relative to the top-left of the component's parent, or relative
  23147. to the origin of the screen is the component is on the desktop.
  23148. If this method changes the component's top-left position, it will make a synchronous
  23149. call to moved(). If it changes the size, it will also make a call to resized().
  23150. Note that if you've used setTransform() to apply a transform, then the component's
  23151. bounds will no longer be a direct reflection of the position at which it appears within
  23152. its parent, as the transform will be applied to whatever bounds you set for it.
  23153. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  23154. */
  23155. void setBounds (int x, int y, int width, int height);
  23156. /** Changes the component's position and size.
  23157. The coordinates are relative to the top-left of the component's parent, or relative
  23158. to the origin of the screen is the component is on the desktop.
  23159. If this method changes the component's top-left position, it will make a synchronous
  23160. call to moved(). If it changes the size, it will also make a call to resized().
  23161. Note that if you've used setTransform() to apply a transform, then the component's
  23162. bounds will no longer be a direct reflection of the position at which it appears within
  23163. its parent, as the transform will be applied to whatever bounds you set for it.
  23164. @see setBounds
  23165. */
  23166. void setBounds (const Rectangle<int>& newBounds);
  23167. /** Changes the component's position and size.
  23168. This is similar to the other setBounds() methods, but uses RelativeRectangle::applyToComponent()
  23169. to set the position, This uses a Component::Positioner to make sure that any dynamic
  23170. expressions are used in the RelativeRectangle will be automatically re-applied to the
  23171. component's bounds when the source values change. See RelativeRectangle::applyToComponent()
  23172. for more details.
  23173. When using relative expressions, the following symbols are available:
  23174. - "left", "right", "top", "bottom" refer to the position of those edges in this component, so
  23175. e.g. for a component whose width is always 100, you might set the right edge to the "left + 100".
  23176. - "[id].left", "[id].right", "[id].top", "[id].bottom", "[id].width", "[id].height", where [id] is
  23177. the identifier of one of this component's siblings. A component's identifier is set with
  23178. Component::setComponentID(). So for example if you want your component to always be 50 pixels to the
  23179. right of the one called "xyz", you could set your left edge to be "xyz.right + 50".
  23180. - Instead of an [id], you can use the name "parent" to refer to this component's parent. Like
  23181. any other component, these values are relative to their component's parent, so "parent.right" won't be
  23182. very useful for positioning a component because it refers to a position with the parent's parent.. but
  23183. "parent.width" can be used for setting positions relative to the parent's size. E.g. to make a 10x10
  23184. component which remains 1 pixel away from its parent's bottom-right, you could use
  23185. "right - 10, bottom - 10, parent.width - 1, parent.height - 1".
  23186. - The name of one of the parent component's markers can also be used as a symbol. For markers to be
  23187. used, the parent component must implement its Component::getMarkers() method, and return at least one
  23188. valid MarkerList. So if you want your component's top edge to be 10 pixels below the
  23189. marker called "foobar", you'd set it to "foobar + 10".
  23190. See the Expression class for details about the operators that are supported, but for example
  23191. if you wanted to make your component remain centred within its parent with a size of 100, 100,
  23192. you could express it as:
  23193. @code myComp.setBounds (RelativeBounds ("parent.width / 2 - 50, parent.height / 2 - 50, left + 100, top + 100"));
  23194. @endcode
  23195. ..or an alternative way to achieve the same thing:
  23196. @code myComp.setBounds (RelativeBounds ("right - 100, bottom - 100, parent.width / 2 + 50, parent.height / 2 + 50"));
  23197. @endcode
  23198. Or if you wanted a 100x100 component whose top edge is lined up to a marker called "topMarker" and
  23199. which is positioned 50 pixels to the right of another component called "otherComp", you could write:
  23200. @code myComp.setBounds (RelativeBounds ("otherComp.right + 50, topMarker, left + 100, top + 100"));
  23201. @endcode
  23202. Be careful not to make your coordinate expressions recursive, though, or exceptions and assertions will
  23203. be thrown!
  23204. @see setBounds, RelativeRectangle::applyToComponent(), Expression
  23205. */
  23206. void setBounds (const RelativeRectangle& newBounds);
  23207. /** Sets the component's bounds with an expression.
  23208. The string is parsed as a RelativeRectangle expression - see the notes for
  23209. Component::setBounds (const RelativeRectangle&) for more information. This method is
  23210. basically just a shortcut for writing setBounds (RelativeRectangle ("..."))
  23211. */
  23212. void setBounds (const String& newBoundsExpression);
  23213. /** Changes the component's position and size in terms of fractions of its parent's size.
  23214. The values are factors of the parent's size, so for example
  23215. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  23216. width and height of the parent, with its top-left position 20% of
  23217. the way across and down the parent.
  23218. @see setBounds
  23219. */
  23220. void setBoundsRelative (float proportionalX, float proportionalY,
  23221. float proportionalWidth, float proportionalHeight);
  23222. /** Changes the component's position and size based on the amount of space to leave around it.
  23223. This will position the component within its parent, leaving the specified number of
  23224. pixels around each edge.
  23225. @see setBounds
  23226. */
  23227. void setBoundsInset (const BorderSize<int>& borders);
  23228. /** Positions the component within a given rectangle, keeping its proportions
  23229. unchanged.
  23230. If onlyReduceInSize is false, the component will be resized to fill as much of the
  23231. rectangle as possible without changing its aspect ratio (the component's
  23232. current size is used to determine its aspect ratio, so a zero-size component
  23233. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  23234. too big to fit inside the rectangle.
  23235. It will then be positioned within the rectangle according to the justification flags
  23236. specified.
  23237. @see setBounds
  23238. */
  23239. void setBoundsToFit (int x, int y, int width, int height,
  23240. const Justification& justification,
  23241. bool onlyReduceInSize);
  23242. /** Changes the position of the component's centre.
  23243. Leaves the component's size unchanged, but sets the position of its centre
  23244. relative to its parent's top-left.
  23245. @see setBounds
  23246. */
  23247. void setCentrePosition (int x, int y);
  23248. /** Changes the position of the component's centre.
  23249. Leaves the position unchanged, but positions its centre relative to its
  23250. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  23251. its parent.
  23252. */
  23253. void setCentreRelative (float x, float y);
  23254. /** Changes the component's size and centres it within its parent.
  23255. After changing the size, the component will be moved so that it's
  23256. centred within its parent. If the component is on the desktop (or has no
  23257. parent component), then it'll be centred within the main monitor area.
  23258. */
  23259. void centreWithSize (int width, int height);
  23260. /** Sets a transform matrix to be applied to this component.
  23261. If you set a transform for a component, the component's position will be warped by it, relative to
  23262. the component's parent's top-left origin. This means that the values you pass into setBounds() will no
  23263. longer reflect the actual area within the parent that the component covers, as the bounds will be
  23264. transformed and the component will probably end up actually appearing somewhere else within its parent.
  23265. When using transforms you need to be extremely careful when converting coordinates between the
  23266. coordinate spaces of different components or the screen - you should always use getLocalPoint(),
  23267. getLocalArea(), etc to do this, and never just manually add a component's position to a point in order to
  23268. convert it between different components (but I'm sure you would never have done that anyway...).
  23269. Currently, transforms are not supported for desktop windows, so the transform will be ignored if you
  23270. put a component on the desktop.
  23271. To remove a component's transform, simply pass AffineTransform::identity as the parameter to this method.
  23272. */
  23273. void setTransform (const AffineTransform& transform);
  23274. /** Returns the transform that is currently being applied to this component.
  23275. For more details about transforms, see setTransform().
  23276. @see setTransform
  23277. */
  23278. const AffineTransform getTransform() const;
  23279. /** Returns true if a non-identity transform is being applied to this component.
  23280. For more details about transforms, see setTransform().
  23281. @see setTransform
  23282. */
  23283. bool isTransformed() const throw();
  23284. /** Returns a proportion of the component's width.
  23285. This is a handy equivalent of (getWidth() * proportion).
  23286. */
  23287. int proportionOfWidth (float proportion) const throw();
  23288. /** Returns a proportion of the component's height.
  23289. This is a handy equivalent of (getHeight() * proportion).
  23290. */
  23291. int proportionOfHeight (float proportion) const throw();
  23292. /** Returns the width of the component's parent.
  23293. If the component has no parent (i.e. if it's on the desktop), this will return
  23294. the width of the screen.
  23295. */
  23296. int getParentWidth() const throw();
  23297. /** Returns the height of the component's parent.
  23298. If the component has no parent (i.e. if it's on the desktop), this will return
  23299. the height of the screen.
  23300. */
  23301. int getParentHeight() const throw();
  23302. /** Returns the screen coordinates of the monitor that contains this component.
  23303. If there's only one monitor, this will return its size - if there are multiple
  23304. monitors, it will return the area of the monitor that contains the component's
  23305. centre.
  23306. */
  23307. const Rectangle<int> getParentMonitorArea() const;
  23308. /** Returns the number of child components that this component contains.
  23309. @see getChildComponent, getIndexOfChildComponent
  23310. */
  23311. int getNumChildComponents() const throw();
  23312. /** Returns one of this component's child components, by it index.
  23313. The component with index 0 is at the back of the z-order, the one at the
  23314. front will have index (getNumChildComponents() - 1).
  23315. If the index is out-of-range, this will return a null pointer.
  23316. @see getNumChildComponents, getIndexOfChildComponent
  23317. */
  23318. Component* getChildComponent (int index) const throw();
  23319. /** Returns the index of this component in the list of child components.
  23320. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  23321. values are further towards the front.
  23322. Returns -1 if the component passed-in is not a child of this component.
  23323. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  23324. */
  23325. int getIndexOfChildComponent (const Component* child) const throw();
  23326. /** Adds a child component to this one.
  23327. Adding a child component does not mean that the component will own or delete the child - it's
  23328. your responsibility to delete the component. Note that it's safe to delete a component
  23329. without first removing it from its parent - doing so will automatically remove it and
  23330. send out the appropriate notifications before the deletion completes.
  23331. If the child is already a child of this component, then no action will be taken, and its
  23332. z-order will be left unchanged.
  23333. @param child the new component to add. If the component passed-in is already
  23334. the child of another component, it'll first be removed from it current parent.
  23335. @param zOrder The index in the child-list at which this component should be inserted.
  23336. A value of -1 will insert it in front of the others, 0 is the back.
  23337. @see removeChildComponent, addAndMakeVisible, getChild, ComponentListener::componentChildrenChanged
  23338. */
  23339. void addChildComponent (Component* child, int zOrder = -1);
  23340. /** Adds a child component to this one, and also makes the child visible if it isn't.
  23341. Quite a useful function, this is just the same as calling setVisible (true) on the child
  23342. and then addChildComponent(). See addChildComponent() for more details.
  23343. */
  23344. void addAndMakeVisible (Component* child, int zOrder = -1);
  23345. /** Removes one of this component's child-components.
  23346. If the child passed-in isn't actually a child of this component (either because
  23347. it's invalid or is the child of a different parent), then no action is taken.
  23348. Note that removing a child will not delete it! But it's ok to delete a component
  23349. without first removing it - doing so will automatically remove it and send out the
  23350. appropriate notifications before the deletion completes.
  23351. @see addChildComponent, ComponentListener::componentChildrenChanged
  23352. */
  23353. void removeChildComponent (Component* childToRemove);
  23354. /** Removes one of this component's child-components by index.
  23355. This will return a pointer to the component that was removed, or null if
  23356. the index was out-of-range.
  23357. Note that removing a child will not delete it! But it's ok to delete a component
  23358. without first removing it - doing so will automatically remove it and send out the
  23359. appropriate notifications before the deletion completes.
  23360. @see addChildComponent, ComponentListener::componentChildrenChanged
  23361. */
  23362. Component* removeChildComponent (int childIndexToRemove);
  23363. /** Removes all this component's children.
  23364. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  23365. */
  23366. void removeAllChildren();
  23367. /** Removes all this component's children, and deletes them.
  23368. @see removeAllChildren
  23369. */
  23370. void deleteAllChildren();
  23371. /** Returns the component which this component is inside.
  23372. If this is the highest-level component or hasn't yet been added to
  23373. a parent, this will return null.
  23374. */
  23375. Component* getParentComponent() const throw() { return parentComponent; }
  23376. /** Searches the parent components for a component of a specified class.
  23377. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  23378. component that can be dynamically cast to a MyComp, or will return 0 if none
  23379. of the parents are suitable.
  23380. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  23381. */
  23382. template <class TargetClass>
  23383. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  23384. {
  23385. (void) dummyParameter;
  23386. Component* p = parentComponent;
  23387. while (p != 0)
  23388. {
  23389. TargetClass* target = dynamic_cast <TargetClass*> (p);
  23390. if (target != 0)
  23391. return target;
  23392. p = p->parentComponent;
  23393. }
  23394. return 0;
  23395. }
  23396. /** Returns the highest-level component which contains this one or its parents.
  23397. This will search upwards in the parent-hierarchy from this component, until it
  23398. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  23399. not yet added to a parent), and will return that.
  23400. */
  23401. Component* getTopLevelComponent() const throw();
  23402. /** Checks whether a component is anywhere inside this component or its children.
  23403. This will recursively check through this component's children to see if the
  23404. given component is anywhere inside.
  23405. */
  23406. bool isParentOf (const Component* possibleChild) const throw();
  23407. /** Called to indicate that the component's parents have changed.
  23408. When a component is added or removed from its parent, this method will
  23409. be called on all of its children (recursively - so all children of its
  23410. children will also be called as well).
  23411. Subclasses can override this if they need to react to this in some way.
  23412. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  23413. */
  23414. virtual void parentHierarchyChanged();
  23415. /** Subclasses can use this callback to be told when children are added or removed.
  23416. @see parentHierarchyChanged
  23417. */
  23418. virtual void childrenChanged();
  23419. /** Tests whether a given point inside the component.
  23420. Overriding this method allows you to create components which only intercept
  23421. mouse-clicks within a user-defined area.
  23422. This is called to find out whether a particular x, y coordinate is
  23423. considered to be inside the component or not, and is used by methods such
  23424. as contains() and getComponentAt() to work out which component
  23425. the mouse is clicked on.
  23426. Components with custom shapes will probably want to override it to perform
  23427. some more complex hit-testing.
  23428. The default implementation of this method returns either true or false,
  23429. depending on the value that was set by calling setInterceptsMouseClicks() (true
  23430. is the default return value).
  23431. Note that the hit-test region is not related to the opacity with which
  23432. areas of a component are painted.
  23433. Applications should never call hitTest() directly - instead use the
  23434. contains() method, because this will also test for occlusion by the
  23435. component's parent.
  23436. Note that for components on the desktop, this method will be ignored, because it's
  23437. not always possible to implement this behaviour on all platforms.
  23438. @param x the x coordinate to test, relative to the left hand edge of this
  23439. component. This value is guaranteed to be greater than or equal to
  23440. zero, and less than the component's width
  23441. @param y the y coordinate to test, relative to the top edge of this
  23442. component. This value is guaranteed to be greater than or equal to
  23443. zero, and less than the component's height
  23444. @returns true if the click is considered to be inside the component
  23445. @see setInterceptsMouseClicks, contains
  23446. */
  23447. virtual bool hitTest (int x, int y);
  23448. /** Changes the default return value for the hitTest() method.
  23449. Setting this to false is an easy way to make a component pass its mouse-clicks
  23450. through to the components behind it.
  23451. When a component is created, the default setting for this is true.
  23452. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  23453. return false (or true for child components if allowClicksOnChildComponents
  23454. is true)
  23455. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  23456. components can be clicked on as normal but clicks on this component pass
  23457. straight through; if this is false and allowClicksOnThisComponent
  23458. is false, then neither this component nor any child components can
  23459. be clicked on
  23460. @see hitTest, getInterceptsMouseClicks
  23461. */
  23462. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  23463. bool allowClicksOnChildComponents) throw();
  23464. /** Retrieves the current state of the mouse-click interception flags.
  23465. On return, the two parameters are set to the state used in the last call to
  23466. setInterceptsMouseClicks().
  23467. @see setInterceptsMouseClicks
  23468. */
  23469. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  23470. bool& allowsClicksOnChildComponents) const throw();
  23471. /** Returns true if a given point lies within this component or one of its children.
  23472. Never override this method! Use hitTest to create custom hit regions.
  23473. @param localPoint the coordinate to test, relative to this component's top-left.
  23474. @returns true if the point is within the component's hit-test area, but only if
  23475. that part of the component isn't clipped by its parent component. Note
  23476. that this won't take into account any overlapping sibling components
  23477. which might be in the way - for that, see reallyContains()
  23478. @see hitTest, reallyContains, getComponentAt
  23479. */
  23480. bool contains (const Point<int>& localPoint);
  23481. /** Returns true if a given point lies in this component, taking any overlapping
  23482. siblings into account.
  23483. @param localPoint the coordinate to test, relative to this component's top-left.
  23484. @param returnTrueIfWithinAChild if the point actually lies within a child of this component,
  23485. this determines whether that is counted as a hit.
  23486. @see contains, getComponentAt
  23487. */
  23488. bool reallyContains (const Point<int>& localPoint, bool returnTrueIfWithinAChild);
  23489. /** Returns the component at a certain point within this one.
  23490. @param x the x coordinate to test, relative to this component's left edge.
  23491. @param y the y coordinate to test, relative to this component's top edge.
  23492. @returns the component that is at this position - which may be 0, this component,
  23493. or one of its children. Note that overlapping siblings that might actually
  23494. be in the way are not taken into account by this method - to account for these,
  23495. instead call getComponentAt on the top-level parent of this component.
  23496. @see hitTest, contains, reallyContains
  23497. */
  23498. Component* getComponentAt (int x, int y);
  23499. /** Returns the component at a certain point within this one.
  23500. @param position the coordinate to test, relative to this component's top-left.
  23501. @returns the component that is at this position - which may be 0, this component,
  23502. or one of its children. Note that overlapping siblings that might actually
  23503. be in the way are not taken into account by this method - to account for these,
  23504. instead call getComponentAt on the top-level parent of this component.
  23505. @see hitTest, contains, reallyContains
  23506. */
  23507. Component* getComponentAt (const Point<int>& position);
  23508. /** Marks the whole component as needing to be redrawn.
  23509. Calling this will not do any repainting immediately, but will mark the component
  23510. as 'dirty'. At some point in the near future the operating system will send a paint
  23511. message, which will redraw all the dirty regions of all components.
  23512. There's no guarantee about how soon after calling repaint() the redraw will actually
  23513. happen, and other queued events may be delivered before a redraw is done.
  23514. If the setBufferedToImage() method has been used to cause this component
  23515. to use a buffer, the repaint() call will invalidate the component's buffer.
  23516. To redraw just a subsection of the component rather than the whole thing,
  23517. use the repaint (int, int, int, int) method.
  23518. @see paint
  23519. */
  23520. void repaint();
  23521. /** Marks a subsection of this component as needing to be redrawn.
  23522. Calling this will not do any repainting immediately, but will mark the given region
  23523. of the component as 'dirty'. At some point in the near future the operating system
  23524. will send a paint message, which will redraw all the dirty regions of all components.
  23525. There's no guarantee about how soon after calling repaint() the redraw will actually
  23526. happen, and other queued events may be delivered before a redraw is done.
  23527. The region that is passed in will be clipped to keep it within the bounds of this
  23528. component.
  23529. @see repaint()
  23530. */
  23531. void repaint (int x, int y, int width, int height);
  23532. /** Marks a subsection of this component as needing to be redrawn.
  23533. Calling this will not do any repainting immediately, but will mark the given region
  23534. of the component as 'dirty'. At some point in the near future the operating system
  23535. will send a paint message, which will redraw all the dirty regions of all components.
  23536. There's no guarantee about how soon after calling repaint() the redraw will actually
  23537. happen, and other queued events may be delivered before a redraw is done.
  23538. The region that is passed in will be clipped to keep it within the bounds of this
  23539. component.
  23540. @see repaint()
  23541. */
  23542. void repaint (const Rectangle<int>& area);
  23543. /** Makes the component use an internal buffer to optimise its redrawing.
  23544. Setting this flag to true will cause the component to allocate an
  23545. internal buffer into which it paints itself, so that when asked to
  23546. redraw itself, it can use this buffer rather than actually calling the
  23547. paint() method.
  23548. The buffer is kept until the repaint() method is called directly on
  23549. this component (or until it is resized), when the image is invalidated
  23550. and then redrawn the next time the component is painted.
  23551. Note that only the drawing that happens within the component's paint()
  23552. method is drawn into the buffer, it's child components are not buffered, and
  23553. nor is the paintOverChildren() method.
  23554. @see repaint, paint, createComponentSnapshot
  23555. */
  23556. void setBufferedToImage (bool shouldBeBuffered);
  23557. /** Generates a snapshot of part of this component.
  23558. This will return a new Image, the size of the rectangle specified,
  23559. containing a snapshot of the specified area of the component and all
  23560. its children.
  23561. The image may or may not have an alpha-channel, depending on whether the
  23562. image is opaque or not.
  23563. If the clipImageToComponentBounds parameter is true and the area is greater than
  23564. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  23565. then parts of the component beyond its bounds can be drawn.
  23566. @see paintEntireComponent
  23567. */
  23568. const Image createComponentSnapshot (const Rectangle<int>& areaToGrab,
  23569. bool clipImageToComponentBounds = true);
  23570. /** Draws this component and all its subcomponents onto the specified graphics
  23571. context.
  23572. You should very rarely have to use this method, it's simply there in case you need
  23573. to draw a component with a custom graphics context for some reason, e.g. for
  23574. creating a snapshot of the component.
  23575. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  23576. on its children in order to render the entire tree.
  23577. The graphics context may be left in an undefined state after this method returns,
  23578. so you may need to reset it if you're going to use it again.
  23579. If ignoreAlphaLevel is false, then the component will be drawn with the opacity level
  23580. specified by getAlpha(); if ignoreAlphaLevel is true, then this will be ignored and
  23581. an alpha of 1.0 will be used.
  23582. */
  23583. void paintEntireComponent (Graphics& context, bool ignoreAlphaLevel);
  23584. /** This allows you to indicate that this component doesn't require its graphics
  23585. context to be clipped when it is being painted.
  23586. Most people will never need to use this setting, but in situations where you have a very large
  23587. number of simple components being rendered, and where they are guaranteed never to do any drawing
  23588. beyond their own boundaries, setting this to true will reduce the overhead involved in clipping
  23589. the graphics context that gets passed to the component's paint() callback.
  23590. If you enable this mode, you'll need to make sure your paint method doesn't call anything like
  23591. Graphics::fillAll(), and doesn't draw beyond the component's bounds, because that'll produce
  23592. artifacts. Your component also can't have any child components that may be placed beyond its
  23593. bounds.
  23594. */
  23595. void setPaintingIsUnclipped (bool shouldPaintWithoutClipping) throw();
  23596. /** Adds an effect filter to alter the component's appearance.
  23597. When a component has an effect filter set, then this is applied to the
  23598. results of its paint() method. There are a few preset effects, such as
  23599. a drop-shadow or glow, but they can be user-defined as well.
  23600. The effect that is passed in will not be deleted by the component - the
  23601. caller must take care of deleting it.
  23602. To remove an effect from a component, pass a null pointer in as the parameter.
  23603. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  23604. */
  23605. void setComponentEffect (ImageEffectFilter* newEffect);
  23606. /** Returns the current component effect.
  23607. @see setComponentEffect
  23608. */
  23609. ImageEffectFilter* getComponentEffect() const throw() { return effect; }
  23610. /** Finds the appropriate look-and-feel to use for this component.
  23611. If the component hasn't had a look-and-feel explicitly set, this will
  23612. return the parent's look-and-feel, or just the default one if there's no
  23613. parent.
  23614. @see setLookAndFeel, lookAndFeelChanged
  23615. */
  23616. LookAndFeel& getLookAndFeel() const throw();
  23617. /** Sets the look and feel to use for this component.
  23618. This will also change the look and feel for any child components that haven't
  23619. had their look set explicitly.
  23620. The object passed in will not be deleted by the component, so it's the caller's
  23621. responsibility to manage it. It may be used at any time until this component
  23622. has been deleted.
  23623. Calling this method will also invoke the sendLookAndFeelChange() method.
  23624. @see getLookAndFeel, lookAndFeelChanged
  23625. */
  23626. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  23627. /** Called to let the component react to a change in the look-and-feel setting.
  23628. When the look-and-feel is changed for a component, this will be called in
  23629. all its child components, recursively.
  23630. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  23631. an application uses a LookAndFeel class that might have changed internally.
  23632. @see sendLookAndFeelChange, getLookAndFeel
  23633. */
  23634. virtual void lookAndFeelChanged();
  23635. /** Calls the lookAndFeelChanged() method in this component and all its children.
  23636. This will recurse through the children and their children, calling lookAndFeelChanged()
  23637. on them all.
  23638. @see lookAndFeelChanged
  23639. */
  23640. void sendLookAndFeelChange();
  23641. /** Indicates whether any parts of the component might be transparent.
  23642. Components that always paint all of their contents with solid colour and
  23643. thus completely cover any components behind them should use this method
  23644. to tell the repaint system that they are opaque.
  23645. This information is used to optimise drawing, because it means that
  23646. objects underneath opaque windows don't need to be painted.
  23647. By default, components are considered transparent, unless this is used to
  23648. make it otherwise.
  23649. @see isOpaque, getVisibleArea
  23650. */
  23651. void setOpaque (bool shouldBeOpaque);
  23652. /** Returns true if no parts of this component are transparent.
  23653. @returns the value that was set by setOpaque, (the default being false)
  23654. @see setOpaque
  23655. */
  23656. bool isOpaque() const throw();
  23657. /** Indicates whether the component should be brought to the front when clicked.
  23658. Setting this flag to true will cause the component to be brought to the front
  23659. when the mouse is clicked somewhere inside it or its child components.
  23660. Note that a top-level desktop window might still be brought to the front by the
  23661. operating system when it's clicked, depending on how the OS works.
  23662. By default this is set to false.
  23663. @see setMouseClickGrabsKeyboardFocus
  23664. */
  23665. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) throw();
  23666. /** Indicates whether the component should be brought to the front when clicked-on.
  23667. @see setBroughtToFrontOnMouseClick
  23668. */
  23669. bool isBroughtToFrontOnMouseClick() const throw();
  23670. // Keyboard focus methods
  23671. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  23672. By default components aren't actually interested in gaining the
  23673. focus, but this method can be used to turn this on.
  23674. See the grabKeyboardFocus() method for details about the way a component
  23675. is chosen to receive the focus.
  23676. @see grabKeyboardFocus, getWantsKeyboardFocus
  23677. */
  23678. void setWantsKeyboardFocus (bool wantsFocus) throw();
  23679. /** Returns true if the component is interested in getting keyboard focus.
  23680. This returns the flag set by setWantsKeyboardFocus(). The default
  23681. setting is false.
  23682. @see setWantsKeyboardFocus
  23683. */
  23684. bool getWantsKeyboardFocus() const throw();
  23685. /** Chooses whether a click on this component automatically grabs the focus.
  23686. By default this is set to true, but you might want a component which can
  23687. be focused, but where you don't want the user to be able to affect it directly
  23688. by clicking.
  23689. */
  23690. void setMouseClickGrabsKeyboardFocus (bool shouldGrabFocus);
  23691. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  23692. See setMouseClickGrabsKeyboardFocus() for more info.
  23693. */
  23694. bool getMouseClickGrabsKeyboardFocus() const throw();
  23695. /** Tries to give keyboard focus to this component.
  23696. When the user clicks on a component or its grabKeyboardFocus()
  23697. method is called, the following procedure is used to work out which
  23698. component should get it:
  23699. - if the component that was clicked on actually wants focus (as indicated
  23700. by calling getWantsKeyboardFocus), it gets it.
  23701. - if the component itself doesn't want focus, it will try to pass it
  23702. on to whichever of its children is the default component, as determined by
  23703. KeyboardFocusTraverser::getDefaultComponent()
  23704. - if none of its children want focus at all, it will pass it up to its
  23705. parent instead, unless it's a top-level component without a parent,
  23706. in which case it just takes the focus itself.
  23707. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  23708. getCurrentlyFocusedComponent, focusGained, focusLost,
  23709. keyPressed, keyStateChanged
  23710. */
  23711. void grabKeyboardFocus();
  23712. /** Returns true if this component currently has the keyboard focus.
  23713. @param trueIfChildIsFocused if this is true, then the method returns true if
  23714. either this component or any of its children (recursively)
  23715. have the focus. If false, the method only returns true if
  23716. this component has the focus.
  23717. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  23718. focusGained, focusLost
  23719. */
  23720. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  23721. /** Returns the component that currently has the keyboard focus.
  23722. @returns the focused component, or null if nothing is focused.
  23723. */
  23724. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  23725. /** Tries to move the keyboard focus to one of this component's siblings.
  23726. This will try to move focus to either the next or previous component. (This
  23727. is the method that is used when shifting focus by pressing the tab key).
  23728. Components for which getWantsKeyboardFocus() returns false are not looked at.
  23729. @param moveToNext if true, the focus will move forwards; if false, it will
  23730. move backwards
  23731. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  23732. */
  23733. void moveKeyboardFocusToSibling (bool moveToNext);
  23734. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  23735. which focus should be passed from this component.
  23736. The default implementation of this method will return a default
  23737. KeyboardFocusTraverser if this component is a focus container (as determined
  23738. by the setFocusContainer() method). If the component isn't a focus
  23739. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  23740. If you overrride this to return a custom KeyboardFocusTraverser, then
  23741. this component and all its sub-components will use the new object to
  23742. make their focusing decisions.
  23743. The method should return a new object, which the caller is required to
  23744. delete when no longer needed.
  23745. */
  23746. virtual KeyboardFocusTraverser* createFocusTraverser();
  23747. /** Returns the focus order of this component, if one has been specified.
  23748. By default components don't have a focus order - in that case, this
  23749. will return 0. Lower numbers indicate that the component will be
  23750. earlier in the focus traversal order.
  23751. To change the order, call setExplicitFocusOrder().
  23752. The focus order may be used by the KeyboardFocusTraverser class as part of
  23753. its algorithm for deciding the order in which components should be traversed.
  23754. See the KeyboardFocusTraverser class for more details on this.
  23755. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  23756. */
  23757. int getExplicitFocusOrder() const;
  23758. /** Sets the index used in determining the order in which focusable components
  23759. should be traversed.
  23760. A value of 0 or less is taken to mean that no explicit order is wanted, and
  23761. that traversal should use other factors, like the component's position.
  23762. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  23763. */
  23764. void setExplicitFocusOrder (int newFocusOrderIndex);
  23765. /** Indicates whether this component is a parent for components that can have
  23766. their focus traversed.
  23767. This flag is used by the default implementation of the createFocusTraverser()
  23768. method, which uses the flag to find the first parent component (of the currently
  23769. focused one) which wants to be a focus container.
  23770. So using this method to set the flag to 'true' causes this component to
  23771. act as the top level within which focus is passed around.
  23772. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  23773. */
  23774. void setFocusContainer (bool shouldBeFocusContainer) throw();
  23775. /** Returns true if this component has been marked as a focus container.
  23776. See setFocusContainer() for more details.
  23777. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  23778. */
  23779. bool isFocusContainer() const throw();
  23780. /** Returns true if the component (and all its parents) are enabled.
  23781. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  23782. what difference this makes to the component depends on the type. E.g. buttons
  23783. and sliders will choose to draw themselves differently, etc.
  23784. Note that if one of this component's parents is disabled, this will always
  23785. return false, even if this component itself is enabled.
  23786. @see setEnabled, enablementChanged
  23787. */
  23788. bool isEnabled() const throw();
  23789. /** Enables or disables this component.
  23790. Disabling a component will also cause all of its child components to become
  23791. disabled.
  23792. Similarly, enabling a component which is inside a disabled parent
  23793. component won't make any difference until the parent is re-enabled.
  23794. @see isEnabled, enablementChanged
  23795. */
  23796. void setEnabled (bool shouldBeEnabled);
  23797. /** Callback to indicate that this component has been enabled or disabled.
  23798. This can be triggered by one of the component's parent components
  23799. being enabled or disabled, as well as changes to the component itself.
  23800. The default implementation of this method does nothing; your class may
  23801. wish to repaint itself or something when this happens.
  23802. @see setEnabled, isEnabled
  23803. */
  23804. virtual void enablementChanged();
  23805. /** Changes the transparency of this component.
  23806. When painted, the entire component and all its children will be rendered
  23807. with this as the overall opacity level, where 0 is completely invisible, and
  23808. 1.0 is fully opaque (i.e. normal).
  23809. @see getAlpha
  23810. */
  23811. void setAlpha (float newAlpha);
  23812. /** Returns the component's current transparancy level.
  23813. See setAlpha() for more details.
  23814. */
  23815. float getAlpha() const;
  23816. /** Changes the mouse cursor shape to use when the mouse is over this component.
  23817. Note that the cursor set by this method can be overridden by the getMouseCursor
  23818. method.
  23819. @see MouseCursor
  23820. */
  23821. void setMouseCursor (const MouseCursor& cursorType);
  23822. /** Returns the mouse cursor shape to use when the mouse is over this component.
  23823. The default implementation will return the cursor that was set by setCursor()
  23824. but can be overridden for more specialised purposes, e.g. returning different
  23825. cursors depending on the mouse position.
  23826. @see MouseCursor
  23827. */
  23828. virtual const MouseCursor getMouseCursor();
  23829. /** Forces the current mouse cursor to be updated.
  23830. If you're overriding the getMouseCursor() method to control which cursor is
  23831. displayed, then this will only be checked each time the user moves the mouse. So
  23832. if you want to force the system to check that the cursor being displayed is
  23833. up-to-date (even if the mouse is just sitting there), call this method.
  23834. (If you're changing the cursor using setMouseCursor(), you don't need to bother
  23835. calling this).
  23836. */
  23837. void updateMouseCursor() const;
  23838. /** Components can override this method to draw their content.
  23839. The paint() method gets called when a region of a component needs redrawing,
  23840. either because the component's repaint() method has been called, or because
  23841. something has happened on the screen that means a section of a window needs
  23842. to be redrawn.
  23843. Any child components will draw themselves over whatever this method draws. If
  23844. you need to paint over the top of your child components, you can also implement
  23845. the paintOverChildren() method to do this.
  23846. If you want to cause a component to redraw itself, this is done asynchronously -
  23847. calling the repaint() method marks a region of the component as "dirty", and the
  23848. paint() method will automatically be called sometime later, by the message thread,
  23849. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  23850. you never redraw something synchronously.
  23851. You should never need to call this method directly - to take a snapshot of the
  23852. component you could use createComponentSnapshot() or paintEntireComponent().
  23853. @param g the graphics context that must be used to do the drawing operations.
  23854. @see repaint, paintOverChildren, Graphics
  23855. */
  23856. virtual void paint (Graphics& g);
  23857. /** Components can override this method to draw over the top of their children.
  23858. For most drawing operations, it's better to use the normal paint() method,
  23859. but if you need to overlay something on top of the children, this can be
  23860. used.
  23861. @see paint, Graphics
  23862. */
  23863. virtual void paintOverChildren (Graphics& g);
  23864. /** Called when the mouse moves inside this component.
  23865. If the mouse button isn't pressed and the mouse moves over a component,
  23866. this will be called to let the component react to this.
  23867. A component will always get a mouseEnter callback before a mouseMove.
  23868. @param e details about the position and status of the mouse event
  23869. @see mouseEnter, mouseExit, mouseDrag, contains
  23870. */
  23871. virtual void mouseMove (const MouseEvent& e);
  23872. /** Called when the mouse first enters this component.
  23873. If the mouse button isn't pressed and the mouse moves into a component,
  23874. this will be called to let the component react to this.
  23875. When the mouse button is pressed and held down while being moved in
  23876. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  23877. mouseDrag messages are sent to the component that the mouse was originally
  23878. clicked on, until the button is released.
  23879. If you're writing a component that needs to repaint itself when the mouse
  23880. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  23881. method.
  23882. @param e details about the position and status of the mouse event
  23883. @see mouseExit, mouseDrag, mouseMove, contains
  23884. */
  23885. virtual void mouseEnter (const MouseEvent& e);
  23886. /** Called when the mouse moves out of this component.
  23887. This will be called when the mouse moves off the edge of this
  23888. component.
  23889. If the mouse button was pressed, and it was then dragged off the
  23890. edge of the component and released, then this callback will happen
  23891. when the button is released, after the mouseUp callback.
  23892. If you're writing a component that needs to repaint itself when the mouse
  23893. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  23894. method.
  23895. @param e details about the position and status of the mouse event
  23896. @see mouseEnter, mouseDrag, mouseMove, contains
  23897. */
  23898. virtual void mouseExit (const MouseEvent& e);
  23899. /** Called when a mouse button is pressed while it's over this component.
  23900. The MouseEvent object passed in contains lots of methods for finding out
  23901. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  23902. were held down at the time.
  23903. Once a button is held down, the mouseDrag method will be called when the
  23904. mouse moves, until the button is released.
  23905. @param e details about the position and status of the mouse event
  23906. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  23907. */
  23908. virtual void mouseDown (const MouseEvent& e);
  23909. /** Called when the mouse is moved while a button is held down.
  23910. When a mouse button is pressed inside a component, that component
  23911. receives mouseDrag callbacks each time the mouse moves, even if the
  23912. mouse strays outside the component's bounds.
  23913. If you want to be able to drag things off the edge of a component
  23914. and have the component scroll when you get to the edges, the
  23915. beginDragAutoRepeat() method might be useful.
  23916. @param e details about the position and status of the mouse event
  23917. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  23918. */
  23919. virtual void mouseDrag (const MouseEvent& e);
  23920. /** Called when a mouse button is released.
  23921. A mouseUp callback is sent to the component in which a button was pressed
  23922. even if the mouse is actually over a different component when the
  23923. button is released.
  23924. The MouseEvent object passed in contains lots of methods for finding out
  23925. which buttons were down just before they were released.
  23926. @param e details about the position and status of the mouse event
  23927. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  23928. */
  23929. virtual void mouseUp (const MouseEvent& e);
  23930. /** Called when a mouse button has been double-clicked in this component.
  23931. The MouseEvent object passed in contains lots of methods for finding out
  23932. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  23933. were held down at the time.
  23934. For altering the time limit used to detect double-clicks,
  23935. see MouseEvent::setDoubleClickTimeout.
  23936. @param e details about the position and status of the mouse event
  23937. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  23938. MouseEvent::getDoubleClickTimeout
  23939. */
  23940. virtual void mouseDoubleClick (const MouseEvent& e);
  23941. /** Called when the mouse-wheel is moved.
  23942. This callback is sent to the component that the mouse is over when the
  23943. wheel is moved.
  23944. If not overridden, the component will forward this message to its parent, so
  23945. that parent components can collect mouse-wheel messages that happen to
  23946. child components which aren't interested in them.
  23947. @param e details about the position and status of the mouse event
  23948. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  23949. value means the wheel has been pushed to the right, negative means it
  23950. was pushed to the left
  23951. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  23952. value means the wheel has been pushed upwards, negative means it
  23953. was pushed downwards
  23954. */
  23955. virtual void mouseWheelMove (const MouseEvent& e,
  23956. float wheelIncrementX,
  23957. float wheelIncrementY);
  23958. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  23959. current mouse-drag operation.
  23960. This allows you to make sure that mouseDrag() events are sent continuously, even
  23961. when the mouse isn't moving. This can be useful for things like auto-scrolling
  23962. components when the mouse is near an edge.
  23963. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  23964. minimum interval between consecutive mouse drag callbacks. The callbacks
  23965. will continue until the mouse is released, and then the interval will be reset,
  23966. so you need to make sure it's called every time you begin a drag event.
  23967. Passing an interval of 0 or less will cancel the auto-repeat.
  23968. @see mouseDrag, Desktop::beginDragAutoRepeat
  23969. */
  23970. static void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  23971. /** Causes automatic repaints when the mouse enters or exits this component.
  23972. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  23973. on the component, it will trigger a repaint.
  23974. This is handy for things like buttons that need to draw themselves differently when
  23975. the mouse moves over them, and it avoids having to override all the different mouse
  23976. callbacks and call repaint().
  23977. @see mouseEnter, mouseExit, mouseDown, mouseUp
  23978. */
  23979. void setRepaintsOnMouseActivity (bool shouldRepaint) throw();
  23980. /** Registers a listener to be told when mouse events occur in this component.
  23981. If you need to get informed about mouse events in a component but can't or
  23982. don't want to override its methods, you can attach any number of listeners
  23983. to the component, and these will get told about the events in addition to
  23984. the component's own callbacks being called.
  23985. Note that a MouseListener can also be attached to more than one component.
  23986. @param newListener the listener to register
  23987. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  23988. for events that happen to any child component
  23989. within this component, including deeply-nested
  23990. child components. If false, it will only be
  23991. told about events that this component handles.
  23992. @see MouseListener, removeMouseListener
  23993. */
  23994. void addMouseListener (MouseListener* newListener,
  23995. bool wantsEventsForAllNestedChildComponents);
  23996. /** Deregisters a mouse listener.
  23997. @see addMouseListener, MouseListener
  23998. */
  23999. void removeMouseListener (MouseListener* listenerToRemove);
  24000. /** Adds a listener that wants to hear about keypresses that this component receives.
  24001. The listeners that are registered with a component are called by its keyPressed() or
  24002. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  24003. If you add an object as a key listener, be careful to remove it when the object
  24004. is deleted, or the component will be left with a dangling pointer.
  24005. @see keyPressed, keyStateChanged, removeKeyListener
  24006. */
  24007. void addKeyListener (KeyListener* newListener);
  24008. /** Removes a previously-registered key listener.
  24009. @see addKeyListener
  24010. */
  24011. void removeKeyListener (KeyListener* listenerToRemove);
  24012. /** Called when a key is pressed.
  24013. When a key is pressed, the component that has the keyboard focus will have this
  24014. method called. Remember that a component will only be given the focus if its
  24015. setWantsKeyboardFocus() method has been used to enable this.
  24016. If your implementation returns true, the event will be consumed and not passed
  24017. on to any other listeners. If it returns false, the key will be passed to any
  24018. KeyListeners that have been registered with this component. As soon as one of these
  24019. returns true, the process will stop, but if they all return false, the event will
  24020. be passed upwards to this component's parent, and so on.
  24021. The default implementation of this method does nothing and returns false.
  24022. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  24023. */
  24024. virtual bool keyPressed (const KeyPress& key);
  24025. /** Called when a key is pressed or released.
  24026. Whenever a key on the keyboard is pressed or released (including modifier keys
  24027. like shift and ctrl), this method will be called on the component that currently
  24028. has the keyboard focus. Remember that a component will only be given the focus if
  24029. its setWantsKeyboardFocus() method has been used to enable this.
  24030. If your implementation returns true, the event will be consumed and not passed
  24031. on to any other listeners. If it returns false, then any KeyListeners that have
  24032. been registered with this component will have their keyStateChanged methods called.
  24033. As soon as one of these returns true, the process will stop, but if they all return
  24034. false, the event will be passed upwards to this component's parent, and so on.
  24035. The default implementation of this method does nothing and returns false.
  24036. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  24037. method.
  24038. @param isKeyDown true if a key has been pressed; false if it has been released
  24039. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  24040. */
  24041. virtual bool keyStateChanged (bool isKeyDown);
  24042. /** Called when a modifier key is pressed or released.
  24043. Whenever the shift, control, alt or command keys are pressed or released,
  24044. this method will be called on the component that currently has the keyboard focus.
  24045. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  24046. method has been used to enable this.
  24047. The default implementation of this method actually calls its parent's modifierKeysChanged
  24048. method, so that focused components which aren't interested in this will give their
  24049. parents a chance to act on the event instead.
  24050. @see keyStateChanged, ModifierKeys
  24051. */
  24052. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  24053. /** Enumeration used by the focusChanged() and focusLost() methods. */
  24054. enum FocusChangeType
  24055. {
  24056. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  24057. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  24058. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  24059. };
  24060. /** Called to indicate that this component has just acquired the keyboard focus.
  24061. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24062. */
  24063. virtual void focusGained (FocusChangeType cause);
  24064. /** Called to indicate that this component has just lost the keyboard focus.
  24065. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24066. */
  24067. virtual void focusLost (FocusChangeType cause);
  24068. /** Called to indicate that one of this component's children has been focused or unfocused.
  24069. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  24070. changed. It happens when focus moves from one of this component's children (at any depth)
  24071. to a component that isn't contained in this one, (or vice-versa).
  24072. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  24073. */
  24074. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  24075. /** Returns true if the mouse is currently over this component.
  24076. If the mouse isn't over the component, this will return false, even if the
  24077. mouse is currently being dragged - so you can use this in your mouseDrag
  24078. method to find out whether it's really over the component or not.
  24079. Note that when the mouse button is being held down, then the only component
  24080. for which this method will return true is the one that was originally
  24081. clicked on.
  24082. If includeChildren is true, then this will also return true if the mouse is over
  24083. any of the component's children (recursively) as well as the component itself.
  24084. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  24085. */
  24086. bool isMouseOver (bool includeChildren = false) const;
  24087. /** Returns true if the mouse button is currently held down in this component.
  24088. Note that this is a test to see whether the mouse is being pressed in this
  24089. component, so it'll return false if called on component A when the mouse
  24090. is actually being dragged in component B.
  24091. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  24092. */
  24093. bool isMouseButtonDown() const throw();
  24094. /** True if the mouse is over this component, or if it's being dragged in this component.
  24095. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  24096. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  24097. */
  24098. bool isMouseOverOrDragging() const throw();
  24099. /** Returns true if a mouse button is currently down.
  24100. Unlike isMouseButtonDown, this will test the current state of the
  24101. buttons without regard to which component (if any) it has been
  24102. pressed in.
  24103. @see isMouseButtonDown, ModifierKeys
  24104. */
  24105. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  24106. /** Returns the mouse's current position, relative to this component.
  24107. The return value is relative to the component's top-left corner.
  24108. */
  24109. const Point<int> getMouseXYRelative() const;
  24110. /** Called when this component's size has been changed.
  24111. A component can implement this method to do things such as laying out its
  24112. child components when its width or height changes.
  24113. The method is called synchronously as a result of the setBounds or setSize
  24114. methods, so repeatedly changing a components size will repeatedly call its
  24115. resized method (unlike things like repainting, where multiple calls to repaint
  24116. are coalesced together).
  24117. If the component is a top-level window on the desktop, its size could also
  24118. be changed by operating-system factors beyond the application's control.
  24119. @see moved, setSize
  24120. */
  24121. virtual void resized();
  24122. /** Called when this component's position has been changed.
  24123. This is called when the position relative to its parent changes, not when
  24124. its absolute position on the screen changes (so it won't be called for
  24125. all child components when a parent component is moved).
  24126. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  24127. or any of the other repositioning methods, and like resized(), it will be
  24128. called each time those methods are called.
  24129. If the component is a top-level window on the desktop, its position could also
  24130. be changed by operating-system factors beyond the application's control.
  24131. @see resized, setBounds
  24132. */
  24133. virtual void moved();
  24134. /** Called when one of this component's children is moved or resized.
  24135. If the parent wants to know about changes to its immediate children (not
  24136. to children of its children), this is the method to override.
  24137. @see moved, resized, parentSizeChanged
  24138. */
  24139. virtual void childBoundsChanged (Component* child);
  24140. /** Called when this component's immediate parent has been resized.
  24141. If the component is a top-level window, this indicates that the screen size
  24142. has changed.
  24143. @see childBoundsChanged, moved, resized
  24144. */
  24145. virtual void parentSizeChanged();
  24146. /** Called when this component has been moved to the front of its siblings.
  24147. The component may have been brought to the front by the toFront() method, or
  24148. by the operating system if it's a top-level window.
  24149. @see toFront
  24150. */
  24151. virtual void broughtToFront();
  24152. /** Adds a listener to be told about changes to the component hierarchy or position.
  24153. Component listeners get called when this component's size, position or children
  24154. change - see the ComponentListener class for more details.
  24155. @param newListener the listener to register - if this is already registered, it
  24156. will be ignored.
  24157. @see ComponentListener, removeComponentListener
  24158. */
  24159. void addComponentListener (ComponentListener* newListener);
  24160. /** Removes a component listener.
  24161. @see addComponentListener
  24162. */
  24163. void removeComponentListener (ComponentListener* listenerToRemove);
  24164. /** Dispatches a numbered message to this component.
  24165. This is a quick and cheap way of allowing simple asynchronous messages to
  24166. be sent to components. It's also safe, because if the component that you
  24167. send the message to is a null or dangling pointer, this won't cause an error.
  24168. The command ID is later delivered to the component's handleCommandMessage() method by
  24169. the application's message queue.
  24170. @see handleCommandMessage
  24171. */
  24172. void postCommandMessage (int commandId);
  24173. /** Called to handle a command that was sent by postCommandMessage().
  24174. This is called by the message thread when a command message arrives, and
  24175. the component can override this method to process it in any way it needs to.
  24176. @see postCommandMessage
  24177. */
  24178. virtual void handleCommandMessage (int commandId);
  24179. /** Runs a component modally, waiting until the loop terminates.
  24180. This method first makes the component visible, brings it to the front and
  24181. gives it the keyboard focus.
  24182. It then runs a loop, dispatching messages from the system message queue, but
  24183. blocking all mouse or keyboard messages from reaching any components other
  24184. than this one and its children.
  24185. This loop continues until the component's exitModalState() method is called (or
  24186. the component is deleted), and then this method returns, returning the value
  24187. passed into exitModalState().
  24188. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  24189. isCurrentlyBlockedByAnotherModalComponent, ModalComponentManager
  24190. */
  24191. #if JUCE_MODAL_LOOPS_PERMITTED
  24192. int runModalLoop();
  24193. #endif
  24194. /** Puts the component into a modal state.
  24195. This makes the component modal, so that messages are blocked from reaching
  24196. any components other than this one and its children, but unlike runModalLoop(),
  24197. this method returns immediately.
  24198. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  24199. get the focus, which is usually what you'll want it to do. If not, it will leave
  24200. the focus unchanged.
  24201. The callback is an optional object which will receive a callback when the modal
  24202. component loses its modal status, either by being hidden or when exitModalState()
  24203. is called. If you pass an object in here, the system will take care of deleting it
  24204. later, after making the callback
  24205. If deleteWhenDismissed is true, then when it is dismissed, the component will be
  24206. deleted and then the callback will be called. (This will safely handle the situation
  24207. where the component is deleted before its exitModalState() method is called).
  24208. @see exitModalState, runModalLoop, ModalComponentManager::attachCallback
  24209. */
  24210. void enterModalState (bool takeKeyboardFocus = true,
  24211. ModalComponentManager::Callback* callback = 0,
  24212. bool deleteWhenDismissed = false);
  24213. /** Ends a component's modal state.
  24214. If this component is currently modal, this will turn of its modalness, and return
  24215. a value to the runModalLoop() method that might have be running its modal loop.
  24216. @see runModalLoop, enterModalState, isCurrentlyModal
  24217. */
  24218. void exitModalState (int returnValue);
  24219. /** Returns true if this component is the modal one.
  24220. It's possible to have nested modal components, e.g. a pop-up dialog box
  24221. that launches another pop-up, but this will only return true for
  24222. the one at the top of the stack.
  24223. @see getCurrentlyModalComponent
  24224. */
  24225. bool isCurrentlyModal() const throw();
  24226. /** Returns the number of components that are currently in a modal state.
  24227. @see getCurrentlyModalComponent
  24228. */
  24229. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  24230. /** Returns one of the components that are currently modal.
  24231. The index specifies which of the possible modal components to return. The order
  24232. of the components in this list is the reverse of the order in which they became
  24233. modal - so the component at index 0 is always the active component, and the others
  24234. are progressively earlier ones that are themselves now blocked by later ones.
  24235. @returns the modal component, or null if no components are modal (or if the
  24236. index is out of range)
  24237. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  24238. */
  24239. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  24240. /** Checks whether there's a modal component somewhere that's stopping this one
  24241. from receiving messages.
  24242. If there is a modal component, its canModalEventBeSentToComponent() method
  24243. will be called to see if it will still allow this component to receive events.
  24244. @see runModalLoop, getCurrentlyModalComponent
  24245. */
  24246. bool isCurrentlyBlockedByAnotherModalComponent() const;
  24247. /** When a component is modal, this callback allows it to choose which other
  24248. components can still receive events.
  24249. When a modal component is active and the user clicks on a non-modal component,
  24250. this method is called on the modal component, and if it returns true, the
  24251. event is allowed to reach its target. If it returns false, the event is blocked
  24252. and the inputAttemptWhenModal() callback is made.
  24253. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  24254. implementation just returns false in all cases.
  24255. */
  24256. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  24257. /** Called when the user tries to click on a component that is blocked by another
  24258. modal component.
  24259. When a component is modal and the user clicks on one of the other components,
  24260. the modal component will receive this callback.
  24261. The default implementation of this method will play a beep, and bring the currently
  24262. modal component to the front, but it can be overridden to do other tasks.
  24263. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  24264. */
  24265. virtual void inputAttemptWhenModal();
  24266. /** Returns the set of properties that belong to this component.
  24267. Each component has a NamedValueSet object which you can use to attach arbitrary
  24268. items of data to it.
  24269. */
  24270. NamedValueSet& getProperties() throw() { return properties; }
  24271. /** Returns the set of properties that belong to this component.
  24272. Each component has a NamedValueSet object which you can use to attach arbitrary
  24273. items of data to it.
  24274. */
  24275. const NamedValueSet& getProperties() const throw() { return properties; }
  24276. /** Looks for a colour that has been registered with the given colour ID number.
  24277. If a colour has been set for this ID number using setColour(), then it is
  24278. returned. If none has been set, the method will try calling the component's
  24279. LookAndFeel class's findColour() method. If none has been registered with the
  24280. look-and-feel either, it will just return black.
  24281. The colour IDs for various purposes are stored as enums in the components that
  24282. they are relevent to - for an example, see Slider::ColourIds,
  24283. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  24284. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  24285. */
  24286. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  24287. /** Registers a colour to be used for a particular purpose.
  24288. Changing a colour will cause a synchronous callback to the colourChanged()
  24289. method, which your component can override if it needs to do something when
  24290. colours are altered.
  24291. For more details about colour IDs, see the comments for findColour().
  24292. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  24293. */
  24294. void setColour (int colourId, const Colour& colour);
  24295. /** If a colour has been set with setColour(), this will remove it.
  24296. This allows you to make a colour revert to its default state.
  24297. */
  24298. void removeColour (int colourId);
  24299. /** Returns true if the specified colour ID has been explicitly set for this
  24300. component using the setColour() method.
  24301. */
  24302. bool isColourSpecified (int colourId) const;
  24303. /** This looks for any colours that have been specified for this component,
  24304. and copies them to the specified target component.
  24305. */
  24306. void copyAllExplicitColoursTo (Component& target) const;
  24307. /** This method is called when a colour is changed by the setColour() method.
  24308. @see setColour, findColour
  24309. */
  24310. virtual void colourChanged();
  24311. /** Components can implement this method to provide a MarkerList.
  24312. The default implementation of this method returns 0, but you can override it to
  24313. return a pointer to the component's marker list. If xAxis is true, it should
  24314. return the X marker list; if false, it should return the Y markers.
  24315. */
  24316. virtual MarkerList* getMarkers (bool xAxis);
  24317. /** Returns the underlying native window handle for this component.
  24318. This is platform-dependent and strictly for power-users only!
  24319. */
  24320. void* getWindowHandle() const;
  24321. /** Holds a pointer to some type of Component, which automatically becomes null if
  24322. the component is deleted.
  24323. If you're using a component which may be deleted by another event that's outside
  24324. of your control, use a SafePointer instead of a normal pointer to refer to it,
  24325. and you can test whether it's null before using it to see if something has deleted
  24326. it.
  24327. The ComponentType typedef must be Component, or some subclass of Component.
  24328. You may also want to use a WeakReference<Component> object for the same purpose.
  24329. */
  24330. template <class ComponentType>
  24331. class SafePointer
  24332. {
  24333. public:
  24334. /** Creates a null SafePointer. */
  24335. SafePointer() throw() {}
  24336. /** Creates a SafePointer that points at the given component. */
  24337. SafePointer (ComponentType* const component) : weakRef (component) {}
  24338. /** Creates a copy of another SafePointer. */
  24339. SafePointer (const SafePointer& other) throw() : weakRef (other.weakRef) {}
  24340. /** Copies another pointer to this one. */
  24341. SafePointer& operator= (const SafePointer& other) { weakRef = other.weakRef; return *this; }
  24342. /** Copies another pointer to this one. */
  24343. SafePointer& operator= (ComponentType* const newComponent) { weakRef = newComponent; return *this; }
  24344. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24345. ComponentType* getComponent() const throw() { return dynamic_cast <ComponentType*> (weakRef.get()); }
  24346. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24347. operator ComponentType*() const throw() { return getComponent(); }
  24348. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24349. ComponentType* operator->() throw() { return getComponent(); }
  24350. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  24351. const ComponentType* operator->() const throw() { return getComponent(); }
  24352. /** If the component is valid, this deletes it and sets this pointer to null. */
  24353. void deleteAndZero() { delete getComponent(); jassert (getComponent() == 0); }
  24354. bool operator== (ComponentType* component) const throw() { return weakRef == component; }
  24355. bool operator!= (ComponentType* component) const throw() { return weakRef != component; }
  24356. private:
  24357. WeakReference<Component> weakRef;
  24358. };
  24359. /** A class to keep an eye on a component and check for it being deleted.
  24360. This is designed for use with the ListenerList::callChecked() methods, to allow
  24361. the list iterator to stop cleanly if the component is deleted by a listener callback
  24362. while the list is still being iterated.
  24363. */
  24364. class JUCE_API BailOutChecker
  24365. {
  24366. public:
  24367. /** Creates a checker that watches one component. */
  24368. BailOutChecker (Component* component);
  24369. /** Returns true if either of the two components have been deleted since this object was created. */
  24370. bool shouldBailOut() const throw();
  24371. private:
  24372. const WeakReference<Component> safePointer;
  24373. JUCE_DECLARE_NON_COPYABLE (BailOutChecker);
  24374. };
  24375. /**
  24376. Base class for objects that can be used to automatically position a component according to
  24377. some kind of algorithm.
  24378. The component class simply holds onto a reference to a Positioner, but doesn't actually do
  24379. anything with it - all the functionality must be implemented by the positioner itself (e.g.
  24380. it might choose to watch some kind of value and move the component when the value changes).
  24381. */
  24382. class JUCE_API Positioner
  24383. {
  24384. public:
  24385. /** Creates a Positioner which can control the specified component. */
  24386. explicit Positioner (Component& component) throw();
  24387. /** Destructor. */
  24388. virtual ~Positioner() {}
  24389. /** Returns the component that this positioner controls. */
  24390. Component& getComponent() const throw() { return component; }
  24391. /** Attempts to set the component's position to the given rectangle.
  24392. Unlike simply calling Component::setBounds(), this may involve the positioner
  24393. being smart enough to adjust itself to fit the new bounds, e.g. a RelativeRectangle's
  24394. positioner may try to reverse the expressions used to make them fit these new coordinates.
  24395. */
  24396. virtual void applyNewBounds (const Rectangle<int>& newBounds) = 0;
  24397. private:
  24398. Component& component;
  24399. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  24400. };
  24401. /** Returns the Positioner object that has been set for this component.
  24402. @see setPositioner()
  24403. */
  24404. Positioner* getPositioner() const throw();
  24405. /** Sets a new Positioner object for this component.
  24406. If there's currently another positioner set, it will be deleted. The object that is passed in
  24407. will be deleted automatically by this component when it's no longer required. Pass a null pointer
  24408. to clear the current positioner.
  24409. @see getPositioner()
  24410. */
  24411. void setPositioner (Positioner* newPositioner);
  24412. #ifndef DOXYGEN
  24413. // These methods are deprecated - use localPointToGlobal, getLocalPoint, getLocalPoint, etc instead.
  24414. JUCE_DEPRECATED (const Point<int> relativePositionToGlobal (const Point<int>&) const);
  24415. JUCE_DEPRECATED (const Point<int> globalPositionToRelative (const Point<int>&) const);
  24416. JUCE_DEPRECATED (const Point<int> relativePositionToOtherComponent (const Component*, const Point<int>&) const);
  24417. #endif
  24418. private:
  24419. friend class ComponentPeer;
  24420. friend class MouseInputSource;
  24421. friend class MouseInputSourceInternal;
  24422. #ifndef DOXYGEN
  24423. static Component* currentlyFocusedComponent;
  24424. String componentName, componentID;
  24425. Component* parentComponent;
  24426. Rectangle<int> bounds;
  24427. ScopedPointer <Positioner> positioner;
  24428. ScopedPointer <AffineTransform> affineTransform;
  24429. Array <Component*> childComponentList;
  24430. LookAndFeel* lookAndFeel;
  24431. MouseCursor cursor;
  24432. ImageEffectFilter* effect;
  24433. Image bufferedImage;
  24434. class MouseListenerList;
  24435. friend class MouseListenerList;
  24436. friend class ScopedPointer <MouseListenerList>;
  24437. ScopedPointer <MouseListenerList> mouseListeners;
  24438. ScopedPointer <Array <KeyListener*> > keyListeners;
  24439. ListenerList <ComponentListener> componentListeners;
  24440. NamedValueSet properties;
  24441. friend class WeakReference<Component>;
  24442. WeakReference<Component>::Master weakReferenceMaster;
  24443. const WeakReference<Component>::SharedRef& getWeakReference();
  24444. struct ComponentFlags
  24445. {
  24446. bool hasHeavyweightPeerFlag : 1;
  24447. bool visibleFlag : 1;
  24448. bool opaqueFlag : 1;
  24449. bool ignoresMouseClicksFlag : 1;
  24450. bool allowChildMouseClicksFlag : 1;
  24451. bool wantsFocusFlag : 1;
  24452. bool isFocusContainerFlag : 1;
  24453. bool dontFocusOnMouseClickFlag : 1;
  24454. bool alwaysOnTopFlag : 1;
  24455. bool bufferToImageFlag : 1;
  24456. bool bringToFrontOnClickFlag : 1;
  24457. bool repaintOnMouseActivityFlag : 1;
  24458. bool mouseDownFlag : 1;
  24459. bool mouseOverFlag : 1;
  24460. bool mouseInsideFlag : 1;
  24461. bool currentlyModalFlag : 1;
  24462. bool isDisabledFlag : 1;
  24463. bool childCompFocusedFlag : 1;
  24464. bool dontClipGraphicsFlag : 1;
  24465. #if JUCE_DEBUG
  24466. bool isInsidePaintCall : 1;
  24467. #endif
  24468. };
  24469. union
  24470. {
  24471. uint32 componentFlags;
  24472. ComponentFlags flags;
  24473. };
  24474. uint8 componentTransparency;
  24475. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24476. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24477. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24478. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  24479. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24480. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24481. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  24482. void internalBroughtToFront();
  24483. void internalFocusGain (const FocusChangeType cause, const WeakReference<Component>&);
  24484. void internalFocusGain (const FocusChangeType cause);
  24485. void internalFocusLoss (const FocusChangeType cause);
  24486. void internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>&);
  24487. void internalModalInputAttempt();
  24488. void internalModifierKeysChanged();
  24489. void internalChildrenChanged();
  24490. void internalHierarchyChanged();
  24491. Component* removeChildComponent (int index, bool sendParentEvents, bool sendChildEvents);
  24492. void moveChildInternal (int sourceIndex, int destIndex);
  24493. void paintComponentAndChildren (Graphics& g);
  24494. void paintComponent (Graphics& g);
  24495. void paintWithinParentContext (Graphics& g);
  24496. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  24497. void repaintParent();
  24498. void sendFakeMouseMove() const;
  24499. void takeKeyboardFocus (const FocusChangeType cause);
  24500. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  24501. static void giveAwayFocus (bool sendFocusLossEvent);
  24502. void sendEnablementChangeMessage();
  24503. void sendVisibilityChangeMessage();
  24504. class ComponentHelpers;
  24505. friend class ComponentHelpers;
  24506. /* Components aren't allowed to have copy constructors, as this would mess up parent hierarchies.
  24507. You might need to give your subclasses a private dummy constructor to avoid compiler warnings.
  24508. */
  24509. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Component);
  24510. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  24511. // This is included here just to cause a compile error if your code is still handling
  24512. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  24513. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  24514. // implement its methods instead of this Component method).
  24515. virtual void filesDropped (const StringArray&, int, int) {}
  24516. // This is included here to cause an error if you use or overload it - it has been deprecated in
  24517. // favour of contains (const Point<int>&)
  24518. void contains (int, int);
  24519. #endif
  24520. protected:
  24521. /** @internal */
  24522. virtual void internalRepaint (int x, int y, int w, int h);
  24523. /** @internal */
  24524. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  24525. #endif
  24526. };
  24527. #endif // __JUCE_COMPONENT_JUCEHEADER__
  24528. /*** End of inlined file: juce_Component.h ***/
  24529. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  24530. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  24531. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  24532. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  24533. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  24534. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  24535. /** A type used to hold the unique ID for an application command.
  24536. This is a numeric type, so it can be stored as an integer.
  24537. @see ApplicationCommandInfo, ApplicationCommandManager,
  24538. ApplicationCommandTarget, KeyPressMappingSet
  24539. */
  24540. typedef int CommandID;
  24541. /** A set of general-purpose application command IDs.
  24542. Because these commands are likely to be used in most apps, they're defined
  24543. here to help different apps to use the same numeric values for them.
  24544. Of course you don't have to use these, but some of them are used internally by
  24545. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  24546. @see ApplicationCommandInfo, ApplicationCommandManager,
  24547. ApplicationCommandTarget, KeyPressMappingSet
  24548. */
  24549. namespace StandardApplicationCommandIDs
  24550. {
  24551. /** This command ID should be used to send a "Quit the App" command.
  24552. This command is recognised by the JUCEApplication class, so if it is invoked
  24553. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  24554. object will catch it and call JUCEApplication::systemRequestedQuit().
  24555. */
  24556. static const CommandID quit = 0x1001;
  24557. /** The command ID that should be used to send a "Delete" command. */
  24558. static const CommandID del = 0x1002;
  24559. /** The command ID that should be used to send a "Cut" command. */
  24560. static const CommandID cut = 0x1003;
  24561. /** The command ID that should be used to send a "Copy to clipboard" command. */
  24562. static const CommandID copy = 0x1004;
  24563. /** The command ID that should be used to send a "Paste from clipboard" command. */
  24564. static const CommandID paste = 0x1005;
  24565. /** The command ID that should be used to send a "Select all" command. */
  24566. static const CommandID selectAll = 0x1006;
  24567. /** The command ID that should be used to send a "Deselect all" command. */
  24568. static const CommandID deselectAll = 0x1007;
  24569. }
  24570. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  24571. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  24572. /**
  24573. Holds information describing an application command.
  24574. This object is used to pass information about a particular command, such as its
  24575. name, description and other usage flags.
  24576. When an ApplicationCommandTarget is asked to provide information about the commands
  24577. it can perform, this is the structure gets filled-in to describe each one.
  24578. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  24579. ApplicationCommandManager
  24580. */
  24581. struct JUCE_API ApplicationCommandInfo
  24582. {
  24583. explicit ApplicationCommandInfo (CommandID commandID) throw();
  24584. /** Sets a number of the structures values at once.
  24585. The meanings of each of the parameters is described below, in the appropriate
  24586. member variable's description.
  24587. */
  24588. void setInfo (const String& shortName,
  24589. const String& description,
  24590. const String& categoryName,
  24591. int flags) throw();
  24592. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  24593. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  24594. is false, the bit is set.
  24595. */
  24596. void setActive (bool isActive) throw();
  24597. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  24598. */
  24599. void setTicked (bool isTicked) throw();
  24600. /** Handy method for adding a keypress to the defaultKeypresses array.
  24601. This is just so you can write things like:
  24602. @code
  24603. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  24604. @endcode
  24605. instead of
  24606. @code
  24607. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  24608. @endcode
  24609. */
  24610. void addDefaultKeypress (int keyCode,
  24611. const ModifierKeys& modifiers) throw();
  24612. /** The command's unique ID number.
  24613. */
  24614. CommandID commandID;
  24615. /** A short name to describe the command.
  24616. This should be suitable for use in menus, on buttons that trigger the command, etc.
  24617. You can use the setInfo() method to quickly set this and some of the command's
  24618. other properties.
  24619. */
  24620. String shortName;
  24621. /** A longer description of the command.
  24622. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  24623. pop-up tooltip describing what the command does.
  24624. You can use the setInfo() method to quickly set this and some of the command's
  24625. other properties.
  24626. */
  24627. String description;
  24628. /** A named category that the command fits into.
  24629. You can give your commands any category you like, and these will be displayed in
  24630. contexts such as the KeyMappingEditorComponent, where the category is used to group
  24631. commands together.
  24632. You can use the setInfo() method to quickly set this and some of the command's
  24633. other properties.
  24634. */
  24635. String categoryName;
  24636. /** A list of zero or more keypresses that should be used as the default keys for
  24637. this command.
  24638. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  24639. this list to initialise the default set of key-to-command mappings.
  24640. @see addDefaultKeypress
  24641. */
  24642. Array <KeyPress> defaultKeypresses;
  24643. /** Flags describing the ways in which this command should be used.
  24644. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  24645. variable.
  24646. */
  24647. enum CommandFlags
  24648. {
  24649. /** Indicates that the command can't currently be performed.
  24650. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  24651. not currently permissable to perform the command. If the flag is set, then
  24652. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  24653. command or show themselves as not being enabled.
  24654. @see ApplicationCommandInfo::setActive
  24655. */
  24656. isDisabled = 1 << 0,
  24657. /** Indicates that the command should have a tick next to it on a menu.
  24658. If your command is shown on a menu and this is set, it'll show a tick next to
  24659. it. Other components such as buttons may also use this flag to indicate that it
  24660. is a value that can be toggled, and is currently in the 'on' state.
  24661. @see ApplicationCommandInfo::setTicked
  24662. */
  24663. isTicked = 1 << 1,
  24664. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  24665. it will call the command twice, once on key-down and again on key-up.
  24666. @see ApplicationCommandTarget::InvocationInfo
  24667. */
  24668. wantsKeyUpDownCallbacks = 1 << 2,
  24669. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  24670. command in its list.
  24671. */
  24672. hiddenFromKeyEditor = 1 << 3,
  24673. /** If this flag is present, then a KeyMappingEditorComponent will display the
  24674. command in its list, but won't allow the assigned keypress to be changed.
  24675. */
  24676. readOnlyInKeyEditor = 1 << 4,
  24677. /** If this flag is present and the command is invoked from a keypress, then any
  24678. buttons or menus that are also connected to the command will not flash to
  24679. indicate that they've been triggered.
  24680. */
  24681. dontTriggerVisualFeedback = 1 << 5
  24682. };
  24683. /** A bitwise-OR of the values specified in the CommandFlags enum.
  24684. You can use the setInfo() method to quickly set this and some of the command's
  24685. other properties.
  24686. */
  24687. int flags;
  24688. };
  24689. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  24690. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  24691. /*** Start of inlined file: juce_MessageListener.h ***/
  24692. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  24693. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  24694. /**
  24695. MessageListener subclasses can post and receive Message objects.
  24696. @see Message, MessageManager, ActionListener, ChangeListener
  24697. */
  24698. class JUCE_API MessageListener
  24699. {
  24700. protected:
  24701. /** Creates a MessageListener. */
  24702. MessageListener() throw();
  24703. public:
  24704. /** Destructor.
  24705. When a MessageListener is deleted, it removes itself from a global list
  24706. of registered listeners, so that the isValidMessageListener() method
  24707. will no longer return true.
  24708. */
  24709. virtual ~MessageListener();
  24710. /** This is the callback method that receives incoming messages.
  24711. This is called by the MessageManager from its dispatch loop.
  24712. @see postMessage
  24713. */
  24714. virtual void handleMessage (const Message& message) = 0;
  24715. /** Sends a message to the message queue, for asynchronous delivery to this listener
  24716. later on.
  24717. This method can be called safely by any thread.
  24718. @param message the message object to send - this will be deleted
  24719. automatically by the message queue, so don't keep any
  24720. references to it after calling this method.
  24721. @see handleMessage
  24722. */
  24723. void postMessage (Message* message) const throw();
  24724. /** Checks whether this MessageListener has been deleted.
  24725. Although not foolproof, this method is safe to call on dangling or null
  24726. pointers. A list of active MessageListeners is kept internally, so this
  24727. checks whether the object is on this list or not.
  24728. Note that it's possible to get a false-positive here, if an object is
  24729. deleted and another is subsequently created that happens to be at the
  24730. exact same memory location, but I can't think of a good way of avoiding
  24731. this.
  24732. */
  24733. bool isValidMessageListener() const throw();
  24734. };
  24735. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  24736. /*** End of inlined file: juce_MessageListener.h ***/
  24737. /**
  24738. A command target publishes a list of command IDs that it can perform.
  24739. An ApplicationCommandManager despatches commands to targets, which must be
  24740. able to provide information about what commands they can handle.
  24741. To create a target, you'll need to inherit from this class, implementing all of
  24742. its pure virtual methods.
  24743. For info about how a target is chosen to receive a command, see
  24744. ApplicationCommandManager::getFirstCommandTarget().
  24745. @see ApplicationCommandManager, ApplicationCommandInfo
  24746. */
  24747. class JUCE_API ApplicationCommandTarget
  24748. {
  24749. public:
  24750. /** Creates a command target. */
  24751. ApplicationCommandTarget();
  24752. /** Destructor. */
  24753. virtual ~ApplicationCommandTarget();
  24754. /**
  24755. */
  24756. struct JUCE_API InvocationInfo
  24757. {
  24758. InvocationInfo (const CommandID commandID);
  24759. /** The UID of the command that should be performed. */
  24760. CommandID commandID;
  24761. /** The command's flags.
  24762. See ApplicationCommandInfo for a description of these flag values.
  24763. */
  24764. int commandFlags;
  24765. /** The types of context in which the command might be called. */
  24766. enum InvocationMethod
  24767. {
  24768. direct = 0, /**< The command is being invoked directly by a piece of code. */
  24769. fromKeyPress, /**< The command is being invoked by a key-press. */
  24770. fromMenu, /**< The command is being invoked by a menu selection. */
  24771. fromButton /**< The command is being invoked by a button click. */
  24772. };
  24773. /** The type of event that triggered this command. */
  24774. InvocationMethod invocationMethod;
  24775. /** If triggered by a keypress or menu, this will be the component that had the
  24776. keyboard focus at the time.
  24777. If triggered by a button, it may be set to that component, or it may be null.
  24778. */
  24779. Component* originatingComponent;
  24780. /** The keypress that was used to invoke it.
  24781. Note that this will be an invalid keypress if the command was invoked
  24782. by some other means than a keyboard shortcut.
  24783. */
  24784. KeyPress keyPress;
  24785. /** True if the callback is being invoked when the key is pressed,
  24786. false if the key is being released.
  24787. @see KeyPressMappingSet::addCommand()
  24788. */
  24789. bool isKeyDown;
  24790. /** If the key is being released, this indicates how long it had been held
  24791. down for.
  24792. (Only relevant if isKeyDown is false.)
  24793. */
  24794. int millisecsSinceKeyPressed;
  24795. };
  24796. /** This must return the next target to try after this one.
  24797. When a command is being sent, and the first target can't handle
  24798. that command, this method is used to determine the next target that should
  24799. be tried.
  24800. It may return 0 if it doesn't know of another target.
  24801. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  24802. method to return a parent component that might want to handle it.
  24803. @see invoke
  24804. */
  24805. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  24806. /** This must return a complete list of commands that this target can handle.
  24807. Your target should add all the command IDs that it handles to the array that is
  24808. passed-in.
  24809. */
  24810. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  24811. /** This must provide details about one of the commands that this target can perform.
  24812. This will be called with one of the command IDs that the target provided in its
  24813. getAllCommands() methods.
  24814. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  24815. suitable information about the command. (The commandID field will already have been filled-in
  24816. by the caller).
  24817. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  24818. set all the fields at once.
  24819. If the command is currently inactive for some reason, this method must use
  24820. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  24821. bit of the ApplicationCommandInfo::flags field).
  24822. Any default key-presses for the command should be appended to the
  24823. ApplicationCommandInfo::defaultKeypresses field.
  24824. Note that if you change something that affects the status of the commands
  24825. that would be returned by this method (e.g. something that makes some commands
  24826. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  24827. to cause the manager to refresh its status.
  24828. */
  24829. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  24830. /** This must actually perform the specified command.
  24831. If this target is able to perform the command specified by the commandID field of the
  24832. InvocationInfo structure, then it should do so, and must return true.
  24833. If it can't handle this command, it should return false, which tells the caller to pass
  24834. the command on to the next target in line.
  24835. @see invoke, ApplicationCommandManager::invoke
  24836. */
  24837. virtual bool perform (const InvocationInfo& info) = 0;
  24838. /** Makes this target invoke a command.
  24839. Your code can call this method to invoke a command on this target, but normally
  24840. you'd call it indirectly via ApplicationCommandManager::invoke() or
  24841. ApplicationCommandManager::invokeDirectly().
  24842. If this target can perform the given command, it will call its perform() method to
  24843. do so. If not, then getNextCommandTarget() will be used to determine the next target
  24844. to try, and the command will be passed along to it.
  24845. @param invocationInfo this must be correctly filled-in, describing the context for
  24846. the invocation.
  24847. @param asynchronously if false, the command will be performed before this method returns.
  24848. If true, a message will be posted so that the command will be performed
  24849. later on the message thread, and this method will return immediately.
  24850. @see perform, ApplicationCommandManager::invoke
  24851. */
  24852. bool invoke (const InvocationInfo& invocationInfo,
  24853. const bool asynchronously);
  24854. /** Invokes a given command directly on this target.
  24855. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  24856. structure.
  24857. */
  24858. bool invokeDirectly (const CommandID commandID,
  24859. const bool asynchronously);
  24860. /** Searches this target and all subsequent ones for the first one that can handle
  24861. the specified command.
  24862. This will use getNextCommandTarget() to determine the chain of targets to try
  24863. after this one.
  24864. */
  24865. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  24866. /** Checks whether this command can currently be performed by this target.
  24867. This will return true only if a call to getCommandInfo() doesn't set the
  24868. isDisabled flag to indicate that the command is inactive.
  24869. */
  24870. bool isCommandActive (const CommandID commandID);
  24871. /** If this object is a Component, this method will seach upwards in its current
  24872. UI hierarchy for the next parent component that implements the
  24873. ApplicationCommandTarget class.
  24874. If your target is a Component, this is a very handy method to use in your
  24875. getNextCommandTarget() implementation.
  24876. */
  24877. ApplicationCommandTarget* findFirstTargetParentComponent();
  24878. private:
  24879. // (for async invocation of commands)
  24880. class CommandTargetMessageInvoker : public MessageListener
  24881. {
  24882. public:
  24883. CommandTargetMessageInvoker (ApplicationCommandTarget* owner);
  24884. ~CommandTargetMessageInvoker();
  24885. void handleMessage (const Message& message);
  24886. private:
  24887. ApplicationCommandTarget* const owner;
  24888. JUCE_DECLARE_NON_COPYABLE (CommandTargetMessageInvoker);
  24889. };
  24890. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  24891. friend class CommandTargetMessageInvoker;
  24892. bool tryToInvoke (const InvocationInfo& info, bool async);
  24893. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandTarget);
  24894. };
  24895. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  24896. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  24897. /*** Start of inlined file: juce_ActionListener.h ***/
  24898. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  24899. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  24900. /**
  24901. Receives callbacks to indicate that some kind of event has occurred.
  24902. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  24903. about something that's happened.
  24904. @see ActionBroadcaster, ChangeListener
  24905. */
  24906. class JUCE_API ActionListener
  24907. {
  24908. public:
  24909. /** Destructor. */
  24910. virtual ~ActionListener() {}
  24911. /** Overridden by your subclass to receive the callback.
  24912. @param message the string that was specified when the event was triggered
  24913. by a call to ActionBroadcaster::sendActionMessage()
  24914. */
  24915. virtual void actionListenerCallback (const String& message) = 0;
  24916. };
  24917. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  24918. /*** End of inlined file: juce_ActionListener.h ***/
  24919. /**
  24920. An instance of this class is used to specify initialisation and shutdown
  24921. code for the application.
  24922. An application that wants to run in the JUCE framework needs to declare a
  24923. subclass of JUCEApplication and implement its various pure virtual methods.
  24924. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  24925. to declare an instance of this class and generate a suitable platform-specific
  24926. main() function.
  24927. e.g. @code
  24928. class MyJUCEApp : public JUCEApplication
  24929. {
  24930. public:
  24931. MyJUCEApp()
  24932. {
  24933. }
  24934. ~MyJUCEApp()
  24935. {
  24936. }
  24937. void initialise (const String& commandLine)
  24938. {
  24939. myMainWindow = new MyApplicationWindow();
  24940. myMainWindow->setBounds (100, 100, 400, 500);
  24941. myMainWindow->setVisible (true);
  24942. }
  24943. void shutdown()
  24944. {
  24945. myMainWindow = 0;
  24946. }
  24947. const String getApplicationName()
  24948. {
  24949. return "Super JUCE-o-matic";
  24950. }
  24951. const String getApplicationVersion()
  24952. {
  24953. return "1.0";
  24954. }
  24955. private:
  24956. ScopedPointer <MyApplicationWindow> myMainWindow;
  24957. };
  24958. // this creates wrapper code to actually launch the app properly.
  24959. START_JUCE_APPLICATION (MyJUCEApp)
  24960. @endcode
  24961. @see MessageManager, DeletedAtShutdown
  24962. */
  24963. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  24964. private ActionListener
  24965. {
  24966. protected:
  24967. /** Constructs a JUCE app object.
  24968. If subclasses implement a constructor or destructor, they shouldn't call any
  24969. JUCE code in there - put your startup/shutdown code in initialise() and
  24970. shutdown() instead.
  24971. */
  24972. JUCEApplication();
  24973. public:
  24974. /** Destructor.
  24975. If subclasses implement a constructor or destructor, they shouldn't call any
  24976. JUCE code in there - put your startup/shutdown code in initialise() and
  24977. shutdown() instead.
  24978. */
  24979. virtual ~JUCEApplication();
  24980. /** Returns the global instance of the application object being run. */
  24981. static JUCEApplication* getInstance() throw() { return appInstance; }
  24982. /** Called when the application starts.
  24983. This will be called once to let the application do whatever initialisation
  24984. it needs, create its windows, etc.
  24985. After the method returns, the normal event-dispatch loop will be run,
  24986. until the quit() method is called, at which point the shutdown()
  24987. method will be called to let the application clear up anything it needs
  24988. to delete.
  24989. If during the initialise() method, the application decides not to start-up
  24990. after all, it can just call the quit() method and the event loop won't be run.
  24991. @param commandLineParameters the line passed in does not include the
  24992. name of the executable, just the parameter list.
  24993. @see shutdown, quit
  24994. */
  24995. virtual void initialise (const String& commandLineParameters) = 0;
  24996. /** Returns true if the application hasn't yet completed its initialise() method
  24997. and entered the main event loop.
  24998. This is handy for things like splash screens to know when the app's up-and-running
  24999. properly.
  25000. */
  25001. bool isInitialising() const throw() { return stillInitialising; }
  25002. /* Called to allow the application to clear up before exiting.
  25003. After JUCEApplication::quit() has been called, the event-dispatch loop will
  25004. terminate, and this method will get called to allow the app to sort itself
  25005. out.
  25006. Be careful that nothing happens in this method that might rely on messages
  25007. being sent, or any kind of window activity, because the message loop is no
  25008. longer running at this point.
  25009. @see DeletedAtShutdown
  25010. */
  25011. virtual void shutdown() = 0;
  25012. /** Returns the application's name.
  25013. An application must implement this to name itself.
  25014. */
  25015. virtual const String getApplicationName() = 0;
  25016. /** Returns the application's version number.
  25017. */
  25018. virtual const String getApplicationVersion() = 0;
  25019. /** Checks whether multiple instances of the app are allowed.
  25020. If you application class returns true for this, more than one instance is
  25021. permitted to run (except on the Mac where this isn't possible).
  25022. If it's false, the second instance won't start, but it you will still get a
  25023. callback to anotherInstanceStarted() to tell you about this - which
  25024. gives you a chance to react to what the user was trying to do.
  25025. */
  25026. virtual bool moreThanOneInstanceAllowed();
  25027. /** Indicates that the user has tried to start up another instance of the app.
  25028. This will get called even if moreThanOneInstanceAllowed() is false.
  25029. */
  25030. virtual void anotherInstanceStarted (const String& commandLine);
  25031. /** Called when the operating system is trying to close the application.
  25032. The default implementation of this method is to call quit(), but it may
  25033. be overloaded to ignore the request or do some other special behaviour
  25034. instead. For example, you might want to offer the user the chance to save
  25035. their changes before quitting, and give them the chance to cancel.
  25036. If you want to send a quit signal to your app, this is the correct method
  25037. to call, because it means that requests that come from the system get handled
  25038. in the same way as those from your own application code. So e.g. you'd
  25039. call this method from a "quit" item on a menu bar.
  25040. */
  25041. virtual void systemRequestedQuit();
  25042. /** If any unhandled exceptions make it through to the message dispatch loop, this
  25043. callback will be triggered, in case you want to log them or do some other
  25044. type of error-handling.
  25045. If the type of exception is derived from the std::exception class, the pointer
  25046. passed-in will be valid. If the exception is of unknown type, this pointer
  25047. will be null.
  25048. */
  25049. virtual void unhandledException (const std::exception* e,
  25050. const String& sourceFilename,
  25051. int lineNumber);
  25052. /** Signals that the main message loop should stop and the application should terminate.
  25053. This isn't synchronous, it just posts a quit message to the main queue, and
  25054. when this message arrives, the message loop will stop, the shutdown() method
  25055. will be called, and the app will exit.
  25056. Note that this will cause an unconditional quit to happen, so if you need an
  25057. extra level before this, e.g. to give the user the chance to save their work
  25058. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  25059. method - see that method's help for more info.
  25060. @see MessageManager, DeletedAtShutdown
  25061. */
  25062. static void quit();
  25063. /** Sets the value that should be returned as the application's exit code when the
  25064. app quits.
  25065. This is the value that's returned by the main() function. Normally you'd leave this
  25066. as 0 unless you want to indicate an error code.
  25067. @see getApplicationReturnValue
  25068. */
  25069. void setApplicationReturnValue (int newReturnValue) throw();
  25070. /** Returns the value that has been set as the application's exit code.
  25071. @see setApplicationReturnValue
  25072. */
  25073. int getApplicationReturnValue() const throw() { return appReturnValue; }
  25074. /** Returns the application's command line params.
  25075. */
  25076. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  25077. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  25078. /** @internal */
  25079. static int main (const String& commandLine);
  25080. /** @internal */
  25081. static int main (int argc, const char* argv[]);
  25082. /** @internal */
  25083. static void sendUnhandledException (const std::exception* e, const char* sourceFile, int lineNumber);
  25084. /** Returns true if this executable is running as an app (as opposed to being a plugin
  25085. or other kind of shared library. */
  25086. static inline bool isStandaloneApp() throw() { return createInstance != 0; }
  25087. /** @internal */
  25088. ApplicationCommandTarget* getNextCommandTarget();
  25089. /** @internal */
  25090. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  25091. /** @internal */
  25092. void getAllCommands (Array <CommandID>& commands);
  25093. /** @internal */
  25094. bool perform (const InvocationInfo& info);
  25095. /** @internal */
  25096. void actionListenerCallback (const String& message);
  25097. /** @internal */
  25098. bool initialiseApp (const String& commandLine);
  25099. /** @internal */
  25100. int shutdownApp();
  25101. /** @internal */
  25102. static void appWillTerminateByForce();
  25103. /** @internal */
  25104. typedef JUCEApplication* (*CreateInstanceFunction)();
  25105. /** @internal */
  25106. static CreateInstanceFunction createInstance;
  25107. private:
  25108. String commandLineParameters;
  25109. int appReturnValue;
  25110. bool stillInitialising;
  25111. ScopedPointer<InterProcessLock> appLock;
  25112. static JUCEApplication* appInstance;
  25113. JUCE_DECLARE_NON_COPYABLE (JUCEApplication);
  25114. };
  25115. #endif // __JUCE_APPLICATION_JUCEHEADER__
  25116. /*** End of inlined file: juce_Application.h ***/
  25117. #endif
  25118. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  25119. #endif
  25120. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  25121. #endif
  25122. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25123. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  25124. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25125. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25126. /*** Start of inlined file: juce_Desktop.h ***/
  25127. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  25128. #define __JUCE_DESKTOP_JUCEHEADER__
  25129. /*** Start of inlined file: juce_Timer.h ***/
  25130. #ifndef __JUCE_TIMER_JUCEHEADER__
  25131. #define __JUCE_TIMER_JUCEHEADER__
  25132. class InternalTimerThread;
  25133. /**
  25134. Makes repeated callbacks to a virtual method at a specified time interval.
  25135. A Timer's timerCallback() method will be repeatedly called at a given
  25136. interval. When you create a Timer object, it will do nothing until the
  25137. startTimer() method is called, which will cause the message thread to
  25138. start making callbacks at the specified interval, until stopTimer() is called
  25139. or the object is deleted.
  25140. The time interval isn't guaranteed to be precise to any more than maybe
  25141. 10-20ms, and the intervals may end up being much longer than requested if the
  25142. system is busy. Because the callbacks are made by the main message thread,
  25143. anything that blocks the message queue for a period of time will also prevent
  25144. any timers from running until it can carry on.
  25145. If you need to have a single callback that is shared by multiple timers with
  25146. different frequencies, then the MultiTimer class allows you to do that - its
  25147. structure is very similar to the Timer class, but contains multiple timers
  25148. internally, each one identified by an ID number.
  25149. @see MultiTimer
  25150. */
  25151. class JUCE_API Timer
  25152. {
  25153. protected:
  25154. /** Creates a Timer.
  25155. When created, the timer is stopped, so use startTimer() to get it going.
  25156. */
  25157. Timer() throw();
  25158. /** Creates a copy of another timer.
  25159. Note that this timer won't be started, even if the one you're copying
  25160. is running.
  25161. */
  25162. Timer (const Timer& other) throw();
  25163. public:
  25164. /** Destructor. */
  25165. virtual ~Timer();
  25166. /** The user-defined callback routine that actually gets called periodically.
  25167. It's perfectly ok to call startTimer() or stopTimer() from within this
  25168. callback to change the subsequent intervals.
  25169. */
  25170. virtual void timerCallback() = 0;
  25171. /** Starts the timer and sets the length of interval required.
  25172. If the timer is already started, this will reset it, so the
  25173. time between calling this method and the next timer callback
  25174. will not be less than the interval length passed in.
  25175. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  25176. rounded up to 1)
  25177. */
  25178. void startTimer (int intervalInMilliseconds) throw();
  25179. /** Stops the timer.
  25180. No more callbacks will be made after this method returns.
  25181. If this is called from a different thread, any callbacks that may
  25182. be currently executing may be allowed to finish before the method
  25183. returns.
  25184. */
  25185. void stopTimer() throw();
  25186. /** Checks if the timer has been started.
  25187. @returns true if the timer is running.
  25188. */
  25189. bool isTimerRunning() const throw() { return periodMs > 0; }
  25190. /** Returns the timer's interval.
  25191. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  25192. */
  25193. int getTimerInterval() const throw() { return periodMs; }
  25194. private:
  25195. friend class InternalTimerThread;
  25196. int countdownMs, periodMs;
  25197. Timer* previous;
  25198. Timer* next;
  25199. Timer& operator= (const Timer&);
  25200. };
  25201. #endif // __JUCE_TIMER_JUCEHEADER__
  25202. /*** End of inlined file: juce_Timer.h ***/
  25203. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  25204. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25205. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25206. /**
  25207. Animates a set of components, moving them to a new position and/or fading their
  25208. alpha levels.
  25209. To animate a component, create a ComponentAnimator instance or (preferably) use the
  25210. global animator object provided by Desktop::getAnimator(), and call its animateComponent()
  25211. method to commence the movement.
  25212. If you're using your own ComponentAnimator instance, you'll need to make sure it isn't
  25213. deleted before it finishes moving the components, or they'll be abandoned before reaching their
  25214. destinations.
  25215. It's ok to delete components while they're being animated - the animator will detect this
  25216. and safely stop using them.
  25217. The class is a ChangeBroadcaster and sends a notification when any components
  25218. start or finish being animated.
  25219. @see Desktop::getAnimator
  25220. */
  25221. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  25222. private Timer
  25223. {
  25224. public:
  25225. /** Creates a ComponentAnimator. */
  25226. ComponentAnimator();
  25227. /** Destructor. */
  25228. ~ComponentAnimator();
  25229. /** Starts a component moving from its current position to a specified position.
  25230. If the component is already in the middle of an animation, that will be abandoned,
  25231. and a new animation will begin, moving the component from its current location.
  25232. The start and end speed parameters let you apply some acceleration to the component's
  25233. movement.
  25234. @param component the component to move
  25235. @param finalBounds the destination bounds to which the component should move. To leave the
  25236. component in the same place, just pass component->getBounds() for this value
  25237. @param finalAlpha the alpha value that the component should have at the end of the animation
  25238. @param animationDurationMilliseconds how long the animation should last, in milliseconds
  25239. @param useProxyComponent if true, this means the component should be replaced by an internally
  25240. managed temporary component which is a snapshot of the original component.
  25241. This avoids the component having to paint itself as it moves, so may
  25242. be more efficient. This option also allows you to delete the original
  25243. component immediately after starting the animation, because the animation
  25244. can proceed without it. If you use a proxy, the original component will be
  25245. made invisible by this call, and then will become visible again at the end
  25246. of the animation. It'll also mean that the proxy component will be temporarily
  25247. added to the component's parent, so avoid it if this might confuse the parent
  25248. component, or if there's a chance the parent might decide to delete its children.
  25249. @param startSpeed a value to indicate the relative start speed of the animation. If this is 0,
  25250. the component will start by accelerating from rest; higher values mean that it
  25251. will have an initial speed greater than zero. If the value if greater than 1, it
  25252. will decelerate towards the middle of its journey. To move the component at a
  25253. constant rate for its entire animation, set both the start and end speeds to 1.0
  25254. @param endSpeed a relative speed at which the component should be moving when the animation finishes.
  25255. If this is 0, the component will decelerate to a standstill at its final position;
  25256. higher values mean the component will still be moving when it stops. To move the component
  25257. at a constant rate for its entire animation, set both the start and end speeds to 1.0
  25258. */
  25259. void animateComponent (Component* component,
  25260. const Rectangle<int>& finalBounds,
  25261. float finalAlpha,
  25262. int animationDurationMilliseconds,
  25263. bool useProxyComponent,
  25264. double startSpeed,
  25265. double endSpeed);
  25266. /** Begins a fade-out of this components alpha level.
  25267. This is a quick way of invoking animateComponent() with a target alpha value of 0.0f, using
  25268. a proxy. You're safe to delete the component after calling this method, and this won't
  25269. interfere with the animation's progress.
  25270. */
  25271. void fadeOut (Component* component, int millisecondsToTake);
  25272. /** Begins a fade-in of a component.
  25273. This is a quick way of invoking animateComponent() with a target alpha value of 1.0f.
  25274. */
  25275. void fadeIn (Component* component, int millisecondsToTake);
  25276. /** Stops a component if it's currently being animated.
  25277. If moveComponentToItsFinalPosition is true, then the component will
  25278. be immediately moved to its destination position and size. If false, it will be
  25279. left in whatever location it currently occupies.
  25280. */
  25281. void cancelAnimation (Component* component,
  25282. bool moveComponentToItsFinalPosition);
  25283. /** Clears all of the active animations.
  25284. If moveComponentsToTheirFinalPositions is true, all the components will
  25285. be immediately set to their final positions. If false, they will be
  25286. left in whatever locations they currently occupy.
  25287. */
  25288. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  25289. /** Returns the destination position for a component.
  25290. If the component is being animated, this will return the target position that
  25291. was specified when animateComponent() was called.
  25292. If the specified component isn't currently being animated, this method will just
  25293. return its current position.
  25294. */
  25295. const Rectangle<int> getComponentDestination (Component* component);
  25296. /** Returns true if the specified component is currently being animated. */
  25297. bool isAnimating (Component* component) const;
  25298. private:
  25299. class AnimationTask;
  25300. OwnedArray <AnimationTask> tasks;
  25301. uint32 lastTime;
  25302. AnimationTask* findTaskFor (Component* component) const;
  25303. void timerCallback();
  25304. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentAnimator);
  25305. };
  25306. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  25307. /*** End of inlined file: juce_ComponentAnimator.h ***/
  25308. class MouseInputSource;
  25309. class MouseInputSourceInternal;
  25310. class MouseListener;
  25311. /**
  25312. Classes can implement this interface and register themselves with the Desktop class
  25313. to receive callbacks when the currently focused component changes.
  25314. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  25315. */
  25316. class JUCE_API FocusChangeListener
  25317. {
  25318. public:
  25319. /** Destructor. */
  25320. virtual ~FocusChangeListener() {}
  25321. /** Callback to indicate that the currently focused component has changed. */
  25322. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  25323. };
  25324. /**
  25325. Describes and controls aspects of the computer's desktop.
  25326. */
  25327. class JUCE_API Desktop : private DeletedAtShutdown,
  25328. private Timer,
  25329. private AsyncUpdater
  25330. {
  25331. public:
  25332. /** There's only one dektop object, and this method will return it.
  25333. */
  25334. static Desktop& JUCE_CALLTYPE getInstance();
  25335. /** Returns a list of the positions of all the monitors available.
  25336. The first rectangle in the list will be the main monitor area.
  25337. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  25338. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  25339. */
  25340. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const throw();
  25341. /** Returns the position and size of the main monitor.
  25342. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  25343. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  25344. */
  25345. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const throw();
  25346. /** Returns the position and size of the monitor which contains this co-ordinate.
  25347. If none of the monitors contains the point, this will just return the
  25348. main monitor.
  25349. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  25350. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  25351. */
  25352. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  25353. /** Returns the mouse position.
  25354. The co-ordinates are relative to the top-left of the main monitor.
  25355. Note that this is just a shortcut for calling getMainMouseSource().getScreenPosition(), and
  25356. you should only resort to grabbing the global mouse position if there's really no
  25357. way to get the coordinates via a mouse event callback instead.
  25358. */
  25359. static const Point<int> getMousePosition();
  25360. /** Makes the mouse pointer jump to a given location.
  25361. The co-ordinates are relative to the top-left of the main monitor.
  25362. */
  25363. static void setMousePosition (const Point<int>& newPosition);
  25364. /** Returns the last position at which a mouse button was pressed.
  25365. Note that this is just a shortcut for calling getMainMouseSource().getLastMouseDownPosition(),
  25366. and in a multi-touch environment, it doesn't make much sense. ALWAYS prefer to
  25367. get this information via other means, such as MouseEvent::getMouseDownScreenPosition()
  25368. if possible, and only ever call this as a last resort.
  25369. */
  25370. static const Point<int> getLastMouseDownPosition();
  25371. /** Returns the number of times the mouse button has been clicked since the
  25372. app started.
  25373. Each mouse-down event increments this number by 1.
  25374. */
  25375. static int getMouseButtonClickCounter();
  25376. /** This lets you prevent the screensaver from becoming active.
  25377. Handy if you're running some sort of presentation app where having a screensaver
  25378. appear would be annoying.
  25379. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  25380. won't enable a screensaver unless the user has actually set one up).
  25381. The disablement will only happen while the Juce application is the foreground
  25382. process - if another task is running in front of it, then the screensaver will
  25383. be unaffected.
  25384. @see isScreenSaverEnabled
  25385. */
  25386. static void setScreenSaverEnabled (bool isEnabled);
  25387. /** Returns true if the screensaver has not been turned off.
  25388. This will return the last value passed into setScreenSaverEnabled(). Note that
  25389. it won't tell you whether the user is actually using a screen saver, just
  25390. whether this app is deliberately preventing one from running.
  25391. @see setScreenSaverEnabled
  25392. */
  25393. static bool isScreenSaverEnabled();
  25394. /** Registers a MouseListener that will receive all mouse events that occur on
  25395. any component.
  25396. @see removeGlobalMouseListener
  25397. */
  25398. void addGlobalMouseListener (MouseListener* listener);
  25399. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  25400. method.
  25401. @see addGlobalMouseListener
  25402. */
  25403. void removeGlobalMouseListener (MouseListener* listener);
  25404. /** Registers a MouseListener that will receive a callback whenever the focused
  25405. component changes.
  25406. */
  25407. void addFocusChangeListener (FocusChangeListener* listener);
  25408. /** Unregisters a listener that was added with addFocusChangeListener(). */
  25409. void removeFocusChangeListener (FocusChangeListener* listener);
  25410. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  25411. The component must already be on the desktop for this method to work. It will
  25412. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  25413. etc will be hidden.
  25414. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  25415. the component that's currently being used will be resized back to the size
  25416. and position it was in before being put into this mode.
  25417. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  25418. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  25419. to hide as much on-screen paraphenalia as possible.
  25420. */
  25421. void setKioskModeComponent (Component* componentToUse,
  25422. bool allowMenusAndBars = true);
  25423. /** Returns the component that is currently being used in kiosk-mode.
  25424. This is the component that was last set by setKioskModeComponent(). If none
  25425. has been set, this returns 0.
  25426. */
  25427. Component* getKioskModeComponent() const throw() { return kioskModeComponent; }
  25428. /** Returns the number of components that are currently active as top-level
  25429. desktop windows.
  25430. @see getComponent, Component::addToDesktop
  25431. */
  25432. int getNumComponents() const throw();
  25433. /** Returns one of the top-level desktop window components.
  25434. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  25435. index is out-of-range.
  25436. @see getNumComponents, Component::addToDesktop
  25437. */
  25438. Component* getComponent (int index) const throw();
  25439. /** Finds the component at a given screen location.
  25440. This will drill down into top-level windows to find the child component at
  25441. the given position.
  25442. Returns 0 if the co-ordinates are inside a non-Juce window.
  25443. */
  25444. Component* findComponentAt (const Point<int>& screenPosition) const;
  25445. /** The Desktop object has a ComponentAnimator instance which can be used for performing
  25446. your animations.
  25447. Having a single shared ComponentAnimator object makes it more efficient when multiple
  25448. components are being moved around simultaneously. It's also more convenient than having
  25449. to manage your own instance of one.
  25450. @see ComponentAnimator
  25451. */
  25452. ComponentAnimator& getAnimator() throw() { return animator; }
  25453. /** Returns the number of MouseInputSource objects the system has at its disposal.
  25454. In a traditional single-mouse system, there might be only one object. On a multi-touch
  25455. system, there could be one input source per potential finger.
  25456. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  25457. @see getMouseSource
  25458. */
  25459. int getNumMouseSources() const throw() { return mouseSources.size(); }
  25460. /** Returns one of the system's MouseInputSource objects.
  25461. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  25462. a null pointer.
  25463. In a traditional single-mouse system, there might be only one object. On a multi-touch
  25464. system, there could be one input source per potential finger.
  25465. */
  25466. MouseInputSource* getMouseSource (int index) const throw() { return mouseSources [index]; }
  25467. /** Returns the main mouse input device that the system is using.
  25468. @see getNumMouseSources()
  25469. */
  25470. MouseInputSource& getMainMouseSource() const throw() { return *mouseSources.getUnchecked(0); }
  25471. /** Returns the number of mouse-sources that are currently being dragged.
  25472. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  25473. juce component has the button down on it. In a multi-touch system, this could
  25474. be any number from 0 to the number of simultaneous touches that can be detected.
  25475. */
  25476. int getNumDraggingMouseSources() const throw();
  25477. /** Returns one of the mouse sources that's currently being dragged.
  25478. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  25479. out of range, or if no mice or fingers are down, this will return a null pointer.
  25480. */
  25481. MouseInputSource* getDraggingMouseSource (int index) const throw();
  25482. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  25483. current mouse-drag operation.
  25484. This allows you to make sure that mouseDrag() events are sent continuously, even
  25485. when the mouse isn't moving. This can be useful for things like auto-scrolling
  25486. components when the mouse is near an edge.
  25487. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  25488. minimum interval between consecutive mouse drag callbacks. The callbacks
  25489. will continue until the mouse is released, and then the interval will be reset,
  25490. so you need to make sure it's called every time you begin a drag event.
  25491. Passing an interval of 0 or less will cancel the auto-repeat.
  25492. @see mouseDrag
  25493. */
  25494. void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  25495. /** In a tablet device which can be turned around, this is used to inidicate the orientation. */
  25496. enum DisplayOrientation
  25497. {
  25498. upright = 1, /**< Indicates that the display is the normal way up. */
  25499. upsideDown = 2, /**< Indicates that the display is upside-down. */
  25500. rotatedClockwise = 4, /**< Indicates that the display is turned 90 degrees clockwise from its upright position. */
  25501. rotatedAntiClockwise = 8, /**< Indicates that the display is turned 90 degrees anti-clockwise from its upright position. */
  25502. allOrientations = 1 + 2 + 4 + 8 /**< A combination of all the orientation values */
  25503. };
  25504. /** In a tablet device which can be turned around, this returns the current orientation. */
  25505. DisplayOrientation getCurrentOrientation() const;
  25506. /** Sets which orientations the display is allowed to auto-rotate to.
  25507. For devices that support rotating desktops, this lets you specify which of the orientations your app can use.
  25508. The parameter is a bitwise or-ed combination of the values in DisplayOrientation, and must contain at least one
  25509. set bit.
  25510. */
  25511. void setOrientationsEnabled (int allowedOrientations);
  25512. /** Returns whether the display is allowed to auto-rotate to the given orientation.
  25513. Each orientation can be enabled using setOrientationEnabled(). By default, all orientations are allowed.
  25514. */
  25515. bool isOrientationEnabled (DisplayOrientation orientation) const throw();
  25516. /** Tells this object to refresh its idea of what the screen resolution is.
  25517. (Called internally by the native code).
  25518. */
  25519. void refreshMonitorSizes();
  25520. /** True if the OS supports semitransparent windows */
  25521. static bool canUseSemiTransparentWindows() throw();
  25522. private:
  25523. static Desktop* instance;
  25524. friend class Component;
  25525. friend class ComponentPeer;
  25526. friend class MouseInputSource;
  25527. friend class MouseInputSourceInternal;
  25528. friend class DeletedAtShutdown;
  25529. friend class TopLevelWindowManager;
  25530. OwnedArray <MouseInputSource> mouseSources;
  25531. void createMouseInputSources();
  25532. ListenerList <MouseListener> mouseListeners;
  25533. ListenerList <FocusChangeListener> focusListeners;
  25534. Array <Component*> desktopComponents;
  25535. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  25536. Point<int> lastFakeMouseMove;
  25537. void sendMouseMove();
  25538. int mouseClickCounter;
  25539. void incrementMouseClickCounter() throw();
  25540. ScopedPointer<Timer> dragRepeater;
  25541. Component* kioskModeComponent;
  25542. Rectangle<int> kioskComponentOriginalBounds;
  25543. int allowedOrientations;
  25544. ComponentAnimator animator;
  25545. void timerCallback();
  25546. void resetTimer();
  25547. int getNumDisplayMonitors() const throw();
  25548. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const throw();
  25549. static void getCurrentMonitorPositions (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea);
  25550. void addDesktopComponent (Component* c);
  25551. void removeDesktopComponent (Component* c);
  25552. void componentBroughtToFront (Component* c);
  25553. void triggerFocusCallback();
  25554. void handleAsyncUpdate();
  25555. Desktop();
  25556. ~Desktop();
  25557. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Desktop);
  25558. };
  25559. #endif // __JUCE_DESKTOP_JUCEHEADER__
  25560. /*** End of inlined file: juce_Desktop.h ***/
  25561. class KeyPressMappingSet;
  25562. class ApplicationCommandManagerListener;
  25563. /**
  25564. One of these objects holds a list of all the commands your app can perform,
  25565. and despatches these commands when needed.
  25566. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  25567. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  25568. to invoke automatically, which means you don't have to handle the result of a menu
  25569. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  25570. which can choose which events they want to handle.
  25571. This architecture also allows for nested ApplicationCommandTargets, so that for example
  25572. you could have two different objects, one inside the other, both of which can respond to
  25573. a "delete" command. Depending on which one has focus, the command will be sent to the
  25574. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  25575. method.
  25576. To set up your app to use commands, you'll need to do the following:
  25577. - Create a global ApplicationCommandManager to hold the list of all possible
  25578. commands. (This will also manage a set of key-mappings for them).
  25579. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  25580. This allows the object to provide a list of commands that it can perform, and
  25581. to handle them.
  25582. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  25583. or ApplicationCommandManager::registerCommand().
  25584. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  25585. method to access the key-mapper object, which you will need to register as a key-listener
  25586. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  25587. about setting this up.
  25588. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  25589. cause these commands to be invoked automatically.
  25590. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  25591. When a command is invoked, the ApplicationCommandManager will try to choose the best
  25592. ApplicationCommandTarget to receive the specified command. To do this it will use the
  25593. current keyboard focus to see which component might be interested, and will search the
  25594. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  25595. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  25596. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  25597. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  25598. point if the command still hasn't been performed, it will be passed to the current
  25599. JUCEApplication object (which is itself an ApplicationCommandTarget).
  25600. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  25601. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  25602. the object yourself.
  25603. @see ApplicationCommandTarget, ApplicationCommandInfo
  25604. */
  25605. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  25606. private FocusChangeListener
  25607. {
  25608. public:
  25609. /** Creates an ApplicationCommandManager.
  25610. Once created, you'll need to register all your app's commands with it, using
  25611. ApplicationCommandManager::registerAllCommandsForTarget() or
  25612. ApplicationCommandManager::registerCommand().
  25613. */
  25614. ApplicationCommandManager();
  25615. /** Destructor.
  25616. Make sure that you don't delete this if pointers to it are still being used by
  25617. objects such as PopupMenus or Buttons.
  25618. */
  25619. virtual ~ApplicationCommandManager();
  25620. /** Clears the current list of all commands.
  25621. Note that this will also clear the contents of the KeyPressMappingSet.
  25622. */
  25623. void clearCommands();
  25624. /** Adds a command to the list of registered commands.
  25625. @see registerAllCommandsForTarget
  25626. */
  25627. void registerCommand (const ApplicationCommandInfo& newCommand);
  25628. /** Adds all the commands that this target publishes to the manager's list.
  25629. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  25630. to get details about all the commands that this target can do, and will call
  25631. registerCommand() to add each one to the manger's list.
  25632. @see registerCommand
  25633. */
  25634. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  25635. /** Removes the command with a specified ID.
  25636. Note that this will also remove any key mappings that are mapped to the command.
  25637. */
  25638. void removeCommand (CommandID commandID);
  25639. /** This should be called to tell the manager that one of its registered commands may have changed
  25640. its active status.
  25641. Because the command manager only finds out whether a command is active or inactive by querying
  25642. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  25643. allows things like buttons to update their enablement, etc.
  25644. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  25645. for any registered listeners.
  25646. */
  25647. void commandStatusChanged();
  25648. /** Returns the number of commands that have been registered.
  25649. @see registerCommand
  25650. */
  25651. int getNumCommands() const throw() { return commands.size(); }
  25652. /** Returns the details about one of the registered commands.
  25653. The index is between 0 and (getNumCommands() - 1).
  25654. */
  25655. const ApplicationCommandInfo* getCommandForIndex (int index) const throw() { return commands [index]; }
  25656. /** Returns the details about a given command ID.
  25657. This will search the list of registered commands for one with the given command
  25658. ID number, and return its associated info. If no matching command is found, this
  25659. will return 0.
  25660. */
  25661. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const throw();
  25662. /** Returns the name field for a command.
  25663. An empty string is returned if no command with this ID has been registered.
  25664. @see getDescriptionOfCommand
  25665. */
  25666. const String getNameOfCommand (CommandID commandID) const throw();
  25667. /** Returns the description field for a command.
  25668. An empty string is returned if no command with this ID has been registered. If the
  25669. command has no description, this will return its short name field instead.
  25670. @see getNameOfCommand
  25671. */
  25672. const String getDescriptionOfCommand (CommandID commandID) const throw();
  25673. /** Returns the list of categories.
  25674. This will go through all registered commands, and return a list of all the distict
  25675. categoryName values from their ApplicationCommandInfo structure.
  25676. @see getCommandsInCategory()
  25677. */
  25678. const StringArray getCommandCategories() const;
  25679. /** Returns a list of all the command UIDs in a particular category.
  25680. @see getCommandCategories()
  25681. */
  25682. const Array <CommandID> getCommandsInCategory (const String& categoryName) const;
  25683. /** Returns the manager's internal set of key mappings.
  25684. This object can be used to edit the keypresses. To actually link this object up
  25685. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  25686. class.
  25687. @see KeyPressMappingSet
  25688. */
  25689. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  25690. /** Invokes the given command directly, sending it to the default target.
  25691. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  25692. structure.
  25693. */
  25694. bool invokeDirectly (CommandID commandID, bool asynchronously);
  25695. /** Sends a command to the default target.
  25696. This will choose a target using getFirstCommandTarget(), and send the specified command
  25697. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  25698. first target can't handle the command, it will be passed on to targets further down the
  25699. chain (see ApplicationCommandTarget::invoke() for more info).
  25700. @param invocationInfo this must be correctly filled-in, describing the context for
  25701. the invocation.
  25702. @param asynchronously if false, the command will be performed before this method returns.
  25703. If true, a message will be posted so that the command will be performed
  25704. later on the message thread, and this method will return immediately.
  25705. @see ApplicationCommandTarget::invoke
  25706. */
  25707. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  25708. bool asynchronously);
  25709. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  25710. Whenever the manager needs to know which target a command should be sent to, it calls
  25711. this method to determine the first one to try.
  25712. By default, this method will return the target that was set by calling setFirstCommandTarget().
  25713. If no target is set, it will return the result of findDefaultComponentTarget().
  25714. If you need to make sure all commands go via your own custom target, then you can
  25715. either use setFirstCommandTarget() to specify a single target, or override this method
  25716. if you need more complex logic to choose one.
  25717. It may return 0 if no targets are available.
  25718. @see getTargetForCommand, invoke, invokeDirectly
  25719. */
  25720. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  25721. /** Sets a target to be returned by getFirstCommandTarget().
  25722. If this is set to 0, then getFirstCommandTarget() will by default return the
  25723. result of findDefaultComponentTarget().
  25724. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  25725. deleting the target object.
  25726. */
  25727. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) throw();
  25728. /** Tries to find the best target to use to perform a given command.
  25729. This will call getFirstCommandTarget() to find the preferred target, and will
  25730. check whether that target can handle the given command. If it can't, then it'll use
  25731. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  25732. so on until no more are available.
  25733. If no targets are found that can perform the command, this method will return 0.
  25734. If a target is found, then it will get the target to fill-in the upToDateInfo
  25735. structure with the latest info about that command, so that the caller can see
  25736. whether the command is disabled, ticked, etc.
  25737. */
  25738. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  25739. ApplicationCommandInfo& upToDateInfo);
  25740. /** Registers a listener that will be called when various events occur. */
  25741. void addListener (ApplicationCommandManagerListener* listener);
  25742. /** Deregisters a previously-added listener. */
  25743. void removeListener (ApplicationCommandManagerListener* listener);
  25744. /** Looks for a suitable command target based on which Components have the keyboard focus.
  25745. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  25746. but is exposed here in case it's useful.
  25747. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  25748. windows, etc., and using the findTargetForComponent() method.
  25749. */
  25750. static ApplicationCommandTarget* findDefaultComponentTarget();
  25751. /** Examines this component and all its parents in turn, looking for the first one
  25752. which is a ApplicationCommandTarget.
  25753. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  25754. that class.
  25755. */
  25756. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  25757. private:
  25758. OwnedArray <ApplicationCommandInfo> commands;
  25759. ListenerList <ApplicationCommandManagerListener> listeners;
  25760. ScopedPointer <KeyPressMappingSet> keyMappings;
  25761. ApplicationCommandTarget* firstTarget;
  25762. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  25763. void handleAsyncUpdate();
  25764. void globalFocusChanged (Component*);
  25765. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  25766. // This is just here to cause a compile error in old code that hasn't been changed to use the new
  25767. // version of this method.
  25768. virtual short getFirstCommandTarget() { return 0; }
  25769. #endif
  25770. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandManager);
  25771. };
  25772. /**
  25773. A listener that receives callbacks from an ApplicationCommandManager when
  25774. commands are invoked or the command list is changed.
  25775. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  25776. */
  25777. class JUCE_API ApplicationCommandManagerListener
  25778. {
  25779. public:
  25780. /** Destructor. */
  25781. virtual ~ApplicationCommandManagerListener() {}
  25782. /** Called when an app command is about to be invoked. */
  25783. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  25784. /** Called when commands are registered or deregistered from the
  25785. command manager, or when commands are made active or inactive.
  25786. Note that if you're using this to watch for changes to whether a command is disabled,
  25787. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  25788. whenever the status of your command might have changed.
  25789. */
  25790. virtual void applicationCommandListChanged() = 0;
  25791. };
  25792. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25793. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  25794. #endif
  25795. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  25796. #endif
  25797. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  25798. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  25799. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  25800. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  25801. /*** Start of inlined file: juce_PropertiesFile.h ***/
  25802. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  25803. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  25804. /** Wrapper on a file that stores a list of key/value data pairs.
  25805. Useful for storing application settings, etc. See the PropertySet class for
  25806. the interfaces that read and write values.
  25807. Not designed for very large amounts of data, as it keeps all the values in
  25808. memory and writes them out to disk lazily when they are changed.
  25809. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  25810. with it, and these will be signalled when a value changes.
  25811. @see PropertySet
  25812. */
  25813. class JUCE_API PropertiesFile : public PropertySet,
  25814. public ChangeBroadcaster,
  25815. private Timer
  25816. {
  25817. public:
  25818. enum FileFormatOptions
  25819. {
  25820. ignoreCaseOfKeyNames = 1,
  25821. storeAsBinary = 2,
  25822. storeAsCompressedBinary = 4,
  25823. storeAsXML = 8
  25824. };
  25825. /**
  25826. Creates a PropertiesFile object.
  25827. @param file the file to use
  25828. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  25829. is changed, the object will wait for this amount
  25830. of time and then save the file. If zero, the file
  25831. will be written to disk immediately on being changed
  25832. (which might be slow, as it'll re-write synchronously
  25833. each time a value-change method is called). If it is
  25834. less than zero, the file won't be saved until
  25835. save() or saveIfNeeded() are explicitly called.
  25836. @param optionFlags a combination of the flags in the FileFormatOptions
  25837. enum, which specify the type of file to save, and other
  25838. options.
  25839. @param processLock an optional InterprocessLock object that will be used to
  25840. prevent multiple threads or processes from writing to the file
  25841. at the same time. The PropertiesFile will keep a pointer to
  25842. this object but will not take ownership of it - the caller is
  25843. responsible for making sure that the lock doesn't get deleted
  25844. before the PropertiesFile has been deleted.
  25845. */
  25846. PropertiesFile (const File& file,
  25847. int millisecondsBeforeSaving,
  25848. int optionFlags,
  25849. InterProcessLock* processLock = 0);
  25850. /** Destructor.
  25851. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  25852. */
  25853. ~PropertiesFile();
  25854. /** Returns true if this file was created from a valid (or non-existent) file.
  25855. If the file failed to load correctly because it was corrupt or had insufficient
  25856. access, this will be false.
  25857. */
  25858. bool isValidFile() const throw() { return loadedOk; }
  25859. /** This will flush all the values to disk if they've changed since the last
  25860. time they were saved.
  25861. Returns false if it fails to write to the file for some reason (maybe because
  25862. it's read-only or the directory doesn't exist or something).
  25863. @see save
  25864. */
  25865. bool saveIfNeeded();
  25866. /** This will force a write-to-disk of the current values, regardless of whether
  25867. anything has changed since the last save.
  25868. Returns false if it fails to write to the file for some reason (maybe because
  25869. it's read-only or the directory doesn't exist or something).
  25870. @see saveIfNeeded
  25871. */
  25872. bool save();
  25873. /** Returns true if the properties have been altered since the last time they were saved.
  25874. The file is flagged as needing to be saved when you change a value, but you can
  25875. explicitly set this flag with setNeedsToBeSaved().
  25876. */
  25877. bool needsToBeSaved() const;
  25878. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  25879. @see needsToBeSaved
  25880. */
  25881. void setNeedsToBeSaved (bool needsToBeSaved);
  25882. /** Returns the file that's being used. */
  25883. const File getFile() const { return file; }
  25884. /** Handy utility to create a properties file in whatever the standard OS-specific
  25885. location is for these things.
  25886. This uses getDefaultAppSettingsFile() to decide what file to create, then
  25887. creates a PropertiesFile object with the specified properties. See
  25888. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  25889. what the parameters do.
  25890. @see getDefaultAppSettingsFile
  25891. */
  25892. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  25893. const String& fileNameSuffix,
  25894. const String& folderName,
  25895. bool commonToAllUsers,
  25896. int millisecondsBeforeSaving,
  25897. int propertiesFileOptions,
  25898. InterProcessLock* processLock = 0);
  25899. /** Handy utility to choose a file in the standard OS-dependent location for application
  25900. settings files.
  25901. So on a Mac, this will return a file called:
  25902. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  25903. On Windows it'll return something like:
  25904. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  25905. On Linux it'll return
  25906. ~/.[folderName]/[applicationName].[fileNameSuffix]
  25907. If you pass an empty string as the folder name, it'll use the app name for this (or
  25908. omit the folder name on the Mac).
  25909. If commonToAllUsers is true, then this will return the same file for all users of the
  25910. computer, regardless of the current user. If it is false, the file will be specific to
  25911. only the current user. Use this to choose whether you're saving settings that are common
  25912. or user-specific.
  25913. */
  25914. static const File getDefaultAppSettingsFile (const String& applicationName,
  25915. const String& fileNameSuffix,
  25916. const String& folderName,
  25917. bool commonToAllUsers);
  25918. protected:
  25919. virtual void propertyChanged();
  25920. private:
  25921. File file;
  25922. int timerInterval;
  25923. const int options;
  25924. bool loadedOk, needsWriting;
  25925. InterProcessLock* processLock;
  25926. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  25927. InterProcessLock::ScopedLockType* createProcessLock() const;
  25928. void timerCallback();
  25929. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertiesFile);
  25930. };
  25931. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  25932. /*** End of inlined file: juce_PropertiesFile.h ***/
  25933. /**
  25934. Manages a collection of properties.
  25935. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  25936. as a singleton.
  25937. It holds two different PropertiesFile objects internally, one for user-specific
  25938. settings (stored in your user directory), and one for settings that are common to
  25939. all users (stored in a folder accessible to all users).
  25940. The class manages the creation of these files on-demand, allowing access via the
  25941. getUserSettings() and getCommonSettings() methods. It also has a few handy
  25942. methods like testWriteAccess() to check that the files can be saved.
  25943. If you're using one of these as a singleton, then your app's start-up code should
  25944. first of all call setStorageParameters() to tell it the parameters to use to create
  25945. the properties files.
  25946. @see PropertiesFile
  25947. */
  25948. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  25949. {
  25950. public:
  25951. /**
  25952. Creates an ApplicationProperties object.
  25953. Before using it, you must call setStorageParameters() to give it the info
  25954. it needs to create the property files.
  25955. */
  25956. ApplicationProperties();
  25957. /** Destructor. */
  25958. ~ApplicationProperties();
  25959. juce_DeclareSingleton (ApplicationProperties, false)
  25960. /** Gives the object the information it needs to create the appropriate properties files.
  25961. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  25962. info about how these parameters are used.
  25963. */
  25964. void setStorageParameters (const String& applicationName,
  25965. const String& fileNameSuffix,
  25966. const String& folderName,
  25967. int millisecondsBeforeSaving,
  25968. int propertiesFileOptions,
  25969. InterProcessLock* processLock = 0);
  25970. /** Tests whether the files can be successfully written to, and can show
  25971. an error message if not.
  25972. Returns true if none of the tests fail.
  25973. @param testUserSettings if true, the user settings file will be tested
  25974. @param testCommonSettings if true, the common settings file will be tested
  25975. @param showWarningDialogOnFailure if true, the method will show a helpful error
  25976. message box if either of the tests fail
  25977. */
  25978. bool testWriteAccess (bool testUserSettings,
  25979. bool testCommonSettings,
  25980. bool showWarningDialogOnFailure);
  25981. /** Returns the user settings file.
  25982. The first time this is called, it will create and load the properties file.
  25983. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  25984. the common settings are used as a second-chance place to look. This is done via the
  25985. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  25986. to the fallback for the user settings.
  25987. @see getCommonSettings
  25988. */
  25989. PropertiesFile* getUserSettings();
  25990. /** Returns the common settings file.
  25991. The first time this is called, it will create and load the properties file.
  25992. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  25993. read-only (e.g. because the user doesn't have permission to write
  25994. to shared files), then this will return the user settings instead,
  25995. (like getUserSettings() would do). This is handy if you'd like to
  25996. write a value to the common settings, but if that's no possible,
  25997. then you'd rather write to the user settings than none at all.
  25998. If returnUserPropsIfReadOnly is false, this method will always return
  25999. the common settings, even if any changes to them can't be saved.
  26000. @see getUserSettings
  26001. */
  26002. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly);
  26003. /** Saves both files if they need to be saved.
  26004. @see PropertiesFile::saveIfNeeded
  26005. */
  26006. bool saveIfNeeded();
  26007. /** Flushes and closes both files if they are open.
  26008. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  26009. and closes both files. They will then be re-opened the next time getUserSettings()
  26010. or getCommonSettings() is called.
  26011. */
  26012. void closeFiles();
  26013. private:
  26014. ScopedPointer <PropertiesFile> userProps, commonProps;
  26015. String appName, fileSuffix, folderName;
  26016. int msBeforeSaving, options;
  26017. int commonSettingsAreReadOnly;
  26018. InterProcessLock* processLock;
  26019. void openFiles();
  26020. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationProperties);
  26021. };
  26022. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  26023. /*** End of inlined file: juce_ApplicationProperties.h ***/
  26024. #endif
  26025. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26026. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  26027. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26028. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26029. /*** Start of inlined file: juce_AudioFormat.h ***/
  26030. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  26031. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  26032. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  26033. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26034. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26035. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  26036. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26037. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26038. /**
  26039. This class a container which holds all the classes pertaining to the AudioData::Pointer
  26040. audio sample format class.
  26041. @see AudioData::Pointer.
  26042. */
  26043. class JUCE_API AudioData
  26044. {
  26045. public:
  26046. // These types can be used as the SampleFormat template parameter for the AudioData::Pointer class.
  26047. class Int8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit integer packed data format. */
  26048. class UInt8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit unsigned integer packed data format. */
  26049. class Int16; /**< Used as a template parameter for AudioData::Pointer. Indicates an 16-bit integer packed data format. */
  26050. class Int24; /**< Used as a template parameter for AudioData::Pointer. Indicates an 24-bit integer packed data format. */
  26051. class Int32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit integer packed data format. */
  26052. class Float32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit float data format. */
  26053. // These types can be used as the Endianness template parameter for the AudioData::Pointer class.
  26054. class BigEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in big-endian order. */
  26055. class LittleEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in little-endian order. */
  26056. class NativeEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in the CPU's native endianness. */
  26057. // These types can be used as the InterleavingType template parameter for the AudioData::Pointer class.
  26058. class NonInterleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored contiguously. */
  26059. class Interleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are interleaved with a number of other channels. */
  26060. // These types can be used as the Constness template parameter for the AudioData::Pointer class.
  26061. class NonConst; /**< Used as a template parameter for AudioData::Pointer. Indicates that the pointer can be used for non-const data. */
  26062. class Const; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples can only be used for const data.. */
  26063. #ifndef DOXYGEN
  26064. class BigEndian
  26065. {
  26066. public:
  26067. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) throw() { return s.getAsFloatBE(); }
  26068. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) throw() { s.setAsFloatBE (newValue); }
  26069. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) throw() { return s.getAsInt32BE(); }
  26070. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) throw() { s.setAsInt32BE (newValue); }
  26071. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) throw() { dest.copyFromBE (source); }
  26072. enum { isBigEndian = 1 };
  26073. };
  26074. class LittleEndian
  26075. {
  26076. public:
  26077. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) throw() { return s.getAsFloatLE(); }
  26078. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) throw() { s.setAsFloatLE (newValue); }
  26079. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) throw() { return s.getAsInt32LE(); }
  26080. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) throw() { s.setAsInt32LE (newValue); }
  26081. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) throw() { dest.copyFromLE (source); }
  26082. enum { isBigEndian = 0 };
  26083. };
  26084. #if JUCE_BIG_ENDIAN
  26085. class NativeEndian : public BigEndian {};
  26086. #else
  26087. class NativeEndian : public LittleEndian {};
  26088. #endif
  26089. class Int8
  26090. {
  26091. public:
  26092. inline Int8 (void* data_) throw() : data (static_cast <int8*> (data_)) {}
  26093. inline void advance() throw() { ++data; }
  26094. inline void skip (int numSamples) throw() { data += numSamples; }
  26095. inline float getAsFloatLE() const throw() { return (float) (*data * (1.0 / (1.0 + maxValue))); }
  26096. inline float getAsFloatBE() const throw() { return getAsFloatLE(); }
  26097. inline void setAsFloatLE (float newValue) throw() { *data = (int8) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))); }
  26098. inline void setAsFloatBE (float newValue) throw() { setAsFloatLE (newValue); }
  26099. inline int32 getAsInt32LE() const throw() { return (int) (*data << 24); }
  26100. inline int32 getAsInt32BE() const throw() { return getAsInt32LE(); }
  26101. inline void setAsInt32LE (int newValue) throw() { *data = (int8) (newValue >> 24); }
  26102. inline void setAsInt32BE (int newValue) throw() { setAsInt32LE (newValue); }
  26103. inline void clear() throw() { *data = 0; }
  26104. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  26105. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  26106. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  26107. inline void copyFromSameType (Int8& source) throw() { *data = *source.data; }
  26108. int8* data;
  26109. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  26110. };
  26111. class UInt8
  26112. {
  26113. public:
  26114. inline UInt8 (void* data_) throw() : data (static_cast <uint8*> (data_)) {}
  26115. inline void advance() throw() { ++data; }
  26116. inline void skip (int numSamples) throw() { data += numSamples; }
  26117. inline float getAsFloatLE() const throw() { return (float) ((*data - 128) * (1.0 / (1.0 + maxValue))); }
  26118. inline float getAsFloatBE() const throw() { return getAsFloatLE(); }
  26119. inline void setAsFloatLE (float newValue) throw() { *data = (uint8) jlimit (0, 255, 128 + roundToInt (newValue * (1.0 + maxValue))); }
  26120. inline void setAsFloatBE (float newValue) throw() { setAsFloatLE (newValue); }
  26121. inline int32 getAsInt32LE() const throw() { return (int) ((*data - 128) << 24); }
  26122. inline int32 getAsInt32BE() const throw() { return getAsInt32LE(); }
  26123. inline void setAsInt32LE (int newValue) throw() { *data = (uint8) (128 + (newValue >> 24)); }
  26124. inline void setAsInt32BE (int newValue) throw() { setAsInt32LE (newValue); }
  26125. inline void clear() throw() { *data = 128; }
  26126. inline void clearMultiple (int num) throw() { memset (data, 128, num) ;}
  26127. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  26128. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  26129. inline void copyFromSameType (UInt8& source) throw() { *data = *source.data; }
  26130. uint8* data;
  26131. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  26132. };
  26133. class Int16
  26134. {
  26135. public:
  26136. inline Int16 (void* data_) throw() : data (static_cast <uint16*> (data_)) {}
  26137. inline void advance() throw() { ++data; }
  26138. inline void skip (int numSamples) throw() { data += numSamples; }
  26139. inline float getAsFloatLE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfBigEndian (*data)); }
  26140. inline float getAsFloatBE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfLittleEndian (*data)); }
  26141. inline void setAsFloatLE (float newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint16) jlimit ((int16) -maxValue, (int16) maxValue, (int16) roundToInt (newValue * (1.0 + maxValue)))); }
  26142. inline void setAsFloatBE (float newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint16) jlimit ((int16) -maxValue, (int16) maxValue, (int16) roundToInt (newValue * (1.0 + maxValue)))); }
  26143. inline int32 getAsInt32LE() const throw() { return (int32) (ByteOrder::swapIfBigEndian ((uint16) *data) << 16); }
  26144. inline int32 getAsInt32BE() const throw() { return (int32) (ByteOrder::swapIfLittleEndian ((uint16) *data) << 16); }
  26145. inline void setAsInt32LE (int32 newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint16) (newValue >> 16)); }
  26146. inline void setAsInt32BE (int32 newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint16) (newValue >> 16)); }
  26147. inline void clear() throw() { *data = 0; }
  26148. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  26149. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  26150. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  26151. inline void copyFromSameType (Int16& source) throw() { *data = *source.data; }
  26152. uint16* data;
  26153. enum { bytesPerSample = 2, maxValue = 0x7fff, resolution = (1 << 16), isFloat = 0 };
  26154. };
  26155. class Int24
  26156. {
  26157. public:
  26158. inline Int24 (void* data_) throw() : data (static_cast <char*> (data_)) {}
  26159. inline void advance() throw() { data += 3; }
  26160. inline void skip (int numSamples) throw() { data += 3 * numSamples; }
  26161. inline float getAsFloatLE() const throw() { return (float) (ByteOrder::littleEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  26162. inline float getAsFloatBE() const throw() { return (float) (ByteOrder::bigEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  26163. inline void setAsFloatLE (float newValue) throw() { ByteOrder::littleEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  26164. inline void setAsFloatBE (float newValue) throw() { ByteOrder::bigEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  26165. inline int32 getAsInt32LE() const throw() { return (int32) ByteOrder::littleEndian24Bit (data) << 8; }
  26166. inline int32 getAsInt32BE() const throw() { return (int32) ByteOrder::bigEndian24Bit (data) << 8; }
  26167. inline void setAsInt32LE (int32 newValue) throw() { ByteOrder::littleEndian24BitToChars (newValue >> 8, data); }
  26168. inline void setAsInt32BE (int32 newValue) throw() { ByteOrder::bigEndian24BitToChars (newValue >> 8, data); }
  26169. inline void clear() throw() { data[0] = 0; data[1] = 0; data[2] = 0; }
  26170. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  26171. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  26172. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  26173. inline void copyFromSameType (Int24& source) throw() { data[0] = source.data[0]; data[1] = source.data[1]; data[2] = source.data[2]; }
  26174. char* data;
  26175. enum { bytesPerSample = 3, maxValue = 0x7fffff, resolution = (1 << 8), isFloat = 0 };
  26176. };
  26177. class Int32
  26178. {
  26179. public:
  26180. inline Int32 (void* data_) throw() : data (static_cast <uint32*> (data_)) {}
  26181. inline void advance() throw() { ++data; }
  26182. inline void skip (int numSamples) throw() { data += numSamples; }
  26183. inline float getAsFloatLE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfBigEndian (*data)); }
  26184. inline float getAsFloatBE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfLittleEndian (*data)); }
  26185. inline void setAsFloatLE (float newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint32) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26186. inline void setAsFloatBE (float newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint32) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  26187. inline int32 getAsInt32LE() const throw() { return (int32) ByteOrder::swapIfBigEndian (*data); }
  26188. inline int32 getAsInt32BE() const throw() { return (int32) ByteOrder::swapIfLittleEndian (*data); }
  26189. inline void setAsInt32LE (int32 newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint32) newValue); }
  26190. inline void setAsInt32BE (int32 newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint32) newValue); }
  26191. inline void clear() throw() { *data = 0; }
  26192. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  26193. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  26194. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  26195. inline void copyFromSameType (Int32& source) throw() { *data = *source.data; }
  26196. uint32* data;
  26197. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = 1, isFloat = 0 };
  26198. };
  26199. class Float32
  26200. {
  26201. public:
  26202. inline Float32 (void* data_) throw() : data (static_cast <float*> (data_)) {}
  26203. inline void advance() throw() { ++data; }
  26204. inline void skip (int numSamples) throw() { data += numSamples; }
  26205. #if JUCE_BIG_ENDIAN
  26206. inline float getAsFloatBE() const throw() { return *data; }
  26207. inline void setAsFloatBE (float newValue) throw() { *data = newValue; }
  26208. inline float getAsFloatLE() const throw() { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  26209. inline void setAsFloatLE (float newValue) throw() { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  26210. #else
  26211. inline float getAsFloatLE() const throw() { return *data; }
  26212. inline void setAsFloatLE (float newValue) throw() { *data = newValue; }
  26213. inline float getAsFloatBE() const throw() { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  26214. inline void setAsFloatBE (float newValue) throw() { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  26215. #endif
  26216. inline int32 getAsInt32LE() const throw() { return (int32) roundToInt (jlimit (-1.0f, 1.0f, getAsFloatLE()) * (1.0 + maxValue)); }
  26217. inline int32 getAsInt32BE() const throw() { return (int32) roundToInt (jlimit (-1.0f, 1.0f, getAsFloatBE()) * (1.0 + maxValue)); }
  26218. inline void setAsInt32LE (int32 newValue) throw() { setAsFloatLE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  26219. inline void setAsInt32BE (int32 newValue) throw() { setAsFloatBE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  26220. inline void clear() throw() { *data = 0; }
  26221. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  26222. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsFloatLE (source.getAsFloat()); }
  26223. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsFloatBE (source.getAsFloat()); }
  26224. inline void copyFromSameType (Float32& source) throw() { *data = *source.data; }
  26225. float* data;
  26226. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = (1 << 8), isFloat = 1 };
  26227. };
  26228. class NonInterleaved
  26229. {
  26230. public:
  26231. inline NonInterleaved() throw() {}
  26232. inline NonInterleaved (const NonInterleaved&) throw() {}
  26233. inline NonInterleaved (const int) throw() {}
  26234. inline void copyFrom (const NonInterleaved&) throw() {}
  26235. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) throw() { s.advance(); }
  26236. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) throw() { s.skip (numSamples); }
  26237. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) throw() { s.clearMultiple (numSamples); }
  26238. template <class SampleFormatType> inline static int getNumBytesBetweenSamples (const SampleFormatType&) throw() { return SampleFormatType::bytesPerSample; }
  26239. enum { isInterleavedType = 0, numInterleavedChannels = 1 };
  26240. };
  26241. class Interleaved
  26242. {
  26243. public:
  26244. inline Interleaved() throw() : numInterleavedChannels (1) {}
  26245. inline Interleaved (const Interleaved& other) throw() : numInterleavedChannels (other.numInterleavedChannels) {}
  26246. inline Interleaved (const int numInterleavedChannels_) throw() : numInterleavedChannels (numInterleavedChannels_) {}
  26247. inline void copyFrom (const Interleaved& other) throw() { numInterleavedChannels = other.numInterleavedChannels; }
  26248. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) throw() { s.skip (numInterleavedChannels); }
  26249. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) throw() { s.skip (numInterleavedChannels * numSamples); }
  26250. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) throw() { while (--numSamples >= 0) { s.clear(); s.skip (numInterleavedChannels); } }
  26251. template <class SampleFormatType> inline int getNumBytesBetweenSamples (const SampleFormatType&) const throw() { return numInterleavedChannels * SampleFormatType::bytesPerSample; }
  26252. int numInterleavedChannels;
  26253. enum { isInterleavedType = 1 };
  26254. };
  26255. class NonConst
  26256. {
  26257. public:
  26258. typedef void VoidType;
  26259. static inline void* toVoidPtr (VoidType* v) throw() { return v; }
  26260. enum { isConst = 0 };
  26261. };
  26262. class Const
  26263. {
  26264. public:
  26265. typedef const void VoidType;
  26266. static inline void* toVoidPtr (VoidType* v) throw() { return const_cast<void*> (v); }
  26267. enum { isConst = 1 };
  26268. };
  26269. #endif
  26270. /**
  26271. A pointer to a block of audio data with a particular encoding.
  26272. This object can be used to read and write from blocks of encoded audio samples. To create one, you specify
  26273. the audio format as a series of template parameters, e.g.
  26274. @code
  26275. // this creates a pointer for reading from a const array of 16-bit little-endian packed samples.
  26276. AudioData::Pointer <AudioData::Int16,
  26277. AudioData::LittleEndian,
  26278. AudioData::NonInterleaved,
  26279. AudioData::Const> pointer (someRawAudioData);
  26280. // These methods read the sample that is being pointed to
  26281. float firstSampleAsFloat = pointer.getAsFloat();
  26282. int32 firstSampleAsInt = pointer.getAsInt32();
  26283. ++pointer; // moves the pointer to the next sample.
  26284. pointer += 3; // skips the next 3 samples.
  26285. @endcode
  26286. The convertSamples() method lets you copy a range of samples from one format to another, automatically
  26287. converting its format.
  26288. @see AudioData::Converter
  26289. */
  26290. template <typename SampleFormat,
  26291. typename Endianness,
  26292. typename InterleavingType,
  26293. typename Constness>
  26294. class Pointer
  26295. {
  26296. public:
  26297. /** Creates a non-interleaved pointer from some raw data in the appropriate format.
  26298. This constructor is only used if you've specified the AudioData::NonInterleaved option -
  26299. for interleaved formats, use the constructor that also takes a number of channels.
  26300. */
  26301. Pointer (typename Constness::VoidType* sourceData) throw()
  26302. : data (Constness::toVoidPtr (sourceData))
  26303. {
  26304. // If you're using interleaved data, call the other constructor! If you're using non-interleaved data,
  26305. // you should pass NonInterleaved as the template parameter for the interleaving type!
  26306. static_jassert (InterleavingType::isInterleavedType == 0);
  26307. }
  26308. /** Creates a pointer from some raw data in the appropriate format with the specified number of interleaved channels.
  26309. For non-interleaved data, use the other constructor.
  26310. */
  26311. Pointer (typename Constness::VoidType* sourceData, int numInterleavedChannels) throw()
  26312. : data (Constness::toVoidPtr (sourceData)),
  26313. interleaving (numInterleavedChannels)
  26314. {
  26315. }
  26316. /** Creates a copy of another pointer. */
  26317. Pointer (const Pointer& other) throw()
  26318. : data (other.data),
  26319. interleaving (other.interleaving)
  26320. {
  26321. }
  26322. Pointer& operator= (const Pointer& other) throw()
  26323. {
  26324. data = other.data;
  26325. interleaving.copyFrom (other.interleaving);
  26326. return *this;
  26327. }
  26328. /** Returns the value of the first sample as a floating point value.
  26329. The value will be in the range -1.0 to 1.0 for integer formats. For floating point
  26330. formats, the value could be outside that range, although -1 to 1 is the standard range.
  26331. */
  26332. inline float getAsFloat() const throw() { return Endianness::getAsFloat (data); }
  26333. /** Sets the value of the first sample as a floating point value.
  26334. (This method can only be used if the AudioData::NonConst option was used).
  26335. The value should be in the range -1.0 to 1.0 - for integer formats, values outside that
  26336. range will be clipped. For floating point formats, any value passed in here will be
  26337. written directly, although -1 to 1 is the standard range.
  26338. */
  26339. inline void setAsFloat (float newValue) throw()
  26340. {
  26341. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26342. Endianness::setAsFloat (data, newValue);
  26343. }
  26344. /** Returns the value of the first sample as a 32-bit integer.
  26345. The value returned will be in the range 0x80000000 to 0x7fffffff, and shorter values will be
  26346. shifted to fill this range (e.g. if you're reading from 24-bit data, the values will be shifted up
  26347. by 8 bits when returned here). If the source data is floating point, values beyond -1.0 to 1.0 will
  26348. be clipped so that -1.0 maps onto -0x7fffffff and 1.0 maps to 0x7fffffff.
  26349. */
  26350. inline int32 getAsInt32() const throw() { return Endianness::getAsInt32 (data); }
  26351. /** Sets the value of the first sample as a 32-bit integer.
  26352. This will be mapped to the range of the format that is being written - see getAsInt32().
  26353. */
  26354. inline void setAsInt32 (int32 newValue) throw()
  26355. {
  26356. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26357. Endianness::setAsInt32 (data, newValue);
  26358. }
  26359. /** Moves the pointer along to the next sample. */
  26360. inline Pointer& operator++() throw() { advance(); return *this; }
  26361. /** Moves the pointer back to the previous sample. */
  26362. inline Pointer& operator--() throw() { interleaving.advanceDataBy (data, -1); return *this; }
  26363. /** Adds a number of samples to the pointer's position. */
  26364. Pointer& operator+= (int samplesToJump) throw() { interleaving.advanceDataBy (data, samplesToJump); return *this; }
  26365. /** Writes a stream of samples into this pointer from another pointer.
  26366. This will copy the specified number of samples, converting between formats appropriately.
  26367. */
  26368. void convertSamples (Pointer source, int numSamples) const throw()
  26369. {
  26370. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26371. Pointer dest (*this);
  26372. while (--numSamples >= 0)
  26373. {
  26374. dest.data.copyFromSameType (source.data);
  26375. dest.advance();
  26376. source.advance();
  26377. }
  26378. }
  26379. /** Writes a stream of samples into this pointer from another pointer.
  26380. This will copy the specified number of samples, converting between formats appropriately.
  26381. */
  26382. template <class OtherPointerType>
  26383. void convertSamples (OtherPointerType source, int numSamples) const throw()
  26384. {
  26385. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  26386. Pointer dest (*this);
  26387. if (source.getRawData() != getRawData() || source.getNumBytesBetweenSamples() >= getNumBytesBetweenSamples())
  26388. {
  26389. while (--numSamples >= 0)
  26390. {
  26391. Endianness::copyFrom (dest.data, source);
  26392. dest.advance();
  26393. ++source;
  26394. }
  26395. }
  26396. else // copy backwards if we're increasing the sample width..
  26397. {
  26398. dest += numSamples;
  26399. source += numSamples;
  26400. while (--numSamples >= 0)
  26401. Endianness::copyFrom ((--dest).data, --source);
  26402. }
  26403. }
  26404. /** Sets a number of samples to zero. */
  26405. void clearSamples (int numSamples) const throw()
  26406. {
  26407. Pointer dest (*this);
  26408. dest.interleaving.clear (dest.data, numSamples);
  26409. }
  26410. /** Returns true if the pointer is using a floating-point format. */
  26411. static bool isFloatingPoint() throw() { return (bool) SampleFormat::isFloat; }
  26412. /** Returns true if the format is big-endian. */
  26413. static bool isBigEndian() throw() { return (bool) Endianness::isBigEndian; }
  26414. /** Returns the number of bytes in each sample (ignoring the number of interleaved channels). */
  26415. static int getBytesPerSample() throw() { return (int) SampleFormat::bytesPerSample; }
  26416. /** Returns the number of interleaved channels in the format. */
  26417. int getNumInterleavedChannels() const throw() { return (int) this->numInterleavedChannels; }
  26418. /** Returns the number of bytes between the start address of each sample. */
  26419. int getNumBytesBetweenSamples() const throw() { return interleaving.getNumBytesBetweenSamples (data); }
  26420. /** Returns the accuracy of this format when represented as a 32-bit integer.
  26421. This is the smallest number above 0 that can be represented in the sample format, converted to
  26422. a 32-bit range. E,g. if the format is 8-bit, its resolution is 0x01000000; if the format is 24-bit,
  26423. its resolution is 0x100.
  26424. */
  26425. static int get32BitResolution() throw() { return (int) SampleFormat::resolution; }
  26426. /** Returns a pointer to the underlying data. */
  26427. const void* getRawData() const throw() { return data.data; }
  26428. private:
  26429. SampleFormat data;
  26430. InterleavingType interleaving; // annoyingly, making the interleaving type a superclass to take
  26431. // advantage of EBCO causes an internal compiler error in VC6..
  26432. inline void advance() throw() { interleaving.advanceData (data); }
  26433. Pointer operator++ (int); // private to force you to use the more efficient pre-increment!
  26434. Pointer operator-- (int);
  26435. };
  26436. /** A base class for objects that are used to convert between two different sample formats.
  26437. The AudioData::ConverterInstance implements this base class and can be templated, so
  26438. you can create an instance that converts between two particular formats, and then
  26439. store this in the abstract base class.
  26440. @see AudioData::ConverterInstance
  26441. */
  26442. class Converter
  26443. {
  26444. public:
  26445. virtual ~Converter() {}
  26446. /** Converts a sequence of samples from the converter's source format into the dest format. */
  26447. virtual void convertSamples (void* destSamples, const void* sourceSamples, int numSamples) const = 0;
  26448. /** Converts a sequence of samples from the converter's source format into the dest format.
  26449. This method takes sub-channel indexes, which can be used with interleaved formats in order to choose a
  26450. particular sub-channel of the data to be used.
  26451. */
  26452. virtual void convertSamples (void* destSamples, int destSubChannel,
  26453. const void* sourceSamples, int sourceSubChannel, int numSamples) const = 0;
  26454. };
  26455. /**
  26456. A class that converts between two templated AudioData::Pointer types, and which
  26457. implements the AudioData::Converter interface.
  26458. This can be used as a concrete instance of the AudioData::Converter abstract class.
  26459. @see AudioData::Converter
  26460. */
  26461. template <class SourceSampleType, class DestSampleType>
  26462. class ConverterInstance : public Converter
  26463. {
  26464. public:
  26465. ConverterInstance (int numSourceChannels = 1, int numDestChannels = 1)
  26466. : sourceChannels (numSourceChannels), destChannels (numDestChannels)
  26467. {}
  26468. ~ConverterInstance() {}
  26469. void convertSamples (void* dest, const void* source, int numSamples) const
  26470. {
  26471. SourceSampleType s (source, sourceChannels);
  26472. DestSampleType d (dest, destChannels);
  26473. d.convertSamples (s, numSamples);
  26474. }
  26475. void convertSamples (void* dest, int destSubChannel,
  26476. const void* source, int sourceSubChannel, int numSamples) const
  26477. {
  26478. jassert (destSubChannel < destChannels && sourceSubChannel < sourceChannels);
  26479. SourceSampleType s (addBytesToPointer (source, sourceSubChannel * SourceSampleType::getBytesPerSample()), sourceChannels);
  26480. DestSampleType d (addBytesToPointer (dest, destSubChannel * DestSampleType::getBytesPerSample()), destChannels);
  26481. d.convertSamples (s, numSamples);
  26482. }
  26483. private:
  26484. JUCE_DECLARE_NON_COPYABLE (ConverterInstance);
  26485. const int sourceChannels, destChannels;
  26486. };
  26487. };
  26488. /**
  26489. A set of routines to convert buffers of 32-bit floating point data to and from
  26490. various integer formats.
  26491. Note that these functions are deprecated - the AudioData class provides a much more
  26492. flexible set of conversion classes now.
  26493. */
  26494. class JUCE_API AudioDataConverters
  26495. {
  26496. public:
  26497. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  26498. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  26499. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  26500. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  26501. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  26502. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  26503. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  26504. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  26505. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  26506. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  26507. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  26508. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  26509. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  26510. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  26511. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  26512. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  26513. enum DataFormat
  26514. {
  26515. int16LE,
  26516. int16BE,
  26517. int24LE,
  26518. int24BE,
  26519. int32LE,
  26520. int32BE,
  26521. float32LE,
  26522. float32BE,
  26523. };
  26524. static void convertFloatToFormat (DataFormat destFormat,
  26525. const float* source, void* dest, int numSamples);
  26526. static void convertFormatToFloat (DataFormat sourceFormat,
  26527. const void* source, float* dest, int numSamples);
  26528. static void interleaveSamples (const float** source, float* dest,
  26529. int numSamples, int numChannels);
  26530. static void deinterleaveSamples (const float* source, float** dest,
  26531. int numSamples, int numChannels);
  26532. private:
  26533. AudioDataConverters();
  26534. JUCE_DECLARE_NON_COPYABLE (AudioDataConverters);
  26535. };
  26536. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26537. /*** End of inlined file: juce_AudioDataConverters.h ***/
  26538. class AudioFormat;
  26539. /**
  26540. Reads samples from an audio file stream.
  26541. A subclass that reads a specific type of audio format will be created by
  26542. an AudioFormat object.
  26543. @see AudioFormat, AudioFormatWriter
  26544. */
  26545. class JUCE_API AudioFormatReader
  26546. {
  26547. protected:
  26548. /** Creates an AudioFormatReader object.
  26549. @param sourceStream the stream to read from - this will be deleted
  26550. by this object when it is no longer needed. (Some
  26551. specialised readers might not use this parameter and
  26552. can leave it as 0).
  26553. @param formatName the description that will be returned by the getFormatName()
  26554. method
  26555. */
  26556. AudioFormatReader (InputStream* sourceStream,
  26557. const String& formatName);
  26558. public:
  26559. /** Destructor. */
  26560. virtual ~AudioFormatReader();
  26561. /** Returns a description of what type of format this is.
  26562. E.g. "AIFF"
  26563. */
  26564. const String getFormatName() const throw() { return formatName; }
  26565. /** Reads samples from the stream.
  26566. @param destSamples an array of buffers into which the sample data for each
  26567. channel will be written.
  26568. If the format is fixed-point, each channel will be written
  26569. as an array of 32-bit signed integers using the full
  26570. range -0x80000000 to 0x7fffffff, regardless of the source's
  26571. bit-depth. If it is a floating-point format, you should cast
  26572. the resulting array to a (float**) to get the values (in the
  26573. range -1.0 to 1.0 or beyond)
  26574. If the format is stereo, then destSamples[0] is the left channel
  26575. data, and destSamples[1] is the right channel.
  26576. The numDestChannels parameter indicates how many pointers this array
  26577. contains, but some of these pointers can be null if you don't want to
  26578. read data for some of the channels
  26579. @param numDestChannels the number of array elements in the destChannels array
  26580. @param startSampleInSource the position in the audio file or stream at which the samples
  26581. should be read, as a number of samples from the start of the
  26582. stream. It's ok for this to be beyond the start or end of the
  26583. available data - any samples that are out-of-range will be returned
  26584. as zeros.
  26585. @param numSamplesToRead the number of samples to read. If this is greater than the number
  26586. of samples that the file or stream contains. the result will be padded
  26587. with zeros
  26588. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  26589. for some of the channels that you pass in, then they should be filled with
  26590. copies of valid source channels.
  26591. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  26592. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  26593. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  26594. was false, then only the first channel would be filled with the file's contents, and
  26595. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  26596. from a stereo file, then the last 3 would all end up with copies of the same data.
  26597. @returns true if the operation succeeded, false if there was an error. Note
  26598. that reading sections of data beyond the extent of the stream isn't an
  26599. error - the reader should just return zeros for these regions
  26600. @see readMaxLevels
  26601. */
  26602. bool read (int* const* destSamples,
  26603. int numDestChannels,
  26604. int64 startSampleInSource,
  26605. int numSamplesToRead,
  26606. bool fillLeftoverChannelsWithCopies);
  26607. /** Finds the highest and lowest sample levels from a section of the audio stream.
  26608. This will read a block of samples from the stream, and measure the
  26609. highest and lowest sample levels from the channels in that section, returning
  26610. these as normalised floating-point levels.
  26611. @param startSample the offset into the audio stream to start reading from. It's
  26612. ok for this to be beyond the start or end of the stream.
  26613. @param numSamples how many samples to read
  26614. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  26615. @param highestLeft on return, this is the highest absolute sample from the left channel
  26616. @param lowestRight on return, this is the lowest absolute sample from the right
  26617. channel (if there is one)
  26618. @param highestRight on return, this is the highest absolute sample from the right
  26619. channel (if there is one)
  26620. @see read
  26621. */
  26622. virtual void readMaxLevels (int64 startSample,
  26623. int64 numSamples,
  26624. float& lowestLeft,
  26625. float& highestLeft,
  26626. float& lowestRight,
  26627. float& highestRight);
  26628. /** Scans the source looking for a sample whose magnitude is in a specified range.
  26629. This will read from the source, either forwards or backwards between two sample
  26630. positions, until it finds a sample whose magnitude lies between two specified levels.
  26631. If it finds a suitable sample, it returns its position; if not, it will return -1.
  26632. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  26633. points when you're searching for a continuous range of samples
  26634. @param startSample the first sample to look at
  26635. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  26636. the search will go backwards
  26637. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  26638. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  26639. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  26640. of this many consecutive samples, all of which lie
  26641. within the target range. When it finds such a sequence,
  26642. it returns the position of the first in-range sample
  26643. it found (i.e. the earliest one if scanning forwards, the
  26644. latest one if scanning backwards)
  26645. */
  26646. int64 searchForLevel (int64 startSample,
  26647. int64 numSamplesToSearch,
  26648. double magnitudeRangeMinimum,
  26649. double magnitudeRangeMaximum,
  26650. int minimumConsecutiveSamples);
  26651. /** The sample-rate of the stream. */
  26652. double sampleRate;
  26653. /** The number of bits per sample, e.g. 16, 24, 32. */
  26654. unsigned int bitsPerSample;
  26655. /** The total number of samples in the audio stream. */
  26656. int64 lengthInSamples;
  26657. /** The total number of channels in the audio stream. */
  26658. unsigned int numChannels;
  26659. /** Indicates whether the data is floating-point or fixed. */
  26660. bool usesFloatingPointData;
  26661. /** A set of metadata values that the reader has pulled out of the stream.
  26662. Exactly what these values are depends on the format, so you can
  26663. check out the format implementation code to see what kind of stuff
  26664. they understand.
  26665. */
  26666. StringPairArray metadataValues;
  26667. /** The input stream, for use by subclasses. */
  26668. InputStream* input;
  26669. /** Subclasses must implement this method to perform the low-level read operation.
  26670. Callers should use read() instead of calling this directly.
  26671. @param destSamples the array of destination buffers to fill. Some of these
  26672. pointers may be null
  26673. @param numDestChannels the number of items in the destSamples array. This
  26674. value is guaranteed not to be greater than the number of
  26675. channels that this reader object contains
  26676. @param startOffsetInDestBuffer the number of samples from the start of the
  26677. dest data at which to begin writing
  26678. @param startSampleInFile the number of samples into the source data at which
  26679. to begin reading. This value is guaranteed to be >= 0.
  26680. @param numSamples the number of samples to read
  26681. */
  26682. virtual bool readSamples (int** destSamples,
  26683. int numDestChannels,
  26684. int startOffsetInDestBuffer,
  26685. int64 startSampleInFile,
  26686. int numSamples) = 0;
  26687. protected:
  26688. /** Used by AudioFormatReader subclasses to copy data to different formats. */
  26689. template <class DestSampleType, class SourceSampleType, class SourceEndianness>
  26690. struct ReadHelper
  26691. {
  26692. typedef AudioData::Pointer <DestSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  26693. typedef AudioData::Pointer <SourceSampleType, SourceEndianness, AudioData::Interleaved, AudioData::Const> SourceType;
  26694. static void read (int** destData, int destOffset, int numDestChannels, const void* sourceData, int numSourceChannels, int numSamples) throw()
  26695. {
  26696. for (int i = 0; i < numDestChannels; ++i)
  26697. {
  26698. if (destData[i] != 0)
  26699. {
  26700. DestType dest (destData[i]);
  26701. dest += destOffset;
  26702. if (i < numSourceChannels)
  26703. dest.convertSamples (SourceType (addBytesToPointer (sourceData, i * SourceType::getBytesPerSample()), numSourceChannels), numSamples);
  26704. else
  26705. dest.clearSamples (numSamples);
  26706. }
  26707. }
  26708. }
  26709. };
  26710. private:
  26711. String formatName;
  26712. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReader);
  26713. };
  26714. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26715. /*** End of inlined file: juce_AudioFormatReader.h ***/
  26716. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  26717. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26718. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26719. /*** Start of inlined file: juce_AudioSource.h ***/
  26720. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  26721. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  26722. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  26723. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  26724. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  26725. class AudioFormatReader;
  26726. class AudioFormatWriter;
  26727. /**
  26728. A multi-channel buffer of 32-bit floating point audio samples.
  26729. */
  26730. class JUCE_API AudioSampleBuffer
  26731. {
  26732. public:
  26733. /** Creates a buffer with a specified number of channels and samples.
  26734. The contents of the buffer will initially be undefined, so use clear() to
  26735. set all the samples to zero.
  26736. The buffer will allocate its memory internally, and this will be released
  26737. when the buffer is deleted.
  26738. */
  26739. AudioSampleBuffer (int numChannels,
  26740. int numSamples) throw();
  26741. /** Creates a buffer using a pre-allocated block of memory.
  26742. Note that if the buffer is resized or its number of channels is changed, it
  26743. will re-allocate memory internally and copy the existing data to this new area,
  26744. so it will then stop directly addressing this memory.
  26745. @param dataToReferTo a pre-allocated array containing pointers to the data
  26746. for each channel that should be used by this buffer. The
  26747. buffer will only refer to this memory, it won't try to delete
  26748. it when the buffer is deleted or resized.
  26749. @param numChannels the number of channels to use - this must correspond to the
  26750. number of elements in the array passed in
  26751. @param numSamples the number of samples to use - this must correspond to the
  26752. size of the arrays passed in
  26753. */
  26754. AudioSampleBuffer (float** dataToReferTo,
  26755. int numChannels,
  26756. int numSamples) throw();
  26757. /** Creates a buffer using a pre-allocated block of memory.
  26758. Note that if the buffer is resized or its number of channels is changed, it
  26759. will re-allocate memory internally and copy the existing data to this new area,
  26760. so it will then stop directly addressing this memory.
  26761. @param dataToReferTo a pre-allocated array containing pointers to the data
  26762. for each channel that should be used by this buffer. The
  26763. buffer will only refer to this memory, it won't try to delete
  26764. it when the buffer is deleted or resized.
  26765. @param numChannels the number of channels to use - this must correspond to the
  26766. number of elements in the array passed in
  26767. @param startSample the offset within the arrays at which the data begins
  26768. @param numSamples the number of samples to use - this must correspond to the
  26769. size of the arrays passed in
  26770. */
  26771. AudioSampleBuffer (float** dataToReferTo,
  26772. int numChannels,
  26773. int startSample,
  26774. int numSamples) throw();
  26775. /** Copies another buffer.
  26776. This buffer will make its own copy of the other's data, unless the buffer was created
  26777. using an external data buffer, in which case boths buffers will just point to the same
  26778. shared block of data.
  26779. */
  26780. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  26781. /** Copies another buffer onto this one.
  26782. This buffer's size will be changed to that of the other buffer.
  26783. */
  26784. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  26785. /** Destructor.
  26786. This will free any memory allocated by the buffer.
  26787. */
  26788. virtual ~AudioSampleBuffer() throw();
  26789. /** Returns the number of channels of audio data that this buffer contains.
  26790. @see getSampleData
  26791. */
  26792. int getNumChannels() const throw() { return numChannels; }
  26793. /** Returns the number of samples allocated in each of the buffer's channels.
  26794. @see getSampleData
  26795. */
  26796. int getNumSamples() const throw() { return size; }
  26797. /** Returns a pointer one of the buffer's channels.
  26798. For speed, this doesn't check whether the channel number is out of range,
  26799. so be careful when using it!
  26800. */
  26801. float* getSampleData (const int channelNumber) const throw()
  26802. {
  26803. jassert (isPositiveAndBelow (channelNumber, numChannels));
  26804. return channels [channelNumber];
  26805. }
  26806. /** Returns a pointer to a sample in one of the buffer's channels.
  26807. For speed, this doesn't check whether the channel and sample number
  26808. are out-of-range, so be careful when using it!
  26809. */
  26810. float* getSampleData (const int channelNumber,
  26811. const int sampleOffset) const throw()
  26812. {
  26813. jassert (isPositiveAndBelow (channelNumber, numChannels));
  26814. jassert (isPositiveAndBelow (sampleOffset, size));
  26815. return channels [channelNumber] + sampleOffset;
  26816. }
  26817. /** Returns an array of pointers to the channels in the buffer.
  26818. Don't modify any of the pointers that are returned, and bear in mind that
  26819. these will become invalid if the buffer is resized.
  26820. */
  26821. float** getArrayOfChannels() const throw() { return channels; }
  26822. /** Changes the buffer's size or number of channels.
  26823. This can expand or contract the buffer's length, and add or remove channels.
  26824. If keepExistingContent is true, it will try to preserve as much of the
  26825. old data as it can in the new buffer.
  26826. If clearExtraSpace is true, then any extra channels or space that is
  26827. allocated will be also be cleared. If false, then this space is left
  26828. uninitialised.
  26829. If avoidReallocating is true, then changing the buffer's size won't reduce the
  26830. amount of memory that is currently allocated (but it will still increase it if
  26831. the new size is bigger than the amount it currently has). If this is false, then
  26832. a new allocation will be done so that the buffer uses takes up the minimum amount
  26833. of memory that it needs.
  26834. */
  26835. void setSize (int newNumChannels,
  26836. int newNumSamples,
  26837. bool keepExistingContent = false,
  26838. bool clearExtraSpace = false,
  26839. bool avoidReallocating = false) throw();
  26840. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  26841. There's also a constructor that lets you specify arrays like this, but this
  26842. lets you change the channels dynamically.
  26843. Note that if the buffer is resized or its number of channels is changed, it
  26844. will re-allocate memory internally and copy the existing data to this new area,
  26845. so it will then stop directly addressing this memory.
  26846. @param dataToReferTo a pre-allocated array containing pointers to the data
  26847. for each channel that should be used by this buffer. The
  26848. buffer will only refer to this memory, it won't try to delete
  26849. it when the buffer is deleted or resized.
  26850. @param numChannels the number of channels to use - this must correspond to the
  26851. number of elements in the array passed in
  26852. @param numSamples the number of samples to use - this must correspond to the
  26853. size of the arrays passed in
  26854. */
  26855. void setDataToReferTo (float** dataToReferTo,
  26856. int numChannels,
  26857. int numSamples) throw();
  26858. /** Clears all the samples in all channels. */
  26859. void clear() throw();
  26860. /** Clears a specified region of all the channels.
  26861. For speed, this doesn't check whether the channel and sample number
  26862. are in-range, so be careful!
  26863. */
  26864. void clear (int startSample,
  26865. int numSamples) throw();
  26866. /** Clears a specified region of just one channel.
  26867. For speed, this doesn't check whether the channel and sample number
  26868. are in-range, so be careful!
  26869. */
  26870. void clear (int channel,
  26871. int startSample,
  26872. int numSamples) throw();
  26873. /** Applies a gain multiple to a region of one channel.
  26874. For speed, this doesn't check whether the channel and sample number
  26875. are in-range, so be careful!
  26876. */
  26877. void applyGain (int channel,
  26878. int startSample,
  26879. int numSamples,
  26880. float gain) throw();
  26881. /** Applies a gain multiple to a region of all the channels.
  26882. For speed, this doesn't check whether the sample numbers
  26883. are in-range, so be careful!
  26884. */
  26885. void applyGain (int startSample,
  26886. int numSamples,
  26887. float gain) throw();
  26888. /** Applies a range of gains to a region of a channel.
  26889. The gain that is applied to each sample will vary from
  26890. startGain on the first sample to endGain on the last Sample,
  26891. so it can be used to do basic fades.
  26892. For speed, this doesn't check whether the sample numbers
  26893. are in-range, so be careful!
  26894. */
  26895. void applyGainRamp (int channel,
  26896. int startSample,
  26897. int numSamples,
  26898. float startGain,
  26899. float endGain) throw();
  26900. /** Adds samples from another buffer to this one.
  26901. @param destChannel the channel within this buffer to add the samples to
  26902. @param destStartSample the start sample within this buffer's channel
  26903. @param source the source buffer to add from
  26904. @param sourceChannel the channel within the source buffer to read from
  26905. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  26906. @param numSamples the number of samples to process
  26907. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  26908. added to this buffer's samples
  26909. @see copyFrom
  26910. */
  26911. void addFrom (int destChannel,
  26912. int destStartSample,
  26913. const AudioSampleBuffer& source,
  26914. int sourceChannel,
  26915. int sourceStartSample,
  26916. int numSamples,
  26917. float gainToApplyToSource = 1.0f) throw();
  26918. /** Adds samples from an array of floats to one of the channels.
  26919. @param destChannel the channel within this buffer to add the samples to
  26920. @param destStartSample the start sample within this buffer's channel
  26921. @param source the source data to use
  26922. @param numSamples the number of samples to process
  26923. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  26924. added to this buffer's samples
  26925. @see copyFrom
  26926. */
  26927. void addFrom (int destChannel,
  26928. int destStartSample,
  26929. const float* source,
  26930. int numSamples,
  26931. float gainToApplyToSource = 1.0f) throw();
  26932. /** Adds samples from an array of floats, applying a gain ramp to them.
  26933. @param destChannel the channel within this buffer to add the samples to
  26934. @param destStartSample the start sample within this buffer's channel
  26935. @param source the source data to use
  26936. @param numSamples the number of samples to process
  26937. @param startGain the gain to apply to the first sample (this is multiplied with
  26938. the source samples before they are added to this buffer)
  26939. @param endGain the gain to apply to the final sample. The gain is linearly
  26940. interpolated between the first and last samples.
  26941. */
  26942. void addFromWithRamp (int destChannel,
  26943. int destStartSample,
  26944. const float* source,
  26945. int numSamples,
  26946. float startGain,
  26947. float endGain) throw();
  26948. /** Copies samples from another buffer to this one.
  26949. @param destChannel the channel within this buffer to copy the samples to
  26950. @param destStartSample the start sample within this buffer's channel
  26951. @param source the source buffer to read from
  26952. @param sourceChannel the channel within the source buffer to read from
  26953. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  26954. @param numSamples the number of samples to process
  26955. @see addFrom
  26956. */
  26957. void copyFrom (int destChannel,
  26958. int destStartSample,
  26959. const AudioSampleBuffer& source,
  26960. int sourceChannel,
  26961. int sourceStartSample,
  26962. int numSamples) throw();
  26963. /** Copies samples from an array of floats into one of the channels.
  26964. @param destChannel the channel within this buffer to copy the samples to
  26965. @param destStartSample the start sample within this buffer's channel
  26966. @param source the source buffer to read from
  26967. @param numSamples the number of samples to process
  26968. @see addFrom
  26969. */
  26970. void copyFrom (int destChannel,
  26971. int destStartSample,
  26972. const float* source,
  26973. int numSamples) throw();
  26974. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  26975. @param destChannel the channel within this buffer to copy the samples to
  26976. @param destStartSample the start sample within this buffer's channel
  26977. @param source the source buffer to read from
  26978. @param numSamples the number of samples to process
  26979. @param gain the gain to apply
  26980. @see addFrom
  26981. */
  26982. void copyFrom (int destChannel,
  26983. int destStartSample,
  26984. const float* source,
  26985. int numSamples,
  26986. float gain) throw();
  26987. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  26988. @param destChannel the channel within this buffer to copy the samples to
  26989. @param destStartSample the start sample within this buffer's channel
  26990. @param source the source buffer to read from
  26991. @param numSamples the number of samples to process
  26992. @param startGain the gain to apply to the first sample (this is multiplied with
  26993. the source samples before they are copied to this buffer)
  26994. @param endGain the gain to apply to the final sample. The gain is linearly
  26995. interpolated between the first and last samples.
  26996. @see addFrom
  26997. */
  26998. void copyFromWithRamp (int destChannel,
  26999. int destStartSample,
  27000. const float* source,
  27001. int numSamples,
  27002. float startGain,
  27003. float endGain) throw();
  27004. /** Finds the highest and lowest sample values in a given range.
  27005. @param channel the channel to read from
  27006. @param startSample the start sample within the channel
  27007. @param numSamples the number of samples to check
  27008. @param minVal on return, the lowest value that was found
  27009. @param maxVal on return, the highest value that was found
  27010. */
  27011. void findMinMax (int channel,
  27012. int startSample,
  27013. int numSamples,
  27014. float& minVal,
  27015. float& maxVal) const throw();
  27016. /** Finds the highest absolute sample value within a region of a channel.
  27017. */
  27018. float getMagnitude (int channel,
  27019. int startSample,
  27020. int numSamples) const throw();
  27021. /** Finds the highest absolute sample value within a region on all channels.
  27022. */
  27023. float getMagnitude (int startSample,
  27024. int numSamples) const throw();
  27025. /** Returns the root mean squared level for a region of a channel.
  27026. */
  27027. float getRMSLevel (int channel,
  27028. int startSample,
  27029. int numSamples) const throw();
  27030. /** Fills a section of the buffer using an AudioReader as its source.
  27031. This will convert the reader's fixed- or floating-point data to
  27032. the buffer's floating-point format, and will try to intelligently
  27033. cope with mismatches between the number of channels in the reader
  27034. and the buffer.
  27035. @see writeToAudioWriter
  27036. */
  27037. void readFromAudioReader (AudioFormatReader* reader,
  27038. int startSample,
  27039. int numSamples,
  27040. int64 readerStartSample,
  27041. bool useReaderLeftChan,
  27042. bool useReaderRightChan);
  27043. /** Writes a section of this buffer to an audio writer.
  27044. This saves you having to mess about with channels or floating/fixed
  27045. point conversion.
  27046. @see readFromAudioReader
  27047. */
  27048. void writeToAudioWriter (AudioFormatWriter* writer,
  27049. int startSample,
  27050. int numSamples) const;
  27051. private:
  27052. int numChannels, size;
  27053. size_t allocatedBytes;
  27054. float** channels;
  27055. HeapBlock <char> allocatedData;
  27056. float* preallocatedChannelSpace [32];
  27057. void allocateData();
  27058. void allocateChannels (float** dataToReferTo, int offset);
  27059. JUCE_LEAK_DETECTOR (AudioSampleBuffer);
  27060. };
  27061. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27062. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  27063. /**
  27064. Used by AudioSource::getNextAudioBlock().
  27065. */
  27066. struct JUCE_API AudioSourceChannelInfo
  27067. {
  27068. /** The destination buffer to fill with audio data.
  27069. When the AudioSource::getNextAudioBlock() method is called, the active section
  27070. of this buffer should be filled with whatever output the source produces.
  27071. Only the samples specified by the startSample and numSamples members of this structure
  27072. should be affected by the call.
  27073. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  27074. method can be treated as the input if the source is performing some kind of filter operation,
  27075. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  27076. a handy way of doing this.
  27077. The number of channels in the buffer could be anything, so the AudioSource
  27078. must cope with this in whatever way is appropriate for its function.
  27079. */
  27080. AudioSampleBuffer* buffer;
  27081. /** The first sample in the buffer from which the callback is expected
  27082. to write data. */
  27083. int startSample;
  27084. /** The number of samples in the buffer which the callback is expected to
  27085. fill with data. */
  27086. int numSamples;
  27087. /** Convenient method to clear the buffer if the source is not producing any data. */
  27088. void clearActiveBufferRegion() const
  27089. {
  27090. if (buffer != 0)
  27091. buffer->clear (startSample, numSamples);
  27092. }
  27093. };
  27094. /**
  27095. Base class for objects that can produce a continuous stream of audio.
  27096. An AudioSource has two states: 'prepared' and 'unprepared'.
  27097. When a source needs to be played, it is first put into a 'prepared' state by a call to
  27098. prepareToPlay(), and then repeated calls will be made to its getNextAudioBlock() method to
  27099. process the audio data.
  27100. Once playback has finished, the releaseResources() method is called to put the stream
  27101. back into an 'unprepared' state.
  27102. @see AudioFormatReaderSource, ResamplingAudioSource
  27103. */
  27104. class JUCE_API AudioSource
  27105. {
  27106. protected:
  27107. /** Creates an AudioSource. */
  27108. AudioSource() throw() {}
  27109. public:
  27110. /** Destructor. */
  27111. virtual ~AudioSource() {}
  27112. /** Tells the source to prepare for playing.
  27113. An AudioSource has two states: prepared and unprepared.
  27114. The prepareToPlay() method is guaranteed to be called at least once on an 'unpreprared'
  27115. source to put it into a 'prepared' state before any calls will be made to getNextAudioBlock().
  27116. This callback allows the source to initialise any resources it might need when playing.
  27117. Once playback has finished, the releaseResources() method is called to put the stream
  27118. back into an 'unprepared' state.
  27119. Note that this method could be called more than once in succession without
  27120. a matching call to releaseResources(), so make sure your code is robust and
  27121. can handle that kind of situation.
  27122. @param samplesPerBlockExpected the number of samples that the source
  27123. will be expected to supply each time its
  27124. getNextAudioBlock() method is called. This
  27125. number may vary slightly, because it will be dependent
  27126. on audio hardware callbacks, and these aren't
  27127. guaranteed to always use a constant block size, so
  27128. the source should be able to cope with small variations.
  27129. @param sampleRate the sample rate that the output will be used at - this
  27130. is needed by sources such as tone generators.
  27131. @see releaseResources, getNextAudioBlock
  27132. */
  27133. virtual void prepareToPlay (int samplesPerBlockExpected,
  27134. double sampleRate) = 0;
  27135. /** Allows the source to release anything it no longer needs after playback has stopped.
  27136. This will be called when the source is no longer going to have its getNextAudioBlock()
  27137. method called, so it should release any spare memory, etc. that it might have
  27138. allocated during the prepareToPlay() call.
  27139. Note that there's no guarantee that prepareToPlay() will actually have been called before
  27140. releaseResources(), and it may be called more than once in succession, so make sure your
  27141. code is robust and doesn't make any assumptions about when it will be called.
  27142. @see prepareToPlay, getNextAudioBlock
  27143. */
  27144. virtual void releaseResources() = 0;
  27145. /** Called repeatedly to fetch subsequent blocks of audio data.
  27146. After calling the prepareToPlay() method, this callback will be made each
  27147. time the audio playback hardware (or whatever other destination the audio
  27148. data is going to) needs another block of data.
  27149. It will generally be called on a high-priority system thread, or possibly even
  27150. an interrupt, so be careful not to do too much work here, as that will cause
  27151. audio glitches!
  27152. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  27153. */
  27154. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  27155. };
  27156. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  27157. /*** End of inlined file: juce_AudioSource.h ***/
  27158. class AudioThumbnail;
  27159. /**
  27160. Writes samples to an audio file stream.
  27161. A subclass that writes a specific type of audio format will be created by
  27162. an AudioFormat object.
  27163. After creating one of these with the AudioFormat::createWriterFor() method
  27164. you can call its write() method to store the samples, and then delete it.
  27165. @see AudioFormat, AudioFormatReader
  27166. */
  27167. class JUCE_API AudioFormatWriter
  27168. {
  27169. protected:
  27170. /** Creates an AudioFormatWriter object.
  27171. @param destStream the stream to write to - this will be deleted
  27172. by this object when it is no longer needed
  27173. @param formatName the description that will be returned by the getFormatName()
  27174. method
  27175. @param sampleRate the sample rate to use - the base class just stores
  27176. this value, it doesn't do anything with it
  27177. @param numberOfChannels the number of channels to write - the base class just stores
  27178. this value, it doesn't do anything with it
  27179. @param bitsPerSample the bit depth of the stream - the base class just stores
  27180. this value, it doesn't do anything with it
  27181. */
  27182. AudioFormatWriter (OutputStream* destStream,
  27183. const String& formatName,
  27184. double sampleRate,
  27185. unsigned int numberOfChannels,
  27186. unsigned int bitsPerSample);
  27187. public:
  27188. /** Destructor. */
  27189. virtual ~AudioFormatWriter();
  27190. /** Returns a description of what type of format this is.
  27191. E.g. "AIFF file"
  27192. */
  27193. const String getFormatName() const throw() { return formatName; }
  27194. /** Writes a set of samples to the audio stream.
  27195. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  27196. can use AudioSampleBuffer::writeToAudioWriter().
  27197. @param samplesToWrite an array of arrays containing the sample data for
  27198. each channel to write. This is a zero-terminated
  27199. array of arrays, and can contain a different number
  27200. of channels than the actual stream uses, and the
  27201. writer should do its best to cope with this.
  27202. If the format is fixed-point, each channel will be formatted
  27203. as an array of signed integers using the full 32-bit
  27204. range -0x80000000 to 0x7fffffff, regardless of the source's
  27205. bit-depth. If it is a floating-point format, you should treat
  27206. the arrays as arrays of floats, and just cast it to an (int**)
  27207. to pass it into the method.
  27208. @param numSamples the number of samples to write
  27209. */
  27210. virtual bool write (const int** samplesToWrite,
  27211. int numSamples) = 0;
  27212. /** Reads a section of samples from an AudioFormatReader, and writes these to
  27213. the output.
  27214. This will take care of any floating-point conversion that's required to convert
  27215. between the two formats. It won't deal with sample-rate conversion, though.
  27216. If numSamplesToRead < 0, it will write the entire length of the reader.
  27217. @returns false if it can't read or write properly during the operation
  27218. */
  27219. bool writeFromAudioReader (AudioFormatReader& reader,
  27220. int64 startSample,
  27221. int64 numSamplesToRead);
  27222. /** Reads some samples from an AudioSource, and writes these to the output.
  27223. The source must already have been initialised with the AudioSource::prepareToPlay() method
  27224. @param source the source to read from
  27225. @param numSamplesToRead total number of samples to read and write
  27226. @param samplesPerBlock the maximum number of samples to fetch from the source
  27227. @returns false if it can't read or write properly during the operation
  27228. */
  27229. bool writeFromAudioSource (AudioSource& source,
  27230. int numSamplesToRead,
  27231. int samplesPerBlock = 2048);
  27232. /** Writes some samples from an AudioSampleBuffer.
  27233. */
  27234. bool writeFromAudioSampleBuffer (const AudioSampleBuffer& source,
  27235. int startSample, int numSamples);
  27236. /** Returns the sample rate being used. */
  27237. double getSampleRate() const throw() { return sampleRate; }
  27238. /** Returns the number of channels being written. */
  27239. int getNumChannels() const throw() { return numChannels; }
  27240. /** Returns the bit-depth of the data being written. */
  27241. int getBitsPerSample() const throw() { return bitsPerSample; }
  27242. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  27243. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  27244. /**
  27245. Provides a FIFO for an AudioFormatWriter, allowing you to push incoming
  27246. data into a buffer which will be flushed to disk by a background thread.
  27247. */
  27248. class ThreadedWriter
  27249. {
  27250. public:
  27251. /** Creates a ThreadedWriter for a given writer and a thread.
  27252. The writer object which is passed in here will be owned and deleted by
  27253. the ThreadedWriter when it is no longer needed.
  27254. To stop the writer and flush the buffer to disk, simply delete this object.
  27255. */
  27256. ThreadedWriter (AudioFormatWriter* writer,
  27257. TimeSliceThread& backgroundThread,
  27258. int numSamplesToBuffer);
  27259. /** Destructor. */
  27260. ~ThreadedWriter();
  27261. /** Pushes some incoming audio data into the FIFO.
  27262. If there's enough free space in the buffer, this will add the data to it,
  27263. If the FIFO is too full to accept this many samples, the method will return
  27264. false - then you could either wait until the background thread has had time to
  27265. consume some of the buffered data and try again, or you can give up
  27266. and lost this block.
  27267. The data must be an array containing the same number of channels as the
  27268. AudioFormatWriter object is using. None of these channels can be null.
  27269. */
  27270. bool write (const float** data, int numSamples);
  27271. /** Allows you to specify a thumbnail that this writer should update with the
  27272. incoming data.
  27273. The thumbnail will be cleared and will the writer will begin adding data to
  27274. it as it arrives. Pass a null pointer to stop the writer updating any thumbnails.
  27275. */
  27276. void setThumbnailToUpdate (AudioThumbnail* thumbnailToUpdate);
  27277. /** @internal */
  27278. class Buffer; // (only public for VC6 compatibility)
  27279. private:
  27280. friend class ScopedPointer<Buffer>;
  27281. ScopedPointer<Buffer> buffer;
  27282. };
  27283. protected:
  27284. /** The sample rate of the stream. */
  27285. double sampleRate;
  27286. /** The number of channels being written to the stream. */
  27287. unsigned int numChannels;
  27288. /** The bit depth of the file. */
  27289. unsigned int bitsPerSample;
  27290. /** True if it's a floating-point format, false if it's fixed-point. */
  27291. bool usesFloatingPointData;
  27292. /** The output stream for Use by subclasses. */
  27293. OutputStream* output;
  27294. /** Used by AudioFormatWriter subclasses to copy data to different formats. */
  27295. template <class DestSampleType, class SourceSampleType, class DestEndianness>
  27296. struct WriteHelper
  27297. {
  27298. typedef AudioData::Pointer <DestSampleType, DestEndianness, AudioData::Interleaved, AudioData::NonConst> DestType;
  27299. typedef AudioData::Pointer <SourceSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  27300. static void write (void* destData, int numDestChannels, const int** source,
  27301. int numSamples, const int sourceOffset = 0) throw()
  27302. {
  27303. for (int i = 0; i < numDestChannels; ++i)
  27304. {
  27305. const DestType dest (addBytesToPointer (destData, i * DestType::getBytesPerSample()), numDestChannels);
  27306. if (*source != 0)
  27307. {
  27308. dest.convertSamples (SourceType (*source + sourceOffset), numSamples);
  27309. ++source;
  27310. }
  27311. else
  27312. {
  27313. dest.clearSamples (numSamples);
  27314. }
  27315. }
  27316. }
  27317. };
  27318. private:
  27319. String formatName;
  27320. friend class ThreadedWriter;
  27321. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatWriter);
  27322. };
  27323. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27324. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  27325. /**
  27326. Subclasses of AudioFormat are used to read and write different audio
  27327. file formats.
  27328. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  27329. */
  27330. class JUCE_API AudioFormat
  27331. {
  27332. public:
  27333. /** Destructor. */
  27334. virtual ~AudioFormat();
  27335. /** Returns the name of this format.
  27336. e.g. "WAV file" or "AIFF file"
  27337. */
  27338. const String& getFormatName() const;
  27339. /** Returns all the file extensions that might apply to a file of this format.
  27340. The first item will be the one that's preferred when creating a new file.
  27341. So for a wav file this might just return ".wav"; for an AIFF file it might
  27342. return two items, ".aif" and ".aiff"
  27343. */
  27344. const StringArray& getFileExtensions() const;
  27345. /** Returns true if this the given file can be read by this format.
  27346. Subclasses shouldn't do too much work here, just check the extension or
  27347. file type. The base class implementation just checks the file's extension
  27348. against one of the ones that was registered in the constructor.
  27349. */
  27350. virtual bool canHandleFile (const File& fileToTest);
  27351. /** Returns a set of sample rates that the format can read and write. */
  27352. virtual const Array <int> getPossibleSampleRates() = 0;
  27353. /** Returns a set of bit depths that the format can read and write. */
  27354. virtual const Array <int> getPossibleBitDepths() = 0;
  27355. /** Returns true if the format can do 2-channel audio. */
  27356. virtual bool canDoStereo() = 0;
  27357. /** Returns true if the format can do 1-channel audio. */
  27358. virtual bool canDoMono() = 0;
  27359. /** Returns true if the format uses compressed data. */
  27360. virtual bool isCompressed();
  27361. /** Returns a list of different qualities that can be used when writing.
  27362. Non-compressed formats will just return an empty array, but for something
  27363. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  27364. When calling createWriterFor(), an index from this array is passed in to
  27365. tell the format which option is required.
  27366. */
  27367. virtual const StringArray getQualityOptions();
  27368. /** Tries to create an object that can read from a stream containing audio
  27369. data in this format.
  27370. The reader object that is returned can be used to read from the stream, and
  27371. should then be deleted by the caller.
  27372. @param sourceStream the stream to read from - the AudioFormatReader object
  27373. that is returned will delete this stream when it no longer
  27374. needs it.
  27375. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  27376. should delete the stream object that was passed-in. (If a valid
  27377. reader is returned, it will always be in charge of deleting the
  27378. stream, so this parameter is ignored)
  27379. @see AudioFormatReader
  27380. */
  27381. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27382. bool deleteStreamIfOpeningFails) = 0;
  27383. /** Tries to create an object that can write to a stream with this audio format.
  27384. The writer object that is returned can be used to write to the stream, and
  27385. should then be deleted by the caller.
  27386. If the stream can't be created for some reason (e.g. the parameters passed in
  27387. here aren't suitable), this will return 0.
  27388. @param streamToWriteTo the stream that the data will go to - this will be
  27389. deleted by the AudioFormatWriter object when it's no longer
  27390. needed. If no AudioFormatWriter can be created by this method,
  27391. the stream will NOT be deleted, so that the caller can re-use it
  27392. to try to open a different format, etc
  27393. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  27394. returned by getPossibleSampleRates()
  27395. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  27396. the choice will depend on the results of canDoMono() and
  27397. canDoStereo()
  27398. @param bitsPerSample the bits per sample to use - this must be one of the values
  27399. returned by getPossibleBitDepths()
  27400. @param metadataValues a set of metadata values that the writer should try to write
  27401. to the stream. Exactly what these are depends on the format,
  27402. and the subclass doesn't actually have to do anything with
  27403. them if it doesn't want to. Have a look at the specific format
  27404. implementation classes to see possible values that can be
  27405. used
  27406. @param qualityOptionIndex the index of one of compression qualities returned by the
  27407. getQualityOptions() method. If there aren't any quality options
  27408. for this format, just pass 0 in this parameter, as it'll be
  27409. ignored
  27410. @see AudioFormatWriter
  27411. */
  27412. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27413. double sampleRateToUse,
  27414. unsigned int numberOfChannels,
  27415. int bitsPerSample,
  27416. const StringPairArray& metadataValues,
  27417. int qualityOptionIndex) = 0;
  27418. protected:
  27419. /** Creates an AudioFormat object.
  27420. @param formatName this sets the value that will be returned by getFormatName()
  27421. @param fileExtensions a zero-terminated list of file extensions - this is what will
  27422. be returned by getFileExtension()
  27423. */
  27424. AudioFormat (const String& formatName,
  27425. const StringArray& fileExtensions);
  27426. private:
  27427. String formatName;
  27428. StringArray fileExtensions;
  27429. };
  27430. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  27431. /*** End of inlined file: juce_AudioFormat.h ***/
  27432. /**
  27433. Reads and Writes AIFF format audio files.
  27434. @see AudioFormat
  27435. */
  27436. class JUCE_API AiffAudioFormat : public AudioFormat
  27437. {
  27438. public:
  27439. /** Creates an format object. */
  27440. AiffAudioFormat();
  27441. /** Destructor. */
  27442. ~AiffAudioFormat();
  27443. const Array <int> getPossibleSampleRates();
  27444. const Array <int> getPossibleBitDepths();
  27445. bool canDoStereo();
  27446. bool canDoMono();
  27447. #if JUCE_MAC
  27448. bool canHandleFile (const File& fileToTest);
  27449. #endif
  27450. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27451. bool deleteStreamIfOpeningFails);
  27452. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27453. double sampleRateToUse,
  27454. unsigned int numberOfChannels,
  27455. int bitsPerSample,
  27456. const StringPairArray& metadataValues,
  27457. int qualityOptionIndex);
  27458. private:
  27459. JUCE_LEAK_DETECTOR (AiffAudioFormat);
  27460. };
  27461. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27462. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  27463. #endif
  27464. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27465. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  27466. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27467. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27468. #if JUCE_USE_CDBURNER || DOXYGEN
  27469. /**
  27470. */
  27471. class AudioCDBurner : public ChangeBroadcaster
  27472. {
  27473. public:
  27474. /** Returns a list of available optical drives.
  27475. Use openDevice() to open one of the items from this list.
  27476. */
  27477. static const StringArray findAvailableDevices();
  27478. /** Tries to open one of the optical drives.
  27479. The deviceIndex is an index into the array returned by findAvailableDevices().
  27480. */
  27481. static AudioCDBurner* openDevice (const int deviceIndex);
  27482. /** Destructor. */
  27483. ~AudioCDBurner();
  27484. enum DiskState
  27485. {
  27486. unknown, /**< An error condition, if the device isn't responding. */
  27487. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  27488. may seem to be permanently open. */
  27489. noDisc, /**< The drive has no disk in it. */
  27490. writableDiskPresent, /**< The drive contains a writeable disk. */
  27491. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  27492. };
  27493. /** Returns the current status of the device.
  27494. To get informed when the drive's status changes, attach a ChangeListener to
  27495. the AudioCDBurner.
  27496. */
  27497. DiskState getDiskState() const;
  27498. /** Returns true if there's a writable disk in the drive. */
  27499. bool isDiskPresent() const;
  27500. /** Sends an eject signal to the drive.
  27501. The eject will happen asynchronously, so you can use getDiskState() and
  27502. waitUntilStateChange() to monitor its progress.
  27503. */
  27504. bool openTray();
  27505. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  27506. @returns the device's new state
  27507. */
  27508. DiskState waitUntilStateChange (int timeOutMilliseconds);
  27509. /** Returns the set of possible write speeds that the device can handle.
  27510. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  27511. Note that if there's no media present in the drive, this value may be unavailable!
  27512. @see setWriteSpeed, getWriteSpeed
  27513. */
  27514. const Array<int> getAvailableWriteSpeeds() const;
  27515. /** Tries to enable or disable buffer underrun safety on devices that support it.
  27516. @returns true if it's now enabled. If the device doesn't support it, this
  27517. will always return false.
  27518. */
  27519. bool setBufferUnderrunProtection (bool shouldBeEnabled);
  27520. /** Returns the number of free blocks on the disk.
  27521. There are 75 blocks per second, at 44100Hz.
  27522. */
  27523. int getNumAvailableAudioBlocks() const;
  27524. /** Adds a track to be written.
  27525. The source passed-in here will be kept by this object, and it will
  27526. be used and deleted at some point in the future, either during the
  27527. burn() method or when this AudioCDBurner object is deleted. Your caller
  27528. method shouldn't keep a reference to it or use it again after passing
  27529. it in here.
  27530. */
  27531. bool addAudioTrack (AudioSource* source, int numSamples);
  27532. /** Receives progress callbacks during a cd-burn operation.
  27533. @see AudioCDBurner::burn()
  27534. */
  27535. class BurnProgressListener
  27536. {
  27537. public:
  27538. BurnProgressListener() throw() {}
  27539. virtual ~BurnProgressListener() {}
  27540. /** Called at intervals to report on the progress of the AudioCDBurner.
  27541. To cancel the burn, return true from this method.
  27542. */
  27543. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  27544. };
  27545. /** Runs the burn process.
  27546. This method will block until the operation is complete.
  27547. @param listener the object to receive callbacks about progress
  27548. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  27549. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  27550. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  27551. 0 or less to mean the fastest speed.
  27552. */
  27553. const String burn (BurnProgressListener* listener,
  27554. bool ejectDiscAfterwards,
  27555. bool performFakeBurnForTesting,
  27556. int writeSpeed);
  27557. /** If a burn operation is currently in progress, this tells it to stop
  27558. as soon as possible.
  27559. It's also possible to stop the burn process by returning true from
  27560. BurnProgressListener::audioCDBurnProgress()
  27561. */
  27562. void abortBurn();
  27563. private:
  27564. AudioCDBurner (const int deviceIndex);
  27565. class Pimpl;
  27566. friend class ScopedPointer<Pimpl>;
  27567. ScopedPointer<Pimpl> pimpl;
  27568. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDBurner);
  27569. };
  27570. #endif
  27571. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27572. /*** End of inlined file: juce_AudioCDBurner.h ***/
  27573. #endif
  27574. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27575. /*** Start of inlined file: juce_AudioCDReader.h ***/
  27576. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27577. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  27578. #if JUCE_USE_CDREADER || DOXYGEN
  27579. #if JUCE_MAC
  27580. #endif
  27581. /**
  27582. A type of AudioFormatReader that reads from an audio CD.
  27583. One of these can be used to read a CD as if it's one big audio stream. Use the
  27584. getPositionOfTrackStart() method to find where the individual tracks are
  27585. within the stream.
  27586. @see AudioFormatReader
  27587. */
  27588. class JUCE_API AudioCDReader : public AudioFormatReader
  27589. {
  27590. public:
  27591. /** Returns a list of names of Audio CDs currently available for reading.
  27592. If there's a CD drive but no CD in it, this might return an empty list, or
  27593. possibly a device that can be opened but which has no tracks, depending
  27594. on the platform.
  27595. @see createReaderForCD
  27596. */
  27597. static const StringArray getAvailableCDNames();
  27598. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  27599. @param index the index of one of the available CDs - use getAvailableCDNames()
  27600. to find out how many there are.
  27601. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  27602. caller will be responsible for deleting the object returned.
  27603. */
  27604. static AudioCDReader* createReaderForCD (const int index);
  27605. /** Destructor. */
  27606. ~AudioCDReader();
  27607. /** Implementation of the AudioFormatReader method. */
  27608. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  27609. int64 startSampleInFile, int numSamples);
  27610. /** Checks whether the CD has been removed from the drive.
  27611. */
  27612. bool isCDStillPresent() const;
  27613. /** Returns the total number of tracks (audio + data).
  27614. */
  27615. int getNumTracks() const;
  27616. /** Finds the sample offset of the start of a track.
  27617. @param trackNum the track number, where trackNum = 0 is the first track
  27618. and trackNum = getNumTracks() means the end of the CD.
  27619. */
  27620. int getPositionOfTrackStart (int trackNum) const;
  27621. /** Returns true if a given track is an audio track.
  27622. @param trackNum the track number, where 0 is the first track.
  27623. */
  27624. bool isTrackAudio (int trackNum) const;
  27625. /** Returns an array of sample offsets for the start of each track, followed by
  27626. the sample position of the end of the CD.
  27627. */
  27628. const Array<int>& getTrackOffsets() const;
  27629. /** Refreshes the object's table of contents.
  27630. If the disc has been ejected and a different one put in since this
  27631. object was created, this will cause it to update its idea of how many tracks
  27632. there are, etc.
  27633. */
  27634. void refreshTrackLengths();
  27635. /** Enables scanning for indexes within tracks.
  27636. @see getLastIndex
  27637. */
  27638. void enableIndexScanning (bool enabled);
  27639. /** Returns the index number found during the last read() call.
  27640. Index scanning is turned off by default - turn it on with enableIndexScanning().
  27641. Then when the read() method is called, if it comes across an index within that
  27642. block, the index number is stored and returned by this method.
  27643. Some devices might not support indexes, of course.
  27644. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  27645. @see enableIndexScanning
  27646. */
  27647. int getLastIndex() const;
  27648. /** Scans a track to find the position of any indexes within it.
  27649. @param trackNumber the track to look in, where 0 is the first track on the disc
  27650. @returns an array of sample positions of any index points found (not including
  27651. the index that marks the start of the track)
  27652. */
  27653. const Array <int> findIndexesInTrack (const int trackNumber);
  27654. /** Returns the CDDB id number for the CD.
  27655. It's not a great way of identifying a disc, but it's traditional.
  27656. */
  27657. int getCDDBId();
  27658. /** Tries to eject the disk.
  27659. Of course this might not be possible, if some other process is using it.
  27660. */
  27661. void ejectDisk();
  27662. enum
  27663. {
  27664. framesPerSecond = 75,
  27665. samplesPerFrame = 44100 / framesPerSecond
  27666. };
  27667. private:
  27668. Array<int> trackStartSamples;
  27669. #if JUCE_MAC
  27670. File volumeDir;
  27671. Array<File> tracks;
  27672. int currentReaderTrack;
  27673. ScopedPointer <AudioFormatReader> reader;
  27674. AudioCDReader (const File& volume);
  27675. #elif JUCE_WINDOWS
  27676. bool audioTracks [100];
  27677. void* handle;
  27678. bool indexingEnabled;
  27679. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  27680. MemoryBlock buffer;
  27681. AudioCDReader (void* handle);
  27682. int getIndexAt (int samplePos);
  27683. #elif JUCE_LINUX
  27684. AudioCDReader();
  27685. #endif
  27686. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDReader);
  27687. };
  27688. #endif
  27689. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  27690. /*** End of inlined file: juce_AudioCDReader.h ***/
  27691. #endif
  27692. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27693. #endif
  27694. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27695. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  27696. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27697. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27698. /**
  27699. A class for keeping a list of available audio formats, and for deciding which
  27700. one to use to open a given file.
  27701. You can either use this class as a singleton object, or create instances of it
  27702. yourself. Once created, use its registerFormat() method to tell it which
  27703. formats it should use.
  27704. @see AudioFormat
  27705. */
  27706. class JUCE_API AudioFormatManager
  27707. {
  27708. public:
  27709. /** Creates an empty format manager.
  27710. Before it'll be any use, you'll need to call registerFormat() with all the
  27711. formats you want it to be able to recognise.
  27712. */
  27713. AudioFormatManager();
  27714. /** Destructor. */
  27715. ~AudioFormatManager();
  27716. /** Adds a format to the manager's list of available file types.
  27717. The object passed-in will be deleted by this object, so don't keep a pointer
  27718. to it!
  27719. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  27720. return this one when called.
  27721. */
  27722. void registerFormat (AudioFormat* newFormat,
  27723. bool makeThisTheDefaultFormat);
  27724. /** Handy method to make it easy to register the formats that come with Juce.
  27725. Currently, this will add WAV and AIFF to the list.
  27726. */
  27727. void registerBasicFormats();
  27728. /** Clears the list of known formats. */
  27729. void clearFormats();
  27730. /** Returns the number of currently registered file formats. */
  27731. int getNumKnownFormats() const;
  27732. /** Returns one of the registered file formats. */
  27733. AudioFormat* getKnownFormat (int index) const;
  27734. /** Looks for which of the known formats is listed as being for a given file
  27735. extension.
  27736. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  27737. */
  27738. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  27739. /** Returns the format which has been set as the default one.
  27740. You can set a format as being the default when it is registered. It's useful
  27741. when you want to write to a file, because the best format may change between
  27742. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  27743. If none has been set as the default, this method will just return the first
  27744. one in the list.
  27745. */
  27746. AudioFormat* getDefaultFormat() const;
  27747. /** Returns a set of wildcards for file-matching that contains the extensions for
  27748. all known formats.
  27749. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  27750. */
  27751. const String getWildcardForAllFormats() const;
  27752. /** Searches through the known formats to try to create a suitable reader for
  27753. this file.
  27754. If none of the registered formats can open the file, it'll return 0. If it
  27755. returns a reader, it's the caller's responsibility to delete the reader.
  27756. */
  27757. AudioFormatReader* createReaderFor (const File& audioFile);
  27758. /** Searches through the known formats to try to create a suitable reader for
  27759. this stream.
  27760. The stream object that is passed-in will be deleted by this method or by the
  27761. reader that is returned, so the caller should not keep any references to it.
  27762. The stream that is passed-in must be capable of being repositioned so
  27763. that all the formats can have a go at opening it.
  27764. If none of the registered formats can open the stream, it'll return 0. If it
  27765. returns a reader, it's the caller's responsibility to delete the reader.
  27766. */
  27767. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  27768. private:
  27769. OwnedArray<AudioFormat> knownFormats;
  27770. int defaultFormatIndex;
  27771. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatManager);
  27772. };
  27773. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27774. /*** End of inlined file: juce_AudioFormatManager.h ***/
  27775. #endif
  27776. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27777. #endif
  27778. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27779. #endif
  27780. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27781. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  27782. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27783. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27784. /**
  27785. This class is used to wrap an AudioFormatReader and only read from a
  27786. subsection of the file.
  27787. So if you have a reader which can read a 1000 sample file, you could wrap it
  27788. in one of these to only access, e.g. samples 100 to 200, and any samples
  27789. outside that will come back as 0. Accessing sample 0 from this reader will
  27790. actually read the first sample from the other's subsection, which might
  27791. be at a non-zero position.
  27792. @see AudioFormatReader
  27793. */
  27794. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  27795. {
  27796. public:
  27797. /** Creates a AudioSubsectionReader for a given data source.
  27798. @param sourceReader the source reader from which we'll be taking data
  27799. @param subsectionStartSample the sample within the source reader which will be
  27800. mapped onto sample 0 for this reader.
  27801. @param subsectionLength the number of samples from the source that will
  27802. make up the subsection. If this reader is asked for
  27803. any samples beyond this region, it will return zero.
  27804. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  27805. this object is deleted.
  27806. */
  27807. AudioSubsectionReader (AudioFormatReader* sourceReader,
  27808. int64 subsectionStartSample,
  27809. int64 subsectionLength,
  27810. bool deleteSourceWhenDeleted);
  27811. /** Destructor. */
  27812. ~AudioSubsectionReader();
  27813. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  27814. int64 startSampleInFile, int numSamples);
  27815. void readMaxLevels (int64 startSample,
  27816. int64 numSamples,
  27817. float& lowestLeft,
  27818. float& highestLeft,
  27819. float& lowestRight,
  27820. float& highestRight);
  27821. private:
  27822. AudioFormatReader* const source;
  27823. int64 startSample, length;
  27824. const bool deleteSourceWhenDeleted;
  27825. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSubsectionReader);
  27826. };
  27827. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27828. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  27829. #endif
  27830. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27831. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  27832. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27833. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27834. class AudioThumbnailCache;
  27835. /**
  27836. Makes it easy to quickly draw scaled views of the waveform shape of an
  27837. audio file.
  27838. To use this class, just create an AudioThumbNail class for the file you want
  27839. to draw, call setSource to tell it which file or resource to use, then call
  27840. drawChannel() to draw it.
  27841. The class will asynchronously scan the wavefile to create its scaled-down view,
  27842. so you should make your UI repaint itself as this data comes in. To do this, the
  27843. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  27844. listeners should repaint themselves.
  27845. The thumbnail stores an internal low-res version of the wave data, and this can
  27846. be loaded and saved to avoid having to scan the file again.
  27847. @see AudioThumbnailCache
  27848. */
  27849. class JUCE_API AudioThumbnail : public ChangeBroadcaster
  27850. {
  27851. public:
  27852. /** Creates an audio thumbnail.
  27853. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  27854. of the audio data, this is the scale at which it should be done. (This
  27855. number is the number of original samples that will be averaged for each
  27856. low-res sample)
  27857. @param formatManagerToUse the audio format manager that is used to open the file
  27858. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  27859. thread and storage that is used to by the thumbnail, and the cache
  27860. object can be shared between multiple thumbnails
  27861. */
  27862. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  27863. AudioFormatManager& formatManagerToUse,
  27864. AudioThumbnailCache& cacheToUse);
  27865. /** Destructor. */
  27866. ~AudioThumbnail();
  27867. /** Clears and resets the thumbnail. */
  27868. void clear();
  27869. /** Specifies the file or stream that contains the audio file.
  27870. For a file, just call
  27871. @code
  27872. setSource (new FileInputSource (file))
  27873. @endcode
  27874. You can pass a zero in here to clear the thumbnail.
  27875. The source that is passed in will be deleted by this object when it is no longer needed.
  27876. @returns true if the source could be opened as a valid audio file, false if this failed for
  27877. some reason.
  27878. */
  27879. bool setSource (InputSource* newSource);
  27880. /** Gives the thumbnail an AudioFormatReader to use directly.
  27881. This will start parsing the audio in a background thread (unless the hash code
  27882. can be looked-up successfully in the thumbnail cache). Note that the reader
  27883. object will be held by the thumbnail and deleted later when no longer needed.
  27884. The thumbnail will actually keep hold of this reader until you clear the thumbnail
  27885. or change the input source, so the file will be held open for all this time. If
  27886. you don't want the thumbnail to keep a file handle open continuously, you
  27887. should use the setSource() method instead, which will only open the file when
  27888. it needs to.
  27889. */
  27890. void setReader (AudioFormatReader* newReader, int64 hashCode);
  27891. /** Resets the thumbnail, ready for adding data with the specified format.
  27892. If you're going to generate a thumbnail yourself, call this before using addBlock()
  27893. to add the data.
  27894. */
  27895. void reset (int numChannels, double sampleRate, int64 totalSamplesInSource = 0);
  27896. /** Adds a block of level data to the thumbnail.
  27897. Call reset() before using this, to tell the thumbnail about the data format.
  27898. */
  27899. void addBlock (int64 sampleNumberInSource, const AudioSampleBuffer& newData,
  27900. int startOffsetInBuffer, int numSamples);
  27901. /** Reloads the low res thumbnail data from an input stream.
  27902. This is not an audio file stream! It takes a stream of thumbnail data that would
  27903. previously have been created by the saveTo() method.
  27904. @see saveTo
  27905. */
  27906. void loadFrom (InputStream& input);
  27907. /** Saves the low res thumbnail data to an output stream.
  27908. The data that is written can later be reloaded using loadFrom().
  27909. @see loadFrom
  27910. */
  27911. void saveTo (OutputStream& output) const;
  27912. /** Returns the number of channels in the file. */
  27913. int getNumChannels() const throw();
  27914. /** Returns the length of the audio file, in seconds. */
  27915. double getTotalLength() const throw();
  27916. /** Draws the waveform for a channel.
  27917. The waveform will be drawn within the specified rectangle, where startTime
  27918. and endTime specify the times within the audio file that should be positioned
  27919. at the left and right edges of the rectangle.
  27920. The waveform will be scaled vertically so that a full-volume sample will fill
  27921. the rectangle vertically, but you can also specify an extra vertical scale factor
  27922. with the verticalZoomFactor parameter.
  27923. */
  27924. void drawChannel (Graphics& g,
  27925. const Rectangle<int>& area,
  27926. double startTimeSeconds,
  27927. double endTimeSeconds,
  27928. int channelNum,
  27929. float verticalZoomFactor);
  27930. /** Draws the waveforms for all channels in the thumbnail.
  27931. This will call drawChannel() to render each of the thumbnail's channels, stacked
  27932. above each other within the specified area.
  27933. @see drawChannel
  27934. */
  27935. void drawChannels (Graphics& g,
  27936. const Rectangle<int>& area,
  27937. double startTimeSeconds,
  27938. double endTimeSeconds,
  27939. float verticalZoomFactor);
  27940. /** Returns true if the low res preview is fully generated. */
  27941. bool isFullyLoaded() const throw();
  27942. /** Returns the number of samples that have been set in the thumbnail. */
  27943. int64 getNumSamplesFinished() const throw();
  27944. /** Returns the highest level in the thumbnail.
  27945. Note that because the thumb only stores low-resolution data, this isn't
  27946. an accurate representation of the highest value, it's only a rough approximation.
  27947. */
  27948. float getApproximatePeak() const;
  27949. /** Returns the hash code that was set by setSource() or setReader(). */
  27950. int64 getHashCode() const;
  27951. #ifndef DOXYGEN
  27952. // (this is only public to avoid a VC6 bug)
  27953. class LevelDataSource;
  27954. #endif
  27955. private:
  27956. AudioFormatManager& formatManagerToUse;
  27957. AudioThumbnailCache& cache;
  27958. struct MinMaxValue;
  27959. class ThumbData;
  27960. class CachedWindow;
  27961. friend class LevelDataSource;
  27962. friend class ScopedPointer<LevelDataSource>;
  27963. friend class ThumbData;
  27964. friend class OwnedArray<ThumbData>;
  27965. friend class CachedWindow;
  27966. friend class ScopedPointer<CachedWindow>;
  27967. ScopedPointer<LevelDataSource> source;
  27968. ScopedPointer<CachedWindow> window;
  27969. OwnedArray<ThumbData> channels;
  27970. int32 samplesPerThumbSample;
  27971. int64 totalSamples, numSamplesFinished;
  27972. int32 numChannels;
  27973. double sampleRate;
  27974. CriticalSection lock;
  27975. bool setDataSource (LevelDataSource* newSource);
  27976. void setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues);
  27977. void createChannels (int length);
  27978. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnail);
  27979. };
  27980. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27981. /*** End of inlined file: juce_AudioThumbnail.h ***/
  27982. #endif
  27983. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27984. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  27985. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27986. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27987. struct ThumbnailCacheEntry;
  27988. /**
  27989. An instance of this class is used to manage multiple AudioThumbnail objects.
  27990. The cache runs a single background thread that is shared by all the thumbnails
  27991. that need it, and it maintains a set of low-res previews in memory, to avoid
  27992. having to re-scan audio files too often.
  27993. @see AudioThumbnail
  27994. */
  27995. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  27996. {
  27997. public:
  27998. /** Creates a cache object.
  27999. The maxNumThumbsToStore parameter lets you specify how many previews should
  28000. be kept in memory at once.
  28001. */
  28002. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  28003. /** Destructor. */
  28004. ~AudioThumbnailCache();
  28005. /** Clears out any stored thumbnails.
  28006. */
  28007. void clear();
  28008. /** Reloads the specified thumb if this cache contains the appropriate stored
  28009. data.
  28010. This is called automatically by the AudioThumbnail class, so you shouldn't
  28011. normally need to call it directly.
  28012. */
  28013. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  28014. /** Stores the cachable data from the specified thumb in this cache.
  28015. This is called automatically by the AudioThumbnail class, so you shouldn't
  28016. normally need to call it directly.
  28017. */
  28018. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  28019. private:
  28020. OwnedArray <ThumbnailCacheEntry> thumbs;
  28021. int maxNumThumbsToStore;
  28022. ThumbnailCacheEntry* findThumbFor (int64 hash) const;
  28023. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnailCache);
  28024. };
  28025. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28026. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  28027. #endif
  28028. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28029. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  28030. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28031. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28032. #if JUCE_USE_FLAC || defined (DOXYGEN)
  28033. /**
  28034. Reads and writes the lossless-compression FLAC audio format.
  28035. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  28036. and make sure your include search path and library search path are set up to find
  28037. the FLAC header files and static libraries.
  28038. @see AudioFormat
  28039. */
  28040. class JUCE_API FlacAudioFormat : public AudioFormat
  28041. {
  28042. public:
  28043. FlacAudioFormat();
  28044. ~FlacAudioFormat();
  28045. const Array <int> getPossibleSampleRates();
  28046. const Array <int> getPossibleBitDepths();
  28047. bool canDoStereo();
  28048. bool canDoMono();
  28049. bool isCompressed();
  28050. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28051. bool deleteStreamIfOpeningFails);
  28052. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28053. double sampleRateToUse,
  28054. unsigned int numberOfChannels,
  28055. int bitsPerSample,
  28056. const StringPairArray& metadataValues,
  28057. int qualityOptionIndex);
  28058. private:
  28059. JUCE_LEAK_DETECTOR (FlacAudioFormat);
  28060. };
  28061. #endif
  28062. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28063. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  28064. #endif
  28065. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28066. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  28067. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28068. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28069. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  28070. /**
  28071. Reads and writes the Ogg-Vorbis audio format.
  28072. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  28073. and make sure your include search path and library search path are set up to find
  28074. the Vorbis and Ogg header files and static libraries.
  28075. @see AudioFormat,
  28076. */
  28077. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  28078. {
  28079. public:
  28080. OggVorbisAudioFormat();
  28081. ~OggVorbisAudioFormat();
  28082. const Array <int> getPossibleSampleRates();
  28083. const Array <int> getPossibleBitDepths();
  28084. bool canDoStereo();
  28085. bool canDoMono();
  28086. bool isCompressed();
  28087. const StringArray getQualityOptions();
  28088. /** Tries to estimate the quality level of an ogg file based on its size.
  28089. If it can't read the file for some reason, this will just return 1 (medium quality),
  28090. otherwise it will return the approximate quality setting that would have been used
  28091. to create the file.
  28092. @see getQualityOptions
  28093. */
  28094. int estimateOggFileQuality (const File& source);
  28095. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28096. bool deleteStreamIfOpeningFails);
  28097. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28098. double sampleRateToUse,
  28099. unsigned int numberOfChannels,
  28100. int bitsPerSample,
  28101. const StringPairArray& metadataValues,
  28102. int qualityOptionIndex);
  28103. private:
  28104. JUCE_LEAK_DETECTOR (OggVorbisAudioFormat);
  28105. };
  28106. #endif
  28107. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28108. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  28109. #endif
  28110. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28111. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  28112. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28113. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28114. #if JUCE_QUICKTIME
  28115. /**
  28116. Uses QuickTime to read the audio track a movie or media file.
  28117. As well as QuickTime movies, this should also manage to open other audio
  28118. files that quicktime can understand, like mp3, m4a, etc.
  28119. @see AudioFormat
  28120. */
  28121. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  28122. {
  28123. public:
  28124. /** Creates a format object. */
  28125. QuickTimeAudioFormat();
  28126. /** Destructor. */
  28127. ~QuickTimeAudioFormat();
  28128. const Array <int> getPossibleSampleRates();
  28129. const Array <int> getPossibleBitDepths();
  28130. bool canDoStereo();
  28131. bool canDoMono();
  28132. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28133. bool deleteStreamIfOpeningFails);
  28134. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28135. double sampleRateToUse,
  28136. unsigned int numberOfChannels,
  28137. int bitsPerSample,
  28138. const StringPairArray& metadataValues,
  28139. int qualityOptionIndex);
  28140. private:
  28141. JUCE_LEAK_DETECTOR (QuickTimeAudioFormat);
  28142. };
  28143. #endif
  28144. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28145. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  28146. #endif
  28147. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28148. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  28149. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28150. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28151. /**
  28152. Reads and Writes WAV format audio files.
  28153. @see AudioFormat
  28154. */
  28155. class JUCE_API WavAudioFormat : public AudioFormat
  28156. {
  28157. public:
  28158. /** Creates a format object. */
  28159. WavAudioFormat();
  28160. /** Destructor. */
  28161. ~WavAudioFormat();
  28162. /** Metadata property name used by wav readers and writers for adding
  28163. a BWAV chunk to the file.
  28164. @see AudioFormatReader::metadataValues, createWriterFor
  28165. */
  28166. static const char* const bwavDescription;
  28167. /** Metadata property name used by wav readers and writers for adding
  28168. a BWAV chunk to the file.
  28169. @see AudioFormatReader::metadataValues, createWriterFor
  28170. */
  28171. static const char* const bwavOriginator;
  28172. /** Metadata property name used by wav readers and writers for adding
  28173. a BWAV chunk to the file.
  28174. @see AudioFormatReader::metadataValues, createWriterFor
  28175. */
  28176. static const char* const bwavOriginatorRef;
  28177. /** Metadata property name used by wav readers and writers for adding
  28178. a BWAV chunk to the file.
  28179. Date format is: yyyy-mm-dd
  28180. @see AudioFormatReader::metadataValues, createWriterFor
  28181. */
  28182. static const char* const bwavOriginationDate;
  28183. /** Metadata property name used by wav readers and writers for adding
  28184. a BWAV chunk to the file.
  28185. Time format is: hh-mm-ss
  28186. @see AudioFormatReader::metadataValues, createWriterFor
  28187. */
  28188. static const char* const bwavOriginationTime;
  28189. /** Metadata property name used by wav readers and writers for adding
  28190. a BWAV chunk to the file.
  28191. This is the number of samples from the start of an edit that the
  28192. file is supposed to begin at. Seems like an obvious mistake to
  28193. only allow a file to occur in an edit once, but that's the way
  28194. it is..
  28195. @see AudioFormatReader::metadataValues, createWriterFor
  28196. */
  28197. static const char* const bwavTimeReference;
  28198. /** Metadata property name used by wav readers and writers for adding
  28199. a BWAV chunk to the file.
  28200. This is a
  28201. @see AudioFormatReader::metadataValues, createWriterFor
  28202. */
  28203. static const char* const bwavCodingHistory;
  28204. /** Utility function to fill out the appropriate metadata for a BWAV file.
  28205. This just makes it easier than using the property names directly, and it
  28206. fills out the time and date in the right format.
  28207. */
  28208. static const StringPairArray createBWAVMetadata (const String& description,
  28209. const String& originator,
  28210. const String& originatorRef,
  28211. const Time& dateAndTime,
  28212. const int64 timeReferenceSamples,
  28213. const String& codingHistory);
  28214. const Array <int> getPossibleSampleRates();
  28215. const Array <int> getPossibleBitDepths();
  28216. bool canDoStereo();
  28217. bool canDoMono();
  28218. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28219. bool deleteStreamIfOpeningFails);
  28220. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28221. double sampleRateToUse,
  28222. unsigned int numberOfChannels,
  28223. int bitsPerSample,
  28224. const StringPairArray& metadataValues,
  28225. int qualityOptionIndex);
  28226. /** Utility function to replace the metadata in a wav file with a new set of values.
  28227. If possible, this cheats by overwriting just the metadata region of the file, rather
  28228. than by copying the whole file again.
  28229. */
  28230. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  28231. private:
  28232. JUCE_LEAK_DETECTOR (WavAudioFormat);
  28233. };
  28234. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28235. /*** End of inlined file: juce_WavAudioFormat.h ***/
  28236. #endif
  28237. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28238. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  28239. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28240. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28241. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  28242. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28243. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28244. /**
  28245. A type of AudioSource which can be repositioned.
  28246. The basic AudioSource just streams continuously with no idea of a current
  28247. time or length, so the PositionableAudioSource is used for a finite stream
  28248. that has a current read position.
  28249. @see AudioSource, AudioTransportSource
  28250. */
  28251. class JUCE_API PositionableAudioSource : public AudioSource
  28252. {
  28253. protected:
  28254. /** Creates the PositionableAudioSource. */
  28255. PositionableAudioSource() throw() {}
  28256. public:
  28257. /** Destructor */
  28258. ~PositionableAudioSource() {}
  28259. /** Tells the stream to move to a new position.
  28260. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  28261. should return samples from this position.
  28262. Note that this may be called on a different thread to getNextAudioBlock(),
  28263. so the subclass should make sure it's synchronised.
  28264. */
  28265. virtual void setNextReadPosition (int64 newPosition) = 0;
  28266. /** Returns the position from which the next block will be returned.
  28267. @see setNextReadPosition
  28268. */
  28269. virtual int64 getNextReadPosition() const = 0;
  28270. /** Returns the total length of the stream (in samples). */
  28271. virtual int64 getTotalLength() const = 0;
  28272. /** Returns true if this source is actually playing in a loop. */
  28273. virtual bool isLooping() const = 0;
  28274. /** Tells the source whether you'd like it to play in a loop. */
  28275. virtual void setLooping (bool shouldLoop) { (void) shouldLoop; }
  28276. };
  28277. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28278. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  28279. /**
  28280. A type of AudioSource that will read from an AudioFormatReader.
  28281. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  28282. */
  28283. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  28284. {
  28285. public:
  28286. /** Creates an AudioFormatReaderSource for a given reader.
  28287. @param sourceReader the reader to use as the data source
  28288. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  28289. when this object is deleted; if false it will be
  28290. left up to the caller to manage its lifetime
  28291. */
  28292. AudioFormatReaderSource (AudioFormatReader* sourceReader,
  28293. bool deleteReaderWhenThisIsDeleted);
  28294. /** Destructor. */
  28295. ~AudioFormatReaderSource();
  28296. /** Toggles loop-mode.
  28297. If set to true, it will continuously loop the input source. If false,
  28298. it will just emit silence after the source has finished.
  28299. @see isLooping
  28300. */
  28301. void setLooping (bool shouldLoop);
  28302. /** Returns whether loop-mode is turned on or not. */
  28303. bool isLooping() const { return looping; }
  28304. /** Returns the reader that's being used. */
  28305. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  28306. /** Implementation of the AudioSource method. */
  28307. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28308. /** Implementation of the AudioSource method. */
  28309. void releaseResources();
  28310. /** Implementation of the AudioSource method. */
  28311. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28312. /** Implements the PositionableAudioSource method. */
  28313. void setNextReadPosition (int64 newPosition);
  28314. /** Implements the PositionableAudioSource method. */
  28315. int64 getNextReadPosition() const;
  28316. /** Implements the PositionableAudioSource method. */
  28317. int64 getTotalLength() const;
  28318. private:
  28319. AudioFormatReader* reader;
  28320. bool deleteReader;
  28321. int64 volatile nextPlayPos;
  28322. bool volatile looping;
  28323. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  28324. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReaderSource);
  28325. };
  28326. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  28327. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  28328. #endif
  28329. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  28330. #endif
  28331. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  28332. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  28333. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  28334. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  28335. /*** Start of inlined file: juce_AudioIODevice.h ***/
  28336. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  28337. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  28338. class AudioIODevice;
  28339. /**
  28340. One of these is passed to an AudioIODevice object to stream the audio data
  28341. in and out.
  28342. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  28343. method on its own high-priority audio thread, when it needs to send or receive
  28344. the next block of data.
  28345. @see AudioIODevice, AudioDeviceManager
  28346. */
  28347. class JUCE_API AudioIODeviceCallback
  28348. {
  28349. public:
  28350. /** Destructor. */
  28351. virtual ~AudioIODeviceCallback() {}
  28352. /** Processes a block of incoming and outgoing audio data.
  28353. The subclass's implementation should use the incoming audio for whatever
  28354. purposes it needs to, and must fill all the output channels with the next
  28355. block of output data before returning.
  28356. The channel data is arranged with the same array indices as the channel name
  28357. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  28358. that aren't specified in AudioIODevice::open() will have a null pointer for their
  28359. associated channel, so remember to check for this.
  28360. @param inputChannelData a set of arrays containing the audio data for each
  28361. incoming channel - this data is valid until the function
  28362. returns. There will be one channel of data for each input
  28363. channel that was enabled when the audio device was opened
  28364. (see AudioIODevice::open())
  28365. @param numInputChannels the number of pointers to channel data in the
  28366. inputChannelData array.
  28367. @param outputChannelData a set of arrays which need to be filled with the data
  28368. that should be sent to each outgoing channel of the device.
  28369. There will be one channel of data for each output channel
  28370. that was enabled when the audio device was opened (see
  28371. AudioIODevice::open())
  28372. The initial contents of the array is undefined, so the
  28373. callback function must fill all the channels with zeros if
  28374. its output is silence. Failing to do this could cause quite
  28375. an unpleasant noise!
  28376. @param numOutputChannels the number of pointers to channel data in the
  28377. outputChannelData array.
  28378. @param numSamples the number of samples in each channel of the input and
  28379. output arrays. The number of samples will depend on the
  28380. audio device's buffer size and will usually remain constant,
  28381. although this isn't guaranteed, so make sure your code can
  28382. cope with reasonable changes in the buffer size from one
  28383. callback to the next.
  28384. */
  28385. virtual void audioDeviceIOCallback (const float** inputChannelData,
  28386. int numInputChannels,
  28387. float** outputChannelData,
  28388. int numOutputChannels,
  28389. int numSamples) = 0;
  28390. /** Called to indicate that the device is about to start calling back.
  28391. This will be called just before the audio callbacks begin, either when this
  28392. callback has just been added to an audio device, or after the device has been
  28393. restarted because of a sample-rate or block-size change.
  28394. You can use this opportunity to find out the sample rate and block size
  28395. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  28396. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  28397. @param device the audio IO device that will be used to drive the callback.
  28398. Note that if you're going to store this this pointer, it is
  28399. only valid until the next time that audioDeviceStopped is called.
  28400. */
  28401. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  28402. /** Called to indicate that the device has stopped.
  28403. */
  28404. virtual void audioDeviceStopped() = 0;
  28405. };
  28406. /**
  28407. Base class for an audio device with synchronised input and output channels.
  28408. Subclasses of this are used to implement different protocols such as DirectSound,
  28409. ASIO, CoreAudio, etc.
  28410. To create one of these, you'll need to use the AudioIODeviceType class - see the
  28411. documentation for that class for more info.
  28412. For an easier way of managing audio devices and their settings, have a look at the
  28413. AudioDeviceManager class.
  28414. @see AudioIODeviceType, AudioDeviceManager
  28415. */
  28416. class JUCE_API AudioIODevice
  28417. {
  28418. public:
  28419. /** Destructor. */
  28420. virtual ~AudioIODevice();
  28421. /** Returns the device's name, (as set in the constructor). */
  28422. const String& getName() const throw() { return name; }
  28423. /** Returns the type of the device.
  28424. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  28425. */
  28426. const String& getTypeName() const throw() { return typeName; }
  28427. /** Returns the names of all the available output channels on this device.
  28428. To find out which of these are currently in use, call getActiveOutputChannels().
  28429. */
  28430. virtual const StringArray getOutputChannelNames() = 0;
  28431. /** Returns the names of all the available input channels on this device.
  28432. To find out which of these are currently in use, call getActiveInputChannels().
  28433. */
  28434. virtual const StringArray getInputChannelNames() = 0;
  28435. /** Returns the number of sample-rates this device supports.
  28436. To find out which rates are available on this device, use this method to
  28437. find out how many there are, and getSampleRate() to get the rates.
  28438. @see getSampleRate
  28439. */
  28440. virtual int getNumSampleRates() = 0;
  28441. /** Returns one of the sample-rates this device supports.
  28442. To find out which rates are available on this device, use getNumSampleRates() to
  28443. find out how many there are, and getSampleRate() to get the individual rates.
  28444. The sample rate is set by the open() method.
  28445. (Note that for DirectSound some rates might not work, depending on combinations
  28446. of i/o channels that are being opened).
  28447. @see getNumSampleRates
  28448. */
  28449. virtual double getSampleRate (int index) = 0;
  28450. /** Returns the number of sizes of buffer that are available.
  28451. @see getBufferSizeSamples, getDefaultBufferSize
  28452. */
  28453. virtual int getNumBufferSizesAvailable() = 0;
  28454. /** Returns one of the possible buffer-sizes.
  28455. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  28456. @returns a number of samples
  28457. @see getNumBufferSizesAvailable, getDefaultBufferSize
  28458. */
  28459. virtual int getBufferSizeSamples (int index) = 0;
  28460. /** Returns the default buffer-size to use.
  28461. @returns a number of samples
  28462. @see getNumBufferSizesAvailable, getBufferSizeSamples
  28463. */
  28464. virtual int getDefaultBufferSize() = 0;
  28465. /** Tries to open the device ready to play.
  28466. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  28467. input channel should be enabled
  28468. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  28469. output channel should be enabled
  28470. @param sampleRate the sample rate to try to use - to find out which rates are
  28471. available, see getNumSampleRates() and getSampleRate()
  28472. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  28473. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  28474. @returns an error description if there's a problem, or an empty string if it succeeds in
  28475. opening the device
  28476. @see close
  28477. */
  28478. virtual const String open (const BigInteger& inputChannels,
  28479. const BigInteger& outputChannels,
  28480. double sampleRate,
  28481. int bufferSizeSamples) = 0;
  28482. /** Closes and releases the device if it's open. */
  28483. virtual void close() = 0;
  28484. /** Returns true if the device is still open.
  28485. A device might spontaneously close itself if something goes wrong, so this checks if
  28486. it's still open.
  28487. */
  28488. virtual bool isOpen() = 0;
  28489. /** Starts the device actually playing.
  28490. This must be called after the device has been opened.
  28491. @param callback the callback to use for streaming the data.
  28492. @see AudioIODeviceCallback, open
  28493. */
  28494. virtual void start (AudioIODeviceCallback* callback) = 0;
  28495. /** Stops the device playing.
  28496. Once a device has been started, this will stop it. Any pending calls to the
  28497. callback class will be flushed before this method returns.
  28498. */
  28499. virtual void stop() = 0;
  28500. /** Returns true if the device is still calling back.
  28501. The device might mysteriously stop, so this checks whether it's
  28502. still playing.
  28503. */
  28504. virtual bool isPlaying() = 0;
  28505. /** Returns the last error that happened if anything went wrong. */
  28506. virtual const String getLastError() = 0;
  28507. /** Returns the buffer size that the device is currently using.
  28508. If the device isn't actually open, this value doesn't really mean much.
  28509. */
  28510. virtual int getCurrentBufferSizeSamples() = 0;
  28511. /** Returns the sample rate that the device is currently using.
  28512. If the device isn't actually open, this value doesn't really mean much.
  28513. */
  28514. virtual double getCurrentSampleRate() = 0;
  28515. /** Returns the device's current physical bit-depth.
  28516. If the device isn't actually open, this value doesn't really mean much.
  28517. */
  28518. virtual int getCurrentBitDepth() = 0;
  28519. /** Returns a mask showing which of the available output channels are currently
  28520. enabled.
  28521. @see getOutputChannelNames
  28522. */
  28523. virtual const BigInteger getActiveOutputChannels() const = 0;
  28524. /** Returns a mask showing which of the available input channels are currently
  28525. enabled.
  28526. @see getInputChannelNames
  28527. */
  28528. virtual const BigInteger getActiveInputChannels() const = 0;
  28529. /** Returns the device's output latency.
  28530. This is the delay in samples between a callback getting a block of data, and
  28531. that data actually getting played.
  28532. */
  28533. virtual int getOutputLatencyInSamples() = 0;
  28534. /** Returns the device's input latency.
  28535. This is the delay in samples between some audio actually arriving at the soundcard,
  28536. and the callback getting passed this block of data.
  28537. */
  28538. virtual int getInputLatencyInSamples() = 0;
  28539. /** True if this device can show a pop-up control panel for editing its settings.
  28540. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  28541. to display it.
  28542. */
  28543. virtual bool hasControlPanel() const;
  28544. /** Shows a device-specific control panel if there is one.
  28545. This should only be called for devices which return true from hasControlPanel().
  28546. */
  28547. virtual bool showControlPanel();
  28548. protected:
  28549. /** Creates a device, setting its name and type member variables. */
  28550. AudioIODevice (const String& deviceName,
  28551. const String& typeName);
  28552. /** @internal */
  28553. String name, typeName;
  28554. };
  28555. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  28556. /*** End of inlined file: juce_AudioIODevice.h ***/
  28557. /**
  28558. Wrapper class to continuously stream audio from an audio source to an
  28559. AudioIODevice.
  28560. This object acts as an AudioIODeviceCallback, so can be attached to an
  28561. output device, and will stream audio from an AudioSource.
  28562. */
  28563. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  28564. {
  28565. public:
  28566. /** Creates an empty AudioSourcePlayer. */
  28567. AudioSourcePlayer();
  28568. /** Destructor.
  28569. Make sure this object isn't still being used by an AudioIODevice before
  28570. deleting it!
  28571. */
  28572. virtual ~AudioSourcePlayer();
  28573. /** Changes the current audio source to play from.
  28574. If the source passed in is already being used, this method will do nothing.
  28575. If the source is not null, its prepareToPlay() method will be called
  28576. before it starts being used for playback.
  28577. If there's another source currently playing, its releaseResources() method
  28578. will be called after it has been swapped for the new one.
  28579. @param newSource the new source to use - this will NOT be deleted
  28580. by this object when no longer needed, so it's the
  28581. caller's responsibility to manage it.
  28582. */
  28583. void setSource (AudioSource* newSource);
  28584. /** Returns the source that's playing.
  28585. May return 0 if there's no source.
  28586. */
  28587. AudioSource* getCurrentSource() const throw() { return source; }
  28588. /** Sets a gain to apply to the audio data.
  28589. @see getGain
  28590. */
  28591. void setGain (float newGain) throw();
  28592. /** Returns the current gain.
  28593. @see setGain
  28594. */
  28595. float getGain() const throw() { return gain; }
  28596. /** Implementation of the AudioIODeviceCallback method. */
  28597. void audioDeviceIOCallback (const float** inputChannelData,
  28598. int totalNumInputChannels,
  28599. float** outputChannelData,
  28600. int totalNumOutputChannels,
  28601. int numSamples);
  28602. /** Implementation of the AudioIODeviceCallback method. */
  28603. void audioDeviceAboutToStart (AudioIODevice* device);
  28604. /** Implementation of the AudioIODeviceCallback method. */
  28605. void audioDeviceStopped();
  28606. private:
  28607. CriticalSection readLock;
  28608. AudioSource* source;
  28609. double sampleRate;
  28610. int bufferSize;
  28611. float* channels [128];
  28612. float* outputChans [128];
  28613. const float* inputChans [128];
  28614. AudioSampleBuffer tempBuffer;
  28615. float lastGain, gain;
  28616. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSourcePlayer);
  28617. };
  28618. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  28619. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  28620. #endif
  28621. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  28622. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  28623. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  28624. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  28625. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  28626. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  28627. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  28628. /**
  28629. An AudioSource which takes another source as input, and buffers it using a thread.
  28630. Create this as a wrapper around another thread, and it will read-ahead with
  28631. a background thread to smooth out playback. You can either create one of these
  28632. directly, or use it indirectly using an AudioTransportSource.
  28633. @see PositionableAudioSource, AudioTransportSource
  28634. */
  28635. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  28636. {
  28637. public:
  28638. /** Creates a BufferingAudioSource.
  28639. @param source the input source to read from
  28640. @param deleteSourceWhenDeleted if true, then the input source object will
  28641. be deleted when this object is deleted
  28642. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  28643. */
  28644. BufferingAudioSource (PositionableAudioSource* source,
  28645. bool deleteSourceWhenDeleted,
  28646. int numberOfSamplesToBuffer);
  28647. /** Destructor.
  28648. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  28649. flag was set in the constructor.
  28650. */
  28651. ~BufferingAudioSource();
  28652. /** Implementation of the AudioSource method. */
  28653. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28654. /** Implementation of the AudioSource method. */
  28655. void releaseResources();
  28656. /** Implementation of the AudioSource method. */
  28657. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28658. /** Implements the PositionableAudioSource method. */
  28659. void setNextReadPosition (int64 newPosition);
  28660. /** Implements the PositionableAudioSource method. */
  28661. int64 getNextReadPosition() const;
  28662. /** Implements the PositionableAudioSource method. */
  28663. int64 getTotalLength() const { return source->getTotalLength(); }
  28664. /** Implements the PositionableAudioSource method. */
  28665. bool isLooping() const { return source->isLooping(); }
  28666. private:
  28667. PositionableAudioSource* source;
  28668. bool deleteSourceWhenDeleted;
  28669. int numberOfSamplesToBuffer;
  28670. AudioSampleBuffer buffer;
  28671. CriticalSection bufferStartPosLock;
  28672. int64 volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  28673. bool wasSourceLooping;
  28674. double volatile sampleRate;
  28675. friend class SharedBufferingAudioSourceThread;
  28676. bool readNextBufferChunk();
  28677. void readBufferSection (int64 start, int length, int bufferOffset);
  28678. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferingAudioSource);
  28679. };
  28680. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  28681. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  28682. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  28683. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  28684. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  28685. /**
  28686. A type of AudioSource that takes an input source and changes its sample rate.
  28687. @see AudioSource
  28688. */
  28689. class JUCE_API ResamplingAudioSource : public AudioSource
  28690. {
  28691. public:
  28692. /** Creates a ResamplingAudioSource for a given input source.
  28693. @param inputSource the input source to read from
  28694. @param deleteInputWhenDeleted if true, the input source will be deleted when
  28695. this object is deleted
  28696. @param numChannels the number of channels to process
  28697. */
  28698. ResamplingAudioSource (AudioSource* inputSource,
  28699. bool deleteInputWhenDeleted,
  28700. int numChannels = 2);
  28701. /** Destructor. */
  28702. ~ResamplingAudioSource();
  28703. /** Changes the resampling ratio.
  28704. (This value can be changed at any time, even while the source is running).
  28705. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  28706. values will speed it up; lower values will slow it
  28707. down. The ratio must be greater than 0
  28708. */
  28709. void setResamplingRatio (double samplesInPerOutputSample);
  28710. /** Returns the current resampling ratio.
  28711. This is the value that was set by setResamplingRatio().
  28712. */
  28713. double getResamplingRatio() const throw() { return ratio; }
  28714. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28715. void releaseResources();
  28716. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28717. private:
  28718. AudioSource* const input;
  28719. const bool deleteInputWhenDeleted;
  28720. double ratio, lastRatio;
  28721. AudioSampleBuffer buffer;
  28722. int bufferPos, sampsInBuffer;
  28723. double subSampleOffset;
  28724. double coefficients[6];
  28725. CriticalSection ratioLock;
  28726. const int numChannels;
  28727. HeapBlock<float*> destBuffers, srcBuffers;
  28728. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  28729. void createLowPass (double proportionalRate);
  28730. struct FilterState
  28731. {
  28732. double x1, x2, y1, y2;
  28733. };
  28734. HeapBlock<FilterState> filterStates;
  28735. void resetFilters();
  28736. void applyFilter (float* samples, int num, FilterState& fs);
  28737. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResamplingAudioSource);
  28738. };
  28739. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  28740. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  28741. /**
  28742. An AudioSource that takes a PositionableAudioSource and allows it to be
  28743. played, stopped, started, etc.
  28744. This can also be told use a buffer and background thread to read ahead, and
  28745. if can correct for different sample-rates.
  28746. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  28747. to control playback of an audio file.
  28748. @see AudioSource, AudioSourcePlayer
  28749. */
  28750. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  28751. public ChangeBroadcaster
  28752. {
  28753. public:
  28754. /** Creates an AudioTransportSource.
  28755. After creating one of these, use the setSource() method to select an input source.
  28756. */
  28757. AudioTransportSource();
  28758. /** Destructor. */
  28759. ~AudioTransportSource();
  28760. /** Sets the reader that is being used as the input source.
  28761. This will stop playback, reset the position to 0 and change to the new reader.
  28762. The source passed in will not be deleted by this object, so must be managed by
  28763. the caller.
  28764. @param newSource the new input source to use. This may be zero
  28765. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  28766. is zero, no reading ahead will be done; if it's
  28767. greater than zero, a BufferingAudioSource will be used
  28768. to do the reading-ahead
  28769. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  28770. rate of the source, and playback will be sample-rate
  28771. adjusted to maintain playback at the correct pitch. If
  28772. this is 0, no sample-rate adjustment will be performed
  28773. @param maxNumChannels the maximum number of channels that may need to be played
  28774. */
  28775. void setSource (PositionableAudioSource* newSource,
  28776. int readAheadBufferSize = 0,
  28777. double sourceSampleRateToCorrectFor = 0.0,
  28778. int maxNumChannels = 2);
  28779. /** Changes the current playback position in the source stream.
  28780. The next time the getNextAudioBlock() method is called, this
  28781. is the time from which it'll read data.
  28782. @see getPosition
  28783. */
  28784. void setPosition (double newPosition);
  28785. /** Returns the position that the next data block will be read from
  28786. This is a time in seconds.
  28787. */
  28788. double getCurrentPosition() const;
  28789. /** Returns the stream's length in seconds. */
  28790. double getLengthInSeconds() const;
  28791. /** Returns true if the player has stopped because its input stream ran out of data.
  28792. */
  28793. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  28794. /** Starts playing (if a source has been selected).
  28795. If it starts playing, this will send a message to any ChangeListeners
  28796. that are registered with this object.
  28797. */
  28798. void start();
  28799. /** Stops playing.
  28800. If it's actually playing, this will send a message to any ChangeListeners
  28801. that are registered with this object.
  28802. */
  28803. void stop();
  28804. /** Returns true if it's currently playing. */
  28805. bool isPlaying() const throw() { return playing; }
  28806. /** Changes the gain to apply to the output.
  28807. @param newGain a factor by which to multiply the outgoing samples,
  28808. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  28809. */
  28810. void setGain (float newGain) throw();
  28811. /** Returns the current gain setting.
  28812. @see setGain
  28813. */
  28814. float getGain() const throw() { return gain; }
  28815. /** Implementation of the AudioSource method. */
  28816. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28817. /** Implementation of the AudioSource method. */
  28818. void releaseResources();
  28819. /** Implementation of the AudioSource method. */
  28820. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28821. /** Implements the PositionableAudioSource method. */
  28822. void setNextReadPosition (int64 newPosition);
  28823. /** Implements the PositionableAudioSource method. */
  28824. int64 getNextReadPosition() const;
  28825. /** Implements the PositionableAudioSource method. */
  28826. int64 getTotalLength() const;
  28827. /** Implements the PositionableAudioSource method. */
  28828. bool isLooping() const;
  28829. private:
  28830. PositionableAudioSource* source;
  28831. ResamplingAudioSource* resamplerSource;
  28832. BufferingAudioSource* bufferingSource;
  28833. PositionableAudioSource* positionableSource;
  28834. AudioSource* masterSource;
  28835. CriticalSection callbackLock;
  28836. float volatile gain, lastGain;
  28837. bool volatile playing, stopped;
  28838. double sampleRate, sourceSampleRate;
  28839. int blockSize, readAheadBufferSize;
  28840. bool isPrepared, inputStreamEOF;
  28841. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioTransportSource);
  28842. };
  28843. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  28844. /*** End of inlined file: juce_AudioTransportSource.h ***/
  28845. #endif
  28846. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  28847. #endif
  28848. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  28849. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  28850. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  28851. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  28852. /**
  28853. An AudioSource that takes the audio from another source, and re-maps its
  28854. input and output channels to a different arrangement.
  28855. You can use this to increase or decrease the number of channels that an
  28856. audio source uses, or to re-order those channels.
  28857. Call the reset() method before using it to set up a default mapping, and then
  28858. the setInputChannelMapping() and setOutputChannelMapping() methods to
  28859. create an appropriate mapping, otherwise no channels will be connected and
  28860. it'll produce silence.
  28861. @see AudioSource
  28862. */
  28863. class ChannelRemappingAudioSource : public AudioSource
  28864. {
  28865. public:
  28866. /** Creates a remapping source that will pass on audio from the given input.
  28867. @param source the input source to use. Make sure that this doesn't
  28868. get deleted before the ChannelRemappingAudioSource object
  28869. @param deleteSourceWhenDeleted if true, the input source will be deleted
  28870. when this object is deleted, if false, the caller is
  28871. responsible for its deletion
  28872. */
  28873. ChannelRemappingAudioSource (AudioSource* source,
  28874. bool deleteSourceWhenDeleted);
  28875. /** Destructor. */
  28876. ~ChannelRemappingAudioSource();
  28877. /** Specifies a number of channels that this audio source must produce from its
  28878. getNextAudioBlock() callback.
  28879. */
  28880. void setNumberOfChannelsToProduce (int requiredNumberOfChannels);
  28881. /** Clears any mapped channels.
  28882. After this, no channels are mapped, so this object will produce silence. Create
  28883. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  28884. */
  28885. void clearAllMappings();
  28886. /** Creates an input channel mapping.
  28887. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  28888. data will be sent to destChannelIndex of our input source.
  28889. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  28890. source specified when this object was created).
  28891. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  28892. during our getNextAudioBlock() callback
  28893. */
  28894. void setInputChannelMapping (int destChannelIndex,
  28895. int sourceChannelIndex);
  28896. /** Creates an output channel mapping.
  28897. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  28898. our input audio source will be copied to channel destChannelIndex of the final buffer.
  28899. @param sourceChannelIndex the index of an output channel coming from our input audio source
  28900. (i.e. the source specified when this object was created).
  28901. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  28902. during our getNextAudioBlock() callback
  28903. */
  28904. void setOutputChannelMapping (int sourceChannelIndex,
  28905. int destChannelIndex);
  28906. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  28907. our input audio source.
  28908. */
  28909. int getRemappedInputChannel (int inputChannelIndex) const;
  28910. /** Returns the output channel to which channel outputChannelIndex of our input audio
  28911. source will be sent to.
  28912. */
  28913. int getRemappedOutputChannel (int outputChannelIndex) const;
  28914. /** Returns an XML object to encapsulate the state of the mappings.
  28915. @see restoreFromXml
  28916. */
  28917. XmlElement* createXml() const;
  28918. /** Restores the mappings from an XML object created by createXML().
  28919. @see createXml
  28920. */
  28921. void restoreFromXml (const XmlElement& e);
  28922. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28923. void releaseResources();
  28924. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28925. private:
  28926. int requiredNumberOfChannels;
  28927. Array <int> remappedInputs, remappedOutputs;
  28928. AudioSource* const source;
  28929. const bool deleteSourceWhenDeleted;
  28930. AudioSampleBuffer buffer;
  28931. AudioSourceChannelInfo remappedInfo;
  28932. CriticalSection lock;
  28933. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelRemappingAudioSource);
  28934. };
  28935. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  28936. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  28937. #endif
  28938. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  28939. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  28940. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  28941. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  28942. /*** Start of inlined file: juce_IIRFilter.h ***/
  28943. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  28944. #define __JUCE_IIRFILTER_JUCEHEADER__
  28945. /**
  28946. An IIR filter that can perform low, high, or band-pass filtering on an
  28947. audio signal.
  28948. @see IIRFilterAudioSource
  28949. */
  28950. class JUCE_API IIRFilter
  28951. {
  28952. public:
  28953. /** Creates a filter.
  28954. Initially the filter is inactive, so will have no effect on samples that
  28955. you process with it. Use the appropriate method to turn it into the type
  28956. of filter needed.
  28957. */
  28958. IIRFilter();
  28959. /** Creates a copy of another filter. */
  28960. IIRFilter (const IIRFilter& other);
  28961. /** Destructor. */
  28962. ~IIRFilter();
  28963. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  28964. Note that this clears the processing state, but the type of filter and
  28965. its coefficients aren't changed. To put a filter into an inactive state, use
  28966. the makeInactive() method.
  28967. */
  28968. void reset() throw();
  28969. /** Performs the filter operation on the given set of samples.
  28970. */
  28971. void processSamples (float* samples,
  28972. int numSamples) throw();
  28973. /** Processes a single sample, without any locking or checking.
  28974. Use this if you need fast processing of a single value, but be aware that
  28975. this isn't thread-safe in the way that processSamples() is.
  28976. */
  28977. float processSingleSampleRaw (float sample) throw();
  28978. /** Sets the filter up to act as a low-pass filter.
  28979. */
  28980. void makeLowPass (double sampleRate,
  28981. double frequency) throw();
  28982. /** Sets the filter up to act as a high-pass filter.
  28983. */
  28984. void makeHighPass (double sampleRate,
  28985. double frequency) throw();
  28986. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  28987. The gain is a scale factor that the low frequencies are multiplied by, so values
  28988. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  28989. attenuate them.
  28990. */
  28991. void makeLowShelf (double sampleRate,
  28992. double cutOffFrequency,
  28993. double Q,
  28994. float gainFactor) throw();
  28995. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  28996. The gain is a scale factor that the high frequencies are multiplied by, so values
  28997. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  28998. attenuate them.
  28999. */
  29000. void makeHighShelf (double sampleRate,
  29001. double cutOffFrequency,
  29002. double Q,
  29003. float gainFactor) throw();
  29004. /** Sets the filter up to act as a band pass filter centred around a
  29005. frequency, with a variable Q and gain.
  29006. The gain is a scale factor that the centre frequencies are multiplied by, so
  29007. values greater than 1.0 will boost the centre frequencies, values less than
  29008. 1.0 will attenuate them.
  29009. */
  29010. void makeBandPass (double sampleRate,
  29011. double centreFrequency,
  29012. double Q,
  29013. float gainFactor) throw();
  29014. /** Clears the filter's coefficients so that it becomes inactive.
  29015. */
  29016. void makeInactive() throw();
  29017. /** Makes this filter duplicate the set-up of another one.
  29018. */
  29019. void copyCoefficientsFrom (const IIRFilter& other) throw();
  29020. protected:
  29021. CriticalSection processLock;
  29022. void setCoefficients (double c1, double c2, double c3,
  29023. double c4, double c5, double c6) throw();
  29024. bool active;
  29025. float coefficients[6];
  29026. float x1, x2, y1, y2;
  29027. // (use the copyCoefficientsFrom() method instead of this operator)
  29028. IIRFilter& operator= (const IIRFilter&);
  29029. JUCE_LEAK_DETECTOR (IIRFilter);
  29030. };
  29031. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  29032. /*** End of inlined file: juce_IIRFilter.h ***/
  29033. /**
  29034. An AudioSource that performs an IIR filter on another source.
  29035. */
  29036. class JUCE_API IIRFilterAudioSource : public AudioSource
  29037. {
  29038. public:
  29039. /** Creates a IIRFilterAudioSource for a given input source.
  29040. @param inputSource the input source to read from
  29041. @param deleteInputWhenDeleted if true, the input source will be deleted when
  29042. this object is deleted
  29043. */
  29044. IIRFilterAudioSource (AudioSource* inputSource,
  29045. bool deleteInputWhenDeleted);
  29046. /** Destructor. */
  29047. ~IIRFilterAudioSource();
  29048. /** Changes the filter to use the same parameters as the one being passed in.
  29049. */
  29050. void setFilterParameters (const IIRFilter& newSettings);
  29051. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29052. void releaseResources();
  29053. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29054. private:
  29055. AudioSource* const input;
  29056. const bool deleteInputWhenDeleted;
  29057. OwnedArray <IIRFilter> iirFilters;
  29058. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IIRFilterAudioSource);
  29059. };
  29060. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  29061. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  29062. #endif
  29063. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29064. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  29065. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29066. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29067. /**
  29068. An AudioSource that mixes together the output of a set of other AudioSources.
  29069. Input sources can be added and removed while the mixer is running as long as their
  29070. prepareToPlay() and releaseResources() methods are called before and after adding
  29071. them to the mixer.
  29072. */
  29073. class JUCE_API MixerAudioSource : public AudioSource
  29074. {
  29075. public:
  29076. /** Creates a MixerAudioSource.
  29077. */
  29078. MixerAudioSource();
  29079. /** Destructor. */
  29080. ~MixerAudioSource();
  29081. /** Adds an input source to the mixer.
  29082. If the mixer is running you'll need to make sure that the input source
  29083. is ready to play by calling its prepareToPlay() method before adding it.
  29084. If the mixer is stopped, then its input sources will be automatically
  29085. prepared when the mixer's prepareToPlay() method is called.
  29086. @param newInput the source to add to the mixer
  29087. @param deleteWhenRemoved if true, then this source will be deleted when
  29088. the mixer is deleted or when removeAllInputs() is
  29089. called (unless the source is previously removed
  29090. with the removeInputSource method)
  29091. */
  29092. void addInputSource (AudioSource* newInput, bool deleteWhenRemoved);
  29093. /** Removes an input source.
  29094. If the mixer is running, this will remove the source but not call its
  29095. releaseResources() method, so the caller might want to do this manually.
  29096. @param input the source to remove
  29097. @param deleteSource whether to delete this source after it's been removed
  29098. */
  29099. void removeInputSource (AudioSource* input, bool deleteSource);
  29100. /** Removes all the input sources.
  29101. If the mixer is running, this will remove the sources but not call their
  29102. releaseResources() method, so the caller might want to do this manually.
  29103. Any sources which were added with the deleteWhenRemoved flag set will be
  29104. deleted by this method.
  29105. */
  29106. void removeAllInputs();
  29107. /** Implementation of the AudioSource method.
  29108. This will call prepareToPlay() on all its input sources.
  29109. */
  29110. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29111. /** Implementation of the AudioSource method.
  29112. This will call releaseResources() on all its input sources.
  29113. */
  29114. void releaseResources();
  29115. /** Implementation of the AudioSource method. */
  29116. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29117. private:
  29118. Array <AudioSource*> inputs;
  29119. BigInteger inputsToDelete;
  29120. CriticalSection lock;
  29121. AudioSampleBuffer tempBuffer;
  29122. double currentSampleRate;
  29123. int bufferSizeExpected;
  29124. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MixerAudioSource);
  29125. };
  29126. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  29127. /*** End of inlined file: juce_MixerAudioSource.h ***/
  29128. #endif
  29129. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  29130. #endif
  29131. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  29132. #endif
  29133. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29134. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  29135. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29136. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29137. /**
  29138. A simple AudioSource that generates a sine wave.
  29139. */
  29140. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  29141. {
  29142. public:
  29143. /** Creates a ToneGeneratorAudioSource. */
  29144. ToneGeneratorAudioSource();
  29145. /** Destructor. */
  29146. ~ToneGeneratorAudioSource();
  29147. /** Sets the signal's amplitude. */
  29148. void setAmplitude (float newAmplitude);
  29149. /** Sets the signal's frequency. */
  29150. void setFrequency (double newFrequencyHz);
  29151. /** Implementation of the AudioSource method. */
  29152. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  29153. /** Implementation of the AudioSource method. */
  29154. void releaseResources();
  29155. /** Implementation of the AudioSource method. */
  29156. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  29157. private:
  29158. double frequency, sampleRate;
  29159. double currentPhase, phasePerSample;
  29160. float amplitude;
  29161. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToneGeneratorAudioSource);
  29162. };
  29163. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  29164. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  29165. #endif
  29166. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  29167. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  29168. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  29169. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  29170. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  29171. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  29172. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  29173. class AudioDeviceManager;
  29174. class Component;
  29175. /**
  29176. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  29177. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  29178. method. Each of the objects returned can then be used to list the available
  29179. devices of that type. E.g.
  29180. @code
  29181. OwnedArray <AudioIODeviceType> types;
  29182. myAudioDeviceManager.createAudioDeviceTypes (types);
  29183. for (int i = 0; i < types.size(); ++i)
  29184. {
  29185. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  29186. types[i]->scanForDevices(); // This must be called before getting the list of devices
  29187. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  29188. for (int j = 0; j < deviceNames.size(); ++j)
  29189. {
  29190. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  29191. ...
  29192. }
  29193. }
  29194. @endcode
  29195. For an easier way of managing audio devices and their settings, have a look at the
  29196. AudioDeviceManager class.
  29197. @see AudioIODevice, AudioDeviceManager
  29198. */
  29199. class JUCE_API AudioIODeviceType
  29200. {
  29201. public:
  29202. /** Returns the name of this type of driver that this object manages.
  29203. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  29204. */
  29205. const String& getTypeName() const throw() { return typeName; }
  29206. /** Refreshes the object's cached list of known devices.
  29207. This must be called at least once before calling getDeviceNames() or any of
  29208. the other device creation methods.
  29209. */
  29210. virtual void scanForDevices() = 0;
  29211. /** Returns the list of available devices of this type.
  29212. The scanForDevices() method must have been called to create this list.
  29213. @param wantInputNames only really used by DirectSound where devices are split up
  29214. into inputs and outputs, this indicates whether to use
  29215. the input or output name to refer to a pair of devices.
  29216. */
  29217. virtual const StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  29218. /** Returns the name of the default device.
  29219. This will be one of the names from the getDeviceNames() list.
  29220. @param forInput if true, this means that a default input device should be
  29221. returned; if false, it should return the default output
  29222. */
  29223. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  29224. /** Returns the index of a given device in the list of device names.
  29225. If asInput is true, it shows the index in the inputs list, otherwise it
  29226. looks for it in the outputs list.
  29227. */
  29228. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  29229. /** Returns true if two different devices can be used for the input and output.
  29230. */
  29231. virtual bool hasSeparateInputsAndOutputs() const = 0;
  29232. /** Creates one of the devices of this type.
  29233. The deviceName must be one of the strings returned by getDeviceNames(), and
  29234. scanForDevices() must have been called before this method is used.
  29235. */
  29236. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  29237. const String& inputDeviceName) = 0;
  29238. struct DeviceSetupDetails
  29239. {
  29240. AudioDeviceManager* manager;
  29241. int minNumInputChannels, maxNumInputChannels;
  29242. int minNumOutputChannels, maxNumOutputChannels;
  29243. bool useStereoPairs;
  29244. };
  29245. /** Destructor. */
  29246. virtual ~AudioIODeviceType();
  29247. /** Creates a CoreAudio device type if it's available on this platform, or returns null. */
  29248. static AudioIODeviceType* createAudioIODeviceType_CoreAudio();
  29249. /** Creates an iOS device type if it's available on this platform, or returns null. */
  29250. static AudioIODeviceType* createAudioIODeviceType_iOSAudio();
  29251. /** Creates a WASAPI device type if it's available on this platform, or returns null. */
  29252. static AudioIODeviceType* createAudioIODeviceType_WASAPI();
  29253. /** Creates a DirectSound device type if it's available on this platform, or returns null. */
  29254. static AudioIODeviceType* createAudioIODeviceType_DirectSound();
  29255. /** Creates an ASIO device type if it's available on this platform, or returns null. */
  29256. static AudioIODeviceType* createAudioIODeviceType_ASIO();
  29257. /** Creates an ALSA device type if it's available on this platform, or returns null. */
  29258. static AudioIODeviceType* createAudioIODeviceType_ALSA();
  29259. /** Creates a JACK device type if it's available on this platform, or returns null. */
  29260. static AudioIODeviceType* createAudioIODeviceType_JACK();
  29261. protected:
  29262. explicit AudioIODeviceType (const String& typeName);
  29263. private:
  29264. String typeName;
  29265. JUCE_DECLARE_NON_COPYABLE (AudioIODeviceType);
  29266. };
  29267. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  29268. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  29269. /*** Start of inlined file: juce_MidiInput.h ***/
  29270. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  29271. #define __JUCE_MIDIINPUT_JUCEHEADER__
  29272. /*** Start of inlined file: juce_MidiMessage.h ***/
  29273. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  29274. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  29275. /**
  29276. Encapsulates a MIDI message.
  29277. @see MidiMessageSequence, MidiOutput, MidiInput
  29278. */
  29279. class JUCE_API MidiMessage
  29280. {
  29281. public:
  29282. /** Creates a 3-byte short midi message.
  29283. @param byte1 message byte 1
  29284. @param byte2 message byte 2
  29285. @param byte3 message byte 3
  29286. @param timeStamp the time to give the midi message - this value doesn't
  29287. use any particular units, so will be application-specific
  29288. */
  29289. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) throw();
  29290. /** Creates a 2-byte short midi message.
  29291. @param byte1 message byte 1
  29292. @param byte2 message byte 2
  29293. @param timeStamp the time to give the midi message - this value doesn't
  29294. use any particular units, so will be application-specific
  29295. */
  29296. MidiMessage (int byte1, int byte2, double timeStamp = 0) throw();
  29297. /** Creates a 1-byte short midi message.
  29298. @param byte1 message byte 1
  29299. @param timeStamp the time to give the midi message - this value doesn't
  29300. use any particular units, so will be application-specific
  29301. */
  29302. MidiMessage (int byte1, double timeStamp = 0) throw();
  29303. /** Creates a midi message from a block of data. */
  29304. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  29305. /** Reads the next midi message from some data.
  29306. This will read as many bytes from a data stream as it needs to make a
  29307. complete message, and will return the number of bytes it used. This lets
  29308. you read a sequence of midi messages from a file or stream.
  29309. @param data the data to read from
  29310. @param maxBytesToUse the maximum number of bytes it's allowed to read
  29311. @param numBytesUsed returns the number of bytes that were actually needed
  29312. @param lastStatusByte in a sequence of midi messages, the initial byte
  29313. can be dropped from a message if it's the same as the
  29314. first byte of the previous message, so this lets you
  29315. supply the byte to use if the first byte of the message
  29316. has in fact been dropped.
  29317. @param timeStamp the time to give the midi message - this value doesn't
  29318. use any particular units, so will be application-specific
  29319. */
  29320. MidiMessage (const void* data, int maxBytesToUse,
  29321. int& numBytesUsed, uint8 lastStatusByte,
  29322. double timeStamp = 0);
  29323. /** Creates an active-sense message.
  29324. Since the MidiMessage has to contain a valid message, this default constructor
  29325. just initialises it with an empty sysex message.
  29326. */
  29327. MidiMessage() throw();
  29328. /** Creates a copy of another midi message. */
  29329. MidiMessage (const MidiMessage& other);
  29330. /** Creates a copy of another midi message, with a different timestamp. */
  29331. MidiMessage (const MidiMessage& other, double newTimeStamp);
  29332. /** Destructor. */
  29333. ~MidiMessage();
  29334. /** Copies this message from another one. */
  29335. MidiMessage& operator= (const MidiMessage& other);
  29336. /** Returns a pointer to the raw midi data.
  29337. @see getRawDataSize
  29338. */
  29339. uint8* getRawData() const throw() { return data; }
  29340. /** Returns the number of bytes of data in the message.
  29341. @see getRawData
  29342. */
  29343. int getRawDataSize() const throw() { return size; }
  29344. /** Returns the timestamp associated with this message.
  29345. The exact meaning of this time and its units will vary, as messages are used in
  29346. a variety of different contexts.
  29347. If you're getting the message from a midi file, this could be a time in seconds, or
  29348. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  29349. If the message is being used in a MidiBuffer, it might indicate the number of
  29350. audio samples from the start of the buffer.
  29351. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  29352. for details of the way that it initialises this value.
  29353. @see setTimeStamp, addToTimeStamp
  29354. */
  29355. double getTimeStamp() const throw() { return timeStamp; }
  29356. /** Changes the message's associated timestamp.
  29357. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  29358. @see addToTimeStamp, getTimeStamp
  29359. */
  29360. void setTimeStamp (double newTimestamp) throw() { timeStamp = newTimestamp; }
  29361. /** Adds a value to the message's timestamp.
  29362. The units for the timestamp will be application-specific.
  29363. */
  29364. void addToTimeStamp (double delta) throw() { timeStamp += delta; }
  29365. /** Returns the midi channel associated with the message.
  29366. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  29367. if it's a sysex)
  29368. @see isForChannel, setChannel
  29369. */
  29370. int getChannel() const throw();
  29371. /** Returns true if the message applies to the given midi channel.
  29372. @param channelNumber the channel number to look for, in the range 1 to 16
  29373. @see getChannel, setChannel
  29374. */
  29375. bool isForChannel (int channelNumber) const throw();
  29376. /** Changes the message's midi channel.
  29377. This won't do anything for non-channel messages like sysexes.
  29378. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  29379. */
  29380. void setChannel (int newChannelNumber) throw();
  29381. /** Returns true if this is a system-exclusive message.
  29382. */
  29383. bool isSysEx() const throw();
  29384. /** Returns a pointer to the sysex data inside the message.
  29385. If this event isn't a sysex event, it'll return 0.
  29386. @see getSysExDataSize
  29387. */
  29388. const uint8* getSysExData() const throw();
  29389. /** Returns the size of the sysex data.
  29390. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  29391. @see getSysExData
  29392. */
  29393. int getSysExDataSize() const throw();
  29394. /** Returns true if this message is a 'key-down' event.
  29395. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  29396. velocity 0, it will still be considered to be a note-on and the
  29397. method will return true. If returnTrueForVelocity0 is false, then
  29398. if this is a note-on event with velocity 0, it'll be regarded as
  29399. a note-off, and the method will return false
  29400. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  29401. */
  29402. bool isNoteOn (bool returnTrueForVelocity0 = false) const throw();
  29403. /** Creates a key-down message (using a floating-point velocity).
  29404. @param channel the midi channel, in the range 1 to 16
  29405. @param noteNumber the key number, 0 to 127
  29406. @param velocity in the range 0 to 1.0
  29407. @see isNoteOn
  29408. */
  29409. static const MidiMessage noteOn (int channel, int noteNumber, float velocity) throw();
  29410. /** Creates a key-down message (using an integer velocity).
  29411. @param channel the midi channel, in the range 1 to 16
  29412. @param noteNumber the key number, 0 to 127
  29413. @param velocity in the range 0 to 127
  29414. @see isNoteOn
  29415. */
  29416. static const MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) throw();
  29417. /** Returns true if this message is a 'key-up' event.
  29418. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  29419. for a note-on event with a velocity of 0.
  29420. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  29421. */
  29422. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const throw();
  29423. /** Creates a key-up message.
  29424. @param channel the midi channel, in the range 1 to 16
  29425. @param noteNumber the key number, 0 to 127
  29426. @see isNoteOff
  29427. */
  29428. static const MidiMessage noteOff (int channel, int noteNumber, uint8 velocity = 0) throw();
  29429. /** Returns true if this message is a 'key-down' or 'key-up' event.
  29430. @see isNoteOn, isNoteOff
  29431. */
  29432. bool isNoteOnOrOff() const throw();
  29433. /** Returns the midi note number for note-on and note-off messages.
  29434. If the message isn't a note-on or off, the value returned will be
  29435. meaningless.
  29436. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  29437. */
  29438. int getNoteNumber() const throw();
  29439. /** Changes the midi note number of a note-on or note-off message.
  29440. If the message isn't a note on or off, this will do nothing.
  29441. */
  29442. void setNoteNumber (int newNoteNumber) throw();
  29443. /** Returns the velocity of a note-on or note-off message.
  29444. The value returned will be in the range 0 to 127.
  29445. If the message isn't a note-on or off event, it will return 0.
  29446. @see getFloatVelocity
  29447. */
  29448. uint8 getVelocity() const throw();
  29449. /** Returns the velocity of a note-on or note-off message.
  29450. The value returned will be in the range 0 to 1.0
  29451. If the message isn't a note-on or off event, it will return 0.
  29452. @see getVelocity, setVelocity
  29453. */
  29454. float getFloatVelocity() const throw();
  29455. /** Changes the velocity of a note-on or note-off message.
  29456. If the message isn't a note on or off, this will do nothing.
  29457. @param newVelocity the new velocity, in the range 0 to 1.0
  29458. @see getFloatVelocity, multiplyVelocity
  29459. */
  29460. void setVelocity (float newVelocity) throw();
  29461. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  29462. If the message isn't a note on or off, this will do nothing.
  29463. @param scaleFactor the value by which to multiply the velocity
  29464. @see setVelocity
  29465. */
  29466. void multiplyVelocity (float scaleFactor) throw();
  29467. /** Returns true if the message is a program (patch) change message.
  29468. @see getProgramChangeNumber, getGMInstrumentName
  29469. */
  29470. bool isProgramChange() const throw();
  29471. /** Returns the new program number of a program change message.
  29472. If the message isn't a program change, the value returned will be
  29473. nonsense.
  29474. @see isProgramChange, getGMInstrumentName
  29475. */
  29476. int getProgramChangeNumber() const throw();
  29477. /** Creates a program-change message.
  29478. @param channel the midi channel, in the range 1 to 16
  29479. @param programNumber the midi program number, 0 to 127
  29480. @see isProgramChange, getGMInstrumentName
  29481. */
  29482. static const MidiMessage programChange (int channel, int programNumber) throw();
  29483. /** Returns true if the message is a pitch-wheel move.
  29484. @see getPitchWheelValue, pitchWheel
  29485. */
  29486. bool isPitchWheel() const throw();
  29487. /** Returns the pitch wheel position from a pitch-wheel move message.
  29488. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  29489. If called for messages which aren't pitch wheel events, the number returned will be
  29490. nonsense.
  29491. @see isPitchWheel
  29492. */
  29493. int getPitchWheelValue() const throw();
  29494. /** Creates a pitch-wheel move message.
  29495. @param channel the midi channel, in the range 1 to 16
  29496. @param position the wheel position, in the range 0 to 16383
  29497. @see isPitchWheel
  29498. */
  29499. static const MidiMessage pitchWheel (int channel, int position) throw();
  29500. /** Returns true if the message is an aftertouch event.
  29501. For aftertouch events, use the getNoteNumber() method to find out the key
  29502. that it applies to, and getAftertouchValue() to find out the amount. Use
  29503. getChannel() to find out the channel.
  29504. @see getAftertouchValue, getNoteNumber
  29505. */
  29506. bool isAftertouch() const throw();
  29507. /** Returns the amount of aftertouch from an aftertouch messages.
  29508. The value returned is in the range 0 to 127, and will be nonsense for messages
  29509. other than aftertouch messages.
  29510. @see isAftertouch
  29511. */
  29512. int getAfterTouchValue() const throw();
  29513. /** Creates an aftertouch message.
  29514. @param channel the midi channel, in the range 1 to 16
  29515. @param noteNumber the key number, 0 to 127
  29516. @param aftertouchAmount the amount of aftertouch, 0 to 127
  29517. @see isAftertouch
  29518. */
  29519. static const MidiMessage aftertouchChange (int channel,
  29520. int noteNumber,
  29521. int aftertouchAmount) throw();
  29522. /** Returns true if the message is a channel-pressure change event.
  29523. This is like aftertouch, but common to the whole channel rather than a specific
  29524. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  29525. to find out the channel.
  29526. @see channelPressureChange
  29527. */
  29528. bool isChannelPressure() const throw();
  29529. /** Returns the pressure from a channel pressure change message.
  29530. @returns the pressure, in the range 0 to 127
  29531. @see isChannelPressure, channelPressureChange
  29532. */
  29533. int getChannelPressureValue() const throw();
  29534. /** Creates a channel-pressure change event.
  29535. @param channel the midi channel: 1 to 16
  29536. @param pressure the pressure, 0 to 127
  29537. @see isChannelPressure
  29538. */
  29539. static const MidiMessage channelPressureChange (int channel, int pressure) throw();
  29540. /** Returns true if this is a midi controller message.
  29541. @see getControllerNumber, getControllerValue, controllerEvent
  29542. */
  29543. bool isController() const throw();
  29544. /** Returns the controller number of a controller message.
  29545. The name of the controller can be looked up using the getControllerName() method.
  29546. Note that the value returned is invalid for messages that aren't controller changes.
  29547. @see isController, getControllerName, getControllerValue
  29548. */
  29549. int getControllerNumber() const throw();
  29550. /** Returns the controller value from a controller message.
  29551. A value 0 to 127 is returned to indicate the new controller position.
  29552. Note that the value returned is invalid for messages that aren't controller changes.
  29553. @see isController, getControllerNumber
  29554. */
  29555. int getControllerValue() const throw();
  29556. /** Creates a controller message.
  29557. @param channel the midi channel, in the range 1 to 16
  29558. @param controllerType the type of controller
  29559. @param value the controller value
  29560. @see isController
  29561. */
  29562. static const MidiMessage controllerEvent (int channel,
  29563. int controllerType,
  29564. int value) throw();
  29565. /** Checks whether this message is an all-notes-off message.
  29566. @see allNotesOff
  29567. */
  29568. bool isAllNotesOff() const throw();
  29569. /** Checks whether this message is an all-sound-off message.
  29570. @see allSoundOff
  29571. */
  29572. bool isAllSoundOff() const throw();
  29573. /** Creates an all-notes-off message.
  29574. @param channel the midi channel, in the range 1 to 16
  29575. @see isAllNotesOff
  29576. */
  29577. static const MidiMessage allNotesOff (int channel) throw();
  29578. /** Creates an all-sound-off message.
  29579. @param channel the midi channel, in the range 1 to 16
  29580. @see isAllSoundOff
  29581. */
  29582. static const MidiMessage allSoundOff (int channel) throw();
  29583. /** Creates an all-controllers-off message.
  29584. @param channel the midi channel, in the range 1 to 16
  29585. */
  29586. static const MidiMessage allControllersOff (int channel) throw();
  29587. /** Returns true if this event is a meta-event.
  29588. Meta-events are things like tempo changes, track names, etc.
  29589. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  29590. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  29591. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  29592. */
  29593. bool isMetaEvent() const throw();
  29594. /** Returns a meta-event's type number.
  29595. If the message isn't a meta-event, this will return -1.
  29596. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  29597. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  29598. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  29599. */
  29600. int getMetaEventType() const throw();
  29601. /** Returns a pointer to the data in a meta-event.
  29602. @see isMetaEvent, getMetaEventLength
  29603. */
  29604. const uint8* getMetaEventData() const throw();
  29605. /** Returns the length of the data for a meta-event.
  29606. @see isMetaEvent, getMetaEventData
  29607. */
  29608. int getMetaEventLength() const throw();
  29609. /** Returns true if this is a 'track' meta-event. */
  29610. bool isTrackMetaEvent() const throw();
  29611. /** Returns true if this is an 'end-of-track' meta-event. */
  29612. bool isEndOfTrackMetaEvent() const throw();
  29613. /** Creates an end-of-track meta-event.
  29614. @see isEndOfTrackMetaEvent
  29615. */
  29616. static const MidiMessage endOfTrack() throw();
  29617. /** Returns true if this is an 'track name' meta-event.
  29618. You can use the getTextFromTextMetaEvent() method to get the track's name.
  29619. */
  29620. bool isTrackNameEvent() const throw();
  29621. /** Returns true if this is a 'text' meta-event.
  29622. @see getTextFromTextMetaEvent
  29623. */
  29624. bool isTextMetaEvent() const throw();
  29625. /** Returns the text from a text meta-event.
  29626. @see isTextMetaEvent
  29627. */
  29628. const String getTextFromTextMetaEvent() const;
  29629. /** Returns true if this is a 'tempo' meta-event.
  29630. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  29631. */
  29632. bool isTempoMetaEvent() const throw();
  29633. /** Returns the tick length from a tempo meta-event.
  29634. @param timeFormat the 16-bit time format value from the midi file's header.
  29635. @returns the tick length (in seconds).
  29636. @see isTempoMetaEvent
  29637. */
  29638. double getTempoMetaEventTickLength (short timeFormat) const throw();
  29639. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  29640. @see isTempoMetaEvent, getTempoMetaEventTickLength
  29641. */
  29642. double getTempoSecondsPerQuarterNote() const throw();
  29643. /** Creates a tempo meta-event.
  29644. @see isTempoMetaEvent
  29645. */
  29646. static const MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) throw();
  29647. /** Returns true if this is a 'time-signature' meta-event.
  29648. @see getTimeSignatureInfo
  29649. */
  29650. bool isTimeSignatureMetaEvent() const throw();
  29651. /** Returns the time-signature values from a time-signature meta-event.
  29652. @see isTimeSignatureMetaEvent
  29653. */
  29654. void getTimeSignatureInfo (int& numerator, int& denominator) const throw();
  29655. /** Creates a time-signature meta-event.
  29656. @see isTimeSignatureMetaEvent
  29657. */
  29658. static const MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  29659. /** Returns true if this is a 'key-signature' meta-event.
  29660. @see getKeySignatureNumberOfSharpsOrFlats
  29661. */
  29662. bool isKeySignatureMetaEvent() const throw();
  29663. /** Returns the key from a key-signature meta-event.
  29664. @see isKeySignatureMetaEvent
  29665. */
  29666. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  29667. /** Returns true if this is a 'channel' meta-event.
  29668. A channel meta-event specifies the midi channel that should be used
  29669. for subsequent meta-events.
  29670. @see getMidiChannelMetaEventChannel
  29671. */
  29672. bool isMidiChannelMetaEvent() const throw();
  29673. /** Returns the channel number from a channel meta-event.
  29674. @returns the channel, in the range 1 to 16.
  29675. @see isMidiChannelMetaEvent
  29676. */
  29677. int getMidiChannelMetaEventChannel() const throw();
  29678. /** Creates a midi channel meta-event.
  29679. @param channel the midi channel, in the range 1 to 16
  29680. @see isMidiChannelMetaEvent
  29681. */
  29682. static const MidiMessage midiChannelMetaEvent (int channel) throw();
  29683. /** Returns true if this is an active-sense message. */
  29684. bool isActiveSense() const throw();
  29685. /** Returns true if this is a midi start event.
  29686. @see midiStart
  29687. */
  29688. bool isMidiStart() const throw();
  29689. /** Creates a midi start event. */
  29690. static const MidiMessage midiStart() throw();
  29691. /** Returns true if this is a midi continue event.
  29692. @see midiContinue
  29693. */
  29694. bool isMidiContinue() const throw();
  29695. /** Creates a midi continue event. */
  29696. static const MidiMessage midiContinue() throw();
  29697. /** Returns true if this is a midi stop event.
  29698. @see midiStop
  29699. */
  29700. bool isMidiStop() const throw();
  29701. /** Creates a midi stop event. */
  29702. static const MidiMessage midiStop() throw();
  29703. /** Returns true if this is a midi clock event.
  29704. @see midiClock, songPositionPointer
  29705. */
  29706. bool isMidiClock() const throw();
  29707. /** Creates a midi clock event. */
  29708. static const MidiMessage midiClock() throw();
  29709. /** Returns true if this is a song-position-pointer message.
  29710. @see getSongPositionPointerMidiBeat, songPositionPointer
  29711. */
  29712. bool isSongPositionPointer() const throw();
  29713. /** Returns the midi beat-number of a song-position-pointer message.
  29714. @see isSongPositionPointer, songPositionPointer
  29715. */
  29716. int getSongPositionPointerMidiBeat() const throw();
  29717. /** Creates a song-position-pointer message.
  29718. The position is a number of midi beats from the start of the song, where 1 midi
  29719. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  29720. are 4 midi beats in a quarter-note.
  29721. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  29722. */
  29723. static const MidiMessage songPositionPointer (int positionInMidiBeats) throw();
  29724. /** Returns true if this is a quarter-frame midi timecode message.
  29725. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  29726. */
  29727. bool isQuarterFrame() const throw();
  29728. /** Returns the sequence number of a quarter-frame midi timecode message.
  29729. This will be a value between 0 and 7.
  29730. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  29731. */
  29732. int getQuarterFrameSequenceNumber() const throw();
  29733. /** Returns the value from a quarter-frame message.
  29734. This will be the lower nybble of the message's data-byte, a value
  29735. between 0 and 15
  29736. */
  29737. int getQuarterFrameValue() const throw();
  29738. /** Creates a quarter-frame MTC message.
  29739. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  29740. @param value a value 0 to 15 for the lower nybble of the message's data byte
  29741. */
  29742. static const MidiMessage quarterFrame (int sequenceNumber, int value) throw();
  29743. /** SMPTE timecode types.
  29744. Used by the getFullFrameParameters() and fullFrame() methods.
  29745. */
  29746. enum SmpteTimecodeType
  29747. {
  29748. fps24 = 0,
  29749. fps25 = 1,
  29750. fps30drop = 2,
  29751. fps30 = 3
  29752. };
  29753. /** Returns true if this is a full-frame midi timecode message.
  29754. */
  29755. bool isFullFrame() const throw();
  29756. /** Extracts the timecode information from a full-frame midi timecode message.
  29757. You should only call this on messages where you've used isFullFrame() to
  29758. check that they're the right kind.
  29759. */
  29760. void getFullFrameParameters (int& hours,
  29761. int& minutes,
  29762. int& seconds,
  29763. int& frames,
  29764. SmpteTimecodeType& timecodeType) const throw();
  29765. /** Creates a full-frame MTC message.
  29766. */
  29767. static const MidiMessage fullFrame (int hours,
  29768. int minutes,
  29769. int seconds,
  29770. int frames,
  29771. SmpteTimecodeType timecodeType);
  29772. /** Types of MMC command.
  29773. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  29774. */
  29775. enum MidiMachineControlCommand
  29776. {
  29777. mmc_stop = 1,
  29778. mmc_play = 2,
  29779. mmc_deferredplay = 3,
  29780. mmc_fastforward = 4,
  29781. mmc_rewind = 5,
  29782. mmc_recordStart = 6,
  29783. mmc_recordStop = 7,
  29784. mmc_pause = 9
  29785. };
  29786. /** Checks whether this is an MMC message.
  29787. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  29788. */
  29789. bool isMidiMachineControlMessage() const throw();
  29790. /** For an MMC message, this returns its type.
  29791. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  29792. calling this method.
  29793. */
  29794. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  29795. /** Creates an MMC message.
  29796. */
  29797. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  29798. /** Checks whether this is an MMC "goto" message.
  29799. If it is, the parameters passed-in are set to the time that the message contains.
  29800. @see midiMachineControlGoto
  29801. */
  29802. bool isMidiMachineControlGoto (int& hours,
  29803. int& minutes,
  29804. int& seconds,
  29805. int& frames) const throw();
  29806. /** Creates an MMC "goto" message.
  29807. This messages tells the device to go to a specific frame.
  29808. @see isMidiMachineControlGoto
  29809. */
  29810. static const MidiMessage midiMachineControlGoto (int hours,
  29811. int minutes,
  29812. int seconds,
  29813. int frames);
  29814. /** Creates a master-volume change message.
  29815. @param volume the volume, 0 to 1.0
  29816. */
  29817. static const MidiMessage masterVolume (float volume);
  29818. /** Creates a system-exclusive message.
  29819. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  29820. */
  29821. static const MidiMessage createSysExMessage (const uint8* sysexData,
  29822. int dataSize);
  29823. /** Reads a midi variable-length integer.
  29824. @param data the data to read the number from
  29825. @param numBytesUsed on return, this will be set to the number of bytes that were read
  29826. */
  29827. static int readVariableLengthVal (const uint8* data,
  29828. int& numBytesUsed) throw();
  29829. /** Based on the first byte of a short midi message, this uses a lookup table
  29830. to return the message length (either 1, 2, or 3 bytes).
  29831. The value passed in must be 0x80 or higher.
  29832. */
  29833. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  29834. /** Returns the name of a midi note number.
  29835. E.g "C", "D#", etc.
  29836. @param noteNumber the midi note number, 0 to 127
  29837. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  29838. they'll be flattened, e.g. "Db"
  29839. @param includeOctaveNumber if true, the octave number will be appended to the string,
  29840. e.g. "C#4"
  29841. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  29842. number that will be used for middle C's octave
  29843. @see getMidiNoteInHertz
  29844. */
  29845. static const String getMidiNoteName (int noteNumber,
  29846. bool useSharps,
  29847. bool includeOctaveNumber,
  29848. int octaveNumForMiddleC);
  29849. /** Returns the frequency of a midi note number.
  29850. The frequencyOfA parameter is an optional frequency for 'A', normally 440-444Hz for concert pitch.
  29851. @see getMidiNoteName
  29852. */
  29853. static const double getMidiNoteInHertz (int noteNumber, const double frequencyOfA = 440.0) throw();
  29854. /** Returns the standard name of a GM instrument.
  29855. @param midiInstrumentNumber the program number 0 to 127
  29856. @see getProgramChangeNumber
  29857. */
  29858. static const String getGMInstrumentName (int midiInstrumentNumber);
  29859. /** Returns the name of a bank of GM instruments.
  29860. @param midiBankNumber the bank, 0 to 15
  29861. */
  29862. static const String getGMInstrumentBankName (int midiBankNumber);
  29863. /** Returns the standard name of a channel 10 percussion sound.
  29864. @param midiNoteNumber the key number, 35 to 81
  29865. */
  29866. static const String getRhythmInstrumentName (int midiNoteNumber);
  29867. /** Returns the name of a controller type number.
  29868. @see getControllerNumber
  29869. */
  29870. static const String getControllerName (int controllerNumber);
  29871. private:
  29872. double timeStamp;
  29873. uint8* data;
  29874. int size;
  29875. #ifndef DOXYGEN
  29876. union
  29877. {
  29878. uint8 asBytes[4];
  29879. uint32 asInt32;
  29880. } preallocatedData;
  29881. #endif
  29882. };
  29883. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  29884. /*** End of inlined file: juce_MidiMessage.h ***/
  29885. class MidiInput;
  29886. /**
  29887. Receives incoming messages from a physical MIDI input device.
  29888. This class is overridden to handle incoming midi messages. See the MidiInput
  29889. class for more details.
  29890. @see MidiInput
  29891. */
  29892. class JUCE_API MidiInputCallback
  29893. {
  29894. public:
  29895. /** Destructor. */
  29896. virtual ~MidiInputCallback() {}
  29897. /** Receives an incoming message.
  29898. A MidiInput object will call this method when a midi event arrives. It'll be
  29899. called on a high-priority system thread, so avoid doing anything time-consuming
  29900. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  29901. for queueing incoming messages for use later.
  29902. @param source the MidiInput object that generated the message
  29903. @param message the incoming message. The message's timestamp is set to a value
  29904. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  29905. time when the message arrived.
  29906. */
  29907. virtual void handleIncomingMidiMessage (MidiInput* source,
  29908. const MidiMessage& message) = 0;
  29909. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  29910. If a long sysex message is broken up into multiple packets, this callback is made
  29911. for each packet that arrives until the message is finished, at which point
  29912. the normal handleIncomingMidiMessage() callback will be made with the entire
  29913. message.
  29914. The message passed in will contain the start of a sysex, but won't be finished
  29915. with the terminating 0xf7 byte.
  29916. */
  29917. virtual void handlePartialSysexMessage (MidiInput* source,
  29918. const uint8* messageData,
  29919. const int numBytesSoFar,
  29920. const double timestamp)
  29921. {
  29922. // (this bit is just to avoid compiler warnings about unused variables)
  29923. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  29924. }
  29925. };
  29926. /**
  29927. Represents a midi input device.
  29928. To create one of these, use the static getDevices() method to find out what inputs are
  29929. available, and then use the openDevice() method to try to open one.
  29930. @see MidiOutput
  29931. */
  29932. class JUCE_API MidiInput
  29933. {
  29934. public:
  29935. /** Returns a list of the available midi input devices.
  29936. You can open one of the devices by passing its index into the
  29937. openDevice() method.
  29938. @see getDefaultDeviceIndex, openDevice
  29939. */
  29940. static const StringArray getDevices();
  29941. /** Returns the index of the default midi input device to use.
  29942. This refers to the index in the list returned by getDevices().
  29943. */
  29944. static int getDefaultDeviceIndex();
  29945. /** Tries to open one of the midi input devices.
  29946. This will return a MidiInput object if it manages to open it. You can then
  29947. call start() and stop() on this device, and delete it when no longer needed.
  29948. If the device can't be opened, this will return a null pointer.
  29949. @param deviceIndex the index of a device from the list returned by getDevices()
  29950. @param callback the object that will receive the midi messages from this device.
  29951. @see MidiInputCallback, getDevices
  29952. */
  29953. static MidiInput* openDevice (int deviceIndex,
  29954. MidiInputCallback* callback);
  29955. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  29956. /** This will try to create a new midi input device (Not available on Windows).
  29957. This will attempt to create a new midi input device with the specified name,
  29958. for other apps to connect to.
  29959. Returns 0 if a device can't be created.
  29960. @param deviceName the name to use for the new device
  29961. @param callback the object that will receive the midi messages from this device.
  29962. */
  29963. static MidiInput* createNewDevice (const String& deviceName,
  29964. MidiInputCallback* callback);
  29965. #endif
  29966. /** Destructor. */
  29967. virtual ~MidiInput();
  29968. /** Returns the name of this device.
  29969. */
  29970. virtual const String getName() const throw() { return name; }
  29971. /** Allows you to set a custom name for the device, in case you don't like the name
  29972. it was given when created.
  29973. */
  29974. virtual void setName (const String& newName) throw() { name = newName; }
  29975. /** Starts the device running.
  29976. After calling this, the device will start sending midi messages to the
  29977. MidiInputCallback object that was specified when the openDevice() method
  29978. was called.
  29979. @see stop
  29980. */
  29981. virtual void start();
  29982. /** Stops the device running.
  29983. @see start
  29984. */
  29985. virtual void stop();
  29986. protected:
  29987. String name;
  29988. void* internal;
  29989. explicit MidiInput (const String& name);
  29990. private:
  29991. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInput);
  29992. };
  29993. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  29994. /*** End of inlined file: juce_MidiInput.h ***/
  29995. /*** Start of inlined file: juce_MidiOutput.h ***/
  29996. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  29997. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  29998. /*** Start of inlined file: juce_MidiBuffer.h ***/
  29999. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  30000. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  30001. /**
  30002. Holds a sequence of time-stamped midi events.
  30003. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  30004. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  30005. @see MidiMessage
  30006. */
  30007. class JUCE_API MidiBuffer
  30008. {
  30009. public:
  30010. /** Creates an empty MidiBuffer. */
  30011. MidiBuffer() throw();
  30012. /** Creates a MidiBuffer containing a single midi message. */
  30013. explicit MidiBuffer (const MidiMessage& message) throw();
  30014. /** Creates a copy of another MidiBuffer. */
  30015. MidiBuffer (const MidiBuffer& other) throw();
  30016. /** Makes a copy of another MidiBuffer. */
  30017. MidiBuffer& operator= (const MidiBuffer& other) throw();
  30018. /** Destructor */
  30019. ~MidiBuffer();
  30020. /** Removes all events from the buffer. */
  30021. void clear() throw();
  30022. /** Removes all events between two times from the buffer.
  30023. All events for which (start <= event position < start + numSamples) will
  30024. be removed.
  30025. */
  30026. void clear (int start, int numSamples);
  30027. /** Returns true if the buffer is empty.
  30028. To actually retrieve the events, use a MidiBuffer::Iterator object
  30029. */
  30030. bool isEmpty() const throw();
  30031. /** Counts the number of events in the buffer.
  30032. This is actually quite a slow operation, as it has to iterate through all
  30033. the events, so you might prefer to call isEmpty() if that's all you need
  30034. to know.
  30035. */
  30036. int getNumEvents() const throw();
  30037. /** Adds an event to the buffer.
  30038. The sample number will be used to determine the position of the event in
  30039. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  30040. ignored.
  30041. If an event is added whose sample position is the same as one or more events
  30042. already in the buffer, the new event will be placed after the existing ones.
  30043. To retrieve events, use a MidiBuffer::Iterator object
  30044. */
  30045. void addEvent (const MidiMessage& midiMessage, int sampleNumber);
  30046. /** Adds an event to the buffer from raw midi data.
  30047. The sample number will be used to determine the position of the event in
  30048. the buffer, which is always kept sorted.
  30049. If an event is added whose sample position is the same as one or more events
  30050. already in the buffer, the new event will be placed after the existing ones.
  30051. The event data will be inspected to calculate the number of bytes in length that
  30052. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  30053. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  30054. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  30055. add an event at all.
  30056. To retrieve events, use a MidiBuffer::Iterator object
  30057. */
  30058. void addEvent (const void* rawMidiData,
  30059. int maxBytesOfMidiData,
  30060. int sampleNumber);
  30061. /** Adds some events from another buffer to this one.
  30062. @param otherBuffer the buffer containing the events you want to add
  30063. @param startSample the lowest sample number in the source buffer for which
  30064. events should be added. Any source events whose timestamp is
  30065. less than this will be ignored
  30066. @param numSamples the valid range of samples from the source buffer for which
  30067. events should be added - i.e. events in the source buffer whose
  30068. timestamp is greater than or equal to (startSample + numSamples)
  30069. will be ignored. If this value is less than 0, all events after
  30070. startSample will be taken.
  30071. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  30072. that are added to this buffer
  30073. */
  30074. void addEvents (const MidiBuffer& otherBuffer,
  30075. int startSample,
  30076. int numSamples,
  30077. int sampleDeltaToAdd);
  30078. /** Returns the sample number of the first event in the buffer.
  30079. If the buffer's empty, this will just return 0.
  30080. */
  30081. int getFirstEventTime() const throw();
  30082. /** Returns the sample number of the last event in the buffer.
  30083. If the buffer's empty, this will just return 0.
  30084. */
  30085. int getLastEventTime() const throw();
  30086. /** Exchanges the contents of this buffer with another one.
  30087. This is a quick operation, because no memory allocating or copying is done, it
  30088. just swaps the internal state of the two buffers.
  30089. */
  30090. void swapWith (MidiBuffer& other) throw();
  30091. /** Preallocates some memory for the buffer to use.
  30092. This helps to avoid needing to reallocate space when the buffer has messages
  30093. added to it.
  30094. */
  30095. void ensureSize (size_t minimumNumBytes);
  30096. /**
  30097. Used to iterate through the events in a MidiBuffer.
  30098. Note that altering the buffer while an iterator is using it isn't a
  30099. safe operation.
  30100. @see MidiBuffer
  30101. */
  30102. class JUCE_API Iterator
  30103. {
  30104. public:
  30105. /** Creates an Iterator for this MidiBuffer. */
  30106. Iterator (const MidiBuffer& buffer) throw();
  30107. /** Destructor. */
  30108. ~Iterator() throw();
  30109. /** Repositions the iterator so that the next event retrieved will be the first
  30110. one whose sample position is at greater than or equal to the given position.
  30111. */
  30112. void setNextSamplePosition (int samplePosition) throw();
  30113. /** Retrieves a copy of the next event from the buffer.
  30114. @param result on return, this will be the message (the MidiMessage's timestamp
  30115. is not set)
  30116. @param samplePosition on return, this will be the position of the event
  30117. @returns true if an event was found, or false if the iterator has reached
  30118. the end of the buffer
  30119. */
  30120. bool getNextEvent (MidiMessage& result,
  30121. int& samplePosition) throw();
  30122. /** Retrieves the next event from the buffer.
  30123. @param midiData on return, this pointer will be set to a block of data containing
  30124. the midi message. Note that to make it fast, this is a pointer
  30125. directly into the MidiBuffer's internal data, so is only valid
  30126. temporarily until the MidiBuffer is altered.
  30127. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  30128. midi message
  30129. @param samplePosition on return, this will be the position of the event
  30130. @returns true if an event was found, or false if the iterator has reached
  30131. the end of the buffer
  30132. */
  30133. bool getNextEvent (const uint8* &midiData,
  30134. int& numBytesOfMidiData,
  30135. int& samplePosition) throw();
  30136. private:
  30137. const MidiBuffer& buffer;
  30138. const uint8* data;
  30139. JUCE_DECLARE_NON_COPYABLE (Iterator);
  30140. };
  30141. private:
  30142. friend class MidiBuffer::Iterator;
  30143. MemoryBlock data;
  30144. int bytesUsed;
  30145. uint8* getData() const throw();
  30146. uint8* findEventAfter (uint8* d, int samplePosition) const throw();
  30147. static int getEventTime (const void* d) throw();
  30148. static uint16 getEventDataSize (const void* d) throw();
  30149. static uint16 getEventTotalSize (const void* d) throw();
  30150. JUCE_LEAK_DETECTOR (MidiBuffer);
  30151. };
  30152. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  30153. /*** End of inlined file: juce_MidiBuffer.h ***/
  30154. /**
  30155. Controls a physical MIDI output device.
  30156. To create one of these, use the static getDevices() method to get a list of the
  30157. available output devices, then use the openDevice() method to try to open one.
  30158. @see MidiInput
  30159. */
  30160. class JUCE_API MidiOutput : private Thread
  30161. {
  30162. public:
  30163. /** Returns a list of the available midi output devices.
  30164. You can open one of the devices by passing its index into the
  30165. openDevice() method.
  30166. @see getDefaultDeviceIndex, openDevice
  30167. */
  30168. static const StringArray getDevices();
  30169. /** Returns the index of the default midi output device to use.
  30170. This refers to the index in the list returned by getDevices().
  30171. */
  30172. static int getDefaultDeviceIndex();
  30173. /** Tries to open one of the midi output devices.
  30174. This will return a MidiOutput object if it manages to open it. You can then
  30175. send messages to this device, and delete it when no longer needed.
  30176. If the device can't be opened, this will return a null pointer.
  30177. @param deviceIndex the index of a device from the list returned by getDevices()
  30178. @see getDevices
  30179. */
  30180. static MidiOutput* openDevice (int deviceIndex);
  30181. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  30182. /** This will try to create a new midi output device (Not available on Windows).
  30183. This will attempt to create a new midi output device that other apps can connect
  30184. to and use as their midi input.
  30185. Returns 0 if a device can't be created.
  30186. @param deviceName the name to use for the new device
  30187. */
  30188. static MidiOutput* createNewDevice (const String& deviceName);
  30189. #endif
  30190. /** Destructor. */
  30191. virtual ~MidiOutput();
  30192. /** Makes this device output a midi message.
  30193. @see MidiMessage
  30194. */
  30195. virtual void sendMessageNow (const MidiMessage& message);
  30196. /** Sends a midi reset to the device. */
  30197. virtual void reset();
  30198. /** Returns the current volume setting for this device. */
  30199. virtual bool getVolume (float& leftVol,
  30200. float& rightVol);
  30201. /** Changes the overall volume for this device. */
  30202. virtual void setVolume (float leftVol,
  30203. float rightVol);
  30204. /** This lets you supply a block of messages that will be sent out at some point
  30205. in the future.
  30206. The MidiOutput class has an internal thread that can send out timestamped
  30207. messages - this appends a set of messages to its internal buffer, ready for
  30208. sending.
  30209. This will only work if you've already started the thread with startBackgroundThread().
  30210. A time is supplied, at which the block of messages should be sent. This time uses
  30211. the same time base as Time::getMillisecondCounter(), and must be in the future.
  30212. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  30213. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  30214. samplesPerSecondForBuffer value is needed to convert this sample position to a
  30215. real time.
  30216. */
  30217. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  30218. double millisecondCounterToStartAt,
  30219. double samplesPerSecondForBuffer);
  30220. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  30221. */
  30222. virtual void clearAllPendingMessages();
  30223. /** Starts up a background thread so that the device can send blocks of data.
  30224. Call this to get the device ready, before using sendBlockOfMessages().
  30225. */
  30226. virtual void startBackgroundThread();
  30227. /** Stops the background thread, and clears any pending midi events.
  30228. @see startBackgroundThread
  30229. */
  30230. virtual void stopBackgroundThread();
  30231. protected:
  30232. void* internal;
  30233. struct PendingMessage
  30234. {
  30235. PendingMessage (const void* data, int len, double timeStamp);
  30236. MidiMessage message;
  30237. PendingMessage* next;
  30238. };
  30239. CriticalSection lock;
  30240. PendingMessage* firstMessage;
  30241. MidiOutput();
  30242. void run();
  30243. private:
  30244. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutput);
  30245. };
  30246. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  30247. /*** End of inlined file: juce_MidiOutput.h ***/
  30248. /*** Start of inlined file: juce_ComboBox.h ***/
  30249. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  30250. #define __JUCE_COMBOBOX_JUCEHEADER__
  30251. /*** Start of inlined file: juce_Label.h ***/
  30252. #ifndef __JUCE_LABEL_JUCEHEADER__
  30253. #define __JUCE_LABEL_JUCEHEADER__
  30254. /*** Start of inlined file: juce_TextEditor.h ***/
  30255. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  30256. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  30257. /*** Start of inlined file: juce_Viewport.h ***/
  30258. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  30259. #define __JUCE_VIEWPORT_JUCEHEADER__
  30260. /*** Start of inlined file: juce_ScrollBar.h ***/
  30261. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  30262. #define __JUCE_SCROLLBAR_JUCEHEADER__
  30263. /*** Start of inlined file: juce_Button.h ***/
  30264. #ifndef __JUCE_BUTTON_JUCEHEADER__
  30265. #define __JUCE_BUTTON_JUCEHEADER__
  30266. /*** Start of inlined file: juce_TooltipWindow.h ***/
  30267. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  30268. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  30269. /*** Start of inlined file: juce_TooltipClient.h ***/
  30270. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  30271. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  30272. /**
  30273. Components that want to use pop-up tooltips should implement this interface.
  30274. A TooltipWindow will wait for the mouse to hover over a component that
  30275. implements the TooltipClient interface, and when it finds one, it will display
  30276. the tooltip returned by its getTooltip() method.
  30277. @see TooltipWindow, SettableTooltipClient
  30278. */
  30279. class JUCE_API TooltipClient
  30280. {
  30281. public:
  30282. /** Destructor. */
  30283. virtual ~TooltipClient() {}
  30284. /** Returns the string that this object wants to show as its tooltip. */
  30285. virtual const String getTooltip() = 0;
  30286. };
  30287. /**
  30288. An implementation of TooltipClient that stores the tooltip string and a method
  30289. for changing it.
  30290. This makes it easy to add a tooltip to a custom component, by simply adding this
  30291. as a base class and calling setTooltip().
  30292. Many of the Juce widgets already use this as a base class to implement their
  30293. tooltips.
  30294. @see TooltipClient, TooltipWindow
  30295. */
  30296. class JUCE_API SettableTooltipClient : public TooltipClient
  30297. {
  30298. public:
  30299. /** Destructor. */
  30300. virtual ~SettableTooltipClient() {}
  30301. /** Assigns a new tooltip to this object. */
  30302. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  30303. /** Returns the tooltip assigned to this object. */
  30304. virtual const String getTooltip() { return tooltipString; }
  30305. protected:
  30306. SettableTooltipClient() {}
  30307. private:
  30308. String tooltipString;
  30309. };
  30310. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  30311. /*** End of inlined file: juce_TooltipClient.h ***/
  30312. /**
  30313. A window that displays a pop-up tooltip when the mouse hovers over another component.
  30314. To enable tooltips in your app, just create a single instance of a TooltipWindow
  30315. object.
  30316. The TooltipWindow object will then stay invisible, waiting until the mouse
  30317. hovers for the specified length of time - it will then see if it's currently
  30318. over a component which implements the TooltipClient interface, and if so,
  30319. it will make itself visible to show the tooltip in the appropriate place.
  30320. @see TooltipClient, SettableTooltipClient
  30321. */
  30322. class JUCE_API TooltipWindow : public Component,
  30323. private Timer
  30324. {
  30325. public:
  30326. /** Creates a tooltip window.
  30327. Make sure your app only creates one instance of this class, otherwise you'll
  30328. get multiple overlaid tooltips appearing. The window will initially be invisible
  30329. and will make itself visible when it needs to display a tip.
  30330. To change the style of tooltips, see the LookAndFeel class for its tooltip
  30331. methods.
  30332. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  30333. otherwise the tooltip will be added to the given parent
  30334. component.
  30335. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  30336. before a tooltip will be shown
  30337. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  30338. */
  30339. explicit TooltipWindow (Component* parentComponent = 0,
  30340. int millisecondsBeforeTipAppears = 700);
  30341. /** Destructor. */
  30342. ~TooltipWindow();
  30343. /** Changes the time before the tip appears.
  30344. This lets you change the value that was set in the constructor.
  30345. */
  30346. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) throw();
  30347. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  30348. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30349. methods.
  30350. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30351. */
  30352. enum ColourIds
  30353. {
  30354. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  30355. textColourId = 0x1001c00, /**< The colour to use for the text. */
  30356. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  30357. };
  30358. private:
  30359. int millisecondsBeforeTipAppears;
  30360. Point<int> lastMousePos;
  30361. int mouseClicks;
  30362. unsigned int lastCompChangeTime, lastHideTime;
  30363. Component* lastComponentUnderMouse;
  30364. bool changedCompsSinceShown;
  30365. String tipShowing, lastTipUnderMouse;
  30366. void paint (Graphics& g);
  30367. void mouseEnter (const MouseEvent& e);
  30368. void timerCallback();
  30369. static const String getTipFor (Component* c);
  30370. void showFor (const String& tip);
  30371. void hide();
  30372. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TooltipWindow);
  30373. };
  30374. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  30375. /*** End of inlined file: juce_TooltipWindow.h ***/
  30376. #if JUCE_VC6
  30377. #define Listener ButtonListener
  30378. #endif
  30379. /**
  30380. A base class for buttons.
  30381. This contains all the logic for button behaviours such as enabling/disabling,
  30382. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  30383. and radio groups, etc.
  30384. @see TextButton, DrawableButton, ToggleButton
  30385. */
  30386. class JUCE_API Button : public Component,
  30387. public SettableTooltipClient,
  30388. public ApplicationCommandManagerListener,
  30389. public ValueListener,
  30390. private KeyListener
  30391. {
  30392. protected:
  30393. /** Creates a button.
  30394. @param buttonName the text to put in the button (the component's name is also
  30395. initially set to this string, but these can be changed later
  30396. using the setName() and setButtonText() methods)
  30397. */
  30398. explicit Button (const String& buttonName);
  30399. public:
  30400. /** Destructor. */
  30401. virtual ~Button();
  30402. /** Changes the button's text.
  30403. @see getButtonText
  30404. */
  30405. void setButtonText (const String& newText);
  30406. /** Returns the text displayed in the button.
  30407. @see setButtonText
  30408. */
  30409. const String getButtonText() const { return text; }
  30410. /** Returns true if the button is currently being held down by the mouse.
  30411. @see isOver
  30412. */
  30413. bool isDown() const throw();
  30414. /** Returns true if the mouse is currently over the button.
  30415. This will be also be true if the mouse is being held down.
  30416. @see isDown
  30417. */
  30418. bool isOver() const throw();
  30419. /** A button has an on/off state associated with it, and this changes that.
  30420. By default buttons are 'off' and for simple buttons that you click to perform
  30421. an action you won't change this. Toggle buttons, however will want to
  30422. change their state when turned on or off.
  30423. @param shouldBeOn whether to set the button's toggle state to be on or
  30424. off. If it's a member of a button group, this will
  30425. always try to turn it on, and to turn off any other
  30426. buttons in the group
  30427. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  30428. the button will be repainted but no notification will
  30429. be sent
  30430. @see getToggleState, setRadioGroupId
  30431. */
  30432. void setToggleState (bool shouldBeOn,
  30433. bool sendChangeNotification);
  30434. /** Returns true if the button in 'on'.
  30435. By default buttons are 'off' and for simple buttons that you click to perform
  30436. an action you won't change this. Toggle buttons, however will want to
  30437. change their state when turned on or off.
  30438. @see setToggleState
  30439. */
  30440. bool getToggleState() const throw() { return isOn.getValue(); }
  30441. /** Returns the Value object that represents the botton's toggle state.
  30442. You can use this Value object to connect the button's state to external values or setters,
  30443. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  30444. your own Value object.
  30445. @see getToggleState, Value
  30446. */
  30447. Value& getToggleStateValue() { return isOn; }
  30448. /** This tells the button to automatically flip the toggle state when
  30449. the button is clicked.
  30450. If set to true, then before the clicked() callback occurs, the toggle-state
  30451. of the button is flipped.
  30452. */
  30453. void setClickingTogglesState (bool shouldToggle) throw();
  30454. /** Returns true if this button is set to be an automatic toggle-button.
  30455. This returns the last value that was passed to setClickingTogglesState().
  30456. */
  30457. bool getClickingTogglesState() const throw();
  30458. /** Enables the button to act as a member of a mutually-exclusive group
  30459. of 'radio buttons'.
  30460. If the group ID is set to a non-zero number, then this button will
  30461. act as part of a group of buttons with the same ID, only one of
  30462. which can be 'on' at the same time. Note that when it's part of
  30463. a group, clicking a toggle-button that's 'on' won't turn it off.
  30464. To find other buttons with the same ID, this button will search through
  30465. its sibling components for ToggleButtons, so all the buttons for a
  30466. particular group must be placed inside the same parent component.
  30467. Set the group ID back to zero if you want it to act as a normal toggle
  30468. button again.
  30469. @see getRadioGroupId
  30470. */
  30471. void setRadioGroupId (int newGroupId);
  30472. /** Returns the ID of the group to which this button belongs.
  30473. (See setRadioGroupId() for an explanation of this).
  30474. */
  30475. int getRadioGroupId() const throw() { return radioGroupId; }
  30476. /**
  30477. Used to receive callbacks when a button is clicked.
  30478. @see Button::addListener, Button::removeListener
  30479. */
  30480. class JUCE_API Listener
  30481. {
  30482. public:
  30483. /** Destructor. */
  30484. virtual ~Listener() {}
  30485. /** Called when the button is clicked. */
  30486. virtual void buttonClicked (Button* button) = 0;
  30487. /** Called when the button's state changes. */
  30488. virtual void buttonStateChanged (Button*) {}
  30489. };
  30490. /** Registers a listener to receive events when this button's state changes.
  30491. If the listener is already registered, this will not register it again.
  30492. @see removeListener
  30493. */
  30494. void addListener (Listener* newListener);
  30495. /** Removes a previously-registered button listener
  30496. @see addListener
  30497. */
  30498. void removeListener (Listener* listener);
  30499. /** Causes the button to act as if it's been clicked.
  30500. This will asynchronously make the button draw itself going down and up, and
  30501. will then call back the clicked() method as if mouse was clicked on it.
  30502. @see clicked
  30503. */
  30504. virtual void triggerClick();
  30505. /** Sets a command ID for this button to automatically invoke when it's clicked.
  30506. When the button is pressed, it will use the given manager to trigger the
  30507. command ID.
  30508. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  30509. before this button is. To disable the command triggering, call this method and
  30510. pass 0 for the parameters.
  30511. If generateTooltip is true, then the button's tooltip will be automatically
  30512. generated based on the name of this command and its current shortcut key.
  30513. @see addShortcut, getCommandID
  30514. */
  30515. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  30516. int commandID,
  30517. bool generateTooltip);
  30518. /** Returns the command ID that was set by setCommandToTrigger().
  30519. */
  30520. int getCommandID() const throw() { return commandID; }
  30521. /** Assigns a shortcut key to trigger the button.
  30522. The button registers itself with its top-level parent component for keypresses.
  30523. Note that a different way of linking buttons to keypresses is by using the
  30524. setCommandToTrigger() method to invoke a command.
  30525. @see clearShortcuts
  30526. */
  30527. void addShortcut (const KeyPress& key);
  30528. /** Removes all key shortcuts that had been set for this button.
  30529. @see addShortcut
  30530. */
  30531. void clearShortcuts();
  30532. /** Returns true if the given keypress is a shortcut for this button.
  30533. @see addShortcut
  30534. */
  30535. bool isRegisteredForShortcut (const KeyPress& key) const;
  30536. /** Sets an auto-repeat speed for the button when it is held down.
  30537. (Auto-repeat is disabled by default).
  30538. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  30539. triggering the next click. If this is zero, auto-repeat
  30540. is disabled
  30541. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  30542. triggered
  30543. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  30544. get faster, the longer the button is held down, up to the
  30545. minimum interval specified here
  30546. */
  30547. void setRepeatSpeed (int initialDelayInMillisecs,
  30548. int repeatDelayInMillisecs,
  30549. int minimumDelayInMillisecs = -1) throw();
  30550. /** Sets whether the button click should happen when the mouse is pressed or released.
  30551. By default the button is only considered to have been clicked when the mouse is
  30552. released, but setting this to true will make it call the clicked() method as soon
  30553. as the button is pressed.
  30554. This is useful if the button is being used to show a pop-up menu, as it allows
  30555. the click to be used as a drag onto the menu.
  30556. */
  30557. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) throw();
  30558. /** Returns the number of milliseconds since the last time the button
  30559. went into the 'down' state.
  30560. */
  30561. uint32 getMillisecondsSinceButtonDown() const throw();
  30562. /** Sets the tooltip for this button.
  30563. @see TooltipClient, TooltipWindow
  30564. */
  30565. void setTooltip (const String& newTooltip);
  30566. // (implementation of the TooltipClient method)
  30567. const String getTooltip();
  30568. /** A combination of these flags are used by setConnectedEdges().
  30569. */
  30570. enum ConnectedEdgeFlags
  30571. {
  30572. ConnectedOnLeft = 1,
  30573. ConnectedOnRight = 2,
  30574. ConnectedOnTop = 4,
  30575. ConnectedOnBottom = 8
  30576. };
  30577. /** Hints about which edges of the button might be connected to adjoining buttons.
  30578. The value passed in is a bitwise combination of any of the values in the
  30579. ConnectedEdgeFlags enum.
  30580. E.g. if you are placing two buttons adjacent to each other, you could use this to
  30581. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  30582. without rounded corners on the edges that connect. It's only a hint, so the
  30583. LookAndFeel can choose to ignore it if it's not relevent for this type of
  30584. button.
  30585. */
  30586. void setConnectedEdges (int connectedEdgeFlags);
  30587. /** Returns the set of flags passed into setConnectedEdges(). */
  30588. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  30589. /** Indicates whether the button adjoins another one on its left edge.
  30590. @see setConnectedEdges
  30591. */
  30592. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  30593. /** Indicates whether the button adjoins another one on its right edge.
  30594. @see setConnectedEdges
  30595. */
  30596. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  30597. /** Indicates whether the button adjoins another one on its top edge.
  30598. @see setConnectedEdges
  30599. */
  30600. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  30601. /** Indicates whether the button adjoins another one on its bottom edge.
  30602. @see setConnectedEdges
  30603. */
  30604. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  30605. /** Used by setState(). */
  30606. enum ButtonState
  30607. {
  30608. buttonNormal,
  30609. buttonOver,
  30610. buttonDown
  30611. };
  30612. /** Can be used to force the button into a particular state.
  30613. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  30614. from happening.
  30615. The state that you set here will only last until it is automatically changed when the mouse
  30616. enters or exits the button, or the mouse-button is pressed or released.
  30617. */
  30618. void setState (const ButtonState newState);
  30619. // These are deprecated - please use addListener() and removeListener() instead!
  30620. JUCE_DEPRECATED (void addButtonListener (Listener*));
  30621. JUCE_DEPRECATED (void removeButtonListener (Listener*));
  30622. protected:
  30623. /** This method is called when the button has been clicked.
  30624. Subclasses can override this to perform whatever they actions they need
  30625. to do.
  30626. Alternatively, a ButtonListener can be added to the button, and these listeners
  30627. will be called when the click occurs.
  30628. @see triggerClick
  30629. */
  30630. virtual void clicked();
  30631. /** This method is called when the button has been clicked.
  30632. By default it just calls clicked(), but you might want to override it to handle
  30633. things like clicking when a modifier key is pressed, etc.
  30634. @see ModifierKeys
  30635. */
  30636. virtual void clicked (const ModifierKeys& modifiers);
  30637. /** Subclasses should override this to actually paint the button's contents.
  30638. It's better to use this than the paint method, because it gives you information
  30639. about the over/down state of the button.
  30640. @param g the graphics context to use
  30641. @param isMouseOverButton true if the button is either in the 'over' or
  30642. 'down' state
  30643. @param isButtonDown true if the button should be drawn in the 'down' position
  30644. */
  30645. virtual void paintButton (Graphics& g,
  30646. bool isMouseOverButton,
  30647. bool isButtonDown) = 0;
  30648. /** Called when the button's up/down/over state changes.
  30649. Subclasses can override this if they need to do something special when the button
  30650. goes up or down.
  30651. @see isDown, isOver
  30652. */
  30653. virtual void buttonStateChanged();
  30654. /** @internal */
  30655. virtual void internalClickCallback (const ModifierKeys& modifiers);
  30656. /** @internal */
  30657. void handleCommandMessage (int commandId);
  30658. /** @internal */
  30659. void mouseEnter (const MouseEvent& e);
  30660. /** @internal */
  30661. void mouseExit (const MouseEvent& e);
  30662. /** @internal */
  30663. void mouseDown (const MouseEvent& e);
  30664. /** @internal */
  30665. void mouseDrag (const MouseEvent& e);
  30666. /** @internal */
  30667. void mouseUp (const MouseEvent& e);
  30668. /** @internal */
  30669. bool keyPressed (const KeyPress& key);
  30670. /** @internal */
  30671. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  30672. /** @internal */
  30673. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  30674. /** @internal */
  30675. void paint (Graphics& g);
  30676. /** @internal */
  30677. void parentHierarchyChanged();
  30678. /** @internal */
  30679. void visibilityChanged();
  30680. /** @internal */
  30681. void focusGained (FocusChangeType cause);
  30682. /** @internal */
  30683. void focusLost (FocusChangeType cause);
  30684. /** @internal */
  30685. void enablementChanged();
  30686. /** @internal */
  30687. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  30688. /** @internal */
  30689. void applicationCommandListChanged();
  30690. /** @internal */
  30691. void valueChanged (Value& value);
  30692. private:
  30693. Array <KeyPress> shortcuts;
  30694. WeakReference<Component> keySource;
  30695. String text;
  30696. ListenerList <Listener> buttonListeners;
  30697. class RepeatTimer;
  30698. friend class RepeatTimer;
  30699. friend class ScopedPointer <RepeatTimer>;
  30700. ScopedPointer <RepeatTimer> repeatTimer;
  30701. uint32 buttonPressTime, lastRepeatTime;
  30702. ApplicationCommandManager* commandManagerToUse;
  30703. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  30704. int radioGroupId, commandID, connectedEdgeFlags;
  30705. ButtonState buttonState;
  30706. Value isOn;
  30707. bool lastToggleState : 1;
  30708. bool clickTogglesState : 1;
  30709. bool needsToRelease : 1;
  30710. bool needsRepainting : 1;
  30711. bool isKeyDown : 1;
  30712. bool triggerOnMouseDown : 1;
  30713. bool generateTooltip : 1;
  30714. void repeatTimerCallback();
  30715. RepeatTimer& getRepeatTimer();
  30716. ButtonState updateState();
  30717. ButtonState updateState (bool isOver, bool isDown);
  30718. bool isShortcutPressed() const;
  30719. void turnOffOtherButtonsInGroup (bool sendChangeNotification);
  30720. void flashButtonState();
  30721. void sendClickMessage (const ModifierKeys& modifiers);
  30722. void sendStateMessage();
  30723. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Button);
  30724. };
  30725. #ifndef DOXYGEN
  30726. /** This typedef is just for compatibility with old code and VC6 - newer code should use Button::Listener instead. */
  30727. typedef Button::Listener ButtonListener;
  30728. #endif
  30729. #if JUCE_VC6
  30730. #undef Listener
  30731. #endif
  30732. #endif // __JUCE_BUTTON_JUCEHEADER__
  30733. /*** End of inlined file: juce_Button.h ***/
  30734. /**
  30735. A scrollbar component.
  30736. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  30737. sets the range of values it can represent. Then you can use setCurrentRange() to
  30738. change the position and size of the scrollbar's 'thumb'.
  30739. Registering a ScrollBar::Listener with the scrollbar will allow you to find out when
  30740. the user moves it, and you can use the getCurrentRangeStart() to find out where
  30741. they moved it to.
  30742. The scrollbar will adjust its own visibility according to whether its thumb size
  30743. allows it to actually be scrolled.
  30744. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  30745. instead of handling a scrollbar directly.
  30746. @see ScrollBar::Listener
  30747. */
  30748. class JUCE_API ScrollBar : public Component,
  30749. public AsyncUpdater,
  30750. private Timer
  30751. {
  30752. public:
  30753. /** Creates a Scrollbar.
  30754. @param isVertical whether it should be a vertical or horizontal bar
  30755. @param buttonsAreVisible whether to show the up/down or left/right buttons
  30756. */
  30757. ScrollBar (bool isVertical,
  30758. bool buttonsAreVisible = true);
  30759. /** Destructor. */
  30760. ~ScrollBar();
  30761. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  30762. bool isVertical() const throw() { return vertical; }
  30763. /** Changes the scrollbar's direction.
  30764. You'll also need to resize the bar appropriately - this just changes its internal
  30765. layout.
  30766. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  30767. */
  30768. void setOrientation (bool shouldBeVertical);
  30769. /** Shows or hides the scrollbar's buttons. */
  30770. void setButtonVisibility (bool buttonsAreVisible);
  30771. /** Tells the scrollbar whether to make itself invisible when not needed.
  30772. The default behaviour is for a scrollbar to become invisible when the thumb
  30773. fills the whole of its range (i.e. when it can't be moved). Setting this
  30774. value to false forces the bar to always be visible.
  30775. @see autoHides()
  30776. */
  30777. void setAutoHide (bool shouldHideWhenFullRange);
  30778. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  30779. as its maximum range.
  30780. @see setAutoHide
  30781. */
  30782. bool autoHides() const throw();
  30783. /** Sets the minimum and maximum values that the bar will move between.
  30784. The bar's thumb will always be constrained so that the entire thumb lies
  30785. within this range.
  30786. @see setCurrentRange
  30787. */
  30788. void setRangeLimits (const Range<double>& newRangeLimit);
  30789. /** Sets the minimum and maximum values that the bar will move between.
  30790. The bar's thumb will always be constrained so that the entire thumb lies
  30791. within this range.
  30792. @see setCurrentRange
  30793. */
  30794. void setRangeLimits (double minimum, double maximum);
  30795. /** Returns the current limits on the thumb position.
  30796. @see setRangeLimits
  30797. */
  30798. const Range<double> getRangeLimit() const throw() { return totalRange; }
  30799. /** Returns the lower value that the thumb can be set to.
  30800. This is the value set by setRangeLimits().
  30801. */
  30802. double getMinimumRangeLimit() const throw() { return totalRange.getStart(); }
  30803. /** Returns the upper value that the thumb can be set to.
  30804. This is the value set by setRangeLimits().
  30805. */
  30806. double getMaximumRangeLimit() const throw() { return totalRange.getEnd(); }
  30807. /** Changes the position of the scrollbar's 'thumb'.
  30808. If this method call actually changes the scrollbar's position, it will trigger an
  30809. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  30810. are registered.
  30811. @see getCurrentRange. setCurrentRangeStart
  30812. */
  30813. void setCurrentRange (const Range<double>& newRange);
  30814. /** Changes the position of the scrollbar's 'thumb'.
  30815. This sets both the position and size of the thumb - to just set the position without
  30816. changing the size, you can use setCurrentRangeStart().
  30817. If this method call actually changes the scrollbar's position, it will trigger an
  30818. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  30819. are registered.
  30820. @param newStart the top (or left) of the thumb, in the range
  30821. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  30822. value is beyond these limits, it will be clipped.
  30823. @param newSize the size of the thumb, such that
  30824. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  30825. size is beyond these limits, it will be clipped.
  30826. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  30827. */
  30828. void setCurrentRange (double newStart, double newSize);
  30829. /** Moves the bar's thumb position.
  30830. This will move the thumb position without changing the thumb size. Note
  30831. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  30832. If this method call actually changes the scrollbar's position, it will trigger an
  30833. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  30834. are registered.
  30835. @see setCurrentRange
  30836. */
  30837. void setCurrentRangeStart (double newStart);
  30838. /** Returns the current thumb range.
  30839. @see getCurrentRange, setCurrentRange
  30840. */
  30841. const Range<double> getCurrentRange() const throw() { return visibleRange; }
  30842. /** Returns the position of the top of the thumb.
  30843. @see getCurrentRange, setCurrentRangeStart
  30844. */
  30845. double getCurrentRangeStart() const throw() { return visibleRange.getStart(); }
  30846. /** Returns the current size of the thumb.
  30847. @see getCurrentRange, setCurrentRange
  30848. */
  30849. double getCurrentRangeSize() const throw() { return visibleRange.getLength(); }
  30850. /** Sets the amount by which the up and down buttons will move the bar.
  30851. The value here is in terms of the total range, and is added or subtracted
  30852. from the thumb position when the user clicks an up/down (or left/right) button.
  30853. */
  30854. void setSingleStepSize (double newSingleStepSize);
  30855. /** Moves the scrollbar by a number of single-steps.
  30856. This will move the bar by a multiple of its single-step interval (as
  30857. specified using the setSingleStepSize() method).
  30858. A positive value here will move the bar down or to the right, a negative
  30859. value moves it up or to the left.
  30860. */
  30861. void moveScrollbarInSteps (int howManySteps);
  30862. /** Moves the scroll bar up or down in pages.
  30863. This will move the bar by a multiple of its current thumb size, effectively
  30864. doing a page-up or down.
  30865. A positive value here will move the bar down or to the right, a negative
  30866. value moves it up or to the left.
  30867. */
  30868. void moveScrollbarInPages (int howManyPages);
  30869. /** Scrolls to the top (or left).
  30870. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  30871. */
  30872. void scrollToTop();
  30873. /** Scrolls to the bottom (or right).
  30874. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  30875. */
  30876. void scrollToBottom();
  30877. /** Changes the delay before the up and down buttons autorepeat when they are held
  30878. down.
  30879. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  30880. @see Button::setRepeatSpeed
  30881. */
  30882. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  30883. int repeatDelayInMillisecs,
  30884. int minimumDelayInMillisecs = -1);
  30885. /** A set of colour IDs to use to change the colour of various aspects of the component.
  30886. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30887. methods.
  30888. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30889. */
  30890. enum ColourIds
  30891. {
  30892. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  30893. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  30894. 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. */
  30895. };
  30896. /**
  30897. A class for receiving events from a ScrollBar.
  30898. You can register a ScrollBar::Listener with a ScrollBar using the ScrollBar::addListener()
  30899. method, and it will be called when the bar's position changes.
  30900. @see ScrollBar::addListener, ScrollBar::removeListener
  30901. */
  30902. class JUCE_API Listener
  30903. {
  30904. public:
  30905. /** Destructor. */
  30906. virtual ~Listener() {}
  30907. /** Called when a ScrollBar is moved.
  30908. @param scrollBarThatHasMoved the bar that has moved
  30909. @param newRangeStart the new range start of this bar
  30910. */
  30911. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  30912. double newRangeStart) = 0;
  30913. };
  30914. /** Registers a listener that will be called when the scrollbar is moved. */
  30915. void addListener (Listener* listener);
  30916. /** Deregisters a previously-registered listener. */
  30917. void removeListener (Listener* listener);
  30918. /** @internal */
  30919. bool keyPressed (const KeyPress& key);
  30920. /** @internal */
  30921. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  30922. /** @internal */
  30923. void lookAndFeelChanged();
  30924. /** @internal */
  30925. void handleAsyncUpdate();
  30926. /** @internal */
  30927. void mouseDown (const MouseEvent& e);
  30928. /** @internal */
  30929. void mouseDrag (const MouseEvent& e);
  30930. /** @internal */
  30931. void mouseUp (const MouseEvent& e);
  30932. /** @internal */
  30933. void paint (Graphics& g);
  30934. /** @internal */
  30935. void resized();
  30936. private:
  30937. Range <double> totalRange, visibleRange;
  30938. double singleStepSize, dragStartRange;
  30939. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  30940. int dragStartMousePos, lastMousePos;
  30941. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  30942. bool vertical, isDraggingThumb, autohides;
  30943. class ScrollbarButton;
  30944. friend class ScopedPointer<ScrollbarButton>;
  30945. ScopedPointer<ScrollbarButton> upButton, downButton;
  30946. ListenerList <Listener> listeners;
  30947. void updateThumbPosition();
  30948. void timerCallback();
  30949. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollBar);
  30950. };
  30951. /** This typedef is just for compatibility with old code - newer code should use the ScrollBar::Listener class directly. */
  30952. typedef ScrollBar::Listener ScrollBarListener;
  30953. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  30954. /*** End of inlined file: juce_ScrollBar.h ***/
  30955. /**
  30956. A Viewport is used to contain a larger child component, and allows the child
  30957. to be automatically scrolled around.
  30958. To use a Viewport, just create one and set the component that goes inside it
  30959. using the setViewedComponent() method. When the child component changes size,
  30960. the Viewport will adjust its scrollbars accordingly.
  30961. A subclass of the viewport can be created which will receive calls to its
  30962. visibleAreaChanged() method when the subcomponent changes position or size.
  30963. */
  30964. class JUCE_API Viewport : public Component,
  30965. private ComponentListener,
  30966. private ScrollBar::Listener
  30967. {
  30968. public:
  30969. /** Creates a Viewport.
  30970. The viewport is initially empty - use the setViewedComponent() method to
  30971. add a child component for it to manage.
  30972. */
  30973. explicit Viewport (const String& componentName = String::empty);
  30974. /** Destructor. */
  30975. ~Viewport();
  30976. /** Sets the component that this viewport will contain and scroll around.
  30977. This will add the given component to this Viewport and position it at (0, 0).
  30978. (Don't add or remove any child components directly using the normal
  30979. Component::addChildComponent() methods).
  30980. @param newViewedComponent the component to add to this viewport, or null to remove
  30981. the current component.
  30982. @param deleteComponentWhenNoLongerNeeded if true, the component will be deleted
  30983. automatically when the viewport is deleted or when a different
  30984. component is added. If false, the caller must manage the lifetime
  30985. of the component
  30986. @see getViewedComponent
  30987. */
  30988. void setViewedComponent (Component* newViewedComponent,
  30989. bool deleteComponentWhenNoLongerNeeded = true);
  30990. /** Returns the component that's currently being used inside the Viewport.
  30991. @see setViewedComponent
  30992. */
  30993. Component* getViewedComponent() const throw() { return contentComp; }
  30994. /** Changes the position of the viewed component.
  30995. The inner component will be moved so that the pixel at the top left of
  30996. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  30997. within the inner component.
  30998. This will update the scrollbars and might cause a call to visibleAreaChanged().
  30999. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  31000. */
  31001. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  31002. /** Changes the position of the viewed component.
  31003. The inner component will be moved so that the pixel at the top left of
  31004. the viewport will be the pixel at the specified coordinates within the
  31005. inner component.
  31006. This will update the scrollbars and might cause a call to visibleAreaChanged().
  31007. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  31008. */
  31009. void setViewPosition (const Point<int>& newPosition);
  31010. /** Changes the view position as a proportion of the distance it can move.
  31011. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  31012. visible area in the top-left, and (1, 1) would put it as far down and
  31013. to the right as it's possible to go whilst keeping the child component
  31014. on-screen.
  31015. */
  31016. void setViewPositionProportionately (double proportionX, double proportionY);
  31017. /** If the specified position is at the edges of the viewport, this method scrolls
  31018. the viewport to bring that position nearer to the centre.
  31019. Call this if you're dragging an object inside a viewport and want to make it scroll
  31020. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  31021. useful when auto-scrolling.
  31022. @param mouseX the x position, relative to the Viewport's top-left
  31023. @param mouseY the y position, relative to the Viewport's top-left
  31024. @param distanceFromEdge specifies how close to an edge the position needs to be
  31025. before the viewport should scroll in that direction
  31026. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  31027. to scroll by.
  31028. @returns true if the viewport was scrolled
  31029. */
  31030. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  31031. /** Returns the position within the child component of the top-left of its visible area.
  31032. */
  31033. const Point<int> getViewPosition() const throw() { return lastVisibleArea.getPosition(); }
  31034. /** Returns the position within the child component of the top-left of its visible area.
  31035. @see getViewWidth, setViewPosition
  31036. */
  31037. int getViewPositionX() const throw() { return lastVisibleArea.getX(); }
  31038. /** Returns the position within the child component of the top-left of its visible area.
  31039. @see getViewHeight, setViewPosition
  31040. */
  31041. int getViewPositionY() const throw() { return lastVisibleArea.getY(); }
  31042. /** Returns the width of the visible area of the child component.
  31043. This may be less than the width of this Viewport if there's a vertical scrollbar
  31044. or if the child component is itself smaller.
  31045. */
  31046. int getViewWidth() const throw() { return lastVisibleArea.getWidth(); }
  31047. /** Returns the height of the visible area of the child component.
  31048. This may be less than the height of this Viewport if there's a horizontal scrollbar
  31049. or if the child component is itself smaller.
  31050. */
  31051. int getViewHeight() const throw() { return lastVisibleArea.getHeight(); }
  31052. /** Returns the width available within this component for the contents.
  31053. This will be the width of the viewport component minus the width of a
  31054. vertical scrollbar (if visible).
  31055. */
  31056. int getMaximumVisibleWidth() const;
  31057. /** Returns the height available within this component for the contents.
  31058. This will be the height of the viewport component minus the space taken up
  31059. by a horizontal scrollbar (if visible).
  31060. */
  31061. int getMaximumVisibleHeight() const;
  31062. /** Callback method that is called when the visible area changes.
  31063. This will be called when the visible area is moved either be scrolling or
  31064. by calls to setViewPosition(), etc.
  31065. */
  31066. virtual void visibleAreaChanged (const Rectangle<int>& newVisibleArea);
  31067. /** Turns scrollbars on or off.
  31068. If set to false, the scrollbars won't ever appear. When true (the default)
  31069. they will appear only when needed.
  31070. */
  31071. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  31072. bool showHorizontalScrollbarIfNeeded);
  31073. /** True if the vertical scrollbar is enabled.
  31074. @see setScrollBarsShown
  31075. */
  31076. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  31077. /** True if the horizontal scrollbar is enabled.
  31078. @see setScrollBarsShown
  31079. */
  31080. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  31081. /** Changes the width of the scrollbars.
  31082. If this isn't specified, the default width from the LookAndFeel class will be used.
  31083. @see LookAndFeel::getDefaultScrollbarWidth
  31084. */
  31085. void setScrollBarThickness (int thickness);
  31086. /** Returns the thickness of the scrollbars.
  31087. @see setScrollBarThickness
  31088. */
  31089. int getScrollBarThickness() const;
  31090. /** Changes the distance that a single-step click on a scrollbar button
  31091. will move the viewport.
  31092. */
  31093. void setSingleStepSizes (int stepX, int stepY);
  31094. /** Shows or hides the buttons on any scrollbars that are used.
  31095. @see ScrollBar::setButtonVisibility
  31096. */
  31097. void setScrollBarButtonVisibility (bool buttonsVisible);
  31098. /** Returns a pointer to the scrollbar component being used.
  31099. Handy if you need to customise the bar somehow.
  31100. */
  31101. ScrollBar* getVerticalScrollBar() throw() { return &verticalScrollBar; }
  31102. /** Returns a pointer to the scrollbar component being used.
  31103. Handy if you need to customise the bar somehow.
  31104. */
  31105. ScrollBar* getHorizontalScrollBar() throw() { return &horizontalScrollBar; }
  31106. /** @internal */
  31107. void resized();
  31108. /** @internal */
  31109. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  31110. /** @internal */
  31111. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31112. /** @internal */
  31113. bool keyPressed (const KeyPress& key);
  31114. /** @internal */
  31115. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  31116. /** @internal */
  31117. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31118. private:
  31119. WeakReference<Component> contentComp;
  31120. Rectangle<int> lastVisibleArea;
  31121. int scrollBarThickness;
  31122. int singleStepX, singleStepY;
  31123. bool showHScrollbar, showVScrollbar, deleteContent;
  31124. Component contentHolder;
  31125. ScrollBar verticalScrollBar;
  31126. ScrollBar horizontalScrollBar;
  31127. void updateVisibleArea();
  31128. void deleteContentComp();
  31129. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  31130. // If you get an error here, it's because this method's parameters have changed! See the new definition above..
  31131. virtual int visibleAreaChanged (int, int, int, int) { return 0; }
  31132. #endif
  31133. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Viewport);
  31134. };
  31135. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  31136. /*** End of inlined file: juce_Viewport.h ***/
  31137. /*** Start of inlined file: juce_PopupMenu.h ***/
  31138. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  31139. #define __JUCE_POPUPMENU_JUCEHEADER__
  31140. /** Creates and displays a popup-menu.
  31141. To show a popup-menu, you create one of these, add some items to it, then
  31142. call its show() method, which returns the id of the item the user selects.
  31143. E.g. @code
  31144. void MyWidget::mouseDown (const MouseEvent& e)
  31145. {
  31146. PopupMenu m;
  31147. m.addItem (1, "item 1");
  31148. m.addItem (2, "item 2");
  31149. const int result = m.show();
  31150. if (result == 0)
  31151. {
  31152. // user dismissed the menu without picking anything
  31153. }
  31154. else if (result == 1)
  31155. {
  31156. // user picked item 1
  31157. }
  31158. else if (result == 2)
  31159. {
  31160. // user picked item 2
  31161. }
  31162. }
  31163. @endcode
  31164. Submenus are easy too: @code
  31165. void MyWidget::mouseDown (const MouseEvent& e)
  31166. {
  31167. PopupMenu subMenu;
  31168. subMenu.addItem (1, "item 1");
  31169. subMenu.addItem (2, "item 2");
  31170. PopupMenu mainMenu;
  31171. mainMenu.addItem (3, "item 3");
  31172. mainMenu.addSubMenu ("other choices", subMenu);
  31173. const int result = m.show();
  31174. ...etc
  31175. }
  31176. @endcode
  31177. */
  31178. class JUCE_API PopupMenu
  31179. {
  31180. public:
  31181. /** Creates an empty popup menu. */
  31182. PopupMenu();
  31183. /** Creates a copy of another menu. */
  31184. PopupMenu (const PopupMenu& other);
  31185. /** Destructor. */
  31186. ~PopupMenu();
  31187. /** Copies this menu from another one. */
  31188. PopupMenu& operator= (const PopupMenu& other);
  31189. /** Resets the menu, removing all its items. */
  31190. void clear();
  31191. /** Appends a new text item for this menu to show.
  31192. @param itemResultId the number that will be returned from the show() method
  31193. if the user picks this item. The value should never be
  31194. zero, because that's used to indicate that the user didn't
  31195. select anything.
  31196. @param itemText the text to show.
  31197. @param isActive if false, the item will be shown 'greyed-out' and can't be
  31198. picked
  31199. @param isTicked if true, the item will be shown with a tick next to it
  31200. @param iconToUse if this is non-zero, it should be an image that will be
  31201. displayed to the left of the item. This method will take its
  31202. own copy of the image passed-in, so there's no need to keep
  31203. it hanging around.
  31204. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  31205. */
  31206. void addItem (int itemResultId,
  31207. const String& itemText,
  31208. bool isActive = true,
  31209. bool isTicked = false,
  31210. const Image& iconToUse = Image::null);
  31211. /** Adds an item that represents one of the commands in a command manager object.
  31212. @param commandManager the manager to use to trigger the command and get information
  31213. about it
  31214. @param commandID the ID of the command
  31215. @param displayName if this is non-empty, then this string will be used instead of
  31216. the command's registered name
  31217. */
  31218. void addCommandItem (ApplicationCommandManager* commandManager,
  31219. int commandID,
  31220. const String& displayName = String::empty);
  31221. /** Appends a text item with a special colour.
  31222. This is the same as addItem(), but specifies a colour to use for the
  31223. text, which will override the default colours that are used by the
  31224. current look-and-feel. See addItem() for a description of the parameters.
  31225. */
  31226. void addColouredItem (int itemResultId,
  31227. const String& itemText,
  31228. const Colour& itemTextColour,
  31229. bool isActive = true,
  31230. bool isTicked = false,
  31231. const Image& iconToUse = Image::null);
  31232. /** Appends a custom menu item that can't be used to trigger a result.
  31233. This will add a user-defined component to use as a menu item. Unlike the
  31234. addCustomItem() method that takes a PopupMenu::CustomComponent, this version
  31235. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  31236. delete the component when it's finished, so it's the caller's responsibility
  31237. to manage the component that is passed-in.
  31238. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  31239. detection of a mouse-click on your component, and use that to trigger the
  31240. menu ID specified in itemResultId. If this is false, the menu item can't
  31241. be triggered, so itemResultId is not used.
  31242. @see CustomComponent
  31243. */
  31244. void addCustomItem (int itemResultId,
  31245. Component* customComponent,
  31246. int idealWidth, int idealHeight,
  31247. bool triggerMenuItemAutomaticallyWhenClicked);
  31248. /** Appends a sub-menu.
  31249. If the menu that's passed in is empty, it will appear as an inactive item.
  31250. */
  31251. void addSubMenu (const String& subMenuName,
  31252. const PopupMenu& subMenu,
  31253. bool isActive = true,
  31254. const Image& iconToUse = Image::null,
  31255. bool isTicked = false);
  31256. /** Appends a separator to the menu, to help break it up into sections.
  31257. The menu class is smart enough not to display separators at the top or bottom
  31258. of the menu, and it will replace mutliple adjacent separators with a single
  31259. one, so your code can be quite free and easy about adding these, and it'll
  31260. always look ok.
  31261. */
  31262. void addSeparator();
  31263. /** Adds a non-clickable text item to the menu.
  31264. This is a bold-font items which can be used as a header to separate the items
  31265. into named groups.
  31266. */
  31267. void addSectionHeader (const String& title);
  31268. /** Returns the number of items that the menu currently contains.
  31269. (This doesn't count separators).
  31270. */
  31271. int getNumItems() const throw();
  31272. /** Returns true if the menu contains a command item that triggers the given command. */
  31273. bool containsCommandItem (int commandID) const;
  31274. /** Returns true if the menu contains any items that can be used. */
  31275. bool containsAnyActiveItems() const throw();
  31276. /** Class used to create a set of options to pass to the show() method.
  31277. You can chain together a series of calls to this class's methods to create
  31278. a set of whatever options you want to specify.
  31279. E.g. @code
  31280. PopupMenu menu;
  31281. ...
  31282. menu.showMenu (PopupMenu::Options().withMaximumWidth (100),
  31283. .withMaximumNumColumns (3)
  31284. .withTargetComponent (myComp));
  31285. @endcode
  31286. */
  31287. class JUCE_API Options
  31288. {
  31289. public:
  31290. Options();
  31291. const Options withTargetComponent (Component* targetComponent) const;
  31292. const Options withTargetScreenArea (const Rectangle<int>& targetArea) const;
  31293. const Options withMinimumWidth (int minWidth) const;
  31294. const Options withMaximumNumColumns (int maxNumColumns) const;
  31295. const Options withStandardItemHeight (int standardHeight) const;
  31296. const Options withItemThatMustBeVisible (int idOfItemToBeVisible) const;
  31297. private:
  31298. friend class PopupMenu;
  31299. Rectangle<int> targetArea;
  31300. Component* targetComponent;
  31301. int visibleItemID, minWidth, maxColumns, standardHeight;
  31302. };
  31303. #if JUCE_MODAL_LOOPS_PERMITTED
  31304. /** Displays the menu and waits for the user to pick something.
  31305. This will display the menu modally, and return the ID of the item that the
  31306. user picks. If they click somewhere off the menu to get rid of it without
  31307. choosing anything, this will return 0.
  31308. The current location of the mouse will be used as the position to show the
  31309. menu - to explicitly set the menu's position, use showAt() instead. Depending
  31310. on where this point is on the screen, the menu will appear above, below or
  31311. to the side of the point.
  31312. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  31313. then when the menu first appears, it will make sure
  31314. that this item is visible. So if the menu has too many
  31315. items to fit on the screen, it will be scrolled to a
  31316. position where this item is visible.
  31317. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  31318. than this if some items are too long to fit.
  31319. @param maximumNumColumns if there are too many items to fit on-screen in a single
  31320. vertical column, the menu may be laid out as a series of
  31321. columns - this is the maximum number allowed. To use the
  31322. default value for this (probably about 7), you can pass
  31323. in zero.
  31324. @param standardItemHeight if this is non-zero, it will be used as the standard
  31325. height for menu items (apart from custom items)
  31326. @param callback if this is non-zero, the menu will be launched asynchronously,
  31327. returning immediately, and the callback will receive a
  31328. call when the menu is either dismissed or has an item
  31329. selected. This object will be owned and deleted by the
  31330. system, so make sure that it works safely and that any
  31331. pointers that it uses are safely within scope.
  31332. @see showAt
  31333. */
  31334. int show (int itemIdThatMustBeVisible = 0,
  31335. int minimumWidth = 0,
  31336. int maximumNumColumns = 0,
  31337. int standardItemHeight = 0,
  31338. ModalComponentManager::Callback* callback = 0);
  31339. /** Displays the menu at a specific location.
  31340. This is the same as show(), but uses a specific location (in global screen
  31341. co-ordinates) rather than the current mouse position.
  31342. The screenAreaToAttachTo parameter indicates a screen area to which the menu
  31343. will be adjacent. Depending on where this is, the menu will decide which edge to
  31344. attach itself to, in order to fit itself fully on-screen. If you just want to
  31345. trigger a menu at a specific point, you can pass in a rectangle of size (0, 0)
  31346. with the position that you want.
  31347. @see show()
  31348. */
  31349. int showAt (const Rectangle<int>& screenAreaToAttachTo,
  31350. int itemIdThatMustBeVisible = 0,
  31351. int minimumWidth = 0,
  31352. int maximumNumColumns = 0,
  31353. int standardItemHeight = 0,
  31354. ModalComponentManager::Callback* callback = 0);
  31355. /** Displays the menu as if it's attached to a component such as a button.
  31356. This is similar to showAt(), but will position it next to the given component, e.g.
  31357. so that the menu's edge is aligned with that of the component. This is intended for
  31358. things like buttons that trigger a pop-up menu.
  31359. */
  31360. int showAt (Component* componentToAttachTo,
  31361. int itemIdThatMustBeVisible = 0,
  31362. int minimumWidth = 0,
  31363. int maximumNumColumns = 0,
  31364. int standardItemHeight = 0,
  31365. ModalComponentManager::Callback* callback = 0);
  31366. /** Displays and runs the menu modally, with a set of options.
  31367. */
  31368. int showMenu (const Options& options);
  31369. #endif
  31370. /** Runs the menu asynchronously, with a user-provided callback that will receive the result. */
  31371. void showMenuAsync (const Options& options,
  31372. ModalComponentManager::Callback* callback);
  31373. /** Closes any menus that are currently open.
  31374. This might be useful if you have a situation where your window is being closed
  31375. by some means other than a user action, and you'd like to make sure that menus
  31376. aren't left hanging around.
  31377. */
  31378. static bool JUCE_CALLTYPE dismissAllActiveMenus();
  31379. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  31380. This can be called before show() if you need a customised menu. Be careful
  31381. not to delete the LookAndFeel object before the menu has been deleted.
  31382. */
  31383. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  31384. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  31385. These constants can be used either via the LookAndFeel::setColour()
  31386. method for the look and feel that is set for this menu with setLookAndFeel()
  31387. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  31388. */
  31389. enum ColourIds
  31390. {
  31391. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  31392. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  31393. colour is specified when the item is added). */
  31394. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  31395. addSectionHeader() method). */
  31396. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  31397. highlighted menu item. */
  31398. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  31399. highlighted item. */
  31400. };
  31401. /**
  31402. Allows you to iterate through the items in a pop-up menu, and examine
  31403. their properties.
  31404. To use this, just create one and repeatedly call its next() method. When this
  31405. returns true, all the member variables of the iterator are filled-out with
  31406. information describing the menu item. When it returns false, the end of the
  31407. list has been reached.
  31408. */
  31409. class JUCE_API MenuItemIterator
  31410. {
  31411. public:
  31412. /** Creates an iterator that will scan through the items in the specified
  31413. menu.
  31414. Be careful not to add any items to a menu while it is being iterated,
  31415. or things could get out of step.
  31416. */
  31417. MenuItemIterator (const PopupMenu& menu);
  31418. /** Destructor. */
  31419. ~MenuItemIterator();
  31420. /** Returns true if there is another item, and sets up all this object's
  31421. member variables to reflect that item's properties.
  31422. */
  31423. bool next();
  31424. String itemName;
  31425. const PopupMenu* subMenu;
  31426. int itemId;
  31427. bool isSeparator;
  31428. bool isTicked;
  31429. bool isEnabled;
  31430. bool isCustomComponent;
  31431. bool isSectionHeader;
  31432. const Colour* customColour;
  31433. Image customImage;
  31434. ApplicationCommandManager* commandManager;
  31435. private:
  31436. const PopupMenu& menu;
  31437. int index;
  31438. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuItemIterator);
  31439. };
  31440. /** A user-defined copmonent that can be used as an item in a popup menu.
  31441. @see PopupMenu::addCustomItem
  31442. */
  31443. class JUCE_API CustomComponent : public Component,
  31444. public ReferenceCountedObject
  31445. {
  31446. public:
  31447. /** Creates a custom item.
  31448. If isTriggeredAutomatically is true, then the menu will automatically detect
  31449. a mouse-click on this component and use that to invoke the menu item. If it's
  31450. false, then it's up to your class to manually trigger the item when it wants to.
  31451. */
  31452. CustomComponent (bool isTriggeredAutomatically = true);
  31453. /** Destructor. */
  31454. ~CustomComponent();
  31455. /** Returns a rectangle with the size that this component would like to have.
  31456. Note that the size which this method returns isn't necessarily the one that
  31457. the menu will give it, as the items will be stretched to have a uniform width.
  31458. */
  31459. virtual void getIdealSize (int& idealWidth, int& idealHeight) = 0;
  31460. /** Dismisses the menu, indicating that this item has been chosen.
  31461. This will cause the menu to exit from its modal state, returning
  31462. this item's id as the result.
  31463. */
  31464. void triggerMenuItem();
  31465. /** Returns true if this item should be highlighted because the mouse is over it.
  31466. You can call this method in your paint() method to find out whether
  31467. to draw a highlight.
  31468. */
  31469. bool isItemHighlighted() const throw() { return isHighlighted; }
  31470. /** @internal. */
  31471. bool isTriggeredAutomatically() const throw() { return triggeredAutomatically; }
  31472. /** @internal. */
  31473. void setHighlighted (bool shouldBeHighlighted);
  31474. private:
  31475. bool isHighlighted, triggeredAutomatically;
  31476. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponent);
  31477. };
  31478. /** Appends a custom menu item.
  31479. This will add a user-defined component to use as a menu item. The component
  31480. passed in will be deleted by this menu when it's no longer needed.
  31481. @see CustomComponent
  31482. */
  31483. void addCustomItem (int itemResultId, CustomComponent* customComponent);
  31484. private:
  31485. class Item;
  31486. class ItemComponent;
  31487. class Window;
  31488. friend class MenuItemIterator;
  31489. friend class ItemComponent;
  31490. friend class Window;
  31491. friend class CustomComponent;
  31492. friend class MenuBarComponent;
  31493. friend class OwnedArray <Item>;
  31494. friend class OwnedArray <ItemComponent>;
  31495. friend class ScopedPointer <Window>;
  31496. OwnedArray <Item> items;
  31497. LookAndFeel* lookAndFeel;
  31498. bool separatorPending;
  31499. void addSeparatorIfPending();
  31500. Component* createWindow (const Options&, ApplicationCommandManager**) const;
  31501. int showWithOptionalCallback (const Options&, ModalComponentManager::Callback*, bool);
  31502. JUCE_LEAK_DETECTOR (PopupMenu);
  31503. };
  31504. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  31505. /*** End of inlined file: juce_PopupMenu.h ***/
  31506. /*** Start of inlined file: juce_TextInputTarget.h ***/
  31507. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  31508. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  31509. /** An abstract base class that is implemented by components that wish to be used
  31510. as text editors.
  31511. This class allows different types of text editor component to provide a uniform
  31512. interface, which can be used by things like OS-specific input methods, on-screen
  31513. keyboards, etc.
  31514. */
  31515. class JUCE_API TextInputTarget
  31516. {
  31517. public:
  31518. /** */
  31519. TextInputTarget() {}
  31520. /** Destructor. */
  31521. virtual ~TextInputTarget() {}
  31522. /** Returns true if this input target is currently accepting input.
  31523. For example, a text editor might return false if it's in read-only mode.
  31524. */
  31525. virtual bool isTextInputActive() const = 0;
  31526. /** Returns the extents of the selected text region, or an empty range if
  31527. nothing is selected,
  31528. */
  31529. virtual const Range<int> getHighlightedRegion() const = 0;
  31530. /** Sets the currently-selected text region.
  31531. */
  31532. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  31533. /** Returns a specified sub-section of the text.
  31534. */
  31535. virtual const String getTextInRange (const Range<int>& range) const = 0;
  31536. /** Inserts some text, overwriting the selected text region, if there is one. */
  31537. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  31538. };
  31539. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  31540. /*** End of inlined file: juce_TextInputTarget.h ***/
  31541. /**
  31542. A component containing text that can be edited.
  31543. A TextEditor can either be in single- or multi-line mode, and supports mixed
  31544. fonts and colours.
  31545. @see TextEditor::Listener, Label
  31546. */
  31547. class JUCE_API TextEditor : public Component,
  31548. public TextInputTarget,
  31549. public SettableTooltipClient
  31550. {
  31551. public:
  31552. /** Creates a new, empty text editor.
  31553. @param componentName the name to pass to the component for it to use as its name
  31554. @param passwordCharacter if this is not zero, this character will be used as a replacement
  31555. for all characters that are drawn on screen - e.g. to create
  31556. a password-style textbox containing circular blobs instead of text,
  31557. you could set this value to 0x25cf, which is the unicode character
  31558. for a black splodge (not all fonts include this, though), or 0x2022,
  31559. which is a bullet (probably the best choice for linux).
  31560. */
  31561. explicit TextEditor (const String& componentName = String::empty,
  31562. juce_wchar passwordCharacter = 0);
  31563. /** Destructor. */
  31564. virtual ~TextEditor();
  31565. /** Puts the editor into either multi- or single-line mode.
  31566. By default, the editor will be in single-line mode, so use this if you need a multi-line
  31567. editor.
  31568. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  31569. on if you want a multi-line editor with line-breaks.
  31570. @see isMultiLine, setReturnKeyStartsNewLine
  31571. */
  31572. void setMultiLine (bool shouldBeMultiLine,
  31573. bool shouldWordWrap = true);
  31574. /** Returns true if the editor is in multi-line mode.
  31575. */
  31576. bool isMultiLine() const;
  31577. /** Changes the behaviour of the return key.
  31578. If set to true, the return key will insert a new-line into the text; if false
  31579. it will trigger a call to the TextEditor::Listener::textEditorReturnKeyPressed()
  31580. method. By default this is set to false, and when true it will only insert
  31581. new-lines when in multi-line mode (see setMultiLine()).
  31582. */
  31583. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  31584. /** Returns the value set by setReturnKeyStartsNewLine().
  31585. See setReturnKeyStartsNewLine() for more info.
  31586. */
  31587. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  31588. /** Indicates whether the tab key should be accepted and used to input a tab character,
  31589. or whether it gets ignored.
  31590. By default the tab key is ignored, so that it can be used to switch keyboard focus
  31591. between components.
  31592. */
  31593. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  31594. /** Returns true if the tab key is being used for input.
  31595. @see setTabKeyUsedAsCharacter
  31596. */
  31597. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  31598. /** Changes the editor to read-only mode.
  31599. By default, the text editor is not read-only. If you're making it read-only, you
  31600. might also want to call setCaretVisible (false) to get rid of the caret.
  31601. The text can still be highlighted and copied when in read-only mode.
  31602. @see isReadOnly, setCaretVisible
  31603. */
  31604. void setReadOnly (bool shouldBeReadOnly);
  31605. /** Returns true if the editor is in read-only mode.
  31606. */
  31607. bool isReadOnly() const;
  31608. /** Makes the caret visible or invisible.
  31609. By default the caret is visible.
  31610. @see setCaretColour, setCaretPosition
  31611. */
  31612. void setCaretVisible (bool shouldBeVisible);
  31613. /** Returns true if the caret is enabled.
  31614. @see setCaretVisible
  31615. */
  31616. bool isCaretVisible() const { return caretVisible; }
  31617. /** Enables/disables a vertical scrollbar.
  31618. (This only applies when in multi-line mode). When the text gets too long to fit
  31619. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  31620. this is enabled, the scrollbar will be hidden unless it's needed.
  31621. By default the scrollbar is enabled.
  31622. */
  31623. void setScrollbarsShown (bool shouldBeEnabled);
  31624. /** Returns true if scrollbars are enabled.
  31625. @see setScrollbarsShown
  31626. */
  31627. bool areScrollbarsShown() const { return scrollbarVisible; }
  31628. /** Changes the password character used to disguise the text.
  31629. @param passwordCharacter if this is not zero, this character will be used as a replacement
  31630. for all characters that are drawn on screen - e.g. to create
  31631. a password-style textbox containing circular blobs instead of text,
  31632. you could set this value to 0x25cf, which is the unicode character
  31633. for a black splodge (not all fonts include this, though), or 0x2022,
  31634. which is a bullet (probably the best choice for linux).
  31635. */
  31636. void setPasswordCharacter (juce_wchar passwordCharacter);
  31637. /** Returns the current password character.
  31638. @see setPasswordCharacter
  31639. */
  31640. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  31641. /** Allows a right-click menu to appear for the editor.
  31642. (This defaults to being enabled).
  31643. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  31644. of options such as cut/copy/paste, undo/redo, etc.
  31645. */
  31646. void setPopupMenuEnabled (bool menuEnabled);
  31647. /** Returns true if the right-click menu is enabled.
  31648. @see setPopupMenuEnabled
  31649. */
  31650. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  31651. /** Returns true if a popup-menu is currently being displayed.
  31652. */
  31653. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  31654. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  31655. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31656. methods.
  31657. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31658. */
  31659. enum ColourIds
  31660. {
  31661. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  31662. transparent if necessary. */
  31663. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  31664. that because the editor can contain multiple colours, calling this
  31665. method won't change the colour of existing text - to do that, call
  31666. applyFontToAllText() after calling this method.*/
  31667. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  31668. the text - this can be transparent if you don't want to show any
  31669. highlighting.*/
  31670. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  31671. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  31672. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  31673. the edge of the component. */
  31674. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  31675. the edge of the component when it has focus. */
  31676. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  31677. around the edge of the editor. */
  31678. };
  31679. /** Sets the font to use for newly added text.
  31680. This will change the font that will be used next time any text is added or entered
  31681. into the editor. It won't change the font of any existing text - to do that, use
  31682. applyFontToAllText() instead.
  31683. @see applyFontToAllText
  31684. */
  31685. void setFont (const Font& newFont);
  31686. /** Applies a font to all the text in the editor.
  31687. This will also set the current font to use for any new text that's added.
  31688. @see setFont
  31689. */
  31690. void applyFontToAllText (const Font& newFont);
  31691. /** Returns the font that's currently being used for new text.
  31692. @see setFont
  31693. */
  31694. const Font getFont() const;
  31695. /** If set to true, focusing on the editor will highlight all its text.
  31696. (Set to false by default).
  31697. This is useful for boxes where you expect the user to re-enter all the
  31698. text when they focus on the component, rather than editing what's already there.
  31699. */
  31700. void setSelectAllWhenFocused (bool b);
  31701. /** Sets limits on the characters that can be entered.
  31702. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  31703. limit is set
  31704. @param allowedCharacters if this is non-empty, then only characters that occur in
  31705. this string are allowed to be entered into the editor.
  31706. */
  31707. void setInputRestrictions (int maxTextLength,
  31708. const String& allowedCharacters = String::empty);
  31709. /** When the text editor is empty, it can be set to display a message.
  31710. This is handy for things like telling the user what to type in the box - the
  31711. string is only displayed, it's not taken to actually be the contents of
  31712. the editor.
  31713. */
  31714. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  31715. /** Changes the size of the scrollbars that are used.
  31716. Handy if you need smaller scrollbars for a small text box.
  31717. */
  31718. void setScrollBarThickness (int newThicknessPixels);
  31719. /** Shows or hides the buttons on any scrollbars that are used.
  31720. @see ScrollBar::setButtonVisibility
  31721. */
  31722. void setScrollBarButtonVisibility (bool buttonsVisible);
  31723. /**
  31724. Receives callbacks from a TextEditor component when it changes.
  31725. @see TextEditor::addListener
  31726. */
  31727. class JUCE_API Listener
  31728. {
  31729. public:
  31730. /** Destructor. */
  31731. virtual ~Listener() {}
  31732. /** Called when the user changes the text in some way. */
  31733. virtual void textEditorTextChanged (TextEditor& editor);
  31734. /** Called when the user presses the return key. */
  31735. virtual void textEditorReturnKeyPressed (TextEditor& editor);
  31736. /** Called when the user presses the escape key. */
  31737. virtual void textEditorEscapeKeyPressed (TextEditor& editor);
  31738. /** Called when the text editor loses focus. */
  31739. virtual void textEditorFocusLost (TextEditor& editor);
  31740. };
  31741. /** Registers a listener to be told when things happen to the text.
  31742. @see removeListener
  31743. */
  31744. void addListener (Listener* newListener);
  31745. /** Deregisters a listener.
  31746. @see addListener
  31747. */
  31748. void removeListener (Listener* listenerToRemove);
  31749. /** Returns the entire contents of the editor. */
  31750. const String getText() const;
  31751. /** Returns a section of the contents of the editor. */
  31752. const String getTextInRange (const Range<int>& textRange) const;
  31753. /** Returns true if there are no characters in the editor.
  31754. This is more efficient than calling getText().isEmpty().
  31755. */
  31756. bool isEmpty() const;
  31757. /** Sets the entire content of the editor.
  31758. This will clear the editor and insert the given text (using the current text colour
  31759. and font). You can set the current text colour using
  31760. @code setColour (TextEditor::textColourId, ...);
  31761. @endcode
  31762. @param newText the text to add
  31763. @param sendTextChangeMessage if true, this will cause a change message to
  31764. be sent to all the listeners.
  31765. @see insertText
  31766. */
  31767. void setText (const String& newText,
  31768. bool sendTextChangeMessage = true);
  31769. /** Returns a Value object that can be used to get or set the text.
  31770. Bear in mind that this operate quite slowly if your text box contains large
  31771. amounts of text, as it needs to dynamically build the string that's involved. It's
  31772. best used for small text boxes.
  31773. */
  31774. Value& getTextValue();
  31775. /** Inserts some text at the current cursor position.
  31776. If a section of the text is highlighted, it will be replaced by
  31777. this string, otherwise it will be inserted.
  31778. To delete a section of text, you can use setHighlightedRegion() to
  31779. highlight it, and call insertTextAtCursor (String::empty).
  31780. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  31781. */
  31782. void insertTextAtCaret (const String& textToInsert);
  31783. /** Deletes all the text from the editor. */
  31784. void clear();
  31785. /** Deletes the currently selected region, and puts it on the clipboard.
  31786. @see copy, paste, SystemClipboard
  31787. */
  31788. void cut();
  31789. /** Copies any currently selected region to the clipboard.
  31790. @see cut, paste, SystemClipboard
  31791. */
  31792. void copy();
  31793. /** Pastes the contents of the clipboard into the editor at the cursor position.
  31794. @see cut, copy, SystemClipboard
  31795. */
  31796. void paste();
  31797. /** Moves the caret to be in front of a given character.
  31798. @see getCaretPosition
  31799. */
  31800. void setCaretPosition (int newIndex);
  31801. /** Returns the current index of the caret.
  31802. @see setCaretPosition
  31803. */
  31804. int getCaretPosition() const;
  31805. /** Attempts to scroll the text editor so that the caret ends up at
  31806. a specified position.
  31807. This won't affect the caret's position within the text, it tries to scroll
  31808. the entire editor vertically and horizontally so that the caret is sitting
  31809. at the given position (relative to the top-left of this component).
  31810. Depending on the amount of text available, it might not be possible to
  31811. scroll far enough for the caret to reach this exact position, but it
  31812. will go as far as it can in that direction.
  31813. */
  31814. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  31815. /** Get the graphical position of the caret.
  31816. The rectangle returned is relative to the component's top-left corner.
  31817. @see scrollEditorToPositionCaret
  31818. */
  31819. const Rectangle<int> getCaretRectangle();
  31820. /** Selects a section of the text. */
  31821. void setHighlightedRegion (const Range<int>& newSelection);
  31822. /** Returns the range of characters that are selected.
  31823. If nothing is selected, this will return an empty range.
  31824. @see setHighlightedRegion
  31825. */
  31826. const Range<int> getHighlightedRegion() const { return selection; }
  31827. /** Returns the section of text that is currently selected. */
  31828. const String getHighlightedText() const;
  31829. /** Finds the index of the character at a given position.
  31830. The co-ordinates are relative to the component's top-left.
  31831. */
  31832. int getTextIndexAt (int x, int y);
  31833. /** Counts the number of characters in the text.
  31834. This is quicker than getting the text as a string if you just need to know
  31835. the length.
  31836. */
  31837. int getTotalNumChars() const;
  31838. /** Returns the total width of the text, as it is currently laid-out.
  31839. This may be larger than the size of the TextEditor, and can change when
  31840. the TextEditor is resized or the text changes.
  31841. */
  31842. int getTextWidth() const;
  31843. /** Returns the maximum height of the text, as it is currently laid-out.
  31844. This may be larger than the size of the TextEditor, and can change when
  31845. the TextEditor is resized or the text changes.
  31846. */
  31847. int getTextHeight() const;
  31848. /** Changes the size of the gap at the top and left-edge of the editor.
  31849. By default there's a gap of 4 pixels.
  31850. */
  31851. void setIndents (int newLeftIndent, int newTopIndent);
  31852. /** Changes the size of border left around the edge of the component.
  31853. @see getBorder
  31854. */
  31855. void setBorder (const BorderSize<int>& border);
  31856. /** Returns the size of border around the edge of the component.
  31857. @see setBorder
  31858. */
  31859. const BorderSize<int> getBorder() const;
  31860. /** Used to disable the auto-scrolling which keeps the cursor visible.
  31861. If true (the default), the editor will scroll when the cursor moves offscreen. If
  31862. set to false, it won't.
  31863. */
  31864. void setScrollToShowCursor (bool shouldScrollToShowCursor);
  31865. /** @internal */
  31866. void paint (Graphics& g);
  31867. /** @internal */
  31868. void paintOverChildren (Graphics& g);
  31869. /** @internal */
  31870. void mouseDown (const MouseEvent& e);
  31871. /** @internal */
  31872. void mouseUp (const MouseEvent& e);
  31873. /** @internal */
  31874. void mouseDrag (const MouseEvent& e);
  31875. /** @internal */
  31876. void mouseDoubleClick (const MouseEvent& e);
  31877. /** @internal */
  31878. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31879. /** @internal */
  31880. bool keyPressed (const KeyPress& key);
  31881. /** @internal */
  31882. bool keyStateChanged (bool isKeyDown);
  31883. /** @internal */
  31884. void focusGained (FocusChangeType cause);
  31885. /** @internal */
  31886. void focusLost (FocusChangeType cause);
  31887. /** @internal */
  31888. void resized();
  31889. /** @internal */
  31890. void enablementChanged();
  31891. /** @internal */
  31892. void colourChanged();
  31893. /** @internal */
  31894. bool isTextInputActive() const;
  31895. /** This adds the items to the popup menu.
  31896. By default it adds the cut/copy/paste items, but you can override this if
  31897. you need to replace these with your own items.
  31898. If you want to add your own items to the existing ones, you can override this,
  31899. call the base class's addPopupMenuItems() method, then append your own items.
  31900. When the menu has been shown, performPopupMenuAction() will be called to
  31901. perform the item that the user has chosen.
  31902. The default menu items will be added using item IDs in the range
  31903. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  31904. menu IDs.
  31905. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  31906. a pointer to the info about it, or may be null if the menu is being triggered
  31907. by some other means.
  31908. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  31909. */
  31910. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  31911. const MouseEvent* mouseClickEvent);
  31912. /** This is called to perform one of the items that was shown on the popup menu.
  31913. If you've overridden addPopupMenuItems(), you should also override this
  31914. to perform the actions that you've added.
  31915. If you've overridden addPopupMenuItems() but have still left the default items
  31916. on the menu, remember to call the superclass's performPopupMenuAction()
  31917. so that it can perform the default actions if that's what the user clicked on.
  31918. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  31919. */
  31920. virtual void performPopupMenuAction (int menuItemID);
  31921. protected:
  31922. /** Scrolls the minimum distance needed to get the caret into view. */
  31923. void scrollToMakeSureCursorIsVisible();
  31924. /** @internal */
  31925. void moveCaret (int newCaretPos);
  31926. /** @internal */
  31927. void moveCursorTo (int newPosition, bool isSelecting);
  31928. /** Used internally to dispatch a text-change message. */
  31929. void textChanged();
  31930. /** Begins a new transaction in the UndoManager.
  31931. */
  31932. void newTransaction();
  31933. /** Used internally to trigger an undo or redo. */
  31934. void doUndoRedo (bool isRedo);
  31935. /** Can be overridden to intercept return key presses directly */
  31936. virtual void returnPressed();
  31937. /** Can be overridden to intercept escape key presses directly */
  31938. virtual void escapePressed();
  31939. /** @internal */
  31940. void handleCommandMessage (int commandId);
  31941. private:
  31942. class Iterator;
  31943. class UniformTextSection;
  31944. class TextHolderComponent;
  31945. class InsertAction;
  31946. class RemoveAction;
  31947. friend class InsertAction;
  31948. friend class RemoveAction;
  31949. ScopedPointer <Viewport> viewport;
  31950. TextHolderComponent* textHolder;
  31951. BorderSize<int> borderSize;
  31952. bool readOnly : 1;
  31953. bool multiline : 1;
  31954. bool wordWrap : 1;
  31955. bool returnKeyStartsNewLine : 1;
  31956. bool caretVisible : 1;
  31957. bool popupMenuEnabled : 1;
  31958. bool selectAllTextWhenFocused : 1;
  31959. bool scrollbarVisible : 1;
  31960. bool wasFocused : 1;
  31961. bool caretFlashState : 1;
  31962. bool keepCursorOnScreen : 1;
  31963. bool tabKeyUsed : 1;
  31964. bool menuActive : 1;
  31965. bool valueTextNeedsUpdating : 1;
  31966. UndoManager undoManager;
  31967. float cursorX, cursorY, cursorHeight;
  31968. int maxTextLength;
  31969. Range<int> selection;
  31970. int leftIndent, topIndent;
  31971. unsigned int lastTransactionTime;
  31972. Font currentFont;
  31973. mutable int totalNumChars;
  31974. int caretPosition;
  31975. Array <UniformTextSection*> sections;
  31976. String textToShowWhenEmpty;
  31977. Colour colourForTextWhenEmpty;
  31978. juce_wchar passwordCharacter;
  31979. Value textValue;
  31980. enum
  31981. {
  31982. notDragging,
  31983. draggingSelectionStart,
  31984. draggingSelectionEnd
  31985. } dragType;
  31986. String allowedCharacters;
  31987. ListenerList <Listener> listeners;
  31988. void coalesceSimilarSections();
  31989. void splitSection (int sectionIndex, int charToSplitAt);
  31990. void clearInternal (UndoManager* um);
  31991. void insert (const String& text, int insertIndex, const Font& font,
  31992. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  31993. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  31994. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  31995. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  31996. void updateCaretPosition();
  31997. void textWasChangedByValue();
  31998. int indexAtPosition (float x, float y);
  31999. int findWordBreakAfter (int position) const;
  32000. int findWordBreakBefore (int position) const;
  32001. friend class TextHolderComponent;
  32002. friend class TextEditorViewport;
  32003. void drawContent (Graphics& g);
  32004. void updateTextHolderSize();
  32005. float getWordWrapWidth() const;
  32006. void timerCallbackInt();
  32007. void repaintCaret();
  32008. void repaintText (const Range<int>& range);
  32009. UndoManager* getUndoManager() throw();
  32010. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditor);
  32011. };
  32012. /** This typedef is just for compatibility with old code - newer code should use the TextEditor::Listener class directly. */
  32013. typedef TextEditor::Listener TextEditorListener;
  32014. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  32015. /*** End of inlined file: juce_TextEditor.h ***/
  32016. #if JUCE_VC6
  32017. #define Listener ButtonListener
  32018. #endif
  32019. /**
  32020. A component that displays a text string, and can optionally become a text
  32021. editor when clicked.
  32022. */
  32023. class JUCE_API Label : public Component,
  32024. public SettableTooltipClient,
  32025. protected TextEditorListener,
  32026. private ComponentListener,
  32027. private ValueListener
  32028. {
  32029. public:
  32030. /** Creates a Label.
  32031. @param componentName the name to give the component
  32032. @param labelText the text to show in the label
  32033. */
  32034. Label (const String& componentName = String::empty,
  32035. const String& labelText = String::empty);
  32036. /** Destructor. */
  32037. ~Label();
  32038. /** Changes the label text.
  32039. If broadcastChangeMessage is true and the new text is different to the current
  32040. text, then the class will broadcast a change message to any Label::Listener objects
  32041. that are registered.
  32042. */
  32043. void setText (const String& newText, bool broadcastChangeMessage);
  32044. /** Returns the label's current text.
  32045. @param returnActiveEditorContents if this is true and the label is currently
  32046. being edited, then this method will return the
  32047. text as it's being shown in the editor. If false,
  32048. then the value returned here won't be updated until
  32049. the user has finished typing and pressed the return
  32050. key.
  32051. */
  32052. const String getText (bool returnActiveEditorContents = false) const;
  32053. /** Returns the text content as a Value object.
  32054. You can call Value::referTo() on this object to make the label read and control
  32055. a Value object that you supply.
  32056. */
  32057. Value& getTextValue() { return textValue; }
  32058. /** Changes the font to use to draw the text.
  32059. @see getFont
  32060. */
  32061. void setFont (const Font& newFont);
  32062. /** Returns the font currently being used.
  32063. @see setFont
  32064. */
  32065. const Font& getFont() const throw();
  32066. /** A set of colour IDs to use to change the colour of various aspects of the label.
  32067. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32068. methods.
  32069. Note that you can also use the constants from TextEditor::ColourIds to change the
  32070. colour of the text editor that is opened when a label is editable.
  32071. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32072. */
  32073. enum ColourIds
  32074. {
  32075. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  32076. textColourId = 0x1000281, /**< The colour for the text. */
  32077. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  32078. Leave this transparent to not have an outline. */
  32079. };
  32080. /** Sets the style of justification to be used for positioning the text.
  32081. (The default is Justification::centredLeft)
  32082. */
  32083. void setJustificationType (const Justification& justification);
  32084. /** Returns the type of justification, as set in setJustificationType(). */
  32085. const Justification getJustificationType() const throw() { return justification; }
  32086. /** Changes the gap that is left between the edge of the component and the text.
  32087. By default there's a small gap left at the sides of the component to allow for
  32088. the drawing of the border, but you can change this if necessary.
  32089. */
  32090. void setBorderSize (int horizontalBorder, int verticalBorder);
  32091. /** Returns the size of the horizontal gap being left around the text.
  32092. */
  32093. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  32094. /** Returns the size of the vertical gap being left around the text.
  32095. */
  32096. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  32097. /** Makes this label "stick to" another component.
  32098. This will cause the label to follow another component around, staying
  32099. either to its left or above it.
  32100. @param owner the component to follow
  32101. @param onLeft if true, the label will stay on the left of its component; if
  32102. false, it will stay above it.
  32103. */
  32104. void attachToComponent (Component* owner, bool onLeft);
  32105. /** If this label has been attached to another component using attachToComponent, this
  32106. returns the other component.
  32107. Returns 0 if the label is not attached.
  32108. */
  32109. Component* getAttachedComponent() const;
  32110. /** If the label is attached to the left of another component, this returns true.
  32111. Returns false if the label is above the other component. This is only relevent if
  32112. attachToComponent() has been called.
  32113. */
  32114. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  32115. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  32116. using ellipsis.
  32117. @see Graphics::drawFittedText
  32118. */
  32119. void setMinimumHorizontalScale (float newScale);
  32120. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  32121. /**
  32122. A class for receiving events from a Label.
  32123. You can register a Label::Listener with a Label using the Label::addListener()
  32124. method, and it will be called when the text of the label changes, either because
  32125. of a call to Label::setText() or by the user editing the text (if the label is
  32126. editable).
  32127. @see Label::addListener, Label::removeListener
  32128. */
  32129. class JUCE_API Listener
  32130. {
  32131. public:
  32132. /** Destructor. */
  32133. virtual ~Listener() {}
  32134. /** Called when a Label's text has changed.
  32135. */
  32136. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  32137. };
  32138. /** Registers a listener that will be called when the label's text changes. */
  32139. void addListener (Listener* listener);
  32140. /** Deregisters a previously-registered listener. */
  32141. void removeListener (Listener* listener);
  32142. /** Makes the label turn into a TextEditor when clicked.
  32143. By default this is turned off.
  32144. If turned on, then single- or double-clicking will turn the label into
  32145. an editor. If the user then changes the text, then the ChangeBroadcaster
  32146. base class will be used to send change messages to any listeners that
  32147. have registered.
  32148. If the user changes the text, the textWasEdited() method will be called
  32149. afterwards, and subclasses can override this if they need to do anything
  32150. special.
  32151. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  32152. @param editOnDoubleClick if true, a double-click is needed to start editing
  32153. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  32154. edited will discard any changes; if false, then this will
  32155. commit the changes.
  32156. @see showEditor, setEditorColours, TextEditor
  32157. */
  32158. void setEditable (bool editOnSingleClick,
  32159. bool editOnDoubleClick = false,
  32160. bool lossOfFocusDiscardsChanges = false);
  32161. /** Returns true if this option was set using setEditable(). */
  32162. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  32163. /** Returns true if this option was set using setEditable(). */
  32164. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  32165. /** Returns true if this option has been set in a call to setEditable(). */
  32166. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  32167. /** Returns true if the user can edit this label's text. */
  32168. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  32169. /** Makes the editor appear as if the label had been clicked by the user.
  32170. @see textWasEdited, setEditable
  32171. */
  32172. void showEditor();
  32173. /** Hides the editor if it was being shown.
  32174. @param discardCurrentEditorContents if true, the label's text will be
  32175. reset to whatever it was before the editor
  32176. was shown; if false, the current contents of the
  32177. editor will be used to set the label's text
  32178. before it is hidden.
  32179. */
  32180. void hideEditor (bool discardCurrentEditorContents);
  32181. /** Returns true if the editor is currently focused and active. */
  32182. bool isBeingEdited() const throw();
  32183. protected:
  32184. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  32185. Subclasses can override this if they need to customise this component in some way.
  32186. */
  32187. virtual TextEditor* createEditorComponent();
  32188. /** Called after the user changes the text. */
  32189. virtual void textWasEdited();
  32190. /** Called when the text has been altered. */
  32191. virtual void textWasChanged();
  32192. /** Called when the text editor has just appeared, due to a user click or other focus change. */
  32193. virtual void editorShown (TextEditor* editorComponent);
  32194. /** Called when the text editor is going to be deleted, after editing has finished. */
  32195. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  32196. /** @internal */
  32197. void paint (Graphics& g);
  32198. /** @internal */
  32199. void resized();
  32200. /** @internal */
  32201. void mouseUp (const MouseEvent& e);
  32202. /** @internal */
  32203. void mouseDoubleClick (const MouseEvent& e);
  32204. /** @internal */
  32205. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  32206. /** @internal */
  32207. void componentParentHierarchyChanged (Component& component);
  32208. /** @internal */
  32209. void componentVisibilityChanged (Component& component);
  32210. /** @internal */
  32211. void inputAttemptWhenModal();
  32212. /** @internal */
  32213. void focusGained (FocusChangeType);
  32214. /** @internal */
  32215. void enablementChanged();
  32216. /** @internal */
  32217. KeyboardFocusTraverser* createFocusTraverser();
  32218. /** @internal */
  32219. void textEditorTextChanged (TextEditor& editor);
  32220. /** @internal */
  32221. void textEditorReturnKeyPressed (TextEditor& editor);
  32222. /** @internal */
  32223. void textEditorEscapeKeyPressed (TextEditor& editor);
  32224. /** @internal */
  32225. void textEditorFocusLost (TextEditor& editor);
  32226. /** @internal */
  32227. void colourChanged();
  32228. /** @internal */
  32229. void valueChanged (Value&);
  32230. private:
  32231. Value textValue;
  32232. String lastTextValue;
  32233. Font font;
  32234. Justification justification;
  32235. ScopedPointer<TextEditor> editor;
  32236. ListenerList<Listener> listeners;
  32237. WeakReference<Component> ownerComponent;
  32238. int horizontalBorderSize, verticalBorderSize;
  32239. float minimumHorizontalScale;
  32240. bool editSingleClick : 1;
  32241. bool editDoubleClick : 1;
  32242. bool lossOfFocusDiscardsChanges : 1;
  32243. bool leftOfOwnerComp : 1;
  32244. bool updateFromTextEditorContents (TextEditor&);
  32245. void callChangeListeners();
  32246. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Label);
  32247. };
  32248. /** This typedef is just for compatibility with old code - newer code should use the Label::Listener class directly. */
  32249. typedef Label::Listener LabelListener;
  32250. #if JUCE_VC6
  32251. #undef Listener
  32252. #endif
  32253. #endif // __JUCE_LABEL_JUCEHEADER__
  32254. /*** End of inlined file: juce_Label.h ***/
  32255. #if JUCE_VC6
  32256. #define Listener SliderListener
  32257. #endif
  32258. /**
  32259. A component that lets the user choose from a drop-down list of choices.
  32260. The combo-box has a list of text strings, each with an associated id number,
  32261. that will be shown in the drop-down list when the user clicks on the component.
  32262. The currently selected choice is displayed in the combo-box, and this can
  32263. either be read-only text, or editable.
  32264. To find out when the user selects a different item or edits the text, you
  32265. can register a ComboBox::Listener to receive callbacks.
  32266. @see ComboBox::Listener
  32267. */
  32268. class JUCE_API ComboBox : public Component,
  32269. public SettableTooltipClient,
  32270. public LabelListener, // (can't use Label::Listener due to idiotic VC2005 bug)
  32271. public ValueListener,
  32272. private AsyncUpdater
  32273. {
  32274. public:
  32275. /** Creates a combo-box.
  32276. On construction, the text field will be empty, so you should call the
  32277. setSelectedId() or setText() method to choose the initial value before
  32278. displaying it.
  32279. @param componentName the name to set for the component (see Component::setName())
  32280. */
  32281. explicit ComboBox (const String& componentName = String::empty);
  32282. /** Destructor. */
  32283. ~ComboBox();
  32284. /** Sets whether the test in the combo-box is editable.
  32285. The default state for a new ComboBox is non-editable, and can only be changed
  32286. by choosing from the drop-down list.
  32287. */
  32288. void setEditableText (bool isEditable);
  32289. /** Returns true if the text is directly editable.
  32290. @see setEditableText
  32291. */
  32292. bool isTextEditable() const throw();
  32293. /** Sets the style of justification to be used for positioning the text.
  32294. The default is Justification::centredLeft. The text is displayed using a
  32295. Label component inside the ComboBox.
  32296. */
  32297. void setJustificationType (const Justification& justification);
  32298. /** Returns the current justification for the text box.
  32299. @see setJustificationType
  32300. */
  32301. const Justification getJustificationType() const throw();
  32302. /** Adds an item to be shown in the drop-down list.
  32303. @param newItemText the text of the item to show in the list
  32304. @param newItemId an associated ID number that can be set or retrieved - see
  32305. getSelectedId() and setSelectedId(). Note that this value can not
  32306. be 0!
  32307. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  32308. */
  32309. void addItem (const String& newItemText, int newItemId);
  32310. /** Adds a separator line to the drop-down list.
  32311. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  32312. */
  32313. void addSeparator();
  32314. /** Adds a heading to the drop-down list, so that you can group the items into
  32315. different sections.
  32316. The headings are indented slightly differently to set them apart from the
  32317. items on the list, and obviously can't be selected. You might want to add
  32318. separators between your sections too.
  32319. @see addItem, addSeparator
  32320. */
  32321. void addSectionHeading (const String& headingName);
  32322. /** This allows items in the drop-down list to be selectively disabled.
  32323. When you add an item, it's enabled by default, but you can call this
  32324. method to change its status.
  32325. If you disable an item which is already selected, this won't change the
  32326. current selection - it just stops the user choosing that item from the list.
  32327. */
  32328. void setItemEnabled (int itemId, bool shouldBeEnabled);
  32329. /** Returns true if the given item is enabled. */
  32330. bool isItemEnabled (int itemId) const throw();
  32331. /** Changes the text for an existing item.
  32332. */
  32333. void changeItemText (int itemId, const String& newText);
  32334. /** Removes all the items from the drop-down list.
  32335. If this call causes the content to be cleared, then a change-message
  32336. will be broadcast unless dontSendChangeMessage is true.
  32337. @see addItem, removeItem, getNumItems
  32338. */
  32339. void clear (bool dontSendChangeMessage = false);
  32340. /** Returns the number of items that have been added to the list.
  32341. Note that this doesn't include headers or separators.
  32342. */
  32343. int getNumItems() const throw();
  32344. /** Returns the text for one of the items in the list.
  32345. Note that this doesn't include headers or separators.
  32346. @param index the item's index from 0 to (getNumItems() - 1)
  32347. */
  32348. const String getItemText (int index) const;
  32349. /** Returns the ID for one of the items in the list.
  32350. Note that this doesn't include headers or separators.
  32351. @param index the item's index from 0 to (getNumItems() - 1)
  32352. */
  32353. int getItemId (int index) const throw();
  32354. /** Returns the index in the list of a particular item ID.
  32355. If no such ID is found, this will return -1.
  32356. */
  32357. int indexOfItemId (int itemId) const throw();
  32358. /** Returns the ID of the item that's currently shown in the box.
  32359. If no item is selected, or if the text is editable and the user
  32360. has entered something which isn't one of the items in the list, then
  32361. this will return 0.
  32362. @see setSelectedId, getSelectedItemIndex, getText
  32363. */
  32364. int getSelectedId() const throw();
  32365. /** Returns a Value object that can be used to get or set the selected item's ID.
  32366. You can call Value::referTo() on this object to make the combo box control
  32367. another Value object.
  32368. */
  32369. Value& getSelectedIdAsValue() { return currentId; }
  32370. /** Sets one of the items to be the current selection.
  32371. This will set the ComboBox's text to that of the item that matches
  32372. this ID.
  32373. @param newItemId the new item to select
  32374. @param dontSendChangeMessage if set to true, this method won't trigger a
  32375. change notification
  32376. @see getSelectedId, setSelectedItemIndex, setText
  32377. */
  32378. void setSelectedId (int newItemId, bool dontSendChangeMessage = false);
  32379. /** Returns the index of the item that's currently shown in the box.
  32380. If no item is selected, or if the text is editable and the user
  32381. has entered something which isn't one of the items in the list, then
  32382. this will return -1.
  32383. @see setSelectedItemIndex, getSelectedId, getText
  32384. */
  32385. int getSelectedItemIndex() const;
  32386. /** Sets one of the items to be the current selection.
  32387. This will set the ComboBox's text to that of the item at the given
  32388. index in the list.
  32389. @param newItemIndex the new item to select
  32390. @param dontSendChangeMessage if set to true, this method won't trigger a
  32391. change notification
  32392. @see getSelectedItemIndex, setSelectedId, setText
  32393. */
  32394. void setSelectedItemIndex (int newItemIndex, bool dontSendChangeMessage = false);
  32395. /** Returns the text that is currently shown in the combo-box's text field.
  32396. If the ComboBox has editable text, then this text may have been edited
  32397. by the user; otherwise it will be one of the items from the list, or
  32398. possibly an empty string if nothing was selected.
  32399. @see setText, getSelectedId, getSelectedItemIndex
  32400. */
  32401. const String getText() const;
  32402. /** Sets the contents of the combo-box's text field.
  32403. The text passed-in will be set as the current text regardless of whether
  32404. it is one of the items in the list. If the current text isn't one of the
  32405. items, then getSelectedId() will return -1, otherwise it wil return
  32406. the approriate ID.
  32407. @param newText the text to select
  32408. @param dontSendChangeMessage if set to true, this method won't trigger a
  32409. change notification
  32410. @see getText
  32411. */
  32412. void setText (const String& newText, bool dontSendChangeMessage = false);
  32413. /** Programmatically opens the text editor to allow the user to edit the current item.
  32414. This is the same effect as when the box is clicked-on.
  32415. @see Label::showEditor();
  32416. */
  32417. void showEditor();
  32418. /** Pops up the combo box's list. */
  32419. void showPopup();
  32420. /**
  32421. A class for receiving events from a ComboBox.
  32422. You can register a ComboBox::Listener with a ComboBox using the ComboBox::addListener()
  32423. method, and it will be called when the selected item in the box changes.
  32424. @see ComboBox::addListener, ComboBox::removeListener
  32425. */
  32426. class JUCE_API Listener
  32427. {
  32428. public:
  32429. /** Destructor. */
  32430. virtual ~Listener() {}
  32431. /** Called when a ComboBox has its selected item changed. */
  32432. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  32433. };
  32434. /** Registers a listener that will be called when the box's content changes. */
  32435. void addListener (Listener* listener);
  32436. /** Deregisters a previously-registered listener. */
  32437. void removeListener (Listener* listener);
  32438. /** Sets a message to display when there is no item currently selected.
  32439. @see getTextWhenNothingSelected
  32440. */
  32441. void setTextWhenNothingSelected (const String& newMessage);
  32442. /** Returns the text that is shown when no item is selected.
  32443. @see setTextWhenNothingSelected
  32444. */
  32445. const String getTextWhenNothingSelected() const;
  32446. /** Sets the message to show when there are no items in the list, and the user clicks
  32447. on the drop-down box.
  32448. By default it just says "no choices", but this lets you change it to something more
  32449. meaningful.
  32450. */
  32451. void setTextWhenNoChoicesAvailable (const String& newMessage);
  32452. /** Returns the text shown when no items have been added to the list.
  32453. @see setTextWhenNoChoicesAvailable
  32454. */
  32455. const String getTextWhenNoChoicesAvailable() const;
  32456. /** Gives the ComboBox a tooltip. */
  32457. void setTooltip (const String& newTooltip);
  32458. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  32459. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32460. methods.
  32461. To change the colours of the menu that pops up
  32462. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32463. */
  32464. enum ColourIds
  32465. {
  32466. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  32467. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  32468. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  32469. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  32470. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  32471. };
  32472. /** @internal */
  32473. void labelTextChanged (Label*);
  32474. /** @internal */
  32475. void enablementChanged();
  32476. /** @internal */
  32477. void colourChanged();
  32478. /** @internal */
  32479. void focusGained (Component::FocusChangeType cause);
  32480. /** @internal */
  32481. void focusLost (Component::FocusChangeType cause);
  32482. /** @internal */
  32483. void handleAsyncUpdate();
  32484. /** @internal */
  32485. const String getTooltip() { return label->getTooltip(); }
  32486. /** @internal */
  32487. void mouseDown (const MouseEvent&);
  32488. /** @internal */
  32489. void mouseDrag (const MouseEvent&);
  32490. /** @internal */
  32491. void mouseUp (const MouseEvent&);
  32492. /** @internal */
  32493. void lookAndFeelChanged();
  32494. /** @internal */
  32495. void paint (Graphics&);
  32496. /** @internal */
  32497. void resized();
  32498. /** @internal */
  32499. bool keyStateChanged (bool isKeyDown);
  32500. /** @internal */
  32501. bool keyPressed (const KeyPress&);
  32502. /** @internal */
  32503. void valueChanged (Value&);
  32504. private:
  32505. struct ItemInfo
  32506. {
  32507. ItemInfo (const String& name, int itemId, bool isEnabled, bool isHeading);
  32508. bool isSeparator() const throw();
  32509. bool isRealItem() const throw();
  32510. String name;
  32511. int itemId;
  32512. bool isEnabled : 1, isHeading : 1;
  32513. };
  32514. OwnedArray <ItemInfo> items;
  32515. Value currentId;
  32516. int lastCurrentId;
  32517. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  32518. ListenerList <Listener> listeners;
  32519. ScopedPointer<Label> label;
  32520. String textWhenNothingSelected, noChoicesMessage;
  32521. ItemInfo* getItemForId (int itemId) const throw();
  32522. ItemInfo* getItemForIndex (int index) const throw();
  32523. bool selectIfEnabled (int index);
  32524. static void popupMenuFinishedCallback (int, ComboBox*);
  32525. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBox);
  32526. };
  32527. /** This typedef is just for compatibility with old code - newer code should use the ComboBox::Listener class directly. */
  32528. typedef ComboBox::Listener ComboBoxListener;
  32529. #if JUCE_VC6
  32530. #undef Listener
  32531. #endif
  32532. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  32533. /*** End of inlined file: juce_ComboBox.h ***/
  32534. /**
  32535. Manages the state of some audio and midi i/o devices.
  32536. This class keeps tracks of a currently-selected audio device, through
  32537. with which it continuously streams data from an audio callback, as well as
  32538. one or more midi inputs.
  32539. The idea is that your application will create one global instance of this object,
  32540. and let it take care of creating and deleting specific types of audio devices
  32541. internally. So when the device is changed, your callbacks will just keep running
  32542. without having to worry about this.
  32543. The manager can save and reload all of its device settings as XML, which
  32544. makes it very easy for you to save and reload the audio setup of your
  32545. application.
  32546. And to make it easy to let the user change its settings, there's a component
  32547. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  32548. device selection/sample-rate/latency controls.
  32549. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  32550. call addAudioCallback() to register your audio callback with it, and use that to process
  32551. your audio data.
  32552. The manager also acts as a handy hub for incoming midi messages, allowing a
  32553. listener to register for messages from either a specific midi device, or from whatever
  32554. the current default midi input device is. The listener then doesn't have to worry about
  32555. re-registering with different midi devices if they are changed or deleted.
  32556. And yet another neat trick is that amount of CPU time being used is measured and
  32557. available with the getCpuUsage() method.
  32558. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  32559. listeners whenever one of its settings is changed.
  32560. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  32561. */
  32562. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  32563. {
  32564. public:
  32565. /** Creates a default AudioDeviceManager.
  32566. Initially no audio device will be selected. You should call the initialise() method
  32567. and register an audio callback with setAudioCallback() before it'll be able to
  32568. actually make any noise.
  32569. */
  32570. AudioDeviceManager();
  32571. /** Destructor. */
  32572. ~AudioDeviceManager();
  32573. /**
  32574. This structure holds a set of properties describing the current audio setup.
  32575. An AudioDeviceManager uses this class to save/load its current settings, and to
  32576. specify your preferred options when opening a device.
  32577. @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
  32578. */
  32579. struct JUCE_API AudioDeviceSetup
  32580. {
  32581. /** Creates an AudioDeviceSetup object.
  32582. The default constructor sets all the member variables to indicate default values.
  32583. You can then fill-in any values you want to before passing the object to
  32584. AudioDeviceManager::initialise().
  32585. */
  32586. AudioDeviceSetup();
  32587. bool operator== (const AudioDeviceSetup& other) const;
  32588. /** The name of the audio device used for output.
  32589. The name has to be one of the ones listed by the AudioDeviceManager's currently
  32590. selected device type.
  32591. This may be the same as the input device.
  32592. An empty string indicates the default device.
  32593. */
  32594. String outputDeviceName;
  32595. /** The name of the audio device used for input.
  32596. This may be the same as the output device.
  32597. An empty string indicates the default device.
  32598. */
  32599. String inputDeviceName;
  32600. /** The current sample rate.
  32601. This rate is used for both the input and output devices.
  32602. A value of 0 indicates the default rate.
  32603. */
  32604. double sampleRate;
  32605. /** The buffer size, in samples.
  32606. This buffer size is used for both the input and output devices.
  32607. A value of 0 indicates the default buffer size.
  32608. */
  32609. int bufferSize;
  32610. /** The set of active input channels.
  32611. The bits that are set in this array indicate the channels of the
  32612. input device that are active.
  32613. If useDefaultInputChannels is true, this value is ignored.
  32614. */
  32615. BigInteger inputChannels;
  32616. /** If this is true, it indicates that the inputChannels array
  32617. should be ignored, and instead, the device's default channels
  32618. should be used.
  32619. */
  32620. bool useDefaultInputChannels;
  32621. /** The set of active output channels.
  32622. The bits that are set in this array indicate the channels of the
  32623. input device that are active.
  32624. If useDefaultOutputChannels is true, this value is ignored.
  32625. */
  32626. BigInteger outputChannels;
  32627. /** If this is true, it indicates that the outputChannels array
  32628. should be ignored, and instead, the device's default channels
  32629. should be used.
  32630. */
  32631. bool useDefaultOutputChannels;
  32632. };
  32633. /** Opens a set of audio devices ready for use.
  32634. This will attempt to open either a default audio device, or one that was
  32635. previously saved as XML.
  32636. @param numInputChannelsNeeded a minimum number of input channels needed
  32637. by your app.
  32638. @param numOutputChannelsNeeded a minimum number of output channels to open
  32639. @param savedState either a previously-saved state that was produced
  32640. by createStateXml(), or 0 if you want the manager
  32641. to choose the best device to open.
  32642. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  32643. fails to open, then a default device will be used
  32644. instead. If false, then on failure, no device is
  32645. opened.
  32646. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  32647. name, then that will be used as the default device
  32648. (assuming that there wasn't one specified in the XML).
  32649. The string can actually be a simple wildcard, containing "*"
  32650. and "?" characters
  32651. @param preferredSetupOptions if this is non-null, the structure will be used as the
  32652. set of preferred settings when opening the device. If you
  32653. use this parameter, the preferredDefaultDeviceName
  32654. field will be ignored
  32655. @returns an error message if anything went wrong, or an empty string if it worked ok.
  32656. */
  32657. const String initialise (int numInputChannelsNeeded,
  32658. int numOutputChannelsNeeded,
  32659. const XmlElement* savedState,
  32660. bool selectDefaultDeviceOnFailure,
  32661. const String& preferredDefaultDeviceName = String::empty,
  32662. const AudioDeviceSetup* preferredSetupOptions = 0);
  32663. /** Returns some XML representing the current state of the manager.
  32664. This stores the current device, its samplerate, block size, etc, and
  32665. can be restored later with initialise().
  32666. */
  32667. XmlElement* createStateXml() const;
  32668. /** Returns the current device properties that are in use.
  32669. @see setAudioDeviceSetup
  32670. */
  32671. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  32672. /** Changes the current device or its settings.
  32673. If you want to change a device property, like the current sample rate or
  32674. block size, you can call getAudioDeviceSetup() to retrieve the current
  32675. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  32676. and pass it back into this method to apply the new settings.
  32677. @param newSetup the settings that you'd like to use
  32678. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  32679. settings will be taken as having been explicitly chosen by the
  32680. user, and the next time createStateXml() is called, these settings
  32681. will be returned. If it's false, then the device is treated as a
  32682. temporary or default device, and a call to createStateXml() will
  32683. return either the last settings that were made with treatAsChosenDevice
  32684. as true, or the last XML settings that were passed into initialise().
  32685. @returns an error message if anything went wrong, or an empty string if it worked ok.
  32686. @see getAudioDeviceSetup
  32687. */
  32688. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  32689. bool treatAsChosenDevice);
  32690. /** Returns the currently-active audio device. */
  32691. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  32692. /** Returns the type of audio device currently in use.
  32693. @see setCurrentAudioDeviceType
  32694. */
  32695. const String getCurrentAudioDeviceType() const { return currentDeviceType; }
  32696. /** Returns the currently active audio device type object.
  32697. Don't keep a copy of this pointer - it's owned by the device manager and could
  32698. change at any time.
  32699. */
  32700. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  32701. /** Changes the class of audio device being used.
  32702. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  32703. this because there's only one type: CoreAudio.
  32704. For a list of types, see getAvailableDeviceTypes().
  32705. */
  32706. void setCurrentAudioDeviceType (const String& type,
  32707. bool treatAsChosenDevice);
  32708. /** Closes the currently-open device.
  32709. You can call restartLastAudioDevice() later to reopen it in the same state
  32710. that it was just in.
  32711. */
  32712. void closeAudioDevice();
  32713. /** Tries to reload the last audio device that was running.
  32714. Note that this only reloads the last device that was running before
  32715. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  32716. and can only be called after a device has been opened with SetAudioDevice().
  32717. If a device is already open, this call will do nothing.
  32718. */
  32719. void restartLastAudioDevice();
  32720. /** Registers an audio callback to be used.
  32721. The manager will redirect callbacks from whatever audio device is currently
  32722. in use to all registered callback objects. If more than one callback is
  32723. active, they will all be given the same input data, and their outputs will
  32724. be summed.
  32725. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  32726. object before returning.
  32727. To remove a callback, use removeAudioCallback().
  32728. */
  32729. void addAudioCallback (AudioIODeviceCallback* newCallback);
  32730. /** Deregisters a previously added callback.
  32731. If necessary, this method will invoke audioDeviceStopped() on the callback
  32732. object before returning.
  32733. @see addAudioCallback
  32734. */
  32735. void removeAudioCallback (AudioIODeviceCallback* callback);
  32736. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  32737. Returns a value between 0 and 1.0
  32738. */
  32739. double getCpuUsage() const;
  32740. /** Enables or disables a midi input device.
  32741. The list of devices can be obtained with the MidiInput::getDevices() method.
  32742. Any incoming messages from enabled input devices will be forwarded on to all the
  32743. listeners that have been registered with the addMidiInputCallback() method. They
  32744. can either register for messages from a particular device, or from just the
  32745. "default" midi input.
  32746. Routing the midi input via an AudioDeviceManager means that when a listener
  32747. registers for the default midi input, this default device can be changed by the
  32748. manager without the listeners having to know about it or re-register.
  32749. It also means that a listener can stay registered for a midi input that is disabled
  32750. or not present, so that when the input is re-enabled, the listener will start
  32751. receiving messages again.
  32752. @see addMidiInputCallback, isMidiInputEnabled
  32753. */
  32754. void setMidiInputEnabled (const String& midiInputDeviceName, bool enabled);
  32755. /** Returns true if a given midi input device is being used.
  32756. @see setMidiInputEnabled
  32757. */
  32758. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  32759. /** Registers a listener for callbacks when midi events arrive from a midi input.
  32760. The device name can be empty to indicate that it wants events from whatever the
  32761. current "default" device is. Or it can be the name of one of the midi input devices
  32762. (see MidiInput::getDevices() for the names).
  32763. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  32764. events forwarded on to listeners.
  32765. */
  32766. void addMidiInputCallback (const String& midiInputDeviceName,
  32767. MidiInputCallback* callback);
  32768. /** Removes a listener that was previously registered with addMidiInputCallback().
  32769. */
  32770. void removeMidiInputCallback (const String& midiInputDeviceName,
  32771. MidiInputCallback* callback);
  32772. /** Sets a midi output device to use as the default.
  32773. The list of devices can be obtained with the MidiOutput::getDevices() method.
  32774. The specified device will be opened automatically and can be retrieved with the
  32775. getDefaultMidiOutput() method.
  32776. Pass in an empty string to deselect all devices. For the default device, you
  32777. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  32778. @see getDefaultMidiOutput, getDefaultMidiOutputName
  32779. */
  32780. void setDefaultMidiOutput (const String& deviceName);
  32781. /** Returns the name of the default midi output.
  32782. @see setDefaultMidiOutput, getDefaultMidiOutput
  32783. */
  32784. const String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  32785. /** Returns the current default midi output device.
  32786. If no device has been selected, or the device can't be opened, this will
  32787. return 0.
  32788. @see getDefaultMidiOutputName
  32789. */
  32790. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  32791. /** Returns a list of the types of device supported.
  32792. */
  32793. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  32794. /** Creates a list of available types.
  32795. This will add a set of new AudioIODeviceType objects to the specified list, to
  32796. represent each available types of device.
  32797. You can override this if your app needs to do something specific, like avoid
  32798. using DirectSound devices, etc.
  32799. */
  32800. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  32801. /** Plays a beep through the current audio device.
  32802. This is here to allow the audio setup UI panels to easily include a "test"
  32803. button so that the user can check where the audio is coming from.
  32804. */
  32805. void playTestSound();
  32806. /** Turns on level-measuring.
  32807. When enabled, the device manager will measure the peak input level
  32808. across all channels, and you can get this level by calling getCurrentInputLevel().
  32809. This is mainly intended for audio setup UI panels to use to create a mic
  32810. level display, so that the user can check that they've selected the right
  32811. device.
  32812. A simple filter is used to make the level decay smoothly, but this is
  32813. only intended for giving rough feedback, and not for any kind of accurate
  32814. measurement.
  32815. */
  32816. void enableInputLevelMeasurement (bool enableMeasurement);
  32817. /** Returns the current input level.
  32818. To use this, you must first enable it by calling enableInputLevelMeasurement().
  32819. See enableInputLevelMeasurement() for more info.
  32820. */
  32821. double getCurrentInputLevel() const;
  32822. /** Returns the a lock that can be used to synchronise access to the audio callback.
  32823. Obviously while this is locked, you're blocking the audio thread from running, so
  32824. it must only be used for very brief periods when absolutely necessary.
  32825. */
  32826. CriticalSection& getAudioCallbackLock() throw() { return audioCallbackLock; }
  32827. /** Returns the a lock that can be used to synchronise access to the midi callback.
  32828. Obviously while this is locked, you're blocking the midi system from running, so
  32829. it must only be used for very brief periods when absolutely necessary.
  32830. */
  32831. CriticalSection& getMidiCallbackLock() throw() { return midiCallbackLock; }
  32832. private:
  32833. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  32834. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  32835. AudioDeviceSetup currentSetup;
  32836. ScopedPointer <AudioIODevice> currentAudioDevice;
  32837. SortedSet <AudioIODeviceCallback*> callbacks;
  32838. int numInputChansNeeded, numOutputChansNeeded;
  32839. String currentDeviceType;
  32840. BigInteger inputChannels, outputChannels;
  32841. ScopedPointer <XmlElement> lastExplicitSettings;
  32842. mutable bool listNeedsScanning;
  32843. bool useInputNames;
  32844. int inputLevelMeasurementEnabledCount;
  32845. double inputLevel;
  32846. ScopedPointer <AudioSampleBuffer> testSound;
  32847. int testSoundPosition;
  32848. AudioSampleBuffer tempBuffer;
  32849. StringArray midiInsFromXml;
  32850. OwnedArray <MidiInput> enabledMidiInputs;
  32851. Array <MidiInputCallback*> midiCallbacks;
  32852. StringArray midiCallbackDevices;
  32853. String defaultMidiOutputName;
  32854. ScopedPointer <MidiOutput> defaultMidiOutput;
  32855. CriticalSection audioCallbackLock, midiCallbackLock;
  32856. double cpuUsageMs, timeToCpuScale;
  32857. class CallbackHandler : public AudioIODeviceCallback,
  32858. public MidiInputCallback
  32859. {
  32860. public:
  32861. void audioDeviceIOCallback (const float**, int, float**, int, int);
  32862. void audioDeviceAboutToStart (AudioIODevice*);
  32863. void audioDeviceStopped();
  32864. void handleIncomingMidiMessage (MidiInput*, const MidiMessage&);
  32865. AudioDeviceManager* owner;
  32866. };
  32867. CallbackHandler callbackHandler;
  32868. friend class CallbackHandler;
  32869. void audioDeviceIOCallbackInt (const float** inputChannelData, int totalNumInputChannels,
  32870. float** outputChannelData, int totalNumOutputChannels, int numSamples);
  32871. void audioDeviceAboutToStartInt (AudioIODevice*);
  32872. void audioDeviceStoppedInt();
  32873. void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
  32874. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  32875. const BigInteger& ins, const BigInteger& outs);
  32876. void stopDevice();
  32877. void updateXml();
  32878. void createDeviceTypesIfNeeded();
  32879. void scanDevicesIfNeeded();
  32880. void deleteCurrentDevice();
  32881. double chooseBestSampleRate (double preferred) const;
  32882. int chooseBestBufferSize (int preferred) const;
  32883. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  32884. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  32885. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager);
  32886. };
  32887. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  32888. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  32889. #endif
  32890. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  32891. #endif
  32892. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  32893. #endif
  32894. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  32895. #endif
  32896. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  32897. #endif
  32898. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  32899. /*** Start of inlined file: juce_Decibels.h ***/
  32900. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  32901. #define __JUCE_DECIBELS_JUCEHEADER__
  32902. /**
  32903. This class contains some helpful static methods for dealing with decibel values.
  32904. */
  32905. class Decibels
  32906. {
  32907. public:
  32908. /** Converts a dBFS value to its equivalent gain level.
  32909. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values. Any
  32910. decibel value lower than minusInfinityDb will return a gain of 0.
  32911. */
  32912. template <typename Type>
  32913. static Type decibelsToGain (const Type decibels,
  32914. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  32915. {
  32916. return decibels > minusInfinityDb ? powf ((Type) 10.0, decibels * (Type) 0.05)
  32917. : Type();
  32918. }
  32919. /** Converts a gain level into a dBFS value.
  32920. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values.
  32921. If the gain is 0 (or negative), then the method will return the value
  32922. provided as minusInfinityDb.
  32923. */
  32924. template <typename Type>
  32925. static Type gainToDecibels (const Type gain,
  32926. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  32927. {
  32928. return gain > Type() ? jmax (minusInfinityDb, (Type) std::log10 (gain) * (Type) 20.0)
  32929. : minusInfinityDb;
  32930. }
  32931. /** Converts a decibel reading to a string, with the 'dB' suffix.
  32932. If the decibel value is lower than minusInfinityDb, the return value will
  32933. be "-INF dB".
  32934. */
  32935. template <typename Type>
  32936. static const String toString (const Type decibels,
  32937. const int decimalPlaces = 2,
  32938. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  32939. {
  32940. String s;
  32941. if (decibels <= minusInfinityDb)
  32942. {
  32943. s = "-INF dB";
  32944. }
  32945. else
  32946. {
  32947. if (decibels >= Type())
  32948. s << '+';
  32949. s << String (decibels, decimalPlaces) << " dB";
  32950. }
  32951. return s;
  32952. }
  32953. private:
  32954. enum
  32955. {
  32956. defaultMinusInfinitydB = -100
  32957. };
  32958. Decibels(); // This class can't be instantiated, it's just a holder for static methods..
  32959. JUCE_DECLARE_NON_COPYABLE (Decibels);
  32960. };
  32961. #endif // __JUCE_DECIBELS_JUCEHEADER__
  32962. /*** End of inlined file: juce_Decibels.h ***/
  32963. #endif
  32964. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  32965. #endif
  32966. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  32967. #endif
  32968. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  32969. /*** Start of inlined file: juce_MidiFile.h ***/
  32970. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  32971. #define __JUCE_MIDIFILE_JUCEHEADER__
  32972. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  32973. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  32974. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  32975. /**
  32976. A sequence of timestamped midi messages.
  32977. This allows the sequence to be manipulated, and also to be read from and
  32978. written to a standard midi file.
  32979. @see MidiMessage, MidiFile
  32980. */
  32981. class JUCE_API MidiMessageSequence
  32982. {
  32983. public:
  32984. /** Creates an empty midi sequence object. */
  32985. MidiMessageSequence();
  32986. /** Creates a copy of another sequence. */
  32987. MidiMessageSequence (const MidiMessageSequence& other);
  32988. /** Replaces this sequence with another one. */
  32989. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  32990. /** Destructor. */
  32991. ~MidiMessageSequence();
  32992. /** Structure used to hold midi events in the sequence.
  32993. These structures act as 'handles' on the events as they are moved about in
  32994. the list, and make it quick to find the matching note-offs for note-on events.
  32995. @see MidiMessageSequence::getEventPointer
  32996. */
  32997. class MidiEventHolder
  32998. {
  32999. public:
  33000. /** Destructor. */
  33001. ~MidiEventHolder();
  33002. /** The message itself, whose timestamp is used to specify the event's time.
  33003. */
  33004. MidiMessage message;
  33005. /** The matching note-off event (if this is a note-on event).
  33006. If this isn't a note-on, this pointer will be null.
  33007. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  33008. note-offs up-to-date after events have been moved around in the sequence
  33009. or deleted.
  33010. */
  33011. MidiEventHolder* noteOffObject;
  33012. private:
  33013. friend class MidiMessageSequence;
  33014. MidiEventHolder (const MidiMessage& message);
  33015. JUCE_LEAK_DETECTOR (MidiEventHolder);
  33016. };
  33017. /** Clears the sequence. */
  33018. void clear();
  33019. /** Returns the number of events in the sequence. */
  33020. int getNumEvents() const;
  33021. /** Returns a pointer to one of the events. */
  33022. MidiEventHolder* getEventPointer (int index) const;
  33023. /** Returns the time of the note-up that matches the note-on at this index.
  33024. If the event at this index isn't a note-on, it'll just return 0.
  33025. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  33026. */
  33027. double getTimeOfMatchingKeyUp (int index) const;
  33028. /** Returns the index of the note-up that matches the note-on at this index.
  33029. If the event at this index isn't a note-on, it'll just return -1.
  33030. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  33031. */
  33032. int getIndexOfMatchingKeyUp (int index) const;
  33033. /** Returns the index of an event. */
  33034. int getIndexOf (MidiEventHolder* event) const;
  33035. /** Returns the index of the first event on or after the given timestamp.
  33036. If the time is beyond the end of the sequence, this will return the
  33037. number of events.
  33038. */
  33039. int getNextIndexAtTime (double timeStamp) const;
  33040. /** Returns the timestamp of the first event in the sequence.
  33041. @see getEndTime
  33042. */
  33043. double getStartTime() const;
  33044. /** Returns the timestamp of the last event in the sequence.
  33045. @see getStartTime
  33046. */
  33047. double getEndTime() const;
  33048. /** Returns the timestamp of the event at a given index.
  33049. If the index is out-of-range, this will return 0.0
  33050. */
  33051. double getEventTime (int index) const;
  33052. /** Inserts a midi message into the sequence.
  33053. The index at which the new message gets inserted will depend on its timestamp,
  33054. because the sequence is kept sorted.
  33055. Remember to call updateMatchedPairs() after adding note-on events.
  33056. @param newMessage the new message to add (an internal copy will be made)
  33057. @param timeAdjustment an optional value to add to the timestamp of the message
  33058. that will be inserted
  33059. @see updateMatchedPairs
  33060. */
  33061. void addEvent (const MidiMessage& newMessage,
  33062. double timeAdjustment = 0);
  33063. /** Deletes one of the events in the sequence.
  33064. Remember to call updateMatchedPairs() after removing events.
  33065. @param index the index of the event to delete
  33066. @param deleteMatchingNoteUp whether to also remove the matching note-off
  33067. if the event you're removing is a note-on
  33068. */
  33069. void deleteEvent (int index, bool deleteMatchingNoteUp);
  33070. /** Merges another sequence into this one.
  33071. Remember to call updateMatchedPairs() after using this method.
  33072. @param other the sequence to add from
  33073. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  33074. as they are read from the other sequence
  33075. @param firstAllowableDestTime events will not be added if their time is earlier
  33076. than this time. (This is after their time has been adjusted
  33077. by the timeAdjustmentDelta)
  33078. @param endOfAllowableDestTimes events will not be added if their time is equal to
  33079. or greater than this time. (This is after their time has
  33080. been adjusted by the timeAdjustmentDelta)
  33081. */
  33082. void addSequence (const MidiMessageSequence& other,
  33083. double timeAdjustmentDelta,
  33084. double firstAllowableDestTime,
  33085. double endOfAllowableDestTimes);
  33086. /** Makes sure all the note-on and note-off pairs are up-to-date.
  33087. Call this after moving messages about or deleting/adding messages, and it
  33088. will scan the list and make sure all the note-offs in the MidiEventHolder
  33089. structures are pointing at the correct ones.
  33090. */
  33091. void updateMatchedPairs();
  33092. /** Copies all the messages for a particular midi channel to another sequence.
  33093. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  33094. @param destSequence the sequence that the chosen events should be copied to
  33095. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  33096. channel) will also be copied across.
  33097. @see extractSysExMessages
  33098. */
  33099. void extractMidiChannelMessages (int channelNumberToExtract,
  33100. MidiMessageSequence& destSequence,
  33101. bool alsoIncludeMetaEvents) const;
  33102. /** Copies all midi sys-ex messages to another sequence.
  33103. @param destSequence this is the sequence to which any sys-exes in this sequence
  33104. will be added
  33105. @see extractMidiChannelMessages
  33106. */
  33107. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  33108. /** Removes any messages in this sequence that have a specific midi channel.
  33109. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  33110. */
  33111. void deleteMidiChannelMessages (int channelNumberToRemove);
  33112. /** Removes any sys-ex messages from this sequence.
  33113. */
  33114. void deleteSysExMessages();
  33115. /** Adds an offset to the timestamps of all events in the sequence.
  33116. @param deltaTime the amount to add to each timestamp.
  33117. */
  33118. void addTimeToMessages (double deltaTime);
  33119. /** Scans through the sequence to determine the state of any midi controllers at
  33120. a given time.
  33121. This will create a sequence of midi controller changes that can be
  33122. used to set all midi controllers to the state they would be in at the
  33123. specified time within this sequence.
  33124. As well as controllers, it will also recreate the midi program number
  33125. and pitch bend position.
  33126. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  33127. for other channels will be ignored.
  33128. @param time the time at which you want to find out the state - there are
  33129. no explicit units for this time measurement, it's the same units
  33130. as used for the timestamps of the messages
  33131. @param resultMessages an array to which midi controller-change messages will be added. This
  33132. will be the minimum number of controller changes to recreate the
  33133. state at the required time.
  33134. */
  33135. void createControllerUpdatesForTime (int channelNumber, double time,
  33136. OwnedArray<MidiMessage>& resultMessages);
  33137. /** Swaps this sequence with another one. */
  33138. void swapWith (MidiMessageSequence& other) throw();
  33139. /** @internal */
  33140. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  33141. const MidiMessageSequence::MidiEventHolder* second) throw();
  33142. private:
  33143. friend class MidiFile;
  33144. OwnedArray <MidiEventHolder> list;
  33145. void sort();
  33146. JUCE_LEAK_DETECTOR (MidiMessageSequence);
  33147. };
  33148. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  33149. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  33150. /**
  33151. Reads/writes standard midi format files.
  33152. To read a midi file, create a MidiFile object and call its readFrom() method. You
  33153. can then get the individual midi tracks from it using the getTrack() method.
  33154. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  33155. to it using the addTrack() method, and then call its writeTo() method to stream
  33156. it out.
  33157. @see MidiMessageSequence
  33158. */
  33159. class JUCE_API MidiFile
  33160. {
  33161. public:
  33162. /** Creates an empty MidiFile object.
  33163. */
  33164. MidiFile();
  33165. /** Destructor. */
  33166. ~MidiFile();
  33167. /** Returns the number of tracks in the file.
  33168. @see getTrack, addTrack
  33169. */
  33170. int getNumTracks() const throw();
  33171. /** Returns a pointer to one of the tracks in the file.
  33172. @returns a pointer to the track, or 0 if the index is out-of-range
  33173. @see getNumTracks, addTrack
  33174. */
  33175. const MidiMessageSequence* getTrack (int index) const throw();
  33176. /** Adds a midi track to the file.
  33177. This will make its own internal copy of the sequence that is passed-in.
  33178. @see getNumTracks, getTrack
  33179. */
  33180. void addTrack (const MidiMessageSequence& trackSequence);
  33181. /** Removes all midi tracks from the file.
  33182. @see getNumTracks
  33183. */
  33184. void clear();
  33185. /** Returns the raw time format code that will be written to a stream.
  33186. After reading a midi file, this method will return the time-format that
  33187. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  33188. or setSmpteTimeFormat() methods.
  33189. If the value returned is positive, it indicates the number of midi ticks
  33190. per quarter-note - see setTicksPerQuarterNote().
  33191. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  33192. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  33193. */
  33194. short getTimeFormat() const throw();
  33195. /** Sets the time format to use when this file is written to a stream.
  33196. If this is called, the file will be written as bars/beats using the
  33197. specified resolution, rather than SMPTE absolute times, as would be
  33198. used if setSmpteTimeFormat() had been called instead.
  33199. @param ticksPerQuarterNote e.g. 96, 960
  33200. @see setSmpteTimeFormat
  33201. */
  33202. void setTicksPerQuarterNote (int ticksPerQuarterNote) throw();
  33203. /** Sets the time format to use when this file is written to a stream.
  33204. If this is called, the file will be written using absolute times, rather
  33205. than bars/beats as would be the case if setTicksPerBeat() had been called
  33206. instead.
  33207. @param framesPerSecond must be 24, 25, 29 or 30
  33208. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  33209. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  33210. timing, setSmpteTimeFormat (25, 40)
  33211. @see setTicksPerBeat
  33212. */
  33213. void setSmpteTimeFormat (int framesPerSecond,
  33214. int subframeResolution) throw();
  33215. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  33216. Useful for finding the positions of all the tempo changes in a file.
  33217. @param tempoChangeEvents a list to which all the events will be added
  33218. */
  33219. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  33220. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  33221. Useful for finding the positions of all the tempo changes in a file.
  33222. @param timeSigEvents a list to which all the events will be added
  33223. */
  33224. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  33225. /** Returns the latest timestamp in any of the tracks.
  33226. (Useful for finding the length of the file).
  33227. */
  33228. double getLastTimestamp() const;
  33229. /** Reads a midi file format stream.
  33230. After calling this, you can get the tracks that were read from the file by using the
  33231. getNumTracks() and getTrack() methods.
  33232. The timestamps of the midi events in the tracks will represent their positions in
  33233. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  33234. method.
  33235. @returns true if the stream was read successfully
  33236. */
  33237. bool readFrom (InputStream& sourceStream);
  33238. /** Writes the midi tracks as a standard midi file.
  33239. @returns true if the operation succeeded.
  33240. */
  33241. bool writeTo (OutputStream& destStream);
  33242. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  33243. This will use the midi time format and tempo/time signature info in the
  33244. tracks to convert all the timestamps to absolute values in seconds.
  33245. */
  33246. void convertTimestampTicksToSeconds();
  33247. private:
  33248. OwnedArray <MidiMessageSequence> tracks;
  33249. short timeFormat;
  33250. void readNextTrack (const uint8* data, int size);
  33251. void writeTrack (OutputStream& mainOut, int trackNum);
  33252. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiFile);
  33253. };
  33254. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  33255. /*** End of inlined file: juce_MidiFile.h ***/
  33256. #endif
  33257. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  33258. #endif
  33259. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33260. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  33261. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33262. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33263. class MidiKeyboardState;
  33264. /**
  33265. Receives events from a MidiKeyboardState object.
  33266. @see MidiKeyboardState
  33267. */
  33268. class JUCE_API MidiKeyboardStateListener
  33269. {
  33270. public:
  33271. MidiKeyboardStateListener() throw() {}
  33272. virtual ~MidiKeyboardStateListener() {}
  33273. /** Called when one of the MidiKeyboardState's keys is pressed.
  33274. This will be called synchronously when the state is either processing a
  33275. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  33276. when a note is being played with its MidiKeyboardState::noteOn() method.
  33277. Note that this callback could happen from an audio callback thread, so be
  33278. careful not to block, and avoid any UI activity in the callback.
  33279. */
  33280. virtual void handleNoteOn (MidiKeyboardState* source,
  33281. int midiChannel, int midiNoteNumber, float velocity) = 0;
  33282. /** Called when one of the MidiKeyboardState's keys is released.
  33283. This will be called synchronously when the state is either processing a
  33284. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  33285. when a note is being played with its MidiKeyboardState::noteOff() method.
  33286. Note that this callback could happen from an audio callback thread, so be
  33287. careful not to block, and avoid any UI activity in the callback.
  33288. */
  33289. virtual void handleNoteOff (MidiKeyboardState* source,
  33290. int midiChannel, int midiNoteNumber) = 0;
  33291. };
  33292. /**
  33293. Represents a piano keyboard, keeping track of which keys are currently pressed.
  33294. This object can parse a stream of midi events, using them to update its idea
  33295. of which keys are pressed for each individiual midi channel.
  33296. When keys go up or down, it can broadcast these events to listener objects.
  33297. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  33298. methods, and midi messages for these events will be merged into the
  33299. midi stream that gets processed by processNextMidiBuffer().
  33300. */
  33301. class JUCE_API MidiKeyboardState
  33302. {
  33303. public:
  33304. MidiKeyboardState();
  33305. ~MidiKeyboardState();
  33306. /** Resets the state of the object.
  33307. All internal data for all the channels is reset, but no events are sent as a
  33308. result.
  33309. If you want to release any keys that are currently down, and to send out note-up
  33310. midi messages for this, use the allNotesOff() method instead.
  33311. */
  33312. void reset();
  33313. /** Returns true if the given midi key is currently held down for the given midi channel.
  33314. The channel number must be between 1 and 16. If you want to see if any notes are
  33315. on for a range of channels, use the isNoteOnForChannels() method.
  33316. */
  33317. bool isNoteOn (int midiChannel, int midiNoteNumber) const throw();
  33318. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  33319. The channel mask has a bit set for each midi channel you want to test for - bit
  33320. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  33321. If a note is on for at least one of the specified channels, this returns true.
  33322. */
  33323. bool isNoteOnForChannels (int midiChannelMask, int midiNoteNumber) const throw();
  33324. /** Turns a specified note on.
  33325. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  33326. next call to processNextMidiBuffer().
  33327. It will also trigger a synchronous callback to the listeners to tell them that the key has
  33328. gone down.
  33329. */
  33330. void noteOn (int midiChannel, int midiNoteNumber, float velocity);
  33331. /** Turns a specified note off.
  33332. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  33333. next call to processNextMidiBuffer().
  33334. It will also trigger a synchronous callback to the listeners to tell them that the key has
  33335. gone up.
  33336. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  33337. */
  33338. void noteOff (int midiChannel, int midiNoteNumber);
  33339. /** This will turn off any currently-down notes for the given midi channel.
  33340. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  33341. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  33342. and events being added to the midi stream.
  33343. */
  33344. void allNotesOff (int midiChannel);
  33345. /** Looks at a key-up/down event and uses it to update the state of this object.
  33346. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  33347. instead.
  33348. */
  33349. void processNextMidiEvent (const MidiMessage& message);
  33350. /** Scans a midi stream for up/down events and adds its own events to it.
  33351. This will look for any up/down events and use them to update the internal state,
  33352. synchronously making suitable callbacks to the listeners.
  33353. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  33354. and noteOff() calls will be added into the buffer.
  33355. Only the section of the buffer whose timestamps are between startSample and
  33356. (startSample + numSamples) will be affected, and any events added will be placed
  33357. between these times.
  33358. If you're going to use this method, you'll need to keep calling it regularly for
  33359. it to work satisfactorily.
  33360. To process a single midi event at a time, use the processNextMidiEvent() method
  33361. instead.
  33362. */
  33363. void processNextMidiBuffer (MidiBuffer& buffer,
  33364. int startSample,
  33365. int numSamples,
  33366. bool injectIndirectEvents);
  33367. /** Registers a listener for callbacks when keys go up or down.
  33368. @see removeListener
  33369. */
  33370. void addListener (MidiKeyboardStateListener* listener);
  33371. /** Deregisters a listener.
  33372. @see addListener
  33373. */
  33374. void removeListener (MidiKeyboardStateListener* listener);
  33375. private:
  33376. CriticalSection lock;
  33377. uint16 noteStates [128];
  33378. MidiBuffer eventsToAdd;
  33379. Array <MidiKeyboardStateListener*> listeners;
  33380. void noteOnInternal (int midiChannel, int midiNoteNumber, float velocity);
  33381. void noteOffInternal (int midiChannel, int midiNoteNumber);
  33382. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardState);
  33383. };
  33384. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  33385. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  33386. #endif
  33387. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  33388. #endif
  33389. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  33390. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  33391. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  33392. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  33393. /**
  33394. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  33395. processing by a block-based audio callback.
  33396. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  33397. so it can easily use a midi input or keyboard component as its source.
  33398. @see MidiMessage, MidiInput
  33399. */
  33400. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  33401. public MidiInputCallback
  33402. {
  33403. public:
  33404. /** Creates a MidiMessageCollector. */
  33405. MidiMessageCollector();
  33406. /** Destructor. */
  33407. ~MidiMessageCollector();
  33408. /** Clears any messages from the queue.
  33409. You need to call this method before starting to use the collector, so that
  33410. it knows the correct sample rate to use.
  33411. */
  33412. void reset (double sampleRate);
  33413. /** Takes an incoming real-time message and adds it to the queue.
  33414. The message's timestamp is taken, and it will be ready for retrieval as part
  33415. of the block returned by the next call to removeNextBlockOfMessages().
  33416. This method is fully thread-safe when overlapping calls are made with
  33417. removeNextBlockOfMessages().
  33418. */
  33419. void addMessageToQueue (const MidiMessage& message);
  33420. /** Removes all the pending messages from the queue as a buffer.
  33421. This will also correct the messages' timestamps to make sure they're in
  33422. the range 0 to numSamples - 1.
  33423. This call should be made regularly by something like an audio processing
  33424. callback, because the time that it happens is used in calculating the
  33425. midi event positions.
  33426. This method is fully thread-safe when overlapping calls are made with
  33427. addMessageToQueue().
  33428. */
  33429. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  33430. /** @internal */
  33431. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  33432. /** @internal */
  33433. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  33434. /** @internal */
  33435. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  33436. private:
  33437. double lastCallbackTime;
  33438. CriticalSection midiCallbackLock;
  33439. MidiBuffer incomingMessages;
  33440. double sampleRate;
  33441. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiMessageCollector);
  33442. };
  33443. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  33444. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  33445. #endif
  33446. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  33447. #endif
  33448. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  33449. #endif
  33450. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  33451. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  33452. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  33453. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  33454. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  33455. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  33456. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  33457. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  33458. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  33459. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  33460. /*** Start of inlined file: juce_AudioProcessor.h ***/
  33461. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  33462. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  33463. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  33464. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  33465. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  33466. class AudioProcessor;
  33467. /**
  33468. Base class for the component that acts as the GUI for an AudioProcessor.
  33469. Derive your editor component from this class, and create an instance of it
  33470. by overriding the AudioProcessor::createEditor() method.
  33471. @see AudioProcessor, GenericAudioProcessorEditor
  33472. */
  33473. class JUCE_API AudioProcessorEditor : public Component
  33474. {
  33475. protected:
  33476. /** Creates an editor for the specified processor.
  33477. */
  33478. AudioProcessorEditor (AudioProcessor* owner);
  33479. public:
  33480. /** Destructor. */
  33481. ~AudioProcessorEditor();
  33482. /** Returns a pointer to the processor that this editor represents. */
  33483. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  33484. private:
  33485. AudioProcessor* const owner;
  33486. JUCE_DECLARE_NON_COPYABLE (AudioProcessorEditor);
  33487. };
  33488. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  33489. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  33490. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  33491. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  33492. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  33493. class AudioProcessor;
  33494. /**
  33495. Base class for listeners that want to know about changes to an AudioProcessor.
  33496. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  33497. @see AudioProcessor
  33498. */
  33499. class JUCE_API AudioProcessorListener
  33500. {
  33501. public:
  33502. /** Destructor. */
  33503. virtual ~AudioProcessorListener() {}
  33504. /** Receives a callback when a parameter is changed.
  33505. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  33506. many audio processors will change their parameter during their audio callback.
  33507. This means that not only has your handler code got to be completely thread-safe,
  33508. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  33509. this event on your message thread, use this callback to trigger an AsyncUpdater
  33510. or ChangeBroadcaster which you can respond to on the message thread.
  33511. */
  33512. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  33513. int parameterIndex,
  33514. float newValue) = 0;
  33515. /** Called to indicate that something else in the plugin has changed, like its
  33516. program, number of parameters, etc.
  33517. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  33518. call it during their audio callback. This means that not only has your handler code
  33519. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  33520. blocking. If you need to handle this event on your message thread, use this callback
  33521. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  33522. message thread.
  33523. */
  33524. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  33525. /** Indicates that a parameter change gesture has started.
  33526. E.g. if the user is dragging a slider, this would be called when they first
  33527. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  33528. called when they release it.
  33529. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  33530. call it during their audio callback. This means that not only has your handler code
  33531. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  33532. blocking. If you need to handle this event on your message thread, use this callback
  33533. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  33534. message thread.
  33535. @see audioProcessorParameterChangeGestureEnd
  33536. */
  33537. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  33538. int parameterIndex);
  33539. /** Indicates that a parameter change gesture has finished.
  33540. E.g. if the user is dragging a slider, this would be called when they release
  33541. the mouse button.
  33542. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  33543. call it during their audio callback. This means that not only has your handler code
  33544. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  33545. blocking. If you need to handle this event on your message thread, use this callback
  33546. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  33547. message thread.
  33548. @see audioProcessorParameterChangeGestureBegin
  33549. */
  33550. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  33551. int parameterIndex);
  33552. };
  33553. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  33554. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  33555. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  33556. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  33557. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  33558. /**
  33559. A subclass of AudioPlayHead can supply information about the position and
  33560. status of a moving play head during audio playback.
  33561. One of these can be supplied to an AudioProcessor object so that it can find
  33562. out about the position of the audio that it is rendering.
  33563. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  33564. */
  33565. class JUCE_API AudioPlayHead
  33566. {
  33567. protected:
  33568. AudioPlayHead() {}
  33569. public:
  33570. virtual ~AudioPlayHead() {}
  33571. /** Frame rate types. */
  33572. enum FrameRateType
  33573. {
  33574. fps24 = 0,
  33575. fps25 = 1,
  33576. fps2997 = 2,
  33577. fps30 = 3,
  33578. fps2997drop = 4,
  33579. fps30drop = 5,
  33580. fpsUnknown = 99
  33581. };
  33582. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  33583. */
  33584. struct CurrentPositionInfo
  33585. {
  33586. /** The tempo in BPM */
  33587. double bpm;
  33588. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  33589. int timeSigNumerator;
  33590. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  33591. int timeSigDenominator;
  33592. /** The current play position, in seconds from the start of the edit. */
  33593. double timeInSeconds;
  33594. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  33595. double editOriginTime;
  33596. /** The current play position in pulses-per-quarter-note.
  33597. This is the number of quarter notes since the edit start.
  33598. */
  33599. double ppqPosition;
  33600. /** The position of the start of the last bar, in pulses-per-quarter-note.
  33601. This is the number of quarter notes from the start of the edit to the
  33602. start of the current bar.
  33603. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  33604. it's not available, the value will be 0.
  33605. */
  33606. double ppqPositionOfLastBarStart;
  33607. /** The video frame rate, if applicable. */
  33608. FrameRateType frameRate;
  33609. /** True if the transport is currently playing. */
  33610. bool isPlaying;
  33611. /** True if the transport is currently recording.
  33612. (When isRecording is true, then isPlaying will also be true).
  33613. */
  33614. bool isRecording;
  33615. bool operator== (const CurrentPositionInfo& other) const throw();
  33616. bool operator!= (const CurrentPositionInfo& other) const throw();
  33617. void resetToDefault();
  33618. };
  33619. /** Fills-in the given structure with details about the transport's
  33620. position at the start of the current processing block.
  33621. */
  33622. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  33623. };
  33624. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  33625. /*** End of inlined file: juce_AudioPlayHead.h ***/
  33626. /**
  33627. Base class for audio processing filters or plugins.
  33628. This is intended to act as a base class of audio filter that is general enough to
  33629. be wrapped as a VST, AU, RTAS, etc, or used internally.
  33630. It is also used by the plugin hosting code as the wrapper around an instance
  33631. of a loaded plugin.
  33632. Derive your filter class from this base class, and if you're building a plugin,
  33633. you should implement a global function called createPluginFilter() which creates
  33634. and returns a new instance of your subclass.
  33635. */
  33636. class JUCE_API AudioProcessor
  33637. {
  33638. protected:
  33639. /** Constructor.
  33640. You can also do your initialisation tasks in the initialiseFilterInfo()
  33641. call, which will be made after this object has been created.
  33642. */
  33643. AudioProcessor();
  33644. public:
  33645. /** Destructor. */
  33646. virtual ~AudioProcessor();
  33647. /** Returns the name of this processor.
  33648. */
  33649. virtual const String getName() const = 0;
  33650. /** Called before playback starts, to let the filter prepare itself.
  33651. The sample rate is the target sample rate, and will remain constant until
  33652. playback stops.
  33653. The estimatedSamplesPerBlock value is a HINT about the typical number of
  33654. samples that will be processed for each callback, but isn't any kind
  33655. of guarantee. The actual block sizes that the host uses may be different
  33656. each time the callback happens, and may be more or less than this value.
  33657. */
  33658. virtual void prepareToPlay (double sampleRate,
  33659. int estimatedSamplesPerBlock) = 0;
  33660. /** Called after playback has stopped, to let the filter free up any resources it
  33661. no longer needs.
  33662. */
  33663. virtual void releaseResources() = 0;
  33664. /** Renders the next block.
  33665. When this method is called, the buffer contains a number of channels which is
  33666. at least as great as the maximum number of input and output channels that
  33667. this filter is using. It will be filled with the filter's input data and
  33668. should be replaced with the filter's output.
  33669. So for example if your filter has 2 input channels and 4 output channels, then
  33670. the buffer will contain 4 channels, the first two being filled with the
  33671. input data. Your filter should read these, do its processing, and replace
  33672. the contents of all 4 channels with its output.
  33673. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  33674. all filled with data, and your filter should overwrite the first 2 of these
  33675. with its output. But be VERY careful not to write anything to the last 3
  33676. channels, as these might be mapped to memory that the host assumes is read-only!
  33677. Note that if you have more outputs than inputs, then only those channels that
  33678. correspond to an input channel are guaranteed to contain sensible data - e.g.
  33679. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  33680. but the last two channels may contain garbage, so you should be careful not to
  33681. let this pass through without being overwritten or cleared.
  33682. Also note that the buffer may have more channels than are strictly necessary,
  33683. but your should only read/write from the ones that your filter is supposed to
  33684. be using.
  33685. The number of samples in these buffers is NOT guaranteed to be the same for every
  33686. callback, and may be more or less than the estimated value given to prepareToPlay().
  33687. Your code must be able to cope with variable-sized blocks, or you're going to get
  33688. clicks and crashes!
  33689. If the filter is receiving a midi input, then the midiMessages array will be filled
  33690. with the midi messages for this block. Each message's timestamp will indicate the
  33691. message's time, as a number of samples from the start of the block.
  33692. Any messages left in the midi buffer when this method has finished are assumed to
  33693. be the filter's midi output. This means that your filter should be careful to
  33694. clear any incoming messages from the array if it doesn't want them to be passed-on.
  33695. Be very careful about what you do in this callback - it's going to be called by
  33696. the audio thread, so any kind of interaction with the UI is absolutely
  33697. out of the question. If you change a parameter in here and need to tell your UI to
  33698. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  33699. the UI components register as listeners, and then call sendChangeMessage() inside the
  33700. processBlock() method to send out an asynchronous message. You could also use
  33701. the AsyncUpdater class in a similar way.
  33702. */
  33703. virtual void processBlock (AudioSampleBuffer& buffer,
  33704. MidiBuffer& midiMessages) = 0;
  33705. /** Returns the current AudioPlayHead object that should be used to find
  33706. out the state and position of the playhead.
  33707. You can call this from your processBlock() method, and use the AudioPlayHead
  33708. object to get the details about the time of the start of the block currently
  33709. being processed.
  33710. If the host hasn't supplied a playhead object, this will return 0.
  33711. */
  33712. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  33713. /** Returns the current sample rate.
  33714. This can be called from your processBlock() method - it's not guaranteed
  33715. to be valid at any other time, and may return 0 if it's unknown.
  33716. */
  33717. double getSampleRate() const throw() { return sampleRate; }
  33718. /** Returns the current typical block size that is being used.
  33719. This can be called from your processBlock() method - it's not guaranteed
  33720. to be valid at any other time.
  33721. Remember it's not the ONLY block size that may be used when calling
  33722. processBlock, it's just the normal one. The actual block sizes used may be
  33723. larger or smaller than this, and will vary between successive calls.
  33724. */
  33725. int getBlockSize() const throw() { return blockSize; }
  33726. /** Returns the number of input channels that the host will be sending the filter.
  33727. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  33728. number of channels that your filter would prefer to have, and this method lets
  33729. you know how many the host is actually using.
  33730. Note that this method is only valid during or after the prepareToPlay()
  33731. method call. Until that point, the number of channels will be unknown.
  33732. */
  33733. int getNumInputChannels() const throw() { return numInputChannels; }
  33734. /** Returns the number of output channels that the host will be sending the filter.
  33735. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  33736. number of channels that your filter would prefer to have, and this method lets
  33737. you know how many the host is actually using.
  33738. Note that this method is only valid during or after the prepareToPlay()
  33739. method call. Until that point, the number of channels will be unknown.
  33740. */
  33741. int getNumOutputChannels() const throw() { return numOutputChannels; }
  33742. /** Returns the name of one of the input channels, as returned by the host.
  33743. The host might not supply very useful names for channels, and this might be
  33744. something like "1", "2", "left", "right", etc.
  33745. */
  33746. virtual const String getInputChannelName (int channelIndex) const = 0;
  33747. /** Returns the name of one of the output channels, as returned by the host.
  33748. The host might not supply very useful names for channels, and this might be
  33749. something like "1", "2", "left", "right", etc.
  33750. */
  33751. virtual const String getOutputChannelName (int channelIndex) const = 0;
  33752. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  33753. virtual bool isInputChannelStereoPair (int index) const = 0;
  33754. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  33755. virtual bool isOutputChannelStereoPair (int index) const = 0;
  33756. /** This returns the number of samples delay that the filter imposes on the audio
  33757. passing through it.
  33758. The host will call this to find the latency - the filter itself should set this value
  33759. by calling setLatencySamples() as soon as it can during its initialisation.
  33760. */
  33761. int getLatencySamples() const throw() { return latencySamples; }
  33762. /** The filter should call this to set the number of samples delay that it introduces.
  33763. The filter should call this as soon as it can during initialisation, and can call it
  33764. later if the value changes.
  33765. */
  33766. void setLatencySamples (int newLatency);
  33767. /** Returns true if the processor wants midi messages. */
  33768. virtual bool acceptsMidi() const = 0;
  33769. /** Returns true if the processor produces midi messages. */
  33770. virtual bool producesMidi() const = 0;
  33771. /** This returns a critical section that will automatically be locked while the host
  33772. is calling the processBlock() method.
  33773. Use it from your UI or other threads to lock access to variables that are used
  33774. by the process callback, but obviously be careful not to keep it locked for
  33775. too long, because that could cause stuttering playback. If you need to do something
  33776. that'll take a long time and need the processing to stop while it happens, use the
  33777. suspendProcessing() method instead.
  33778. @see suspendProcessing
  33779. */
  33780. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  33781. /** Enables and disables the processing callback.
  33782. If you need to do something time-consuming on a thread and would like to make sure
  33783. the audio processing callback doesn't happen until you've finished, use this
  33784. to disable the callback and re-enable it again afterwards.
  33785. E.g.
  33786. @code
  33787. void loadNewPatch()
  33788. {
  33789. suspendProcessing (true);
  33790. ..do something that takes ages..
  33791. suspendProcessing (false);
  33792. }
  33793. @endcode
  33794. If the host tries to make an audio callback while processing is suspended, the
  33795. filter will return an empty buffer, but won't block the audio thread like it would
  33796. do if you use the getCallbackLock() critical section to synchronise access.
  33797. If you're going to use this, your processBlock() method must call isSuspended() and
  33798. check whether it's suspended or not. If it is, then it should skip doing any real
  33799. processing, either emitting silence or passing the input through unchanged.
  33800. @see getCallbackLock
  33801. */
  33802. void suspendProcessing (bool shouldBeSuspended);
  33803. /** Returns true if processing is currently suspended.
  33804. @see suspendProcessing
  33805. */
  33806. bool isSuspended() const throw() { return suspended; }
  33807. /** A plugin can override this to be told when it should reset any playing voices.
  33808. The default implementation does nothing, but a host may call this to tell the
  33809. plugin that it should stop any tails or sounds that have been left running.
  33810. */
  33811. virtual void reset();
  33812. /** Returns true if the processor is being run in an offline mode for rendering.
  33813. If the processor is being run live on realtime signals, this returns false.
  33814. If the mode is unknown, this will assume it's realtime and return false.
  33815. This value may be unreliable until the prepareToPlay() method has been called,
  33816. and could change each time prepareToPlay() is called.
  33817. @see setNonRealtime()
  33818. */
  33819. bool isNonRealtime() const throw() { return nonRealtime; }
  33820. /** Called by the host to tell this processor whether it's being used in a non-realime
  33821. capacity for offline rendering or bouncing.
  33822. Whatever value is passed-in will be
  33823. */
  33824. void setNonRealtime (bool isNonRealtime) throw();
  33825. /** Creates the filter's UI.
  33826. This can return 0 if you want a UI-less filter, in which case the host may create
  33827. a generic UI that lets the user twiddle the parameters directly.
  33828. If you do want to pass back a component, the component should be created and set to
  33829. the correct size before returning it. If you implement this method, you must
  33830. also implement the hasEditor() method and make it return true.
  33831. Remember not to do anything silly like allowing your filter to keep a pointer to
  33832. the component that gets created - it could be deleted later without any warning, which
  33833. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  33834. The correct way to handle the connection between an editor component and its
  33835. filter is to use something like a ChangeBroadcaster so that the editor can
  33836. register itself as a listener, and be told when a change occurs. This lets them
  33837. safely unregister themselves when they are deleted.
  33838. Here are a few things to bear in mind when writing an editor:
  33839. - Initially there won't be an editor, until the user opens one, or they might
  33840. not open one at all. Your filter mustn't rely on it being there.
  33841. - An editor object may be deleted and a replacement one created again at any time.
  33842. - It's safe to assume that an editor will be deleted before its filter.
  33843. @see hasEditor
  33844. */
  33845. virtual AudioProcessorEditor* createEditor() = 0;
  33846. /** Your filter must override this and return true if it can create an editor component.
  33847. @see createEditor
  33848. */
  33849. virtual bool hasEditor() const = 0;
  33850. /** Returns the active editor, if there is one.
  33851. Bear in mind this can return 0, even if an editor has previously been
  33852. opened.
  33853. */
  33854. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  33855. /** Returns the active editor, or if there isn't one, it will create one.
  33856. This may call createEditor() internally to create the component.
  33857. */
  33858. AudioProcessorEditor* createEditorIfNeeded();
  33859. /** This must return the correct value immediately after the object has been
  33860. created, and mustn't change the number of parameters later.
  33861. */
  33862. virtual int getNumParameters() = 0;
  33863. /** Returns the name of a particular parameter. */
  33864. virtual const String getParameterName (int parameterIndex) = 0;
  33865. /** Called by the host to find out the value of one of the filter's parameters.
  33866. The host will expect the value returned to be between 0 and 1.0.
  33867. This could be called quite frequently, so try to make your code efficient.
  33868. It's also likely to be called by non-UI threads, so the code in here should
  33869. be thread-aware.
  33870. */
  33871. virtual float getParameter (int parameterIndex) = 0;
  33872. /** Returns the value of a parameter as a text string. */
  33873. virtual const String getParameterText (int parameterIndex) = 0;
  33874. /** The host will call this method to change the value of one of the filter's parameters.
  33875. The host may call this at any time, including during the audio processing
  33876. callback, so the filter has to process this very fast and avoid blocking.
  33877. If you want to set the value of a parameter internally, e.g. from your
  33878. editor component, then don't call this directly - instead, use the
  33879. setParameterNotifyingHost() method, which will also send a message to
  33880. the host telling it about the change. If the message isn't sent, the host
  33881. won't be able to automate your parameters properly.
  33882. The value passed will be between 0 and 1.0.
  33883. */
  33884. virtual void setParameter (int parameterIndex,
  33885. float newValue) = 0;
  33886. /** Your filter can call this when it needs to change one of its parameters.
  33887. This could happen when the editor or some other internal operation changes
  33888. a parameter. This method will call the setParameter() method to change the
  33889. value, and will then send a message to the host telling it about the change.
  33890. Note that to make sure the host correctly handles automation, you should call
  33891. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  33892. tell the host when the user has started and stopped changing the parameter.
  33893. */
  33894. void setParameterNotifyingHost (int parameterIndex,
  33895. float newValue);
  33896. /** Returns true if the host can automate this parameter.
  33897. By default, this returns true for all parameters.
  33898. */
  33899. virtual bool isParameterAutomatable (int parameterIndex) const;
  33900. /** Should return true if this parameter is a "meta" parameter.
  33901. A meta-parameter is a parameter that changes other params. It is used
  33902. by some hosts (e.g. AudioUnit hosts).
  33903. By default this returns false.
  33904. */
  33905. virtual bool isMetaParameter (int parameterIndex) const;
  33906. /** Sends a signal to the host to tell it that the user is about to start changing this
  33907. parameter.
  33908. This allows the host to know when a parameter is actively being held by the user, and
  33909. it may use this information to help it record automation.
  33910. If you call this, it must be matched by a later call to endParameterChangeGesture().
  33911. */
  33912. void beginParameterChangeGesture (int parameterIndex);
  33913. /** Tells the host that the user has finished changing this parameter.
  33914. This allows the host to know when a parameter is actively being held by the user, and
  33915. it may use this information to help it record automation.
  33916. A call to this method must follow a call to beginParameterChangeGesture().
  33917. */
  33918. void endParameterChangeGesture (int parameterIndex);
  33919. /** The filter can call this when something (apart from a parameter value) has changed.
  33920. It sends a hint to the host that something like the program, number of parameters,
  33921. etc, has changed, and that it should update itself.
  33922. */
  33923. void updateHostDisplay();
  33924. /** Returns the number of preset programs the filter supports.
  33925. The value returned must be valid as soon as this object is created, and
  33926. must not change over its lifetime.
  33927. This value shouldn't be less than 1.
  33928. */
  33929. virtual int getNumPrograms() = 0;
  33930. /** Returns the number of the currently active program.
  33931. */
  33932. virtual int getCurrentProgram() = 0;
  33933. /** Called by the host to change the current program.
  33934. */
  33935. virtual void setCurrentProgram (int index) = 0;
  33936. /** Must return the name of a given program. */
  33937. virtual const String getProgramName (int index) = 0;
  33938. /** Called by the host to rename a program.
  33939. */
  33940. virtual void changeProgramName (int index, const String& newName) = 0;
  33941. /** The host will call this method when it wants to save the filter's internal state.
  33942. This must copy any info about the filter's state into the block of memory provided,
  33943. so that the host can store this and later restore it using setStateInformation().
  33944. Note that there's also a getCurrentProgramStateInformation() method, which only
  33945. stores the current program, not the state of the entire filter.
  33946. See also the helper function copyXmlToBinary() for storing settings as XML.
  33947. @see getCurrentProgramStateInformation
  33948. */
  33949. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  33950. /** The host will call this method if it wants to save the state of just the filter's
  33951. current program.
  33952. Unlike getStateInformation, this should only return the current program's state.
  33953. Not all hosts support this, and if you don't implement it, the base class
  33954. method just calls getStateInformation() instead. If you do implement it, be
  33955. sure to also implement getCurrentProgramStateInformation.
  33956. @see getStateInformation, setCurrentProgramStateInformation
  33957. */
  33958. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  33959. /** This must restore the filter's state from a block of data previously created
  33960. using getStateInformation().
  33961. Note that there's also a setCurrentProgramStateInformation() method, which tries
  33962. to restore just the current program, not the state of the entire filter.
  33963. See also the helper function getXmlFromBinary() for loading settings as XML.
  33964. @see setCurrentProgramStateInformation
  33965. */
  33966. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  33967. /** The host will call this method if it wants to restore the state of just the filter's
  33968. current program.
  33969. Not all hosts support this, and if you don't implement it, the base class
  33970. method just calls setStateInformation() instead. If you do implement it, be
  33971. sure to also implement getCurrentProgramStateInformation.
  33972. @see setStateInformation, getCurrentProgramStateInformation
  33973. */
  33974. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  33975. /** Adds a listener that will be called when an aspect of this processor changes. */
  33976. void addListener (AudioProcessorListener* newListener);
  33977. /** Removes a previously added listener. */
  33978. void removeListener (AudioProcessorListener* listenerToRemove);
  33979. /** Tells the processor to use this playhead object.
  33980. The processor will not take ownership of the object, so the caller must delete it when
  33981. it is no longer being used.
  33982. */
  33983. void setPlayHead (AudioPlayHead* newPlayHead) throw();
  33984. /** Not for public use - this is called before deleting an editor component. */
  33985. void editorBeingDeleted (AudioProcessorEditor* editor) throw();
  33986. /** Not for public use - this is called to initialise the processor before playing. */
  33987. void setPlayConfigDetails (int numIns, int numOuts,
  33988. double sampleRate,
  33989. int blockSize) throw();
  33990. protected:
  33991. /** Helper function that just converts an xml element into a binary blob.
  33992. Use this in your filter's getStateInformation() method if you want to
  33993. store its state as xml.
  33994. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  33995. from a binary blob.
  33996. */
  33997. static void copyXmlToBinary (const XmlElement& xml,
  33998. JUCE_NAMESPACE::MemoryBlock& destData);
  33999. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  34000. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  34001. an XmlElement object that the caller must delete when no longer needed.
  34002. */
  34003. static XmlElement* getXmlFromBinary (const void* data, int sizeInBytes);
  34004. /** @internal */
  34005. AudioPlayHead* playHead;
  34006. /** @internal */
  34007. void sendParamChangeMessageToListeners (int parameterIndex, float newValue);
  34008. private:
  34009. Array <AudioProcessorListener*> listeners;
  34010. Component::SafePointer<AudioProcessorEditor> activeEditor;
  34011. double sampleRate;
  34012. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  34013. bool suspended, nonRealtime;
  34014. CriticalSection callbackLock, listenerLock;
  34015. #if JUCE_DEBUG
  34016. BigInteger changingParams;
  34017. #endif
  34018. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessor);
  34019. };
  34020. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  34021. /*** End of inlined file: juce_AudioProcessor.h ***/
  34022. /*** Start of inlined file: juce_PluginDescription.h ***/
  34023. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34024. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34025. /**
  34026. A small class to represent some facts about a particular type of plugin.
  34027. This class is for storing and managing the details about a plugin without
  34028. actually having to load an instance of it.
  34029. A KnownPluginList contains a list of PluginDescription objects.
  34030. @see KnownPluginList
  34031. */
  34032. class JUCE_API PluginDescription
  34033. {
  34034. public:
  34035. PluginDescription();
  34036. PluginDescription (const PluginDescription& other);
  34037. PluginDescription& operator= (const PluginDescription& other);
  34038. ~PluginDescription();
  34039. /** The name of the plugin. */
  34040. String name;
  34041. /** A more descriptive name for the plugin.
  34042. This may be the same as the 'name' field, but some plugins may provide an
  34043. alternative name.
  34044. */
  34045. String descriptiveName;
  34046. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  34047. */
  34048. String pluginFormatName;
  34049. /** A category, such as "Dynamics", "Reverbs", etc.
  34050. */
  34051. String category;
  34052. /** The manufacturer. */
  34053. String manufacturerName;
  34054. /** The version. This string doesn't have any particular format. */
  34055. String version;
  34056. /** Either the file containing the plugin module, or some other unique way
  34057. of identifying it.
  34058. E.g. for an AU, this would be an ID string that the component manager
  34059. could use to retrieve the plugin. For a VST, it's the file path.
  34060. */
  34061. String fileOrIdentifier;
  34062. /** The last time the plugin file was changed.
  34063. This is handy when scanning for new or changed plugins.
  34064. */
  34065. Time lastFileModTime;
  34066. /** A unique ID for the plugin.
  34067. Note that this might not be unique between formats, e.g. a VST and some
  34068. other format might actually have the same id.
  34069. @see createIdentifierString
  34070. */
  34071. int uid;
  34072. /** True if the plugin identifies itself as a synthesiser. */
  34073. bool isInstrument;
  34074. /** The number of inputs. */
  34075. int numInputChannels;
  34076. /** The number of outputs. */
  34077. int numOutputChannels;
  34078. /** Returns true if the two descriptions refer the the same plugin.
  34079. This isn't quite as simple as them just having the same file (because of
  34080. shell plugins).
  34081. */
  34082. bool isDuplicateOf (const PluginDescription& other) const;
  34083. /** Returns a string that can be saved and used to uniquely identify the
  34084. plugin again.
  34085. This contains less info than the XML encoding, and is independent of the
  34086. plugin's file location, so can be used to store a plugin ID for use
  34087. across different machines.
  34088. */
  34089. const String createIdentifierString() const;
  34090. /** Creates an XML object containing these details.
  34091. @see loadFromXml
  34092. */
  34093. XmlElement* createXml() const;
  34094. /** Reloads the info in this structure from an XML record that was previously
  34095. saved with createXML().
  34096. Returns true if the XML was a valid plugin description.
  34097. */
  34098. bool loadFromXml (const XmlElement& xml);
  34099. private:
  34100. JUCE_LEAK_DETECTOR (PluginDescription);
  34101. };
  34102. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34103. /*** End of inlined file: juce_PluginDescription.h ***/
  34104. /**
  34105. Base class for an active instance of a plugin.
  34106. This derives from the AudioProcessor class, and adds some extra functionality
  34107. that helps when wrapping dynamically loaded plugins.
  34108. @see AudioProcessor, AudioPluginFormat
  34109. */
  34110. class JUCE_API AudioPluginInstance : public AudioProcessor
  34111. {
  34112. public:
  34113. /** Destructor.
  34114. Make sure that you delete any UI components that belong to this plugin before
  34115. deleting the plugin.
  34116. */
  34117. virtual ~AudioPluginInstance();
  34118. /** Fills-in the appropriate parts of this plugin description object.
  34119. */
  34120. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  34121. /** Returns a pointer to some kind of platform-specific data about the plugin.
  34122. E.g. For a VST, this value can be cast to an AEffect*. For an AudioUnit, it can be
  34123. cast to an AudioUnit handle.
  34124. */
  34125. virtual void* getPlatformSpecificData();
  34126. protected:
  34127. AudioPluginInstance();
  34128. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginInstance);
  34129. };
  34130. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  34131. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  34132. class PluginDescription;
  34133. /**
  34134. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  34135. Use the static getNumFormats() and getFormat() calls to find the types
  34136. of format that are available.
  34137. */
  34138. class JUCE_API AudioPluginFormat
  34139. {
  34140. public:
  34141. /** Destructor. */
  34142. virtual ~AudioPluginFormat();
  34143. /** Returns the format name.
  34144. E.g. "VST", "AudioUnit", etc.
  34145. */
  34146. virtual const String getName() const = 0;
  34147. /** This tries to create descriptions for all the plugin types available in
  34148. a binary module file.
  34149. The file will be some kind of DLL or bundle.
  34150. Normally there will only be one type returned, but some plugins
  34151. (e.g. VST shells) can use a single DLL to create a set of different plugin
  34152. subtypes, so in that case, each subtype is returned as a separate object.
  34153. */
  34154. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  34155. const String& fileOrIdentifier) = 0;
  34156. /** Tries to recreate a type from a previously generated PluginDescription.
  34157. @see PluginDescription::createInstance
  34158. */
  34159. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  34160. /** Should do a quick check to see if this file or directory might be a plugin of
  34161. this format.
  34162. This is for searching for potential files, so it shouldn't actually try to
  34163. load the plugin or do anything time-consuming.
  34164. */
  34165. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  34166. /** Returns a readable version of the name of the plugin that this identifier refers to.
  34167. */
  34168. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  34169. /** Checks whether this plugin could possibly be loaded.
  34170. It doesn't actually need to load it, just to check whether the file or component
  34171. still exists.
  34172. */
  34173. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  34174. /** Searches a suggested set of directories for any plugins in this format.
  34175. The path might be ignored, e.g. by AUs, which are found by the OS rather
  34176. than manually.
  34177. */
  34178. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  34179. bool recursive) = 0;
  34180. /** Returns the typical places to look for this kind of plugin.
  34181. Note that if this returns no paths, it means that the format can't be scanned-for
  34182. (i.e. it's an internal format that doesn't live in files)
  34183. */
  34184. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  34185. protected:
  34186. AudioPluginFormat() throw();
  34187. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormat);
  34188. };
  34189. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  34190. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  34191. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  34192. /**
  34193. Implements a plugin format manager for AudioUnits.
  34194. */
  34195. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  34196. {
  34197. public:
  34198. AudioUnitPluginFormat();
  34199. ~AudioUnitPluginFormat();
  34200. const String getName() const { return "AudioUnit"; }
  34201. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34202. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34203. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34204. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  34205. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  34206. bool doesPluginStillExist (const PluginDescription& desc);
  34207. const FileSearchPath getDefaultLocationsToSearch();
  34208. private:
  34209. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginFormat);
  34210. };
  34211. #endif
  34212. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  34213. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  34214. #endif
  34215. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34216. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  34217. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34218. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34219. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  34220. // Sorry, this file is just a placeholder at the moment!...
  34221. /**
  34222. Implements a plugin format manager for DirectX plugins.
  34223. */
  34224. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  34225. {
  34226. public:
  34227. DirectXPluginFormat();
  34228. ~DirectXPluginFormat();
  34229. const String getName() const { return "DirectX"; }
  34230. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34231. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34232. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34233. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  34234. const FileSearchPath getDefaultLocationsToSearch();
  34235. private:
  34236. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectXPluginFormat);
  34237. };
  34238. #endif
  34239. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  34240. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  34241. #endif
  34242. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34243. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  34244. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34245. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34246. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  34247. // Sorry, this file is just a placeholder at the moment!...
  34248. /**
  34249. Implements a plugin format manager for DirectX plugins.
  34250. */
  34251. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  34252. {
  34253. public:
  34254. LADSPAPluginFormat();
  34255. ~LADSPAPluginFormat();
  34256. const String getName() const { return "LADSPA"; }
  34257. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34258. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34259. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34260. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  34261. const FileSearchPath getDefaultLocationsToSearch();
  34262. private:
  34263. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LADSPAPluginFormat);
  34264. };
  34265. #endif
  34266. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  34267. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  34268. #endif
  34269. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34270. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  34271. #ifdef __aeffect__
  34272. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34273. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34274. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  34275. events to the list.
  34276. This is used by both the VST hosting code and the plugin wrapper.
  34277. */
  34278. class VSTMidiEventList
  34279. {
  34280. public:
  34281. VSTMidiEventList()
  34282. : numEventsUsed (0), numEventsAllocated (0)
  34283. {
  34284. }
  34285. ~VSTMidiEventList()
  34286. {
  34287. freeEvents();
  34288. }
  34289. void clear()
  34290. {
  34291. numEventsUsed = 0;
  34292. if (events != 0)
  34293. events->numEvents = 0;
  34294. }
  34295. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  34296. {
  34297. ensureSize (numEventsUsed + 1);
  34298. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  34299. events->numEvents = ++numEventsUsed;
  34300. if (numBytes <= 4)
  34301. {
  34302. if (e->type == kVstSysExType)
  34303. {
  34304. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  34305. e->type = kVstMidiType;
  34306. e->byteSize = sizeof (VstMidiEvent);
  34307. e->noteLength = 0;
  34308. e->noteOffset = 0;
  34309. e->detune = 0;
  34310. e->noteOffVelocity = 0;
  34311. }
  34312. e->deltaFrames = frameOffset;
  34313. memcpy (e->midiData, midiData, numBytes);
  34314. }
  34315. else
  34316. {
  34317. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  34318. if (se->type == kVstSysExType)
  34319. delete[] se->sysexDump;
  34320. se->sysexDump = new char [numBytes];
  34321. memcpy (se->sysexDump, midiData, numBytes);
  34322. se->type = kVstSysExType;
  34323. se->byteSize = sizeof (VstMidiSysexEvent);
  34324. se->deltaFrames = frameOffset;
  34325. se->flags = 0;
  34326. se->dumpBytes = numBytes;
  34327. se->resvd1 = 0;
  34328. se->resvd2 = 0;
  34329. }
  34330. }
  34331. // Handy method to pull the events out of an event buffer supplied by the host
  34332. // or plugin.
  34333. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  34334. {
  34335. for (int i = 0; i < events->numEvents; ++i)
  34336. {
  34337. const VstEvent* const e = events->events[i];
  34338. if (e != 0)
  34339. {
  34340. if (e->type == kVstMidiType)
  34341. {
  34342. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  34343. 4, e->deltaFrames);
  34344. }
  34345. else if (e->type == kVstSysExType)
  34346. {
  34347. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  34348. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  34349. e->deltaFrames);
  34350. }
  34351. }
  34352. }
  34353. }
  34354. void ensureSize (int numEventsNeeded)
  34355. {
  34356. if (numEventsNeeded > numEventsAllocated)
  34357. {
  34358. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  34359. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  34360. if (events == 0)
  34361. events.calloc (size, 1);
  34362. else
  34363. events.realloc (size, 1);
  34364. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  34365. {
  34366. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  34367. (int) sizeof (VstMidiSysexEvent)));
  34368. e->type = kVstMidiType;
  34369. e->byteSize = sizeof (VstMidiEvent);
  34370. events->events[i] = (VstEvent*) e;
  34371. }
  34372. numEventsAllocated = numEventsNeeded;
  34373. }
  34374. }
  34375. void freeEvents()
  34376. {
  34377. if (events != 0)
  34378. {
  34379. for (int i = numEventsAllocated; --i >= 0;)
  34380. {
  34381. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  34382. if (e->type == kVstSysExType)
  34383. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  34384. juce_free (e);
  34385. }
  34386. events.free();
  34387. numEventsUsed = 0;
  34388. numEventsAllocated = 0;
  34389. }
  34390. }
  34391. HeapBlock <VstEvents> events;
  34392. private:
  34393. int numEventsUsed, numEventsAllocated;
  34394. };
  34395. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34396. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  34397. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  34398. #endif
  34399. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  34400. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  34401. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  34402. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  34403. #if JUCE_PLUGINHOST_VST
  34404. /**
  34405. Implements a plugin format manager for VSTs.
  34406. */
  34407. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  34408. {
  34409. public:
  34410. VSTPluginFormat();
  34411. ~VSTPluginFormat();
  34412. const String getName() const { return "VST"; }
  34413. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  34414. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  34415. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  34416. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  34417. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  34418. bool doesPluginStillExist (const PluginDescription& desc);
  34419. const FileSearchPath getDefaultLocationsToSearch();
  34420. private:
  34421. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  34422. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginFormat);
  34423. };
  34424. #endif
  34425. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  34426. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  34427. #endif
  34428. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  34429. #endif
  34430. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  34431. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  34432. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  34433. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  34434. /**
  34435. This maintains a list of known AudioPluginFormats.
  34436. @see AudioPluginFormat
  34437. */
  34438. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  34439. {
  34440. public:
  34441. AudioPluginFormatManager();
  34442. /** Destructor. */
  34443. ~AudioPluginFormatManager();
  34444. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  34445. /** Adds any formats that it knows about, e.g. VST.
  34446. */
  34447. void addDefaultFormats();
  34448. /** Returns the number of types of format that are available.
  34449. Use getFormat() to get one of them.
  34450. */
  34451. int getNumFormats();
  34452. /** Returns one of the available formats.
  34453. @see getNumFormats
  34454. */
  34455. AudioPluginFormat* getFormat (int index);
  34456. /** Adds a format to the list.
  34457. The object passed in will be owned and deleted by the manager.
  34458. */
  34459. void addFormat (AudioPluginFormat* format);
  34460. /** Tries to load the type for this description, by trying all the formats
  34461. that this manager knows about.
  34462. The caller is responsible for deleting the object that is returned.
  34463. If it can't load the plugin, it returns 0 and leaves a message in the
  34464. errorMessage string.
  34465. */
  34466. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  34467. String& errorMessage) const;
  34468. /** Checks that the file or component for this plugin actually still exists.
  34469. (This won't try to load the plugin)
  34470. */
  34471. bool doesPluginStillExist (const PluginDescription& description) const;
  34472. private:
  34473. OwnedArray <AudioPluginFormat> formats;
  34474. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormatManager);
  34475. };
  34476. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  34477. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  34478. #endif
  34479. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  34480. #endif
  34481. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  34482. /*** Start of inlined file: juce_KnownPluginList.h ***/
  34483. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  34484. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  34485. /**
  34486. Manages a list of plugin types.
  34487. This can be easily edited, saved and loaded, and used to create instances of
  34488. the plugin types in it.
  34489. @see PluginListComponent
  34490. */
  34491. class JUCE_API KnownPluginList : public ChangeBroadcaster
  34492. {
  34493. public:
  34494. /** Creates an empty list.
  34495. */
  34496. KnownPluginList();
  34497. /** Destructor. */
  34498. ~KnownPluginList();
  34499. /** Clears the list. */
  34500. void clear();
  34501. /** Returns the number of types currently in the list.
  34502. @see getType
  34503. */
  34504. int getNumTypes() const throw() { return types.size(); }
  34505. /** Returns one of the types.
  34506. @see getNumTypes
  34507. */
  34508. PluginDescription* getType (int index) const throw() { return types [index]; }
  34509. /** Looks for a type in the list which comes from this file.
  34510. */
  34511. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const;
  34512. /** Looks for a type in the list which matches a plugin type ID.
  34513. The identifierString parameter must have been created by
  34514. PluginDescription::createIdentifierString().
  34515. */
  34516. PluginDescription* getTypeForIdentifierString (const String& identifierString) const;
  34517. /** Adds a type manually from its description. */
  34518. bool addType (const PluginDescription& type);
  34519. /** Removes a type. */
  34520. void removeType (int index);
  34521. /** Looks for all types that can be loaded from a given file, and adds them
  34522. to the list.
  34523. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  34524. re-tested if it's not already in the list, or if the file's modification
  34525. time has changed since the list was created. If dontRescanIfAlreadyInList is
  34526. false, the file will always be reloaded and tested.
  34527. Returns true if any new types were added, and all the types found in this
  34528. file (even if it was already known and hasn't been re-scanned) get returned
  34529. in the array.
  34530. */
  34531. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  34532. bool dontRescanIfAlreadyInList,
  34533. OwnedArray <PluginDescription>& typesFound,
  34534. AudioPluginFormat& formatToUse);
  34535. /** Returns true if the specified file is already known about and if it
  34536. hasn't been modified since our entry was created.
  34537. */
  34538. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const;
  34539. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  34540. If any types are found in the files, their descriptions are returned in the array.
  34541. */
  34542. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  34543. OwnedArray <PluginDescription>& typesFound);
  34544. /** Sort methods used to change the order of the plugins in the list.
  34545. */
  34546. enum SortMethod
  34547. {
  34548. defaultOrder = 0,
  34549. sortAlphabetically,
  34550. sortByCategory,
  34551. sortByManufacturer,
  34552. sortByFileSystemLocation
  34553. };
  34554. /** Adds all the plugin types to a popup menu so that the user can select one.
  34555. Depending on the sort method, it may add sub-menus for categories,
  34556. manufacturers, etc.
  34557. Use getIndexChosenByMenu() to find out the type that was chosen.
  34558. */
  34559. void addToMenu (PopupMenu& menu,
  34560. const SortMethod sortMethod) const;
  34561. /** Converts a menu item index that has been chosen into its index in this list.
  34562. Returns -1 if it's not an ID that was used.
  34563. @see addToMenu
  34564. */
  34565. int getIndexChosenByMenu (int menuResultCode) const;
  34566. /** Sorts the list. */
  34567. void sort (const SortMethod method);
  34568. /** Creates some XML that can be used to store the state of this list.
  34569. */
  34570. XmlElement* createXml() const;
  34571. /** Recreates the state of this list from its stored XML format.
  34572. */
  34573. void recreateFromXml (const XmlElement& xml);
  34574. private:
  34575. OwnedArray <PluginDescription> types;
  34576. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KnownPluginList);
  34577. };
  34578. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  34579. /*** End of inlined file: juce_KnownPluginList.h ***/
  34580. #endif
  34581. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34582. #endif
  34583. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  34584. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  34585. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  34586. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  34587. /**
  34588. Scans a directory for plugins, and adds them to a KnownPluginList.
  34589. To use one of these, create it and call scanNextFile() repeatedly, until
  34590. it returns false.
  34591. */
  34592. class JUCE_API PluginDirectoryScanner
  34593. {
  34594. public:
  34595. /**
  34596. Creates a scanner.
  34597. @param listToAddResultsTo this will get the new types added to it.
  34598. @param formatToLookFor this is the type of format that you want to look for
  34599. @param directoriesToSearch the path to search
  34600. @param searchRecursively true to search recursively
  34601. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  34602. be used as a file to store the names of any plugins
  34603. that crash during initialisation. If there are
  34604. any plugins listed in it, then these will always
  34605. be scanned after all other possible files have
  34606. been tried - in this way, even if there's a few
  34607. dodgy plugins in your path, then a couple of rescans
  34608. will still manage to find all the proper plugins.
  34609. It's probably best to choose a file in the user's
  34610. application data directory (alongside your app's
  34611. settings file) for this. The file format it uses
  34612. is just a list of filenames of the modules that
  34613. failed.
  34614. */
  34615. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  34616. AudioPluginFormat& formatToLookFor,
  34617. FileSearchPath directoriesToSearch,
  34618. bool searchRecursively,
  34619. const File& deadMansPedalFile);
  34620. /** Destructor. */
  34621. ~PluginDirectoryScanner();
  34622. /** Tries the next likely-looking file.
  34623. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  34624. re-tested if it's not already in the list, or if the file's modification
  34625. time has changed since the list was created. If dontRescanIfAlreadyInList is
  34626. false, the file will always be reloaded and tested.
  34627. Returns false when there are no more files to try.
  34628. */
  34629. bool scanNextFile (bool dontRescanIfAlreadyInList);
  34630. /** Skips over the next file without scanning it.
  34631. Returns false when there are no more files to try.
  34632. */
  34633. bool skipNextFile();
  34634. /** Returns the description of the plugin that will be scanned during the next
  34635. call to scanNextFile().
  34636. This is handy if you want to show the user which file is currently getting
  34637. scanned.
  34638. */
  34639. const String getNextPluginFileThatWillBeScanned() const;
  34640. /** Returns the estimated progress, between 0 and 1.
  34641. */
  34642. float getProgress() const { return progress; }
  34643. /** This returns a list of all the filenames of things that looked like being
  34644. a plugin file, but which failed to open for some reason.
  34645. */
  34646. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  34647. private:
  34648. KnownPluginList& list;
  34649. AudioPluginFormat& format;
  34650. StringArray filesOrIdentifiersToScan;
  34651. File deadMansPedalFile;
  34652. StringArray failedFiles;
  34653. int nextIndex;
  34654. float progress;
  34655. const StringArray getDeadMansPedalFile();
  34656. void setDeadMansPedalFile (const StringArray& newContents);
  34657. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginDirectoryScanner);
  34658. };
  34659. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  34660. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  34661. #endif
  34662. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  34663. /*** Start of inlined file: juce_PluginListComponent.h ***/
  34664. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  34665. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  34666. /*** Start of inlined file: juce_ListBox.h ***/
  34667. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  34668. #define __JUCE_LISTBOX_JUCEHEADER__
  34669. class ListViewport;
  34670. /**
  34671. A subclass of this is used to drive a ListBox.
  34672. @see ListBox
  34673. */
  34674. class JUCE_API ListBoxModel
  34675. {
  34676. public:
  34677. /** Destructor. */
  34678. virtual ~ListBoxModel() {}
  34679. /** This has to return the number of items in the list.
  34680. @see ListBox::getNumRows()
  34681. */
  34682. virtual int getNumRows() = 0;
  34683. /** This method must be implemented to draw a row of the list.
  34684. */
  34685. virtual void paintListBoxItem (int rowNumber,
  34686. Graphics& g,
  34687. int width, int height,
  34688. bool rowIsSelected) = 0;
  34689. /** This is used to create or update a custom component to go in a row of the list.
  34690. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  34691. and handle mouse clicks with listBoxItemClicked().
  34692. This method will be called whenever a custom component might need to be updated - e.g.
  34693. when the table is changed, or TableListBox::updateContent() is called.
  34694. If you don't need a custom component for the specified row, then return 0.
  34695. If you do want a custom component, and the existingComponentToUpdate is null, then
  34696. this method must create a suitable new component and return it.
  34697. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  34698. by this method. In this case, the method must either update it to make sure it's correctly representing
  34699. the given row (which may be different from the one that the component was created for), or it can
  34700. delete this component and return a new one.
  34701. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  34702. */
  34703. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  34704. Component* existingComponentToUpdate);
  34705. /** This can be overridden to react to the user clicking on a row.
  34706. @see listBoxItemDoubleClicked
  34707. */
  34708. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  34709. /** This can be overridden to react to the user double-clicking on a row.
  34710. @see listBoxItemClicked
  34711. */
  34712. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  34713. /** This can be overridden to react to the user double-clicking on a part of the list where
  34714. there are no rows.
  34715. @see listBoxItemClicked
  34716. */
  34717. virtual void backgroundClicked();
  34718. /** Override this to be informed when rows are selected or deselected.
  34719. This will be called whenever a row is selected or deselected. If a range of
  34720. rows is selected all at once, this will just be called once for that event.
  34721. @param lastRowSelected the last row that the user selected. If no
  34722. rows are currently selected, this may be -1.
  34723. */
  34724. virtual void selectedRowsChanged (int lastRowSelected);
  34725. /** Override this to be informed when the delete key is pressed.
  34726. If no rows are selected when they press the key, this won't be called.
  34727. @param lastRowSelected the last row that had been selected when they pressed the
  34728. key - if there are multiple selections, this might not be
  34729. very useful
  34730. */
  34731. virtual void deleteKeyPressed (int lastRowSelected);
  34732. /** Override this to be informed when the return key is pressed.
  34733. If no rows are selected when they press the key, this won't be called.
  34734. @param lastRowSelected the last row that had been selected when they pressed the
  34735. key - if there are multiple selections, this might not be
  34736. very useful
  34737. */
  34738. virtual void returnKeyPressed (int lastRowSelected);
  34739. /** Override this to be informed when the list is scrolled.
  34740. This might be caused by the user moving the scrollbar, or by programmatic changes
  34741. to the list position.
  34742. */
  34743. virtual void listWasScrolled();
  34744. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  34745. If this returns a non-empty name then when the user drags a row, the listbox will
  34746. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  34747. a drag-and-drop operation, using this string as the source description, with the listbox
  34748. itself as the source component.
  34749. @see DragAndDropContainer::startDragging
  34750. */
  34751. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  34752. /** You can override this to provide tool tips for specific rows.
  34753. @see TooltipClient
  34754. */
  34755. virtual const String getTooltipForRow (int row);
  34756. };
  34757. /**
  34758. A list of items that can be scrolled vertically.
  34759. To create a list, you'll need to create a subclass of ListBoxModel. This can
  34760. either paint each row of the list and respond to events via callbacks, or for
  34761. more specialised tasks, it can supply a custom component to fill each row.
  34762. @see ComboBox, TableListBox
  34763. */
  34764. class JUCE_API ListBox : public Component,
  34765. public SettableTooltipClient
  34766. {
  34767. public:
  34768. /** Creates a ListBox.
  34769. The model pointer passed-in can be null, in which case you can set it later
  34770. with setModel().
  34771. */
  34772. ListBox (const String& componentName = String::empty,
  34773. ListBoxModel* model = 0);
  34774. /** Destructor. */
  34775. ~ListBox();
  34776. /** Changes the current data model to display. */
  34777. void setModel (ListBoxModel* newModel);
  34778. /** Returns the current list model. */
  34779. ListBoxModel* getModel() const throw() { return model; }
  34780. /** Causes the list to refresh its content.
  34781. Call this when the number of rows in the list changes, or if you want it
  34782. to call refreshComponentForRow() on all the row components.
  34783. Be careful not to call it from a different thread, though, as it's not
  34784. thread-safe.
  34785. */
  34786. void updateContent();
  34787. /** Turns on multiple-selection of rows.
  34788. By default this is disabled.
  34789. When your row component gets clicked you'll need to call the
  34790. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  34791. clicked and to get it to do the appropriate selection based on whether
  34792. the ctrl/shift keys are held down.
  34793. */
  34794. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  34795. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  34796. This function is here primarily for the ComboBox class to use, but might be
  34797. useful for some other purpose too.
  34798. */
  34799. void setMouseMoveSelectsRows (bool shouldSelect);
  34800. /** Selects a row.
  34801. If the row is already selected, this won't do anything.
  34802. @param rowNumber the row to select
  34803. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  34804. the selected row is off-screen, it'll scroll to make
  34805. sure that row is on-screen
  34806. @param deselectOthersFirst if true and there are multiple selections, these will
  34807. first be deselected before this item is selected
  34808. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  34809. deselectAllRows, selectRangeOfRows
  34810. */
  34811. void selectRow (int rowNumber,
  34812. bool dontScrollToShowThisRow = false,
  34813. bool deselectOthersFirst = true);
  34814. /** Selects a set of rows.
  34815. This will add these rows to the current selection, so you might need to
  34816. clear the current selection first with deselectAllRows()
  34817. @param firstRow the first row to select (inclusive)
  34818. @param lastRow the last row to select (inclusive)
  34819. */
  34820. void selectRangeOfRows (int firstRow,
  34821. int lastRow);
  34822. /** Deselects a row.
  34823. If it's not currently selected, this will do nothing.
  34824. @see selectRow, deselectAllRows
  34825. */
  34826. void deselectRow (int rowNumber);
  34827. /** Deselects any currently selected rows.
  34828. @see deselectRow
  34829. */
  34830. void deselectAllRows();
  34831. /** Selects or deselects a row.
  34832. If the row's currently selected, this deselects it, and vice-versa.
  34833. */
  34834. void flipRowSelection (int rowNumber);
  34835. /** Returns a sparse set indicating the rows that are currently selected.
  34836. @see setSelectedRows
  34837. */
  34838. const SparseSet<int> getSelectedRows() const;
  34839. /** Sets the rows that should be selected, based on an explicit set of ranges.
  34840. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  34841. method will be called. If it's false, no notification will be sent to the model.
  34842. @see getSelectedRows
  34843. */
  34844. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  34845. bool sendNotificationEventToModel = true);
  34846. /** Checks whether a row is selected.
  34847. */
  34848. bool isRowSelected (int rowNumber) const;
  34849. /** Returns the number of rows that are currently selected.
  34850. @see getSelectedRow, isRowSelected, getLastRowSelected
  34851. */
  34852. int getNumSelectedRows() const;
  34853. /** Returns the row number of a selected row.
  34854. This will return the row number of the Nth selected row. The row numbers returned will
  34855. be sorted in order from low to high.
  34856. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  34857. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  34858. selected
  34859. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  34860. */
  34861. int getSelectedRow (int index = 0) const;
  34862. /** Returns the last row that the user selected.
  34863. This isn't the same as the highest row number that is currently selected - if the user
  34864. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  34865. If nothing is selected, it will return -1.
  34866. */
  34867. int getLastRowSelected() const;
  34868. /** Multiply-selects rows based on the modifier keys.
  34869. If no modifier keys are down, this will select the given row and
  34870. deselect any others.
  34871. If the ctrl (or command on the Mac) key is down, it'll flip the
  34872. state of the selected row.
  34873. If the shift key is down, it'll select up to the given row from the
  34874. last row selected.
  34875. @see selectRow
  34876. */
  34877. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  34878. const ModifierKeys& modifiers,
  34879. bool isMouseUpEvent);
  34880. /** Scrolls the list to a particular position.
  34881. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  34882. 1.0 scrolls to the bottom.
  34883. If the total number of rows all fit onto the screen at once, then this
  34884. method won't do anything.
  34885. @see getVerticalPosition
  34886. */
  34887. void setVerticalPosition (double newProportion);
  34888. /** Returns the current vertical position as a proportion of the total.
  34889. This can be used in conjunction with setVerticalPosition() to save and restore
  34890. the list's position. It returns a value in the range 0 to 1.
  34891. @see setVerticalPosition
  34892. */
  34893. double getVerticalPosition() const;
  34894. /** Scrolls if necessary to make sure that a particular row is visible.
  34895. */
  34896. void scrollToEnsureRowIsOnscreen (int row);
  34897. /** Returns a pointer to the scrollbar.
  34898. (Unlikely to be useful for most people).
  34899. */
  34900. ScrollBar* getVerticalScrollBar() const throw();
  34901. /** Returns a pointer to the scrollbar.
  34902. (Unlikely to be useful for most people).
  34903. */
  34904. ScrollBar* getHorizontalScrollBar() const throw();
  34905. /** Finds the row index that contains a given x,y position.
  34906. The position is relative to the ListBox's top-left.
  34907. If no row exists at this position, the method will return -1.
  34908. @see getComponentForRowNumber
  34909. */
  34910. int getRowContainingPosition (int x, int y) const throw();
  34911. /** Finds a row index that would be the most suitable place to insert a new
  34912. item for a given position.
  34913. This is useful when the user is e.g. dragging and dropping onto the listbox,
  34914. because it lets you easily choose the best position to insert the item that
  34915. they drop, based on where they drop it.
  34916. If the position is out of range, this will return -1. If the position is
  34917. beyond the end of the list, it will return getNumRows() to indicate the end
  34918. of the list.
  34919. @see getComponentForRowNumber
  34920. */
  34921. int getInsertionIndexForPosition (int x, int y) const throw();
  34922. /** Returns the position of one of the rows, relative to the top-left of
  34923. the listbox.
  34924. This may be off-screen, and the range of the row number that is passed-in is
  34925. not checked to see if it's a valid row.
  34926. */
  34927. const Rectangle<int> getRowPosition (int rowNumber,
  34928. bool relativeToComponentTopLeft) const throw();
  34929. /** Finds the row component for a given row in the list.
  34930. The component returned will have been created using createRowComponent().
  34931. If the component for this row is off-screen or if the row is out-of-range,
  34932. this will return 0.
  34933. @see getRowContainingPosition
  34934. */
  34935. Component* getComponentForRowNumber (int rowNumber) const throw();
  34936. /** Returns the row number that the given component represents.
  34937. If the component isn't one of the list's rows, this will return -1.
  34938. */
  34939. int getRowNumberOfComponent (Component* rowComponent) const throw();
  34940. /** Returns the width of a row (which may be less than the width of this component
  34941. if there's a scrollbar).
  34942. */
  34943. int getVisibleRowWidth() const throw();
  34944. /** Sets the height of each row in the list.
  34945. The default height is 22 pixels.
  34946. @see getRowHeight
  34947. */
  34948. void setRowHeight (int newHeight);
  34949. /** Returns the height of a row in the list.
  34950. @see setRowHeight
  34951. */
  34952. int getRowHeight() const throw() { return rowHeight; }
  34953. /** Returns the number of rows actually visible.
  34954. This is the number of whole rows which will fit on-screen, so the value might
  34955. be more than the actual number of rows in the list.
  34956. */
  34957. int getNumRowsOnScreen() const throw();
  34958. /** A set of colour IDs to use to change the colour of various aspects of the label.
  34959. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34960. methods.
  34961. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34962. */
  34963. enum ColourIds
  34964. {
  34965. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  34966. Make this transparent if you don't want the background to be filled. */
  34967. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  34968. Make this transparent to not have an outline. */
  34969. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  34970. };
  34971. /** Sets the thickness of a border that will be drawn around the box.
  34972. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  34973. @see outlineColourId
  34974. */
  34975. void setOutlineThickness (int outlineThickness);
  34976. /** Returns the thickness of outline that will be drawn around the listbox.
  34977. @see setOutlineColour
  34978. */
  34979. int getOutlineThickness() const throw() { return outlineThickness; }
  34980. /** Sets a component that the list should use as a header.
  34981. This will position the given component at the top of the list, maintaining the
  34982. height of the component passed-in, but rescaling it horizontally to match the
  34983. width of the items in the listbox.
  34984. The component will be deleted when setHeaderComponent() is called with a
  34985. different component, or when the listbox is deleted.
  34986. */
  34987. void setHeaderComponent (Component* newHeaderComponent);
  34988. /** Changes the width of the rows in the list.
  34989. This can be used to make the list's row components wider than the list itself - the
  34990. width of the rows will be either the width of the list or this value, whichever is
  34991. greater, and if the rows become wider than the list, a horizontal scrollbar will
  34992. appear.
  34993. The default value for this is 0, which means that the rows will always
  34994. be the same width as the list.
  34995. */
  34996. void setMinimumContentWidth (int newMinimumWidth);
  34997. /** Returns the space currently available for the row items, taking into account
  34998. borders, scrollbars, etc.
  34999. */
  35000. int getVisibleContentWidth() const throw();
  35001. /** Repaints one of the rows.
  35002. This is a lightweight alternative to calling updateContent, and just causes a
  35003. repaint of the row's area.
  35004. */
  35005. void repaintRow (int rowNumber) throw();
  35006. /** This fairly obscure method creates an image that just shows the currently
  35007. selected row components.
  35008. It's a handy method for doing drag-and-drop, as it can be passed to the
  35009. DragAndDropContainer for use as the drag image.
  35010. Note that it will make the row components temporarily invisible, so if you're
  35011. using custom components this could affect them if they're sensitive to that
  35012. sort of thing.
  35013. @see Component::createComponentSnapshot
  35014. */
  35015. virtual const Image createSnapshotOfSelectedRows (int& x, int& y);
  35016. /** Returns the viewport that this ListBox uses.
  35017. You may need to use this to change parameters such as whether scrollbars
  35018. are shown, etc.
  35019. */
  35020. Viewport* getViewport() const throw();
  35021. /** @internal */
  35022. bool keyPressed (const KeyPress& key);
  35023. /** @internal */
  35024. bool keyStateChanged (bool isKeyDown);
  35025. /** @internal */
  35026. void paint (Graphics& g);
  35027. /** @internal */
  35028. void paintOverChildren (Graphics& g);
  35029. /** @internal */
  35030. void resized();
  35031. /** @internal */
  35032. void visibilityChanged();
  35033. /** @internal */
  35034. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  35035. /** @internal */
  35036. void mouseMove (const MouseEvent&);
  35037. /** @internal */
  35038. void mouseExit (const MouseEvent&);
  35039. /** @internal */
  35040. void mouseUp (const MouseEvent&);
  35041. /** @internal */
  35042. void colourChanged();
  35043. /** @internal */
  35044. void startDragAndDrop (const MouseEvent& e, const String& dragDescription);
  35045. private:
  35046. friend class ListViewport;
  35047. friend class TableListBox;
  35048. ListBoxModel* model;
  35049. ScopedPointer<ListViewport> viewport;
  35050. ScopedPointer<Component> headerComponent;
  35051. int totalItems, rowHeight, minimumRowWidth;
  35052. int outlineThickness;
  35053. int lastRowSelected;
  35054. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  35055. SparseSet <int> selected;
  35056. void selectRowInternal (int rowNumber,
  35057. bool dontScrollToShowThisRow,
  35058. bool deselectOthersFirst,
  35059. bool isMouseClick);
  35060. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBox);
  35061. };
  35062. #endif // __JUCE_LISTBOX_JUCEHEADER__
  35063. /*** End of inlined file: juce_ListBox.h ***/
  35064. /*** Start of inlined file: juce_TextButton.h ***/
  35065. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  35066. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  35067. /**
  35068. A button that uses the standard lozenge-shaped background with a line of
  35069. text on it.
  35070. @see Button, DrawableButton
  35071. */
  35072. class JUCE_API TextButton : public Button
  35073. {
  35074. public:
  35075. /** Creates a TextButton.
  35076. @param buttonName the text to put in the button (the component's name is also
  35077. initially set to this string, but these can be changed later
  35078. using the setName() and setButtonText() methods)
  35079. @param toolTip an optional string to use as a toolip
  35080. @see Button
  35081. */
  35082. TextButton (const String& buttonName = String::empty,
  35083. const String& toolTip = String::empty);
  35084. /** Destructor. */
  35085. ~TextButton();
  35086. /** A set of colour IDs to use to change the colour of various aspects of the button.
  35087. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35088. methods.
  35089. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35090. */
  35091. enum ColourIds
  35092. {
  35093. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  35094. 'off'). The look-and-feel class might re-interpret this to add
  35095. effects, etc. */
  35096. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  35097. 'on'). The look-and-feel class might re-interpret this to add
  35098. effects, etc. */
  35099. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  35100. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  35101. };
  35102. /** Resizes the button to fit neatly around its current text.
  35103. If newHeight is >= 0, the button's height will be changed to this
  35104. value. If it's less than zero, its height will be unaffected.
  35105. */
  35106. void changeWidthToFitText (int newHeight = -1);
  35107. /** This can be overridden to use different fonts than the default one.
  35108. Note that you'll need to set the font's size appropriately, too.
  35109. */
  35110. virtual const Font getFont();
  35111. protected:
  35112. /** @internal */
  35113. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  35114. /** @internal */
  35115. void colourChanged();
  35116. private:
  35117. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextButton);
  35118. };
  35119. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  35120. /*** End of inlined file: juce_TextButton.h ***/
  35121. /**
  35122. A component displaying a list of plugins, with options to scan for them,
  35123. add, remove and sort them.
  35124. */
  35125. class JUCE_API PluginListComponent : public Component,
  35126. public ListBoxModel,
  35127. public ChangeListener,
  35128. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  35129. public Timer
  35130. {
  35131. public:
  35132. /**
  35133. Creates the list component.
  35134. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  35135. The properties file, if supplied, is used to store the user's last search paths.
  35136. */
  35137. PluginListComponent (KnownPluginList& listToRepresent,
  35138. const File& deadMansPedalFile,
  35139. PropertiesFile* propertiesToUse);
  35140. /** Destructor. */
  35141. ~PluginListComponent();
  35142. /** @internal */
  35143. void resized();
  35144. /** @internal */
  35145. bool isInterestedInFileDrag (const StringArray& files);
  35146. /** @internal */
  35147. void filesDropped (const StringArray& files, int, int);
  35148. /** @internal */
  35149. int getNumRows();
  35150. /** @internal */
  35151. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  35152. /** @internal */
  35153. void deleteKeyPressed (int lastRowSelected);
  35154. /** @internal */
  35155. void buttonClicked (Button* b);
  35156. /** @internal */
  35157. void changeListenerCallback (ChangeBroadcaster*);
  35158. /** @internal */
  35159. void timerCallback();
  35160. private:
  35161. KnownPluginList& list;
  35162. File deadMansPedalFile;
  35163. ListBox listBox;
  35164. TextButton optionsButton;
  35165. PropertiesFile* propertiesToUse;
  35166. int typeToScan;
  35167. void scanFor (AudioPluginFormat* format);
  35168. static void optionsMenuStaticCallback (int result, PluginListComponent*);
  35169. void optionsMenuCallback (int result);
  35170. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginListComponent);
  35171. };
  35172. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  35173. /*** End of inlined file: juce_PluginListComponent.h ***/
  35174. #endif
  35175. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  35176. #endif
  35177. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  35178. #endif
  35179. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  35180. #endif
  35181. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35182. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  35183. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35184. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35185. /**
  35186. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  35187. Use one of these objects if you want to wire-up a set of AudioProcessors
  35188. and play back the result.
  35189. Processors can be added to the graph as "nodes" using addNode(), and once
  35190. added, you can connect any of their input or output channels to other
  35191. nodes using addConnection().
  35192. To play back a graph through an audio device, you might want to use an
  35193. AudioProcessorPlayer object.
  35194. */
  35195. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  35196. public AsyncUpdater
  35197. {
  35198. public:
  35199. /** Creates an empty graph.
  35200. */
  35201. AudioProcessorGraph();
  35202. /** Destructor.
  35203. Any processor objects that have been added to the graph will also be deleted.
  35204. */
  35205. ~AudioProcessorGraph();
  35206. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  35207. To create a node, call AudioProcessorGraph::addNode().
  35208. */
  35209. class JUCE_API Node : public ReferenceCountedObject
  35210. {
  35211. public:
  35212. /** The ID number assigned to this node.
  35213. This is assigned by the graph that owns it, and can't be changed.
  35214. */
  35215. const uint32 id;
  35216. /** The actual processor object that this node represents. */
  35217. AudioProcessor* getProcessor() const throw() { return processor; }
  35218. /** A set of user-definable properties that are associated with this node.
  35219. This can be used to attach values to the node for whatever purpose seems
  35220. useful. For example, you might store an x and y position if your application
  35221. is displaying the nodes on-screen.
  35222. */
  35223. NamedValueSet properties;
  35224. /** A convenient typedef for referring to a pointer to a node object.
  35225. */
  35226. typedef ReferenceCountedObjectPtr <Node> Ptr;
  35227. private:
  35228. friend class AudioProcessorGraph;
  35229. const ScopedPointer<AudioProcessor> processor;
  35230. bool isPrepared;
  35231. Node (uint32 id, AudioProcessor* processor);
  35232. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  35233. void unprepare();
  35234. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Node);
  35235. };
  35236. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  35237. To create a connection, use AudioProcessorGraph::addConnection().
  35238. */
  35239. struct JUCE_API Connection
  35240. {
  35241. public:
  35242. /** The ID number of the node which is the input source for this connection.
  35243. @see AudioProcessorGraph::getNodeForId
  35244. */
  35245. uint32 sourceNodeId;
  35246. /** The index of the output channel of the source node from which this
  35247. connection takes its data.
  35248. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  35249. it is referring to the source node's midi output. Otherwise, it is the zero-based
  35250. index of an audio output channel in the source node.
  35251. */
  35252. int sourceChannelIndex;
  35253. /** The ID number of the node which is the destination for this connection.
  35254. @see AudioProcessorGraph::getNodeForId
  35255. */
  35256. uint32 destNodeId;
  35257. /** The index of the input channel of the destination node to which this
  35258. connection delivers its data.
  35259. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  35260. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  35261. index of an audio input channel in the destination node.
  35262. */
  35263. int destChannelIndex;
  35264. private:
  35265. JUCE_LEAK_DETECTOR (Connection);
  35266. };
  35267. /** Deletes all nodes and connections from this graph.
  35268. Any processor objects in the graph will be deleted.
  35269. */
  35270. void clear();
  35271. /** Returns the number of nodes in the graph. */
  35272. int getNumNodes() const { return nodes.size(); }
  35273. /** Returns a pointer to one of the nodes in the graph.
  35274. This will return 0 if the index is out of range.
  35275. @see getNodeForId
  35276. */
  35277. Node* getNode (const int index) const { return nodes [index]; }
  35278. /** Searches the graph for a node with the given ID number and returns it.
  35279. If no such node was found, this returns 0.
  35280. @see getNode
  35281. */
  35282. Node* getNodeForId (const uint32 nodeId) const;
  35283. /** Adds a node to the graph.
  35284. This creates a new node in the graph, for the specified processor. Once you have
  35285. added a processor to the graph, the graph owns it and will delete it later when
  35286. it is no longer needed.
  35287. The optional nodeId parameter lets you specify an ID to use for the node, but
  35288. if the value is already in use, this new node will overwrite the old one.
  35289. If this succeeds, it returns a pointer to the newly-created node.
  35290. */
  35291. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  35292. /** Deletes a node within the graph which has the specified ID.
  35293. This will also delete any connections that are attached to this node.
  35294. */
  35295. bool removeNode (uint32 nodeId);
  35296. /** Returns the number of connections in the graph. */
  35297. int getNumConnections() const { return connections.size(); }
  35298. /** Returns a pointer to one of the connections in the graph. */
  35299. const Connection* getConnection (int index) const { return connections [index]; }
  35300. /** Searches for a connection between some specified channels.
  35301. If no such connection is found, this returns 0.
  35302. */
  35303. const Connection* getConnectionBetween (uint32 sourceNodeId,
  35304. int sourceChannelIndex,
  35305. uint32 destNodeId,
  35306. int destChannelIndex) const;
  35307. /** Returns true if there is a connection between any of the channels of
  35308. two specified nodes.
  35309. */
  35310. bool isConnected (uint32 possibleSourceNodeId,
  35311. uint32 possibleDestNodeId) const;
  35312. /** Returns true if it would be legal to connect the specified points.
  35313. */
  35314. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  35315. uint32 destNodeId, int destChannelIndex) const;
  35316. /** Attempts to connect two specified channels of two nodes.
  35317. If this isn't allowed (e.g. because you're trying to connect a midi channel
  35318. to an audio one or other such nonsense), then it'll return false.
  35319. */
  35320. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  35321. uint32 destNodeId, int destChannelIndex);
  35322. /** Deletes the connection with the specified index.
  35323. Returns true if a connection was actually deleted.
  35324. */
  35325. void removeConnection (int index);
  35326. /** Deletes any connection between two specified points.
  35327. Returns true if a connection was actually deleted.
  35328. */
  35329. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  35330. uint32 destNodeId, int destChannelIndex);
  35331. /** Removes all connections from the specified node.
  35332. */
  35333. bool disconnectNode (uint32 nodeId);
  35334. /** Performs a sanity checks of all the connections.
  35335. This might be useful if some of the processors are doing things like changing
  35336. their channel counts, which could render some connections obsolete.
  35337. */
  35338. bool removeIllegalConnections();
  35339. /** A special number that represents the midi channel of a node.
  35340. This is used as a channel index value if you want to refer to the midi input
  35341. or output instead of an audio channel.
  35342. */
  35343. static const int midiChannelIndex;
  35344. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  35345. in order to use the audio that comes into and out of the graph itself.
  35346. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  35347. node in the graph which delivers the audio that is coming into the parent
  35348. graph. This allows you to stream the data to other nodes and process the
  35349. incoming audio.
  35350. Likewise, one of these in "output" mode can be sent data which it will add to
  35351. the sum of data being sent to the graph's output.
  35352. @see AudioProcessorGraph
  35353. */
  35354. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  35355. {
  35356. public:
  35357. /** Specifies the mode in which this processor will operate.
  35358. */
  35359. enum IODeviceType
  35360. {
  35361. audioInputNode, /**< In this mode, the processor has output channels
  35362. representing all the audio input channels that are
  35363. coming into its parent audio graph. */
  35364. audioOutputNode, /**< In this mode, the processor has input channels
  35365. representing all the audio output channels that are
  35366. going out of its parent audio graph. */
  35367. midiInputNode, /**< In this mode, the processor has a midi output which
  35368. delivers the same midi data that is arriving at its
  35369. parent graph. */
  35370. midiOutputNode /**< In this mode, the processor has a midi input and
  35371. any data sent to it will be passed out of the parent
  35372. graph. */
  35373. };
  35374. /** Returns the mode of this processor. */
  35375. IODeviceType getType() const { return type; }
  35376. /** Returns the parent graph to which this processor belongs, or 0 if it
  35377. hasn't yet been added to one. */
  35378. AudioProcessorGraph* getParentGraph() const { return graph; }
  35379. /** True if this is an audio or midi input. */
  35380. bool isInput() const;
  35381. /** True if this is an audio or midi output. */
  35382. bool isOutput() const;
  35383. AudioGraphIOProcessor (const IODeviceType type);
  35384. ~AudioGraphIOProcessor();
  35385. const String getName() const;
  35386. void fillInPluginDescription (PluginDescription& d) const;
  35387. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  35388. void releaseResources();
  35389. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  35390. const String getInputChannelName (int channelIndex) const;
  35391. const String getOutputChannelName (int channelIndex) const;
  35392. bool isInputChannelStereoPair (int index) const;
  35393. bool isOutputChannelStereoPair (int index) const;
  35394. bool acceptsMidi() const;
  35395. bool producesMidi() const;
  35396. bool hasEditor() const;
  35397. AudioProcessorEditor* createEditor();
  35398. int getNumParameters();
  35399. const String getParameterName (int);
  35400. float getParameter (int);
  35401. const String getParameterText (int);
  35402. void setParameter (int, float);
  35403. int getNumPrograms();
  35404. int getCurrentProgram();
  35405. void setCurrentProgram (int);
  35406. const String getProgramName (int);
  35407. void changeProgramName (int, const String&);
  35408. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  35409. void setStateInformation (const void* data, int sizeInBytes);
  35410. /** @internal */
  35411. void setParentGraph (AudioProcessorGraph* graph);
  35412. private:
  35413. const IODeviceType type;
  35414. AudioProcessorGraph* graph;
  35415. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioGraphIOProcessor);
  35416. };
  35417. // AudioProcessor methods:
  35418. const String getName() const;
  35419. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  35420. void releaseResources();
  35421. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  35422. const String getInputChannelName (int channelIndex) const;
  35423. const String getOutputChannelName (int channelIndex) const;
  35424. bool isInputChannelStereoPair (int index) const;
  35425. bool isOutputChannelStereoPair (int index) const;
  35426. bool acceptsMidi() const;
  35427. bool producesMidi() const;
  35428. bool hasEditor() const { return false; }
  35429. AudioProcessorEditor* createEditor() { return 0; }
  35430. int getNumParameters() { return 0; }
  35431. const String getParameterName (int) { return String::empty; }
  35432. float getParameter (int) { return 0; }
  35433. const String getParameterText (int) { return String::empty; }
  35434. void setParameter (int, float) { }
  35435. int getNumPrograms() { return 0; }
  35436. int getCurrentProgram() { return 0; }
  35437. void setCurrentProgram (int) { }
  35438. const String getProgramName (int) { return String::empty; }
  35439. void changeProgramName (int, const String&) { }
  35440. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  35441. void setStateInformation (const void* data, int sizeInBytes);
  35442. /** @internal */
  35443. void handleAsyncUpdate();
  35444. private:
  35445. ReferenceCountedArray <Node> nodes;
  35446. OwnedArray <Connection> connections;
  35447. int lastNodeId;
  35448. AudioSampleBuffer renderingBuffers;
  35449. OwnedArray <MidiBuffer> midiBuffers;
  35450. CriticalSection renderLock;
  35451. Array<void*> renderingOps;
  35452. friend class AudioGraphIOProcessor;
  35453. AudioSampleBuffer* currentAudioInputBuffer;
  35454. AudioSampleBuffer currentAudioOutputBuffer;
  35455. MidiBuffer* currentMidiInputBuffer;
  35456. MidiBuffer currentMidiOutputBuffer;
  35457. void clearRenderingSequence();
  35458. void buildRenderingSequence();
  35459. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  35460. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorGraph);
  35461. };
  35462. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  35463. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  35464. #endif
  35465. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  35466. #endif
  35467. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35468. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  35469. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35470. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35471. /**
  35472. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  35473. To use one of these, just make it the callback used by your AudioIODevice, and
  35474. give it a processor to use by calling setProcessor().
  35475. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  35476. input to send both streams through the processor.
  35477. @see AudioProcessor, AudioProcessorGraph
  35478. */
  35479. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  35480. public MidiInputCallback
  35481. {
  35482. public:
  35483. /**
  35484. */
  35485. AudioProcessorPlayer();
  35486. /** Destructor. */
  35487. virtual ~AudioProcessorPlayer();
  35488. /** Sets the processor that should be played.
  35489. The processor that is passed in will not be deleted or owned by this object.
  35490. To stop anything playing, pass in 0 to this method.
  35491. */
  35492. void setProcessor (AudioProcessor* processorToPlay);
  35493. /** Returns the current audio processor that is being played.
  35494. */
  35495. AudioProcessor* getCurrentProcessor() const { return processor; }
  35496. /** Returns a midi message collector that you can pass midi messages to if you
  35497. want them to be injected into the midi stream that is being sent to the
  35498. processor.
  35499. */
  35500. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  35501. /** @internal */
  35502. void audioDeviceIOCallback (const float** inputChannelData,
  35503. int totalNumInputChannels,
  35504. float** outputChannelData,
  35505. int totalNumOutputChannels,
  35506. int numSamples);
  35507. /** @internal */
  35508. void audioDeviceAboutToStart (AudioIODevice* device);
  35509. /** @internal */
  35510. void audioDeviceStopped();
  35511. /** @internal */
  35512. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  35513. private:
  35514. AudioProcessor* processor;
  35515. CriticalSection lock;
  35516. double sampleRate;
  35517. int blockSize;
  35518. bool isPrepared;
  35519. int numInputChans, numOutputChans;
  35520. float* channels [128];
  35521. AudioSampleBuffer tempBuffer;
  35522. MidiBuffer incomingMidi;
  35523. MidiMessageCollector messageCollector;
  35524. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorPlayer);
  35525. };
  35526. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35527. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  35528. #endif
  35529. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35530. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  35531. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35532. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35533. /*** Start of inlined file: juce_PropertyPanel.h ***/
  35534. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  35535. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  35536. /*** Start of inlined file: juce_PropertyComponent.h ***/
  35537. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35538. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35539. class EditableProperty;
  35540. /**
  35541. A base class for a component that goes in a PropertyPanel and displays one of
  35542. an item's properties.
  35543. Subclasses of this are used to display a property in various forms, e.g. a
  35544. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  35545. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  35546. A subclass must implement the refresh() method which will be called to tell the
  35547. component to update itself, and is also responsible for calling this it when the
  35548. item that it refers to is changed.
  35549. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  35550. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  35551. */
  35552. class JUCE_API PropertyComponent : public Component,
  35553. public SettableTooltipClient
  35554. {
  35555. public:
  35556. /** Creates a PropertyComponent.
  35557. @param propertyName the name is stored as this component's name, and is
  35558. used as the name displayed next to this component in
  35559. a property panel
  35560. @param preferredHeight the height that the component should be given - some
  35561. items may need to be larger than a normal row height.
  35562. This value can also be set if a subclass changes the
  35563. preferredHeight member variable.
  35564. */
  35565. PropertyComponent (const String& propertyName,
  35566. int preferredHeight = 25);
  35567. /** Destructor. */
  35568. ~PropertyComponent();
  35569. /** Returns this item's preferred height.
  35570. This value is specified either in the constructor or by a subclass changing the
  35571. preferredHeight member variable.
  35572. */
  35573. int getPreferredHeight() const throw() { return preferredHeight; }
  35574. void setPreferredHeight (int newHeight) throw() { preferredHeight = newHeight; }
  35575. /** Updates the property component if the item it refers to has changed.
  35576. A subclass must implement this method, and other objects may call it to
  35577. force it to refresh itself.
  35578. The subclass should be economical in the amount of work is done, so for
  35579. example it should check whether it really needs to do a repaint rather than
  35580. just doing one every time this method is called, as it may be called when
  35581. the value being displayed hasn't actually changed.
  35582. */
  35583. virtual void refresh() = 0;
  35584. /** The default paint method fills the background and draws a label for the
  35585. item's name.
  35586. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  35587. */
  35588. void paint (Graphics& g);
  35589. /** The default resize method positions any child component to the right of this
  35590. one, based on the look and feel's default label size.
  35591. */
  35592. void resized();
  35593. /** By default, this just repaints the component. */
  35594. void enablementChanged();
  35595. protected:
  35596. /** Used by the PropertyPanel to determine how high this component needs to be.
  35597. A subclass can update this value in its constructor but shouldn't alter it later
  35598. as changes won't necessarily be picked up.
  35599. */
  35600. int preferredHeight;
  35601. private:
  35602. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyComponent);
  35603. };
  35604. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35605. /*** End of inlined file: juce_PropertyComponent.h ***/
  35606. /**
  35607. A panel that holds a list of PropertyComponent objects.
  35608. This panel displays a list of PropertyComponents, and allows them to be organised
  35609. into collapsible sections.
  35610. To use, simply create one of these and add your properties to it with addProperties()
  35611. or addSection().
  35612. @see PropertyComponent
  35613. */
  35614. class JUCE_API PropertyPanel : public Component
  35615. {
  35616. public:
  35617. /** Creates an empty property panel. */
  35618. PropertyPanel();
  35619. /** Destructor. */
  35620. ~PropertyPanel();
  35621. /** Deletes all property components from the panel.
  35622. */
  35623. void clear();
  35624. /** Adds a set of properties to the panel.
  35625. The components in the list will be owned by this object and will be automatically
  35626. deleted later on when no longer needed.
  35627. These properties are added without them being inside a named section. If you
  35628. want them to be kept together in a collapsible section, use addSection() instead.
  35629. */
  35630. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  35631. /** Adds a set of properties to the panel.
  35632. These properties are added at the bottom of the list, under a section heading with
  35633. a plus/minus button that allows it to be opened and closed.
  35634. The components in the list will be owned by this object and will be automatically
  35635. deleted later on when no longer needed.
  35636. To add properies without them being in a section, use addProperties().
  35637. */
  35638. void addSection (const String& sectionTitle,
  35639. const Array <PropertyComponent*>& newPropertyComponents,
  35640. bool shouldSectionInitiallyBeOpen = true);
  35641. /** Calls the refresh() method of all PropertyComponents in the panel */
  35642. void refreshAll() const;
  35643. /** Returns a list of all the names of sections in the panel.
  35644. These are the sections that have been added with addSection().
  35645. */
  35646. const StringArray getSectionNames() const;
  35647. /** Returns true if the section at this index is currently open.
  35648. The index is from 0 up to the number of items returned by getSectionNames().
  35649. */
  35650. bool isSectionOpen (int sectionIndex) const;
  35651. /** Opens or closes one of the sections.
  35652. The index is from 0 up to the number of items returned by getSectionNames().
  35653. */
  35654. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  35655. /** Enables or disables one of the sections.
  35656. The index is from 0 up to the number of items returned by getSectionNames().
  35657. */
  35658. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  35659. /** Saves the current state of open/closed sections so it can be restored later.
  35660. The caller is responsible for deleting the object that is returned.
  35661. To restore this state, use restoreOpennessState().
  35662. @see restoreOpennessState
  35663. */
  35664. XmlElement* getOpennessState() const;
  35665. /** Restores a previously saved arrangement of open/closed sections.
  35666. This will try to restore a snapshot of the panel's state that was created by
  35667. the getOpennessState() method. If any of the sections named in the original
  35668. XML aren't present, they will be ignored.
  35669. @see getOpennessState
  35670. */
  35671. void restoreOpennessState (const XmlElement& newState);
  35672. /** Sets a message to be displayed when there are no properties in the panel.
  35673. The default message is "nothing selected".
  35674. */
  35675. void setMessageWhenEmpty (const String& newMessage);
  35676. /** Returns the message that is displayed when there are no properties.
  35677. @see setMessageWhenEmpty
  35678. */
  35679. const String& getMessageWhenEmpty() const;
  35680. /** @internal */
  35681. void paint (Graphics& g);
  35682. /** @internal */
  35683. void resized();
  35684. private:
  35685. Viewport viewport;
  35686. class PropertyHolderComponent;
  35687. PropertyHolderComponent* propertyHolderComponent;
  35688. String messageWhenEmpty;
  35689. void updatePropHolderLayout() const;
  35690. void updatePropHolderLayout (int width) const;
  35691. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyPanel);
  35692. };
  35693. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  35694. /*** End of inlined file: juce_PropertyPanel.h ***/
  35695. /**
  35696. A type of UI component that displays the parameters of an AudioProcessor as
  35697. a simple list of sliders.
  35698. This can be used for showing an editor for a processor that doesn't supply
  35699. its own custom editor.
  35700. @see AudioProcessor
  35701. */
  35702. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  35703. {
  35704. public:
  35705. GenericAudioProcessorEditor (AudioProcessor* owner);
  35706. ~GenericAudioProcessorEditor();
  35707. void paint (Graphics& g);
  35708. void resized();
  35709. private:
  35710. PropertyPanel panel;
  35711. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GenericAudioProcessorEditor);
  35712. };
  35713. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35714. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  35715. #endif
  35716. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  35717. /*** Start of inlined file: juce_Sampler.h ***/
  35718. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  35719. #define __JUCE_SAMPLER_JUCEHEADER__
  35720. /*** Start of inlined file: juce_Synthesiser.h ***/
  35721. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  35722. #define __JUCE_SYNTHESISER_JUCEHEADER__
  35723. /**
  35724. Describes one of the sounds that a Synthesiser can play.
  35725. A synthesiser can contain one or more sounds, and a sound can choose which
  35726. midi notes and channels can trigger it.
  35727. The SynthesiserSound is a passive class that just describes what the sound is -
  35728. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  35729. more than one SynthesiserVoice to play the same sound at the same time.
  35730. @see Synthesiser, SynthesiserVoice
  35731. */
  35732. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  35733. {
  35734. protected:
  35735. SynthesiserSound();
  35736. public:
  35737. /** Destructor. */
  35738. virtual ~SynthesiserSound();
  35739. /** Returns true if this sound should be played when a given midi note is pressed.
  35740. The Synthesiser will use this information when deciding which sounds to trigger
  35741. for a given note.
  35742. */
  35743. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  35744. /** Returns true if the sound should be triggered by midi events on a given channel.
  35745. The Synthesiser will use this information when deciding which sounds to trigger
  35746. for a given note.
  35747. */
  35748. virtual bool appliesToChannel (const int midiChannel) = 0;
  35749. /**
  35750. */
  35751. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  35752. private:
  35753. JUCE_LEAK_DETECTOR (SynthesiserSound);
  35754. };
  35755. /**
  35756. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  35757. A voice plays a single sound at a time, and a synthesiser holds an array of
  35758. voices so that it can play polyphonically.
  35759. @see Synthesiser, SynthesiserSound
  35760. */
  35761. class JUCE_API SynthesiserVoice
  35762. {
  35763. public:
  35764. /** Creates a voice. */
  35765. SynthesiserVoice();
  35766. /** Destructor. */
  35767. virtual ~SynthesiserVoice();
  35768. /** Returns the midi note that this voice is currently playing.
  35769. Returns a value less than 0 if no note is playing.
  35770. */
  35771. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  35772. /** Returns the sound that this voice is currently playing.
  35773. Returns 0 if it's not playing.
  35774. */
  35775. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  35776. /** Must return true if this voice object is capable of playing the given sound.
  35777. If there are different classes of sound, and different classes of voice, a voice can
  35778. choose which ones it wants to take on.
  35779. A typical implementation of this method may just return true if there's only one type
  35780. of voice and sound, or it might check the type of the sound object passed-in and
  35781. see if it's one that it understands.
  35782. */
  35783. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  35784. /** Called to start a new note.
  35785. This will be called during the rendering callback, so must be fast and thread-safe.
  35786. */
  35787. virtual void startNote (const int midiNoteNumber,
  35788. const float velocity,
  35789. SynthesiserSound* sound,
  35790. const int currentPitchWheelPosition) = 0;
  35791. /** Called to stop a note.
  35792. This will be called during the rendering callback, so must be fast and thread-safe.
  35793. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  35794. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  35795. and allow the synth to reassign it another sound.
  35796. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  35797. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  35798. finishes playing (during the rendering callback), it must make sure that it calls
  35799. clearCurrentNote().
  35800. */
  35801. virtual void stopNote (const bool allowTailOff) = 0;
  35802. /** Called to let the voice know that the pitch wheel has been moved.
  35803. This will be called during the rendering callback, so must be fast and thread-safe.
  35804. */
  35805. virtual void pitchWheelMoved (const int newValue) = 0;
  35806. /** Called to let the voice know that a midi controller has been moved.
  35807. This will be called during the rendering callback, so must be fast and thread-safe.
  35808. */
  35809. virtual void controllerMoved (const int controllerNumber,
  35810. const int newValue) = 0;
  35811. /** Renders the next block of data for this voice.
  35812. The output audio data must be added to the current contents of the buffer provided.
  35813. Only the region of the buffer between startSample and (startSample + numSamples)
  35814. should be altered by this method.
  35815. If the voice is currently silent, it should just return without doing anything.
  35816. If the sound that the voice is playing finishes during the course of this rendered
  35817. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  35818. The size of the blocks that are rendered can change each time it is called, and may
  35819. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  35820. the voice's methods will be called to tell it about note and controller events.
  35821. */
  35822. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  35823. int startSample,
  35824. int numSamples) = 0;
  35825. /** Returns true if the voice is currently playing a sound which is mapped to the given
  35826. midi channel.
  35827. If it's not currently playing, this will return false.
  35828. */
  35829. bool isPlayingChannel (int midiChannel) const;
  35830. /** Changes the voice's reference sample rate.
  35831. The rate is set so that subclasses know the output rate and can set their pitch
  35832. accordingly.
  35833. This method is called by the synth, and subclasses can access the current rate with
  35834. the currentSampleRate member.
  35835. */
  35836. void setCurrentPlaybackSampleRate (double newRate);
  35837. protected:
  35838. /** Returns the current target sample rate at which rendering is being done.
  35839. This is available for subclasses so they can pitch things correctly.
  35840. */
  35841. double getSampleRate() const { return currentSampleRate; }
  35842. /** Resets the state of this voice after a sound has finished playing.
  35843. The subclass must call this when it finishes playing a note and becomes available
  35844. to play new ones.
  35845. It must either call it in the stopNote() method, or if the voice is tailing off,
  35846. then it should call it later during the renderNextBlock method, as soon as it
  35847. finishes its tail-off.
  35848. It can also be called at any time during the render callback if the sound happens
  35849. to have finished, e.g. if it's playing a sample and the sample finishes.
  35850. */
  35851. void clearCurrentNote();
  35852. private:
  35853. friend class Synthesiser;
  35854. double currentSampleRate;
  35855. int currentlyPlayingNote;
  35856. uint32 noteOnTime;
  35857. SynthesiserSound::Ptr currentlyPlayingSound;
  35858. JUCE_LEAK_DETECTOR (SynthesiserVoice);
  35859. };
  35860. /**
  35861. Base class for a musical device that can play sounds.
  35862. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  35863. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  35864. which can play back one of these sounds.
  35865. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  35866. set of sounds, and a set of voices it can use to play them. If you only give it
  35867. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  35868. have available.
  35869. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  35870. events that go in will be scanned for note on/off messages, and these are used to
  35871. start and stop the voices playing the appropriate sounds.
  35872. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  35873. noteOff() and other controller methods.
  35874. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  35875. what the target playback rate is. This value is passed on to the voices so that
  35876. they can pitch their output correctly.
  35877. */
  35878. class JUCE_API Synthesiser
  35879. {
  35880. public:
  35881. /** Creates a new synthesiser.
  35882. You'll need to add some sounds and voices before it'll make any sound..
  35883. */
  35884. Synthesiser();
  35885. /** Destructor. */
  35886. virtual ~Synthesiser();
  35887. /** Deletes all voices. */
  35888. void clearVoices();
  35889. /** Returns the number of voices that have been added. */
  35890. int getNumVoices() const { return voices.size(); }
  35891. /** Returns one of the voices that have been added. */
  35892. SynthesiserVoice* getVoice (int index) const;
  35893. /** Adds a new voice to the synth.
  35894. All the voices should be the same class of object and are treated equally.
  35895. The object passed in will be managed by the synthesiser, which will delete
  35896. it later on when no longer needed. The caller should not retain a pointer to the
  35897. voice.
  35898. */
  35899. void addVoice (SynthesiserVoice* newVoice);
  35900. /** Deletes one of the voices. */
  35901. void removeVoice (int index);
  35902. /** Deletes all sounds. */
  35903. void clearSounds();
  35904. /** Returns the number of sounds that have been added to the synth. */
  35905. int getNumSounds() const { return sounds.size(); }
  35906. /** Returns one of the sounds. */
  35907. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  35908. /** Adds a new sound to the synthesiser.
  35909. The object passed in is reference counted, so will be deleted when it is removed
  35910. from the synthesiser, and when no voices are still using it.
  35911. */
  35912. void addSound (const SynthesiserSound::Ptr& newSound);
  35913. /** Removes and deletes one of the sounds. */
  35914. void removeSound (int index);
  35915. /** If set to true, then the synth will try to take over an existing voice if
  35916. it runs out and needs to play another note.
  35917. The value of this boolean is passed into findFreeVoice(), so the result will
  35918. depend on the implementation of this method.
  35919. */
  35920. void setNoteStealingEnabled (bool shouldStealNotes);
  35921. /** Returns true if note-stealing is enabled.
  35922. @see setNoteStealingEnabled
  35923. */
  35924. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  35925. /** Triggers a note-on event.
  35926. The default method here will find all the sounds that want to be triggered by
  35927. this note/channel. For each sound, it'll try to find a free voice, and use the
  35928. voice to start playing the sound.
  35929. Subclasses might want to override this if they need a more complex algorithm.
  35930. This method will be called automatically according to the midi data passed into
  35931. renderNextBlock(), but may be called explicitly too.
  35932. */
  35933. virtual void noteOn (int midiChannel,
  35934. int midiNoteNumber,
  35935. float velocity);
  35936. /** Triggers a note-off event.
  35937. This will turn off any voices that are playing a sound for the given note/channel.
  35938. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  35939. (if they can do). If this is false, the notes will all be cut off immediately.
  35940. This method will be called automatically according to the midi data passed into
  35941. renderNextBlock(), but may be called explicitly too.
  35942. */
  35943. virtual void noteOff (int midiChannel,
  35944. int midiNoteNumber,
  35945. bool allowTailOff);
  35946. /** Turns off all notes.
  35947. This will turn off any voices that are playing a sound on the given midi channel.
  35948. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  35949. which channel they're playing.
  35950. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  35951. (if they can do). If this is false, the notes will all be cut off immediately.
  35952. This method will be called automatically according to the midi data passed into
  35953. renderNextBlock(), but may be called explicitly too.
  35954. */
  35955. virtual void allNotesOff (int midiChannel,
  35956. bool allowTailOff);
  35957. /** Sends a pitch-wheel message.
  35958. This will send a pitch-wheel message to any voices that are playing sounds on
  35959. the given midi channel.
  35960. This method will be called automatically according to the midi data passed into
  35961. renderNextBlock(), but may be called explicitly too.
  35962. @param midiChannel the midi channel for the event
  35963. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  35964. */
  35965. virtual void handlePitchWheel (int midiChannel,
  35966. int wheelValue);
  35967. /** Sends a midi controller message.
  35968. This will send a midi controller message to any voices that are playing sounds on
  35969. the given midi channel.
  35970. This method will be called automatically according to the midi data passed into
  35971. renderNextBlock(), but may be called explicitly too.
  35972. @param midiChannel the midi channel for the event
  35973. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  35974. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  35975. */
  35976. virtual void handleController (int midiChannel,
  35977. int controllerNumber,
  35978. int controllerValue);
  35979. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  35980. render.
  35981. This value is propagated to the voices so that they can use it to render the correct
  35982. pitches.
  35983. */
  35984. void setCurrentPlaybackSampleRate (double sampleRate);
  35985. /** Creates the next block of audio output.
  35986. This will process the next numSamples of data from all the voices, and add that output
  35987. to the audio block supplied, starting from the offset specified. Note that the
  35988. data will be added to the current contents of the buffer, so you should clear it
  35989. before calling this method if necessary.
  35990. The midi events in the inputMidi buffer are parsed for note and controller events,
  35991. and these are used to trigger the voices. Note that the startSample offset applies
  35992. both to the audio output buffer and the midi input buffer, so any midi events
  35993. with timestamps outside the specified region will be ignored.
  35994. */
  35995. void renderNextBlock (AudioSampleBuffer& outputAudio,
  35996. const MidiBuffer& inputMidi,
  35997. int startSample,
  35998. int numSamples);
  35999. protected:
  36000. /** This is used to control access to the rendering callback and the note trigger methods. */
  36001. CriticalSection lock;
  36002. OwnedArray <SynthesiserVoice> voices;
  36003. ReferenceCountedArray <SynthesiserSound> sounds;
  36004. /** The last pitch-wheel values for each midi channel. */
  36005. int lastPitchWheelValues [16];
  36006. /** Searches through the voices to find one that's not currently playing, and which
  36007. can play the given sound.
  36008. Returns 0 if all voices are busy and stealing isn't enabled.
  36009. This can be overridden to implement custom voice-stealing algorithms.
  36010. */
  36011. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  36012. const bool stealIfNoneAvailable) const;
  36013. /** Starts a specified voice playing a particular sound.
  36014. You'll probably never need to call this, it's used internally by noteOn(), but
  36015. may be needed by subclasses for custom behaviours.
  36016. */
  36017. void startVoice (SynthesiserVoice* voice,
  36018. SynthesiserSound* sound,
  36019. int midiChannel,
  36020. int midiNoteNumber,
  36021. float velocity);
  36022. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  36023. // Temporary method here to cause a compiler error - note the new parameters for this method.
  36024. int findFreeVoice (const bool) const { return 0; }
  36025. #endif
  36026. private:
  36027. double sampleRate;
  36028. uint32 lastNoteOnCounter;
  36029. bool shouldStealNotes;
  36030. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Synthesiser);
  36031. };
  36032. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  36033. /*** End of inlined file: juce_Synthesiser.h ***/
  36034. /**
  36035. A subclass of SynthesiserSound that represents a sampled audio clip.
  36036. This is a pretty basic sampler, and just attempts to load the whole audio stream
  36037. into memory.
  36038. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36039. give it some SampledSound objects to play.
  36040. @see SamplerVoice, Synthesiser, SynthesiserSound
  36041. */
  36042. class JUCE_API SamplerSound : public SynthesiserSound
  36043. {
  36044. public:
  36045. /** Creates a sampled sound from an audio reader.
  36046. This will attempt to load the audio from the source into memory and store
  36047. it in this object.
  36048. @param name a name for the sample
  36049. @param source the audio to load. This object can be safely deleted by the
  36050. caller after this constructor returns
  36051. @param midiNotes the set of midi keys that this sound should be played on. This
  36052. is used by the SynthesiserSound::appliesToNote() method
  36053. @param midiNoteForNormalPitch the midi note at which the sample should be played
  36054. with its natural rate. All other notes will be pitched
  36055. up or down relative to this one
  36056. @param attackTimeSecs the attack (fade-in) time, in seconds
  36057. @param releaseTimeSecs the decay (fade-out) time, in seconds
  36058. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  36059. source, in seconds
  36060. */
  36061. SamplerSound (const String& name,
  36062. AudioFormatReader& source,
  36063. const BigInteger& midiNotes,
  36064. int midiNoteForNormalPitch,
  36065. double attackTimeSecs,
  36066. double releaseTimeSecs,
  36067. double maxSampleLengthSeconds);
  36068. /** Destructor. */
  36069. ~SamplerSound();
  36070. /** Returns the sample's name */
  36071. const String& getName() const { return name; }
  36072. /** Returns the audio sample data.
  36073. This could be 0 if there was a problem loading it.
  36074. */
  36075. AudioSampleBuffer* getAudioData() const { return data; }
  36076. bool appliesToNote (const int midiNoteNumber);
  36077. bool appliesToChannel (const int midiChannel);
  36078. private:
  36079. friend class SamplerVoice;
  36080. String name;
  36081. ScopedPointer <AudioSampleBuffer> data;
  36082. double sourceSampleRate;
  36083. BigInteger midiNotes;
  36084. int length, attackSamples, releaseSamples;
  36085. int midiRootNote;
  36086. JUCE_LEAK_DETECTOR (SamplerSound);
  36087. };
  36088. /**
  36089. A subclass of SynthesiserVoice that can play a SamplerSound.
  36090. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  36091. give it some SampledSound objects to play.
  36092. @see SamplerSound, Synthesiser, SynthesiserVoice
  36093. */
  36094. class JUCE_API SamplerVoice : public SynthesiserVoice
  36095. {
  36096. public:
  36097. /** Creates a SamplerVoice.
  36098. */
  36099. SamplerVoice();
  36100. /** Destructor. */
  36101. ~SamplerVoice();
  36102. bool canPlaySound (SynthesiserSound* sound);
  36103. void startNote (const int midiNoteNumber,
  36104. const float velocity,
  36105. SynthesiserSound* sound,
  36106. const int currentPitchWheelPosition);
  36107. void stopNote (const bool allowTailOff);
  36108. void pitchWheelMoved (const int newValue);
  36109. void controllerMoved (const int controllerNumber,
  36110. const int newValue);
  36111. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  36112. private:
  36113. double pitchRatio;
  36114. double sourceSamplePosition;
  36115. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  36116. bool isInAttack, isInRelease;
  36117. JUCE_LEAK_DETECTOR (SamplerVoice);
  36118. };
  36119. #endif // __JUCE_SAMPLER_JUCEHEADER__
  36120. /*** End of inlined file: juce_Sampler.h ***/
  36121. #endif
  36122. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  36123. #endif
  36124. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36125. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  36126. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36127. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36128. /** Manages a list of ActionListeners, and can send them messages.
  36129. To quickly add methods to your class that can add/remove action
  36130. listeners and broadcast to them, you can derive from this.
  36131. @see ActionListener, ChangeListener
  36132. */
  36133. class JUCE_API ActionBroadcaster
  36134. {
  36135. public:
  36136. /** Creates an ActionBroadcaster. */
  36137. ActionBroadcaster();
  36138. /** Destructor. */
  36139. virtual ~ActionBroadcaster();
  36140. /** Adds a listener to the list.
  36141. Trying to add a listener that's already on the list will have no effect.
  36142. */
  36143. void addActionListener (ActionListener* listener);
  36144. /** Removes a listener from the list.
  36145. If the listener isn't on the list, this won't have any effect.
  36146. */
  36147. void removeActionListener (ActionListener* listener);
  36148. /** Removes all listeners from the list. */
  36149. void removeAllActionListeners();
  36150. /** Broadcasts a message to all the registered listeners.
  36151. @see ActionListener::actionListenerCallback
  36152. */
  36153. void sendActionMessage (const String& message) const;
  36154. private:
  36155. class CallbackReceiver : public MessageListener
  36156. {
  36157. public:
  36158. CallbackReceiver();
  36159. void handleMessage (const Message&);
  36160. ActionBroadcaster* owner;
  36161. };
  36162. friend class CallbackReceiver;
  36163. CallbackReceiver callback;
  36164. SortedSet <ActionListener*> actionListeners;
  36165. CriticalSection actionListenerLock;
  36166. JUCE_DECLARE_NON_COPYABLE (ActionBroadcaster);
  36167. };
  36168. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  36169. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  36170. #endif
  36171. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  36172. #endif
  36173. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  36174. #endif
  36175. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  36176. #endif
  36177. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  36178. #endif
  36179. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  36180. #endif
  36181. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36182. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  36183. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36184. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36185. class InterprocessConnectionServer;
  36186. /**
  36187. Manages a simple two-way messaging connection to another process, using either
  36188. a socket or a named pipe as the transport medium.
  36189. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  36190. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  36191. and incoming messages will result in a callback via the messageReceived()
  36192. method.
  36193. To open a pipe and wait for another client to connect to it, use the createPipe()
  36194. method.
  36195. To act as a socket server and create connections for one or more client, see the
  36196. InterprocessConnectionServer class.
  36197. @see InterprocessConnectionServer, Socket, NamedPipe
  36198. */
  36199. class JUCE_API InterprocessConnection : public Thread,
  36200. private MessageListener
  36201. {
  36202. public:
  36203. /** Creates a connection.
  36204. Connections are created manually, connecting them with the connectToSocket()
  36205. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  36206. when a client wants to connect.
  36207. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  36208. connectionLost() and messageReceived() methods will
  36209. always be made using the message thread; if false,
  36210. these will be called immediately on the connection's
  36211. own thread.
  36212. @param magicMessageHeaderNumber a magic number to use in the header to check the
  36213. validity of the data blocks being sent and received. This
  36214. can be any number, but the sender and receiver must obviously
  36215. use matching values or they won't recognise each other.
  36216. */
  36217. InterprocessConnection (bool callbacksOnMessageThread = true,
  36218. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  36219. /** Destructor. */
  36220. ~InterprocessConnection();
  36221. /** Tries to connect this object to a socket.
  36222. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  36223. object waiting to receive client connections on this port number.
  36224. @param hostName the host computer, either a network address or name
  36225. @param portNumber the socket port number to try to connect to
  36226. @param timeOutMillisecs how long to keep trying before giving up
  36227. @returns true if the connection is established successfully
  36228. @see Socket
  36229. */
  36230. bool connectToSocket (const String& hostName,
  36231. int portNumber,
  36232. int timeOutMillisecs);
  36233. /** Tries to connect the object to an existing named pipe.
  36234. For this to work, another process on the same computer must already have opened
  36235. an InterprocessConnection object and used createPipe() to create a pipe for this
  36236. to connect to.
  36237. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36238. @returns true if it connects successfully.
  36239. @see createPipe, NamedPipe
  36240. */
  36241. bool connectToPipe (const String& pipeName,
  36242. int pipeReceiveMessageTimeoutMs = -1);
  36243. /** Tries to create a new pipe for other processes to connect to.
  36244. This creates a pipe with the given name, so that other processes can use
  36245. connectToPipe() to connect to the other end.
  36246. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  36247. If another process is already using this pipe, this will fail and return false.
  36248. */
  36249. bool createPipe (const String& pipeName,
  36250. int pipeReceiveMessageTimeoutMs = -1);
  36251. /** Disconnects and closes any currently-open sockets or pipes. */
  36252. void disconnect();
  36253. /** True if a socket or pipe is currently active. */
  36254. bool isConnected() const;
  36255. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  36256. StreamingSocket* getSocket() const throw() { return socket; }
  36257. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  36258. NamedPipe* getPipe() const throw() { return pipe; }
  36259. /** Returns the name of the machine at the other end of this connection.
  36260. This will return an empty string if the other machine isn't known for
  36261. some reason.
  36262. */
  36263. const String getConnectedHostName() const;
  36264. /** Tries to send a message to the other end of this connection.
  36265. This will fail if it's not connected, or if there's some kind of write error. If
  36266. it succeeds, the connection object at the other end will receive the message by
  36267. a callback to its messageReceived() method.
  36268. @see messageReceived
  36269. */
  36270. bool sendMessage (const MemoryBlock& message);
  36271. /** Called when the connection is first connected.
  36272. If the connection was created with the callbacksOnMessageThread flag set, then
  36273. this will be called on the message thread; otherwise it will be called on a server
  36274. thread.
  36275. */
  36276. virtual void connectionMade() = 0;
  36277. /** Called when the connection is broken.
  36278. If the connection was created with the callbacksOnMessageThread flag set, then
  36279. this will be called on the message thread; otherwise it will be called on a server
  36280. thread.
  36281. */
  36282. virtual void connectionLost() = 0;
  36283. /** Called when a message arrives.
  36284. When the object at the other end of this connection sends us a message with sendMessage(),
  36285. this callback is used to deliver it to us.
  36286. If the connection was created with the callbacksOnMessageThread flag set, then
  36287. this will be called on the message thread; otherwise it will be called on a server
  36288. thread.
  36289. @see sendMessage
  36290. */
  36291. virtual void messageReceived (const MemoryBlock& message) = 0;
  36292. private:
  36293. CriticalSection pipeAndSocketLock;
  36294. ScopedPointer <StreamingSocket> socket;
  36295. ScopedPointer <NamedPipe> pipe;
  36296. bool callbackConnectionState;
  36297. const bool useMessageThread;
  36298. const uint32 magicMessageHeader;
  36299. int pipeReceiveMessageTimeout;
  36300. friend class InterprocessConnectionServer;
  36301. void initialiseWithSocket (StreamingSocket* socket_);
  36302. void initialiseWithPipe (NamedPipe* pipe_);
  36303. void handleMessage (const Message& message);
  36304. void connectionMadeInt();
  36305. void connectionLostInt();
  36306. void deliverDataInt (const MemoryBlock& data);
  36307. bool readNextMessageInt();
  36308. void run();
  36309. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnection);
  36310. };
  36311. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  36312. /*** End of inlined file: juce_InterprocessConnection.h ***/
  36313. #endif
  36314. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36315. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  36316. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36317. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36318. /**
  36319. An object that waits for client sockets to connect to a port on this host, and
  36320. creates InterprocessConnection objects for each one.
  36321. To use this, create a class derived from it which implements the createConnectionObject()
  36322. method, so that it creates suitable connection objects for each client that tries
  36323. to connect.
  36324. @see InterprocessConnection
  36325. */
  36326. class JUCE_API InterprocessConnectionServer : private Thread
  36327. {
  36328. public:
  36329. /** Creates an uninitialised server object.
  36330. */
  36331. InterprocessConnectionServer();
  36332. /** Destructor. */
  36333. ~InterprocessConnectionServer();
  36334. /** Starts an internal thread which listens on the given port number.
  36335. While this is running, in another process tries to connect with the
  36336. InterprocessConnection::connectToSocket() method, this object will call
  36337. createConnectionObject() to create a connection to that client.
  36338. Use stop() to stop the thread running.
  36339. @see createConnectionObject, stop
  36340. */
  36341. bool beginWaitingForSocket (int portNumber);
  36342. /** Terminates the listener thread, if it's active.
  36343. @see beginWaitingForSocket
  36344. */
  36345. void stop();
  36346. protected:
  36347. /** Creates a suitable connection object for a client process that wants to
  36348. connect to this one.
  36349. This will be called by the listener thread when a client process tries
  36350. to connect, and must return a new InterprocessConnection object that will
  36351. then run as this end of the connection.
  36352. @see InterprocessConnection
  36353. */
  36354. virtual InterprocessConnection* createConnectionObject() = 0;
  36355. private:
  36356. ScopedPointer <StreamingSocket> socket;
  36357. void run();
  36358. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnectionServer);
  36359. };
  36360. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  36361. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  36362. #endif
  36363. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  36364. #endif
  36365. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  36366. #endif
  36367. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  36368. #endif
  36369. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36370. /*** Start of inlined file: juce_MessageManager.h ***/
  36371. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36372. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36373. class Component;
  36374. class MessageManagerLock;
  36375. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  36376. */
  36377. typedef void* (MessageCallbackFunction) (void* userData);
  36378. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  36379. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  36380. */
  36381. class JUCE_API MessageManager
  36382. {
  36383. public:
  36384. /** Returns the global instance of the MessageManager. */
  36385. static MessageManager* getInstance() throw();
  36386. /** Runs the event dispatch loop until a stop message is posted.
  36387. This method is only intended to be run by the application's startup routine,
  36388. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  36389. @see stopDispatchLoop
  36390. */
  36391. void runDispatchLoop();
  36392. /** Sends a signal that the dispatch loop should terminate.
  36393. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  36394. will be interrupted and will return.
  36395. @see runDispatchLoop
  36396. */
  36397. void stopDispatchLoop();
  36398. /** Returns true if the stopDispatchLoop() method has been called.
  36399. */
  36400. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  36401. #if JUCE_MODAL_LOOPS_PERMITTED
  36402. /** Synchronously dispatches messages until a given time has elapsed.
  36403. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  36404. otherwise returns true.
  36405. */
  36406. bool runDispatchLoopUntil (int millisecondsToRunFor);
  36407. #endif
  36408. /** Calls a function using the message-thread.
  36409. This can be used by any thread to cause this function to be called-back
  36410. by the message thread. If it's the message-thread that's calling this method,
  36411. then the function will just be called; if another thread is calling, a message
  36412. will be posted to the queue, and this method will block until that message
  36413. is delivered, the function is called, and the result is returned.
  36414. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  36415. thread has a critical section locked, which an unrelated message callback then tries to lock
  36416. before the message thread gets round to processing this callback.
  36417. @param callback the function to call - its signature must be @code
  36418. void* myCallbackFunction (void*) @endcode
  36419. @param userData a user-defined pointer that will be passed to the function that gets called
  36420. @returns the value that the callback function returns.
  36421. @see MessageManagerLock
  36422. */
  36423. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  36424. void* userData);
  36425. /** Returns true if the caller-thread is the message thread. */
  36426. bool isThisTheMessageThread() const throw();
  36427. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  36428. (Best to ignore this method unless you really know what you're doing..)
  36429. @see getCurrentMessageThread
  36430. */
  36431. void setCurrentThreadAsMessageThread();
  36432. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  36433. (Best to ignore this method unless you really know what you're doing..)
  36434. @see setCurrentMessageThread
  36435. */
  36436. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  36437. /** Returns true if the caller thread has currenltly got the message manager locked.
  36438. see the MessageManagerLock class for more info about this.
  36439. This will be true if the caller is the message thread, because that automatically
  36440. gains a lock while a message is being dispatched.
  36441. */
  36442. bool currentThreadHasLockedMessageManager() const throw();
  36443. /** Sends a message to all other JUCE applications that are running.
  36444. @param messageText the string that will be passed to the actionListenerCallback()
  36445. method of the broadcast listeners in the other app.
  36446. @see registerBroadcastListener, ActionListener
  36447. */
  36448. static void broadcastMessage (const String& messageText);
  36449. /** Registers a listener to get told about broadcast messages.
  36450. The actionListenerCallback() callback's string parameter
  36451. is the message passed into broadcastMessage().
  36452. @see broadcastMessage
  36453. */
  36454. void registerBroadcastListener (ActionListener* listener);
  36455. /** Deregisters a broadcast listener. */
  36456. void deregisterBroadcastListener (ActionListener* listener);
  36457. /** @internal */
  36458. void deliverMessage (Message*);
  36459. /** @internal */
  36460. void deliverBroadcastMessage (const String&);
  36461. /** @internal */
  36462. ~MessageManager() throw();
  36463. private:
  36464. MessageManager() throw();
  36465. friend class MessageListener;
  36466. friend class ChangeBroadcaster;
  36467. friend class ActionBroadcaster;
  36468. friend class CallbackMessage;
  36469. static MessageManager* instance;
  36470. SortedSet <const MessageListener*> messageListeners;
  36471. ScopedPointer <ActionBroadcaster> broadcaster;
  36472. friend class JUCEApplication;
  36473. bool quitMessagePosted, quitMessageReceived;
  36474. Thread::ThreadID messageThreadId;
  36475. static void* exitModalLoopCallback (void*);
  36476. void postMessageToQueue (Message* message);
  36477. static void doPlatformSpecificInitialisation();
  36478. static void doPlatformSpecificShutdown();
  36479. friend class MessageManagerLock;
  36480. Thread::ThreadID volatile threadWithLock;
  36481. CriticalSection lockingLock;
  36482. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager);
  36483. };
  36484. /** Used to make sure that the calling thread has exclusive access to the message loop.
  36485. Because it's not thread-safe to call any of the Component or other UI classes
  36486. from threads other than the message thread, one of these objects can be used to
  36487. lock the message loop and allow this to be done. The message thread will be
  36488. suspended for the lifetime of the MessageManagerLock object, so create one on
  36489. the stack like this: @code
  36490. void MyThread::run()
  36491. {
  36492. someData = 1234;
  36493. const MessageManagerLock mmLock;
  36494. // the event loop will now be locked so it's safe to make a few calls..
  36495. myComponent->setBounds (newBounds);
  36496. myComponent->repaint();
  36497. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  36498. }
  36499. @endcode
  36500. Obviously be careful not to create one of these and leave it lying around, or
  36501. your app will grind to a halt!
  36502. Another caveat is that using this in conjunction with other CriticalSections
  36503. can create lots of interesting ways of producing a deadlock! In particular, if
  36504. your message thread calls stopThread() for a thread that uses these locks,
  36505. you'll get an (occasional) deadlock..
  36506. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  36507. */
  36508. class JUCE_API MessageManagerLock
  36509. {
  36510. public:
  36511. /** Tries to acquire a lock on the message manager.
  36512. The constructor attempts to gain a lock on the message loop, and the lock will be
  36513. kept for the lifetime of this object.
  36514. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  36515. this method will keep checking whether the thread has been given the
  36516. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  36517. without gaining the lock. If you pass a thread, you must check whether the lock was
  36518. successful by calling lockWasGained(). If this is false, your thread is being told to
  36519. die, so you should take evasive action.
  36520. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  36521. careful when doing this, because it's very easy to deadlock if your message thread
  36522. attempts to call stopThread() on a thread just as that thread attempts to get the
  36523. message lock.
  36524. If the calling thread already has the lock, nothing will be done, so it's safe and
  36525. quick to use these locks recursively.
  36526. E.g.
  36527. @code
  36528. void run()
  36529. {
  36530. ...
  36531. while (! threadShouldExit())
  36532. {
  36533. MessageManagerLock mml (Thread::getCurrentThread());
  36534. if (! mml.lockWasGained())
  36535. return; // another thread is trying to kill us!
  36536. ..do some locked stuff here..
  36537. }
  36538. ..and now the MM is now unlocked..
  36539. }
  36540. @endcode
  36541. */
  36542. MessageManagerLock (Thread* threadToCheckForExitSignal = 0);
  36543. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  36544. instead of a thread.
  36545. See the MessageManagerLock (Thread*) constructor for details on how this works.
  36546. */
  36547. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  36548. /** Releases the current thread's lock on the message manager.
  36549. Make sure this object is created and deleted by the same thread,
  36550. otherwise there are no guarantees what will happen!
  36551. */
  36552. ~MessageManagerLock() throw();
  36553. /** Returns true if the lock was successfully acquired.
  36554. (See the constructor that takes a Thread for more info).
  36555. */
  36556. bool lockWasGained() const throw() { return locked; }
  36557. private:
  36558. class BlockingMessage;
  36559. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  36560. ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  36561. bool locked;
  36562. void init (Thread* thread, ThreadPoolJob* job);
  36563. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock);
  36564. };
  36565. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36566. /*** End of inlined file: juce_MessageManager.h ***/
  36567. #endif
  36568. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  36569. /*** Start of inlined file: juce_MultiTimer.h ***/
  36570. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  36571. #define __JUCE_MULTITIMER_JUCEHEADER__
  36572. /**
  36573. A type of timer class that can run multiple timers with different frequencies,
  36574. all of which share a single callback.
  36575. This class is very similar to the Timer class, but allows you run multiple
  36576. separate timers, where each one has a unique ID number. The methods in this
  36577. class are exactly equivalent to those in Timer, but with the addition of
  36578. this ID number.
  36579. To use it, you need to create a subclass of MultiTimer, implementing the
  36580. timerCallback() method. Then you can start timers with startTimer(), and
  36581. each time the callback is triggered, it passes in the ID of the timer that
  36582. caused it.
  36583. @see Timer
  36584. */
  36585. class JUCE_API MultiTimer
  36586. {
  36587. protected:
  36588. /** Creates a MultiTimer.
  36589. When created, no timers are running, so use startTimer() to start things off.
  36590. */
  36591. MultiTimer() throw();
  36592. /** Creates a copy of another timer.
  36593. Note that this timer will not contain any running timers, even if the one you're
  36594. copying from was running.
  36595. */
  36596. MultiTimer (const MultiTimer& other) throw();
  36597. public:
  36598. /** Destructor. */
  36599. virtual ~MultiTimer();
  36600. /** The user-defined callback routine that actually gets called by each of the
  36601. timers that are running.
  36602. It's perfectly ok to call startTimer() or stopTimer() from within this
  36603. callback to change the subsequent intervals.
  36604. */
  36605. virtual void timerCallback (int timerId) = 0;
  36606. /** Starts a timer and sets the length of interval required.
  36607. If the timer is already started, this will reset it, so the
  36608. time between calling this method and the next timer callback
  36609. will not be less than the interval length passed in.
  36610. @param timerId a unique Id number that identifies the timer to
  36611. start. This is the id that will be passed back
  36612. to the timerCallback() method when this timer is
  36613. triggered
  36614. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  36615. rounded up to 1)
  36616. */
  36617. void startTimer (int timerId, int intervalInMilliseconds) throw();
  36618. /** Stops a timer.
  36619. If a timer has been started with the given ID number, it will be cancelled.
  36620. No more callbacks will be made for the specified timer after this method returns.
  36621. If this is called from a different thread, any callbacks that may
  36622. be currently executing may be allowed to finish before the method
  36623. returns.
  36624. */
  36625. void stopTimer (int timerId) throw();
  36626. /** Checks whether a timer has been started for a specified ID.
  36627. @returns true if a timer with the given ID is running.
  36628. */
  36629. bool isTimerRunning (int timerId) const throw();
  36630. /** Returns the interval for a specified timer ID.
  36631. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  36632. is running for the ID number specified.
  36633. */
  36634. int getTimerInterval (int timerId) const throw();
  36635. private:
  36636. class MultiTimerCallback;
  36637. CriticalSection timerListLock;
  36638. OwnedArray <MultiTimerCallback> timers;
  36639. MultiTimer& operator= (const MultiTimer&);
  36640. };
  36641. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  36642. /*** End of inlined file: juce_MultiTimer.h ***/
  36643. #endif
  36644. #ifndef __JUCE_TIMER_JUCEHEADER__
  36645. #endif
  36646. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  36647. /*** Start of inlined file: juce_ArrowButton.h ***/
  36648. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  36649. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  36650. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  36651. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36652. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36653. /**
  36654. An effect filter that adds a drop-shadow behind the image's content.
  36655. (This will only work on images/components that aren't opaque, of course).
  36656. When added to a component, this effect will draw a soft-edged
  36657. shadow based on what gets drawn inside it. The shadow will also
  36658. be applied to the component's children.
  36659. For speed, this doesn't use a proper gaussian blur, but cheats by
  36660. using a simple bilinear filter. If you need a really high-quality
  36661. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  36662. @see Component::setComponentEffect
  36663. */
  36664. class JUCE_API DropShadowEffect : public ImageEffectFilter
  36665. {
  36666. public:
  36667. /** Creates a default drop-shadow effect.
  36668. To customise the shadow's appearance, use the setShadowProperties()
  36669. method.
  36670. */
  36671. DropShadowEffect();
  36672. /** Destructor. */
  36673. ~DropShadowEffect();
  36674. /** Sets up parameters affecting the shadow's appearance.
  36675. @param newRadius the (approximate) radius of the blur used
  36676. @param newOpacity the opacity with which the shadow is rendered
  36677. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  36678. component's contents
  36679. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  36680. component's contents
  36681. */
  36682. void setShadowProperties (float newRadius,
  36683. float newOpacity,
  36684. int newShadowOffsetX,
  36685. int newShadowOffsetY);
  36686. /** @internal */
  36687. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  36688. private:
  36689. int offsetX, offsetY;
  36690. float radius, opacity;
  36691. JUCE_LEAK_DETECTOR (DropShadowEffect);
  36692. };
  36693. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36694. /*** End of inlined file: juce_DropShadowEffect.h ***/
  36695. /**
  36696. A button with an arrow in it.
  36697. @see Button
  36698. */
  36699. class JUCE_API ArrowButton : public Button
  36700. {
  36701. public:
  36702. /** Creates an ArrowButton.
  36703. @param buttonName the name to give the button
  36704. @param arrowDirection the direction the arrow should point in, where 0.0 is
  36705. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  36706. @param arrowColour the colour to use for the arrow
  36707. */
  36708. ArrowButton (const String& buttonName,
  36709. float arrowDirection,
  36710. const Colour& arrowColour);
  36711. /** Destructor. */
  36712. ~ArrowButton();
  36713. protected:
  36714. /** @internal */
  36715. void paintButton (Graphics& g,
  36716. bool isMouseOverButton,
  36717. bool isButtonDown);
  36718. /** @internal */
  36719. void buttonStateChanged();
  36720. private:
  36721. Colour colour;
  36722. DropShadowEffect shadow;
  36723. Path path;
  36724. int offset;
  36725. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ArrowButton);
  36726. };
  36727. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  36728. /*** End of inlined file: juce_ArrowButton.h ***/
  36729. #endif
  36730. #ifndef __JUCE_BUTTON_JUCEHEADER__
  36731. #endif
  36732. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36733. /*** Start of inlined file: juce_DrawableButton.h ***/
  36734. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36735. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36736. /*** Start of inlined file: juce_Drawable.h ***/
  36737. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  36738. #define __JUCE_DRAWABLE_JUCEHEADER__
  36739. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  36740. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36741. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36742. /**
  36743. Expresses a coordinate as a dynamically evaluated expression.
  36744. @see RelativePoint, RelativeRectangle
  36745. */
  36746. class JUCE_API RelativeCoordinate
  36747. {
  36748. public:
  36749. /** Creates a zero coordinate. */
  36750. RelativeCoordinate();
  36751. RelativeCoordinate (const Expression& expression);
  36752. RelativeCoordinate (const RelativeCoordinate& other);
  36753. RelativeCoordinate& operator= (const RelativeCoordinate& other);
  36754. /** Creates an absolute position from the parent origin on either the X or Y axis.
  36755. @param absoluteDistanceFromOrigin the distance from the origin
  36756. */
  36757. RelativeCoordinate (double absoluteDistanceFromOrigin);
  36758. /** Recreates a coordinate from a string description.
  36759. The string will be parsed by ExpressionParser::parse().
  36760. @param stringVersion the expression to use
  36761. @see toString
  36762. */
  36763. RelativeCoordinate (const String& stringVersion);
  36764. /** Destructor. */
  36765. ~RelativeCoordinate();
  36766. bool operator== (const RelativeCoordinate& other) const throw();
  36767. bool operator!= (const RelativeCoordinate& other) const throw();
  36768. /** Calculates the absolute position of this coordinate.
  36769. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  36770. be needed to calculate the result.
  36771. */
  36772. double resolve (const Expression::Scope* evaluationScope) const;
  36773. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  36774. This will recursively check any coordinates upon which this one depends.
  36775. */
  36776. bool references (const String& coordName, const Expression::Scope* evaluationScope) const;
  36777. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  36778. bool isRecursive (const Expression::Scope* evaluationScope) const;
  36779. /** Returns true if this coordinate depends on any other coordinates for its position. */
  36780. bool isDynamic() const;
  36781. /** Changes the value of this coord to make it resolve to the specified position.
  36782. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  36783. or relative position to whatever value is necessary to make its resultant position
  36784. match the position that is provided.
  36785. */
  36786. void moveToAbsolute (double absoluteTargetPosition, const Expression::Scope* evaluationScope);
  36787. /** Returns the expression that defines this coordinate. */
  36788. const Expression& getExpression() const { return term; }
  36789. /** Returns a string which represents this coordinate.
  36790. For details of the string syntax, see the constructor notes.
  36791. */
  36792. const String toString() const;
  36793. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  36794. As well as avoiding using string literals in your code, using these preset values
  36795. has the advantage that all instances of the same string will share the same, reference-counted
  36796. String object, so if you have thousands of points which all refer to the same
  36797. anchor points, this can save a significant amount of memory allocation.
  36798. */
  36799. struct Strings
  36800. {
  36801. static const String parent; /**< "parent" */
  36802. static const String left; /**< "left" */
  36803. static const String right; /**< "right" */
  36804. static const String top; /**< "top" */
  36805. static const String bottom; /**< "bottom" */
  36806. static const String x; /**< "x" */
  36807. static const String y; /**< "y" */
  36808. static const String width; /**< "width" */
  36809. static const String height; /**< "height" */
  36810. };
  36811. struct StandardStrings
  36812. {
  36813. enum Type
  36814. {
  36815. left, right, top, bottom,
  36816. x, y, width, height,
  36817. parent,
  36818. unknown
  36819. };
  36820. static Type getTypeOf (const String& s) throw();
  36821. };
  36822. private:
  36823. Expression term;
  36824. };
  36825. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36826. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  36827. /*** Start of inlined file: juce_RelativeCoordinatePositioner.h ***/
  36828. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  36829. #define __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  36830. /*** Start of inlined file: juce_RelativePoint.h ***/
  36831. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  36832. #define __JUCE_RELATIVEPOINT_JUCEHEADER__
  36833. /**
  36834. An X-Y position stored as a pair of RelativeCoordinate values.
  36835. @see RelativeCoordinate, RelativeRectangle
  36836. */
  36837. class JUCE_API RelativePoint
  36838. {
  36839. public:
  36840. /** Creates a point at the origin. */
  36841. RelativePoint();
  36842. /** Creates an absolute point, relative to the origin. */
  36843. RelativePoint (const Point<float>& absolutePoint);
  36844. /** Creates an absolute point, relative to the origin. */
  36845. RelativePoint (float absoluteX, float absoluteY);
  36846. /** Creates an absolute point from two coordinates. */
  36847. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  36848. /** Creates a point from a stringified representation.
  36849. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  36850. strings is explained in the RelativeCoordinate class.
  36851. @see toString
  36852. */
  36853. RelativePoint (const String& stringVersion);
  36854. bool operator== (const RelativePoint& other) const throw();
  36855. bool operator!= (const RelativePoint& other) const throw();
  36856. /** Calculates the absolute position of this point.
  36857. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  36858. be needed to calculate the result.
  36859. */
  36860. const Point<float> resolve (const Expression::Scope* evaluationContext) const;
  36861. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  36862. Calling this will leave any anchor points unchanged, but will set any absolute
  36863. or relative positions to whatever values are necessary to make the resultant position
  36864. match the position that is provided.
  36865. */
  36866. void moveToAbsolute (const Point<float>& newPos, const Expression::Scope* evaluationContext);
  36867. /** Returns a string which represents this point.
  36868. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  36869. coordinates, see the RelativeCoordinate constructor notes.
  36870. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  36871. */
  36872. const String toString() const;
  36873. /** Returns true if this point depends on any other coordinates for its position. */
  36874. bool isDynamic() const;
  36875. // The actual X and Y coords...
  36876. RelativeCoordinate x, y;
  36877. };
  36878. #endif // __JUCE_RELATIVEPOINT_JUCEHEADER__
  36879. /*** End of inlined file: juce_RelativePoint.h ***/
  36880. /*** Start of inlined file: juce_MarkerList.h ***/
  36881. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  36882. #define __JUCE_MARKERLIST_JUCEHEADER__
  36883. class Component;
  36884. /**
  36885. Holds a set of named marker points along a one-dimensional axis.
  36886. This class is used to store sets of X and Y marker points in components.
  36887. @see Component::getMarkers().
  36888. */
  36889. class JUCE_API MarkerList
  36890. {
  36891. public:
  36892. /** Creates an empty marker list. */
  36893. MarkerList();
  36894. /** Creates a copy of another marker list. */
  36895. MarkerList (const MarkerList& other);
  36896. /** Copies another marker list to this one. */
  36897. MarkerList& operator= (const MarkerList& other);
  36898. /** Destructor. */
  36899. ~MarkerList();
  36900. /** Represents a marker in a MarkerList. */
  36901. class JUCE_API Marker
  36902. {
  36903. public:
  36904. /** Creates a copy of another Marker. */
  36905. Marker (const Marker& other);
  36906. /** Creates a Marker with a given name and position. */
  36907. Marker (const String& name, const RelativeCoordinate& position);
  36908. /** The marker's name. */
  36909. String name;
  36910. /** The marker's position.
  36911. The expression used to define the coordinate may use the names of other
  36912. markers, so that markers can be linked in arbitrary ways, but be careful
  36913. not to create recursive loops of markers whose positions are based on each
  36914. other! It can also refer to "parent.right" and "parent.bottom" so that you
  36915. can set markers which are relative to the size of the component that contains
  36916. them.
  36917. To resolve the coordinate, you can use the MarkerList::getMarkerPosition() method.
  36918. */
  36919. RelativeCoordinate position;
  36920. /** Returns true if both the names and positions of these two markers match. */
  36921. bool operator== (const Marker&) const throw();
  36922. /** Returns true if either the name or position of these two markers differ. */
  36923. bool operator!= (const Marker&) const throw();
  36924. };
  36925. /** Returns the number of markers in the list. */
  36926. int getNumMarkers() const throw();
  36927. /** Returns one of the markers in the list, by its index. */
  36928. const Marker* getMarker (int index) const throw();
  36929. /** Returns a named marker, or 0 if no such name is found.
  36930. Note that name comparisons are case-sensitive.
  36931. */
  36932. const Marker* getMarker (const String& name) const throw();
  36933. /** Evaluates the given marker and returns its absolute position.
  36934. The parent component must be supplied in case the marker's expression refers to
  36935. the size of its parent component.
  36936. */
  36937. double getMarkerPosition (const Marker& marker, Component* parentComponent) const;
  36938. /** Sets the position of a marker.
  36939. If the name already exists, then the existing marker is moved; if it doesn't exist, then a
  36940. new marker is added.
  36941. */
  36942. void setMarker (const String& name, const RelativeCoordinate& position);
  36943. /** Deletes the marker at the given list index. */
  36944. void removeMarker (int index);
  36945. /** Deletes the marker with the given name. */
  36946. void removeMarker (const String& name);
  36947. /** Returns true if all the markers in these two lists match exactly. */
  36948. bool operator== (const MarkerList& other) const throw();
  36949. /** Returns true if not all the markers in these two lists match exactly. */
  36950. bool operator!= (const MarkerList& other) const throw();
  36951. /**
  36952. A class for receiving events when changes are made to a MarkerList.
  36953. You can register a MarkerList::Listener with a MarkerList using the MarkerList::addListener()
  36954. method, and it will be called when markers are moved, added, or deleted.
  36955. @see MarkerList::addListener, MarkerList::removeListener
  36956. */
  36957. class JUCE_API Listener
  36958. {
  36959. public:
  36960. /** Destructor. */
  36961. virtual ~Listener() {}
  36962. /** Called when something in the given marker list changes. */
  36963. virtual void markersChanged (MarkerList* markerList) = 0;
  36964. /** Called when the given marker list is being deleted. */
  36965. virtual void markerListBeingDeleted (MarkerList* markerList);
  36966. };
  36967. /** Registers a listener that will be called when the markers are changed. */
  36968. void addListener (Listener* listener);
  36969. /** Deregisters a previously-registered listener. */
  36970. void removeListener (Listener* listener);
  36971. /** Synchronously calls markersChanged() on all the registered listeners. */
  36972. void markersHaveChanged();
  36973. /** Forms a wrapper around a ValueTree that can be used for storing a MarkerList. */
  36974. class ValueTreeWrapper
  36975. {
  36976. public:
  36977. ValueTreeWrapper (const ValueTree& state);
  36978. ValueTree& getState() throw() { return state; }
  36979. int getNumMarkers() const;
  36980. const ValueTree getMarkerState (int index) const;
  36981. const ValueTree getMarkerState (const String& name) const;
  36982. bool containsMarker (const ValueTree& state) const;
  36983. const MarkerList::Marker getMarker (const ValueTree& state) const;
  36984. void setMarker (const MarkerList::Marker& marker, UndoManager* undoManager);
  36985. void removeMarker (const ValueTree& state, UndoManager* undoManager);
  36986. void applyTo (MarkerList& markerList);
  36987. void readFrom (const MarkerList& markerList, UndoManager* undoManager);
  36988. static const Identifier markerTag, nameProperty, posProperty;
  36989. private:
  36990. ValueTree state;
  36991. };
  36992. private:
  36993. OwnedArray<Marker> markers;
  36994. ListenerList<Listener> listeners;
  36995. JUCE_LEAK_DETECTOR (MarkerList);
  36996. };
  36997. #endif // __JUCE_MARKERLIST_JUCEHEADER__
  36998. /*** End of inlined file: juce_MarkerList.h ***/
  36999. /**
  37000. Base class for Component::Positioners that are based upon relative coordinates.
  37001. */
  37002. class JUCE_API RelativeCoordinatePositionerBase : public Component::Positioner,
  37003. public ComponentListener,
  37004. public MarkerList::Listener
  37005. {
  37006. public:
  37007. RelativeCoordinatePositionerBase (Component& component_);
  37008. ~RelativeCoordinatePositionerBase();
  37009. void componentMovedOrResized (Component&, bool, bool);
  37010. void componentParentHierarchyChanged (Component&);
  37011. void componentChildrenChanged (Component& component);
  37012. void componentBeingDeleted (Component& component);
  37013. void markersChanged (MarkerList*);
  37014. void markerListBeingDeleted (MarkerList* markerList);
  37015. void apply();
  37016. bool addCoordinate (const RelativeCoordinate& coord);
  37017. bool addPoint (const RelativePoint& point);
  37018. /** Used for resolving a RelativeCoordinate expression in the context of a component. */
  37019. class ComponentScope : public Expression::Scope
  37020. {
  37021. public:
  37022. ComponentScope (Component& component_);
  37023. const Expression getSymbolValue (const String& symbol) const;
  37024. void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  37025. const String getScopeUID() const;
  37026. protected:
  37027. Component& component;
  37028. Component* findSiblingComponent (const String& componentID) const;
  37029. const MarkerList::Marker* findMarker (const String& name, MarkerList*& list) const;
  37030. private:
  37031. JUCE_DECLARE_NON_COPYABLE (ComponentScope);
  37032. };
  37033. protected:
  37034. virtual bool registerCoordinates() = 0;
  37035. virtual void applyToComponentBounds() = 0;
  37036. private:
  37037. class DependencyFinderScope;
  37038. friend class DependencyFinderScope;
  37039. Array <Component*> sourceComponents;
  37040. Array <MarkerList*> sourceMarkerLists;
  37041. bool registeredOk;
  37042. void registerComponentListener (Component& comp);
  37043. void registerMarkerListListener (MarkerList* const list);
  37044. void unregisterListeners();
  37045. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeCoordinatePositionerBase);
  37046. };
  37047. #endif // __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  37048. /*** End of inlined file: juce_RelativeCoordinatePositioner.h ***/
  37049. /*** Start of inlined file: juce_ComponentBuilder.h ***/
  37050. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37051. #define __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37052. /**
  37053. Loads and maintains a tree of Components from a ValueTree that represents them.
  37054. To allow the state of a tree of components to be saved as a ValueTree and re-loaded,
  37055. this class lets you register a set of type-handlers for the different components that
  37056. are involved, and then uses these types to re-create a set of components from its
  37057. stored state.
  37058. Essentially, to use this, you need to create a ComponentBuilder with your ValueTree,
  37059. then use registerTypeHandler() to give it a set of type handlers that can cope with
  37060. all the items in your tree. Then you can call getComponent() to build the component.
  37061. Once you've got the component you can either take it and delete the ComponentBuilder
  37062. object, or if you keep the ComponentBuilder around, it'll monitor any changes in the
  37063. ValueTree and automatically update the component to reflect these changes.
  37064. */
  37065. class JUCE_API ComponentBuilder : public ValueTree::Listener
  37066. {
  37067. public:
  37068. /** Creates a ComponentBuilder that will use the given state.
  37069. Once you've created your builder, you should use registerTypeHandler() to register some
  37070. type handlers for it, and then you can call createComponent() or getManagedComponent()
  37071. to get the actual component.
  37072. */
  37073. explicit ComponentBuilder (const ValueTree& state);
  37074. /** Destructor. */
  37075. ~ComponentBuilder();
  37076. /** Returns the ValueTree that this builder is working with. */
  37077. ValueTree& getState() throw() { return state; }
  37078. /** Returns the ValueTree that this builder is working with. */
  37079. const ValueTree& getState() const throw() { return state; }
  37080. /** Returns the builder's component (creating it if necessary).
  37081. The first time that this method is called, the builder will attempt to create a component
  37082. from the ValueTree, so you must have registered some suitable type handlers before calling
  37083. this. If there's a problem and the component can't be created, this method returns 0.
  37084. The component that is returned is owned by this ComponentBuilder, so you can put it inside
  37085. your own parent components, but don't delete it! The ComponentBuilder will delete it automatically
  37086. when the builder is destroyed. If you want to get a component that you can delete yourself,
  37087. call createComponent() instead.
  37088. The ComponentBuilder will update this component if any changes are made to the ValueTree, so if
  37089. there's a chance that the tree might change, be careful not to keep any pointers to sub-components,
  37090. as they may be changed or removed.
  37091. */
  37092. Component* getManagedComponent();
  37093. /** Creates and returns a new instance of the component that the ValueTree represents.
  37094. The caller is responsible for using and deleting the object that is returned. Unlike
  37095. getManagedComponent(), the component that is returned will not be updated by the builder.
  37096. */
  37097. Component* createComponent();
  37098. /**
  37099. The class is a base class for objects that manage the loading of a type of component
  37100. from a ValueTree.
  37101. To store and re-load a tree of components as a ValueTree, each component type must have
  37102. a TypeHandler to represent it.
  37103. @see ComponentBuilder::registerTypeHandler(), Drawable::registerDrawableTypeHandlers()
  37104. */
  37105. class JUCE_API TypeHandler
  37106. {
  37107. public:
  37108. /** Creates a TypeHandler.
  37109. The valueTreeType must be the type name of the ValueTrees that this handler can parse.
  37110. */
  37111. explicit TypeHandler (const Identifier& valueTreeType);
  37112. /** Destructor. */
  37113. virtual ~TypeHandler();
  37114. /** Returns the type of the ValueTrees that this handler can parse. */
  37115. const Identifier& getType() const throw() { return valueTreeType; }
  37116. /** Returns the builder that this type is registered with. */
  37117. ComponentBuilder* getBuilder() const throw();
  37118. /** This method must create a new component from the given state, add it to the specified
  37119. parent component (which may be null), and return it.
  37120. The ValueTree will have been pre-checked to make sure that its type matches the type
  37121. that this handler supports.
  37122. There's no need to set the new Component's ID to match that of the state - the builder
  37123. will take care of that itself.
  37124. */
  37125. virtual Component* addNewComponentFromState (const ValueTree& state, Component* parent) = 0;
  37126. /** This method must update an existing component from a new ValueTree state.
  37127. A component that has been created with addNewComponentFromState() may need to be updated
  37128. if the ValueTree changes, so this method is used to do that. Your implementation must do
  37129. whatever's necessary to update the component from the new state provided.
  37130. The ValueTree will have been pre-checked to make sure that its type matches the type
  37131. that this handler supports, and the component will have been created by this type's
  37132. addNewComponentFromState() method.
  37133. */
  37134. virtual void updateComponentFromState (Component* component, const ValueTree& state) = 0;
  37135. private:
  37136. friend class ComponentBuilder;
  37137. ComponentBuilder* builder;
  37138. const Identifier valueTreeType;
  37139. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypeHandler);
  37140. };
  37141. /** Adds a type handler that the builder can use when trying to load components.
  37142. @see Drawable::registerDrawableTypeHandlers()
  37143. */
  37144. void registerTypeHandler (TypeHandler* type);
  37145. /** Tries to find a registered type handler that can load a component from the given ValueTree. */
  37146. TypeHandler* getHandlerForState (const ValueTree& state) const;
  37147. /** Returns the number of registered type handlers.
  37148. @see getHandler, registerTypeHandler
  37149. */
  37150. int getNumHandlers() const throw();
  37151. /** Returns one of the registered type handlers.
  37152. @see getNumHandlers, registerTypeHandler
  37153. */
  37154. TypeHandler* getHandler (int index) const throw();
  37155. /** This class is used when references to images need to be stored in ValueTrees.
  37156. An instance of an ImageProvider provides a mechanism for converting an Image to/from
  37157. a reference, which may be a file, URL, ID string, or whatever system is appropriate in
  37158. your app.
  37159. When you're loading components from a ValueTree that may need a way of loading images, you
  37160. should call ComponentBuilder::setImageProvider() to supply a suitable provider before
  37161. trying to load the component.
  37162. @see ComponentBuilder::setImageProvider()
  37163. */
  37164. class JUCE_API ImageProvider
  37165. {
  37166. public:
  37167. ImageProvider() {}
  37168. virtual ~ImageProvider() {}
  37169. /** Retrieves the image associated with this identifier, which could be any
  37170. kind of string, number, filename, etc.
  37171. The image that is returned will be owned by the caller, but it may come
  37172. from the ImageCache.
  37173. */
  37174. virtual const Image getImageForIdentifier (const var& imageIdentifier) = 0;
  37175. /** Returns an identifier to be used to refer to a given image.
  37176. This is used when a reference to an image is stored in a ValueTree.
  37177. */
  37178. virtual const var getIdentifierForImage (const Image& image) = 0;
  37179. };
  37180. /** Gives the builder an ImageProvider object that the type handlers can use when
  37181. loading images from stored references.
  37182. The object that is passed in is not owned by the builder, so the caller must delete
  37183. it when it is no longer needed, but not while the builder may still be using it. To
  37184. clear the image provider, just call setImageProvider (0).
  37185. */
  37186. void setImageProvider (ImageProvider* newImageProvider) throw();
  37187. /** Returns the current image provider that this builder is using, or 0 if none has been set. */
  37188. ImageProvider* getImageProvider() const throw();
  37189. /** Updates the children of a parent component by updating them from the children of
  37190. a given ValueTree.
  37191. */
  37192. void updateChildComponents (Component& parent, const ValueTree& children);
  37193. /** An identifier for the property of the ValueTrees that is used to store a unique ID
  37194. for that component.
  37195. */
  37196. static const Identifier idProperty;
  37197. /** @internal */
  37198. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& property);
  37199. /** @internal */
  37200. void valueTreeChildAdded (ValueTree& parentTree, ValueTree& childWhichHasBeenAdded);
  37201. /** @internal */
  37202. void valueTreeChildRemoved (ValueTree& parentTree, ValueTree& childWhichHasBeenRemoved);
  37203. /** @internal */
  37204. void valueTreeChildOrderChanged (ValueTree& parentTree);
  37205. /** @internal */
  37206. void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged);
  37207. private:
  37208. ValueTree state;
  37209. OwnedArray <TypeHandler> types;
  37210. ScopedPointer<Component> component;
  37211. ImageProvider* imageProvider;
  37212. #if JUCE_DEBUG
  37213. WeakReference<Component> componentRef;
  37214. #endif
  37215. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBuilder);
  37216. };
  37217. #endif // __JUCE_COMPONENTBUILDER_JUCEHEADER__
  37218. /*** End of inlined file: juce_ComponentBuilder.h ***/
  37219. class DrawableComposite;
  37220. /**
  37221. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  37222. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37223. */
  37224. class JUCE_API Drawable : public Component
  37225. {
  37226. protected:
  37227. /** The base class can't be instantiated directly.
  37228. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  37229. */
  37230. Drawable();
  37231. public:
  37232. /** Destructor. */
  37233. virtual ~Drawable();
  37234. /** Creates a deep copy of this Drawable object.
  37235. Use this to create a new copy of this and any sub-objects in the tree.
  37236. */
  37237. virtual Drawable* createCopy() const = 0;
  37238. /** Renders this Drawable object.
  37239. Note that the preferred way to render a drawable in future is by using it
  37240. as a component and adding it to a parent, so you might want to consider that
  37241. before using this method.
  37242. @see drawWithin
  37243. */
  37244. void draw (Graphics& g, float opacity,
  37245. const AffineTransform& transform = AffineTransform::identity) const;
  37246. /** Renders the Drawable at a given offset within the Graphics context.
  37247. The co-ordinates passed-in are used to translate the object relative to its own
  37248. origin before drawing it - this is basically a quick way of saying:
  37249. @code
  37250. draw (g, AffineTransform::translation (x, y)).
  37251. @endcode
  37252. Note that the preferred way to render a drawable in future is by using it
  37253. as a component and adding it to a parent, so you might want to consider that
  37254. before using this method.
  37255. */
  37256. void drawAt (Graphics& g, float x, float y, float opacity) const;
  37257. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  37258. changing its aspect-ratio.
  37259. The object can placed arbitrarily within the rectangle based on a Justification type,
  37260. and can either be made as big as possible, or just reduced to fit.
  37261. Note that the preferred way to render a drawable in future is by using it
  37262. as a component and adding it to a parent, so you might want to consider that
  37263. before using this method.
  37264. @param g the graphics context to render onto
  37265. @param destArea the target rectangle to fit the drawable into
  37266. @param placement defines the alignment and rescaling to use to fit
  37267. this object within the target rectangle.
  37268. @param opacity the opacity to use, in the range 0 to 1.0
  37269. */
  37270. void drawWithin (Graphics& g,
  37271. const Rectangle<float>& destArea,
  37272. const RectanglePlacement& placement,
  37273. float opacity) const;
  37274. /** Resets any transformations on this drawable, and positions its origin within
  37275. its parent component.
  37276. */
  37277. void setOriginWithOriginalSize (const Point<float>& originWithinParent);
  37278. /** Sets a transform for this drawable that will position it within the specified
  37279. area of its parent component.
  37280. */
  37281. void setTransformToFit (const Rectangle<float>& areaInParent, const RectanglePlacement& placement);
  37282. /** Returns the DrawableComposite that contains this object, if there is one. */
  37283. DrawableComposite* getParent() const;
  37284. /** Tries to turn some kind of image file into a drawable.
  37285. The data could be an image that the ImageFileFormat class understands, or it
  37286. could be SVG.
  37287. */
  37288. static Drawable* createFromImageData (const void* data, size_t numBytes);
  37289. /** Tries to turn a stream containing some kind of image data into a drawable.
  37290. The data could be an image that the ImageFileFormat class understands, or it
  37291. could be SVG.
  37292. */
  37293. static Drawable* createFromImageDataStream (InputStream& dataSource);
  37294. /** Tries to turn a file containing some kind of image data into a drawable.
  37295. The data could be an image that the ImageFileFormat class understands, or it
  37296. could be SVG.
  37297. */
  37298. static Drawable* createFromImageFile (const File& file);
  37299. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  37300. into a Drawable tree.
  37301. The object returned must be deleted by the caller. If something goes wrong
  37302. while parsing, it may return 0.
  37303. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  37304. implementation, but it can return the basic vector objects.
  37305. */
  37306. static Drawable* createFromSVG (const XmlElement& svgDocument);
  37307. /** Tries to create a Drawable from a previously-saved ValueTree.
  37308. The ValueTree must have been created by the createValueTree() method.
  37309. If there are any images used within the drawable, you'll need to provide a valid
  37310. ImageProvider object that can be used to retrieve these images from whatever type
  37311. of identifier is used to represent them.
  37312. Internally, this uses a ComponentBuilder, and registerDrawableTypeHandlers().
  37313. */
  37314. static Drawable* createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider);
  37315. /** Creates a ValueTree to represent this Drawable.
  37316. The ValueTree that is returned can be turned back into a Drawable with createFromValueTree().
  37317. If there are any images used in this drawable, you'll need to provide a valid ImageProvider
  37318. object that can be used to create storable representations of them.
  37319. */
  37320. virtual const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const = 0;
  37321. /** Returns the area that this drawble covers.
  37322. The result is expressed in this drawable's own coordinate space, and does not take
  37323. into account any transforms that may be applied to the component.
  37324. */
  37325. virtual const Rectangle<float> getDrawableBounds() const = 0;
  37326. /** Internal class used to manage ValueTrees that represent Drawables. */
  37327. class ValueTreeWrapperBase
  37328. {
  37329. public:
  37330. ValueTreeWrapperBase (const ValueTree& state);
  37331. ValueTree& getState() throw() { return state; }
  37332. const String getID() const;
  37333. void setID (const String& newID);
  37334. ValueTree state;
  37335. };
  37336. /** Registers a set of ComponentBuilder::TypeHandler objects that can be used to
  37337. load all the different Drawable types from a saved state.
  37338. @see ComponentBuilder::registerTypeHandler()
  37339. */
  37340. static void registerDrawableTypeHandlers (ComponentBuilder& componentBuilder);
  37341. protected:
  37342. friend class DrawableComposite;
  37343. friend class DrawableShape;
  37344. /** @internal */
  37345. void transformContextToCorrectOrigin (Graphics& g);
  37346. /** @internal */
  37347. void parentHierarchyChanged();
  37348. /** @internal */
  37349. void setBoundsToEnclose (const Rectangle<float>& area);
  37350. Point<int> originRelativeToComponent;
  37351. #ifndef DOXYGEN
  37352. /** Internal utility class used by Drawables. */
  37353. template <class DrawableType>
  37354. class Positioner : public RelativeCoordinatePositionerBase
  37355. {
  37356. public:
  37357. Positioner (DrawableType& component_)
  37358. : RelativeCoordinatePositionerBase (component_),
  37359. owner (component_)
  37360. {}
  37361. bool registerCoordinates() { return owner.registerCoordinates (*this); }
  37362. void applyToComponentBounds()
  37363. {
  37364. ComponentScope scope (getComponent());
  37365. owner.recalculateCoordinates (&scope);
  37366. }
  37367. void applyNewBounds (const Rectangle<int>&)
  37368. {
  37369. jassertfalse; // drawables can't be resized directly!
  37370. }
  37371. private:
  37372. DrawableType& owner;
  37373. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  37374. };
  37375. #endif
  37376. private:
  37377. void nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform);
  37378. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Drawable);
  37379. };
  37380. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  37381. /*** End of inlined file: juce_Drawable.h ***/
  37382. /**
  37383. A button that displays a Drawable.
  37384. Up to three Drawable objects can be given to this button, to represent the
  37385. 'normal', 'over' and 'down' states.
  37386. @see Button
  37387. */
  37388. class JUCE_API DrawableButton : public Button
  37389. {
  37390. public:
  37391. enum ButtonStyle
  37392. {
  37393. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  37394. ImageRaw, /**< The button will just display the images in their normal size and position.
  37395. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  37396. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  37397. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  37398. };
  37399. /** Creates a DrawableButton.
  37400. After creating one of these, use setImages() to specify the drawables to use.
  37401. @param buttonName the name to give the component
  37402. @param buttonStyle the layout to use
  37403. @see ButtonStyle, setButtonStyle, setImages
  37404. */
  37405. DrawableButton (const String& buttonName,
  37406. ButtonStyle buttonStyle);
  37407. /** Destructor. */
  37408. ~DrawableButton();
  37409. /** Sets up the images to draw for the various button states.
  37410. The button will keep its own internal copies of these drawables.
  37411. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  37412. will be made of the object passed-in if it is non-zero.
  37413. @param overImage the thing to draw for the button's 'over' state - if this is
  37414. zero, the button's normal image will be used when the mouse is
  37415. over it. An internal copy will be made of the object passed-in
  37416. if it is non-zero.
  37417. @param downImage the thing to draw for the button's 'down' state - if this is
  37418. zero, the 'over' image will be used instead (or the normal image
  37419. as a last resort). An internal copy will be made of the object
  37420. passed-in if it is non-zero.
  37421. @param disabledImage an image to draw when the button is disabled. If this is zero,
  37422. the normal image will be drawn with a reduced opacity instead.
  37423. An internal copy will be made of the object passed-in if it is
  37424. non-zero.
  37425. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  37426. state is 'on'. If this is 0, the normal image is used instead
  37427. @param overImageOn same as the overImage, but this is used when the button's toggle
  37428. state is 'on'. If this is 0, the normalImageOn is drawn instead
  37429. @param downImageOn same as the downImage, but this is used when the button's toggle
  37430. state is 'on'. If this is 0, the overImageOn is drawn instead
  37431. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  37432. state is 'on'. If this is 0, the normal image will be drawn instead
  37433. with a reduced opacity
  37434. */
  37435. void setImages (const Drawable* normalImage,
  37436. const Drawable* overImage = 0,
  37437. const Drawable* downImage = 0,
  37438. const Drawable* disabledImage = 0,
  37439. const Drawable* normalImageOn = 0,
  37440. const Drawable* overImageOn = 0,
  37441. const Drawable* downImageOn = 0,
  37442. const Drawable* disabledImageOn = 0);
  37443. /** Changes the button's style.
  37444. @see ButtonStyle
  37445. */
  37446. void setButtonStyle (ButtonStyle newStyle);
  37447. /** Changes the button's background colours.
  37448. The toggledOffColour is the colour to use when the button's toggle state
  37449. is off, and toggledOnColour when it's on.
  37450. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  37451. used to fill the background of the component.
  37452. For an ImageOnButtonBackground style, the colour is used to draw the
  37453. button's lozenge shape and exactly how the colour's used will depend
  37454. on the LookAndFeel.
  37455. */
  37456. void setBackgroundColours (const Colour& toggledOffColour,
  37457. const Colour& toggledOnColour);
  37458. /** Returns the current background colour being used.
  37459. @see setBackgroundColour
  37460. */
  37461. const Colour& getBackgroundColour() const throw();
  37462. /** Gives the button an optional amount of space around the edge of the drawable.
  37463. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  37464. ones on a button background. If the button is too small for the given gap, a
  37465. smaller gap will be used.
  37466. By default there's a gap of about 3 pixels.
  37467. */
  37468. void setEdgeIndent (int numPixelsIndent);
  37469. /** Returns the image that the button is currently displaying. */
  37470. Drawable* getCurrentImage() const throw();
  37471. Drawable* getNormalImage() const throw();
  37472. Drawable* getOverImage() const throw();
  37473. Drawable* getDownImage() const throw();
  37474. /** A set of colour IDs to use to change the colour of various aspects of the link.
  37475. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37476. methods.
  37477. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37478. */
  37479. enum ColourIds
  37480. {
  37481. textColourId = 0x1004010, /**< The colour to use for the URL text. */
  37482. };
  37483. protected:
  37484. /** @internal */
  37485. void paintButton (Graphics& g,
  37486. bool isMouseOverButton,
  37487. bool isButtonDown);
  37488. /** @internal */
  37489. void buttonStateChanged();
  37490. /** @internal */
  37491. void resized();
  37492. private:
  37493. ButtonStyle style;
  37494. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  37495. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  37496. Drawable* currentImage;
  37497. Colour backgroundOff, backgroundOn;
  37498. int edgeIndent;
  37499. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DrawableButton);
  37500. };
  37501. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  37502. /*** End of inlined file: juce_DrawableButton.h ***/
  37503. #endif
  37504. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37505. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  37506. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37507. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37508. /**
  37509. A button showing an underlined weblink, that will launch the link
  37510. when it's clicked.
  37511. @see Button
  37512. */
  37513. class JUCE_API HyperlinkButton : public Button
  37514. {
  37515. public:
  37516. /** Creates a HyperlinkButton.
  37517. @param linkText the text that will be displayed in the button - this is
  37518. also set as the Component's name, but the text can be
  37519. changed later with the Button::getButtonText() method
  37520. @param linkURL the URL to launch when the user clicks the button
  37521. */
  37522. HyperlinkButton (const String& linkText,
  37523. const URL& linkURL);
  37524. /** Destructor. */
  37525. ~HyperlinkButton();
  37526. /** Changes the font to use for the text.
  37527. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  37528. to match the size of the component.
  37529. */
  37530. void setFont (const Font& newFont,
  37531. bool resizeToMatchComponentHeight,
  37532. const Justification& justificationType = Justification::horizontallyCentred);
  37533. /** A set of colour IDs to use to change the colour of various aspects of the link.
  37534. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37535. methods.
  37536. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37537. */
  37538. enum ColourIds
  37539. {
  37540. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  37541. };
  37542. /** Changes the URL that the button will trigger. */
  37543. void setURL (const URL& newURL) throw();
  37544. /** Returns the URL that the button will trigger. */
  37545. const URL& getURL() const throw() { return url; }
  37546. /** Resizes the button horizontally to fit snugly around the text.
  37547. This won't affect the button's height.
  37548. */
  37549. void changeWidthToFitText();
  37550. protected:
  37551. /** @internal */
  37552. void clicked();
  37553. /** @internal */
  37554. void colourChanged();
  37555. /** @internal */
  37556. void paintButton (Graphics& g,
  37557. bool isMouseOverButton,
  37558. bool isButtonDown);
  37559. private:
  37560. URL url;
  37561. Font font;
  37562. bool resizeFont;
  37563. Justification justification;
  37564. const Font getFontToUse() const;
  37565. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HyperlinkButton);
  37566. };
  37567. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37568. /*** End of inlined file: juce_HyperlinkButton.h ***/
  37569. #endif
  37570. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  37571. /*** Start of inlined file: juce_ImageButton.h ***/
  37572. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  37573. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  37574. /**
  37575. As the title suggests, this is a button containing an image.
  37576. The colour and transparency of the image can be set to vary when the
  37577. button state changes.
  37578. @see Button, ShapeButton, TextButton
  37579. */
  37580. class JUCE_API ImageButton : public Button
  37581. {
  37582. public:
  37583. /** Creates an ImageButton.
  37584. Use setImage() to specify the image to use. The colours and opacities that
  37585. are specified here can be changed later using setDrawingOptions().
  37586. @param name the name to give the component
  37587. */
  37588. explicit ImageButton (const String& name);
  37589. /** Destructor. */
  37590. ~ImageButton();
  37591. /** Sets up the images to draw in various states.
  37592. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  37593. resized to the same dimensions as the normal image
  37594. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  37595. button when the button's size changes
  37596. @param preserveImageProportions if true then any rescaling of the image to fit
  37597. the button will keep the image's x and y proportions
  37598. correct - i.e. it won't distort its shape, although
  37599. this might create gaps around the edges
  37600. @param normalImage the image to use when the button is in its normal state.
  37601. button no longer needs it.
  37602. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  37603. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  37604. normal image - if this colour is transparent, no overlay
  37605. will be drawn. The overlay will be drawn over the top of the
  37606. image, so you can basically add a solid or semi-transparent
  37607. colour to the image to brighten or darken it
  37608. @param overImage the image to use when the mouse is over the button. If
  37609. you want to use the same image as was set in the normalImage
  37610. parameter, this value can be a null image.
  37611. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  37612. is over the button
  37613. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  37614. image when the mouse is over - if this colour is transparent,
  37615. no overlay will be drawn
  37616. @param downImage an image to use when the button is pressed down. If set
  37617. to a null image, the 'over' image will be drawn instead (or the
  37618. normal image if there isn't an 'over' image either).
  37619. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  37620. is pressed
  37621. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  37622. image when the button is pressed down - if this colour is
  37623. transparent, no overlay will be drawn
  37624. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  37625. whenever it's inside the button's bounding rectangle. If
  37626. set to values higher than 0, the mouse will only be
  37627. considered to be over the image when the value of the
  37628. image's alpha channel at that position is greater than
  37629. this level.
  37630. */
  37631. void setImages (bool resizeButtonNowToFitThisImage,
  37632. bool rescaleImagesWhenButtonSizeChanges,
  37633. bool preserveImageProportions,
  37634. const Image& normalImage,
  37635. float imageOpacityWhenNormal,
  37636. const Colour& overlayColourWhenNormal,
  37637. const Image& overImage,
  37638. float imageOpacityWhenOver,
  37639. const Colour& overlayColourWhenOver,
  37640. const Image& downImage,
  37641. float imageOpacityWhenDown,
  37642. const Colour& overlayColourWhenDown,
  37643. float hitTestAlphaThreshold = 0.0f);
  37644. /** Returns the currently set 'normal' image. */
  37645. const Image getNormalImage() const;
  37646. /** Returns the image that's drawn when the mouse is over the button.
  37647. If a valid 'over' image has been set, this will return it; otherwise it'll
  37648. just return the normal image.
  37649. */
  37650. const Image getOverImage() const;
  37651. /** Returns the image that's drawn when the button is held down.
  37652. If a valid 'down' image has been set, this will return it; otherwise it'll
  37653. return the 'over' image or normal image, depending on what's available.
  37654. */
  37655. const Image getDownImage() const;
  37656. protected:
  37657. /** @internal */
  37658. bool hitTest (int x, int y);
  37659. /** @internal */
  37660. void paintButton (Graphics& g,
  37661. bool isMouseOverButton,
  37662. bool isButtonDown);
  37663. private:
  37664. bool scaleImageToFit, preserveProportions;
  37665. unsigned char alphaThreshold;
  37666. int imageX, imageY, imageW, imageH;
  37667. Image normalImage, overImage, downImage;
  37668. float normalOpacity, overOpacity, downOpacity;
  37669. Colour normalOverlay, overOverlay, downOverlay;
  37670. const Image getCurrentImage() const;
  37671. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageButton);
  37672. };
  37673. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  37674. /*** End of inlined file: juce_ImageButton.h ***/
  37675. #endif
  37676. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  37677. /*** Start of inlined file: juce_ShapeButton.h ***/
  37678. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  37679. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  37680. /**
  37681. A button that contains a filled shape.
  37682. @see Button, ImageButton, TextButton, ArrowButton
  37683. */
  37684. class JUCE_API ShapeButton : public Button
  37685. {
  37686. public:
  37687. /** Creates a ShapeButton.
  37688. @param name a name to give the component - see Component::setName()
  37689. @param normalColour the colour to fill the shape with when the mouse isn't over
  37690. @param overColour the colour to use when the mouse is over the shape
  37691. @param downColour the colour to use when the button is in the pressed-down state
  37692. */
  37693. ShapeButton (const String& name,
  37694. const Colour& normalColour,
  37695. const Colour& overColour,
  37696. const Colour& downColour);
  37697. /** Destructor. */
  37698. ~ShapeButton();
  37699. /** Sets the shape to use.
  37700. @param newShape the shape to use
  37701. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  37702. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  37703. the button is resized
  37704. @param hasDropShadow if true, the button will be given a drop-shadow effect
  37705. */
  37706. void setShape (const Path& newShape,
  37707. bool resizeNowToFitThisShape,
  37708. bool maintainShapeProportions,
  37709. bool hasDropShadow);
  37710. /** Set the colours to use for drawing the shape.
  37711. @param normalColour the colour to fill the shape with when the mouse isn't over
  37712. @param overColour the colour to use when the mouse is over the shape
  37713. @param downColour the colour to use when the button is in the pressed-down state
  37714. */
  37715. void setColours (const Colour& normalColour,
  37716. const Colour& overColour,
  37717. const Colour& downColour);
  37718. /** Sets up an outline to draw around the shape.
  37719. @param outlineColour the colour to use
  37720. @param outlineStrokeWidth the thickness of line to draw
  37721. */
  37722. void setOutline (const Colour& outlineColour,
  37723. float outlineStrokeWidth);
  37724. protected:
  37725. /** @internal */
  37726. void paintButton (Graphics& g,
  37727. bool isMouseOverButton,
  37728. bool isButtonDown);
  37729. private:
  37730. Colour normalColour, overColour, downColour, outlineColour;
  37731. DropShadowEffect shadow;
  37732. Path shape;
  37733. bool maintainShapeProportions;
  37734. float outlineWidth;
  37735. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ShapeButton);
  37736. };
  37737. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  37738. /*** End of inlined file: juce_ShapeButton.h ***/
  37739. #endif
  37740. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  37741. #endif
  37742. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37743. /*** Start of inlined file: juce_ToggleButton.h ***/
  37744. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37745. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37746. /**
  37747. A button that can be toggled on/off.
  37748. All buttons can be toggle buttons, but this lets you create one of the
  37749. standard ones which has a tick-box and a text label next to it.
  37750. @see Button, DrawableButton, TextButton
  37751. */
  37752. class JUCE_API ToggleButton : public Button
  37753. {
  37754. public:
  37755. /** Creates a ToggleButton.
  37756. @param buttonText the text to put in the button (the component's name is also
  37757. initially set to this string, but these can be changed later
  37758. using the setName() and setButtonText() methods)
  37759. */
  37760. explicit ToggleButton (const String& buttonText = String::empty);
  37761. /** Destructor. */
  37762. ~ToggleButton();
  37763. /** Resizes the button to fit neatly around its current text.
  37764. The button's height won't be affected, only its width.
  37765. */
  37766. void changeWidthToFitText();
  37767. /** A set of colour IDs to use to change the colour of various aspects of the button.
  37768. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37769. methods.
  37770. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37771. */
  37772. enum ColourIds
  37773. {
  37774. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  37775. };
  37776. protected:
  37777. /** @internal */
  37778. void paintButton (Graphics& g,
  37779. bool isMouseOverButton,
  37780. bool isButtonDown);
  37781. /** @internal */
  37782. void colourChanged();
  37783. private:
  37784. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToggleButton);
  37785. };
  37786. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37787. /*** End of inlined file: juce_ToggleButton.h ***/
  37788. #endif
  37789. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37790. /*** Start of inlined file: juce_ToolbarButton.h ***/
  37791. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37792. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37793. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  37794. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  37795. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  37796. /*** Start of inlined file: juce_Toolbar.h ***/
  37797. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  37798. #define __JUCE_TOOLBAR_JUCEHEADER__
  37799. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  37800. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  37801. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  37802. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  37803. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  37804. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  37805. /**
  37806. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  37807. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  37808. derive your component from this class, and make sure that it is somewhere inside a
  37809. DragAndDropContainer component.
  37810. Note: If all that you need to do is to respond to files being drag-and-dropped from
  37811. the operating system onto your component, you don't need any of these classes: instead
  37812. see the FileDragAndDropTarget class.
  37813. @see DragAndDropContainer, FileDragAndDropTarget
  37814. */
  37815. class JUCE_API DragAndDropTarget
  37816. {
  37817. public:
  37818. /** Destructor. */
  37819. virtual ~DragAndDropTarget() {}
  37820. /** Callback to check whether this target is interested in the type of object being
  37821. dragged.
  37822. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  37823. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  37824. @returns true if this component wants to receive the other callbacks regarging this
  37825. type of object; if it returns false, no other callbacks will be made.
  37826. */
  37827. virtual bool isInterestedInDragSource (const String& sourceDescription,
  37828. Component* sourceComponent) = 0;
  37829. /** Callback to indicate that something is being dragged over this component.
  37830. This gets called when the user moves the mouse into this component while dragging
  37831. something.
  37832. Use this callback as a trigger to make your component repaint itself to give the
  37833. user feedback about whether the item can be dropped here or not.
  37834. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  37835. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  37836. @param x the mouse x position, relative to this component
  37837. @param y the mouse y position, relative to this component
  37838. @see itemDragExit
  37839. */
  37840. virtual void itemDragEnter (const String& sourceDescription,
  37841. Component* sourceComponent,
  37842. int x, int y);
  37843. /** Callback to indicate that the user is dragging something over this component.
  37844. This gets called when the user moves the mouse over this component while dragging
  37845. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  37846. this lets you know what happens in-between.
  37847. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  37848. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  37849. @param x the mouse x position, relative to this component
  37850. @param y the mouse y position, relative to this component
  37851. */
  37852. virtual void itemDragMove (const String& sourceDescription,
  37853. Component* sourceComponent,
  37854. int x, int y);
  37855. /** Callback to indicate that something has been dragged off the edge of this component.
  37856. This gets called when the user moves the mouse out of this component while dragging
  37857. something.
  37858. If you've used itemDragEnter() to repaint your component and give feedback, use this
  37859. as a signal to repaint it in its normal state.
  37860. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  37861. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  37862. @see itemDragEnter
  37863. */
  37864. virtual void itemDragExit (const String& sourceDescription,
  37865. Component* sourceComponent);
  37866. /** Callback to indicate that the user has dropped something onto this component.
  37867. When the user drops an item this get called, and you can use the description to
  37868. work out whether your object wants to deal with it or not.
  37869. Note that after this is called, the itemDragExit method may not be called, so you should
  37870. clean up in here if there's anything you need to do when the drag finishes.
  37871. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  37872. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  37873. @param x the mouse x position, relative to this component
  37874. @param y the mouse y position, relative to this component
  37875. */
  37876. virtual void itemDropped (const String& sourceDescription,
  37877. Component* sourceComponent,
  37878. int x, int y) = 0;
  37879. /** Overriding this allows the target to tell the drag container whether to
  37880. draw the drag image while the cursor is over it.
  37881. By default it returns true, but if you return false, then the normal drag
  37882. image will not be shown when the cursor is over this target.
  37883. */
  37884. virtual bool shouldDrawDragImageWhenOver();
  37885. };
  37886. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  37887. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  37888. /**
  37889. Enables drag-and-drop behaviour for a component and all its sub-components.
  37890. For a component to be able to make or receive drag-and-drop events, one of its parent
  37891. components must derive from this class. It's probably best for the top-level
  37892. component to implement it.
  37893. Then to start a drag operation, any sub-component can just call the startDragging()
  37894. method, and this object will take over, tracking the mouse and sending appropriate
  37895. callbacks to any child components derived from DragAndDropTarget which the mouse
  37896. moves over.
  37897. Note: If all that you need to do is to respond to files being drag-and-dropped from
  37898. the operating system onto your component, you don't need any of these classes: you can do this
  37899. simply by overriding Component::filesDropped().
  37900. @see DragAndDropTarget
  37901. */
  37902. class JUCE_API DragAndDropContainer
  37903. {
  37904. public:
  37905. /** Creates a DragAndDropContainer.
  37906. The object that derives from this class must also be a Component.
  37907. */
  37908. DragAndDropContainer();
  37909. /** Destructor. */
  37910. virtual ~DragAndDropContainer();
  37911. /** Begins a drag-and-drop operation.
  37912. This starts a drag-and-drop operation - call it when the user drags the
  37913. mouse in your drag-source component, and this object will track mouse
  37914. movements until the user lets go of the mouse button, and will send
  37915. appropriate messages to DragAndDropTarget objects that the mouse moves
  37916. over.
  37917. findParentDragContainerFor() is a handy method to call to find the
  37918. drag container to use for a component.
  37919. @param sourceDescription a string to use as the description of the thing being
  37920. dragged - this will be passed to the objects that might be
  37921. dropped-onto so they can decide if they want to handle it or
  37922. not
  37923. @param sourceComponent the component that is being dragged
  37924. @param dragImage the image to drag around underneath the mouse. If this is a null image,
  37925. a snapshot of the sourceComponent will be used instead.
  37926. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  37927. window, and can be dragged to DragAndDropTargets that are the
  37928. children of components other than this one.
  37929. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  37930. at which the image should be drawn from the mouse. If it isn't
  37931. specified, then the image will be centred around the mouse. If
  37932. an image hasn't been passed-in, this will be ignored.
  37933. */
  37934. void startDragging (const String& sourceDescription,
  37935. Component* sourceComponent,
  37936. const Image& dragImage = Image::null,
  37937. bool allowDraggingToOtherJuceWindows = false,
  37938. const Point<int>* imageOffsetFromMouse = 0);
  37939. /** Returns true if something is currently being dragged. */
  37940. bool isDragAndDropActive() const;
  37941. /** Returns the description of the thing that's currently being dragged.
  37942. If nothing's being dragged, this will return an empty string, otherwise it's the
  37943. string that was passed into startDragging().
  37944. @see startDragging
  37945. */
  37946. const String getCurrentDragDescription() const;
  37947. /** Utility to find the DragAndDropContainer for a given Component.
  37948. This will search up this component's parent hierarchy looking for the first
  37949. parent component which is a DragAndDropContainer.
  37950. It's useful when a component wants to call startDragging but doesn't know
  37951. the DragAndDropContainer it should to use.
  37952. Obviously this may return 0 if it doesn't find a suitable component.
  37953. */
  37954. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  37955. /** This performs a synchronous drag-and-drop of a set of files to some external
  37956. application.
  37957. You can call this function in response to a mouseDrag callback, and it will
  37958. block, running its own internal message loop and tracking the mouse, while it
  37959. uses a native operating system drag-and-drop operation to move or copy some
  37960. files to another application.
  37961. @param files a list of filenames to drag
  37962. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  37963. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  37964. @returns true if the files were successfully dropped somewhere, or false if it
  37965. was interrupted
  37966. @see performExternalDragDropOfText
  37967. */
  37968. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  37969. /** This performs a synchronous drag-and-drop of a block of text to some external
  37970. application.
  37971. You can call this function in response to a mouseDrag callback, and it will
  37972. block, running its own internal message loop and tracking the mouse, while it
  37973. uses a native operating system drag-and-drop operation to move or copy some
  37974. text to another application.
  37975. @param text the text to copy
  37976. @returns true if the text was successfully dropped somewhere, or false if it
  37977. was interrupted
  37978. @see performExternalDragDropOfFiles
  37979. */
  37980. static bool performExternalDragDropOfText (const String& text);
  37981. protected:
  37982. /** Override this if you want to be able to perform an external drag a set of files
  37983. when the user drags outside of this container component.
  37984. This method will be called when a drag operation moves outside the Juce-based window,
  37985. and if you want it to then perform a file drag-and-drop, add the filenames you want
  37986. to the array passed in, and return true.
  37987. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  37988. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  37989. @param files on return, the filenames you want to drag
  37990. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  37991. it must make a copy of them (see the performExternalDragDropOfFiles()
  37992. method)
  37993. @see performExternalDragDropOfFiles
  37994. */
  37995. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  37996. Component* dragSourceComponent,
  37997. StringArray& files,
  37998. bool& canMoveFiles);
  37999. private:
  38000. friend class DragImageComponent;
  38001. ScopedPointer <Component> dragImageComponent;
  38002. String currentDragDesc;
  38003. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DragAndDropContainer);
  38004. };
  38005. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38006. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  38007. class ToolbarItemComponent;
  38008. class ToolbarItemFactory;
  38009. /**
  38010. A toolbar component.
  38011. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  38012. and looks after their order and layout.
  38013. Items (icon buttons or other custom components) are added to a toolbar using a
  38014. ToolbarItemFactory - each type of item is given a unique ID number, and a
  38015. toolbar might contain more than one instance of a particular item type.
  38016. Toolbars can be interactively customised, allowing the user to drag the items
  38017. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  38018. component as a source of new items.
  38019. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  38020. */
  38021. class JUCE_API Toolbar : public Component,
  38022. public DragAndDropContainer,
  38023. public DragAndDropTarget,
  38024. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  38025. {
  38026. public:
  38027. /** Creates an empty toolbar component.
  38028. To add some icons or other components to your toolbar, you'll need to
  38029. create a ToolbarItemFactory class that can create a suitable set of
  38030. ToolbarItemComponents.
  38031. @see ToolbarItemFactory, ToolbarItemComponents
  38032. */
  38033. Toolbar();
  38034. /** Destructor.
  38035. Any items on the bar will be deleted when the toolbar is deleted.
  38036. */
  38037. ~Toolbar();
  38038. /** Changes the bar's orientation.
  38039. @see isVertical
  38040. */
  38041. void setVertical (bool shouldBeVertical);
  38042. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  38043. You can change the bar's orientation with setVertical().
  38044. */
  38045. bool isVertical() const throw() { return vertical; }
  38046. /** Returns the depth of the bar.
  38047. If the bar is horizontal, this will return its height; if it's vertical, it
  38048. will return its width.
  38049. @see getLength
  38050. */
  38051. int getThickness() const throw();
  38052. /** Returns the length of the bar.
  38053. If the bar is horizontal, this will return its width; if it's vertical, it
  38054. will return its height.
  38055. @see getThickness
  38056. */
  38057. int getLength() const throw();
  38058. /** Deletes all items from the bar.
  38059. */
  38060. void clear();
  38061. /** Adds an item to the toolbar.
  38062. The factory's ToolbarItemFactory::createItem() will be called by this method
  38063. to create the component that will actually be added to the bar.
  38064. The new item will be inserted at the specified index (if the index is -1, it
  38065. will be added to the right-hand or bottom end of the bar).
  38066. Once added, the component will be automatically deleted by this object when it
  38067. is no longer needed.
  38068. @see ToolbarItemFactory
  38069. */
  38070. void addItem (ToolbarItemFactory& factory,
  38071. int itemId,
  38072. int insertIndex = -1);
  38073. /** Deletes one of the items from the bar.
  38074. */
  38075. void removeToolbarItem (int itemIndex);
  38076. /** Returns the number of items currently on the toolbar.
  38077. @see getItemId, getItemComponent
  38078. */
  38079. int getNumItems() const throw();
  38080. /** Returns the ID of the item with the given index.
  38081. If the index is less than zero or greater than the number of items,
  38082. this will return 0.
  38083. @see getNumItems
  38084. */
  38085. int getItemId (int itemIndex) const throw();
  38086. /** Returns the component being used for the item with the given index.
  38087. If the index is less than zero or greater than the number of items,
  38088. this will return 0.
  38089. @see getNumItems
  38090. */
  38091. ToolbarItemComponent* getItemComponent (int itemIndex) const throw();
  38092. /** Clears this toolbar and adds to it the default set of items that the specified
  38093. factory creates.
  38094. @see ToolbarItemFactory::getDefaultItemSet
  38095. */
  38096. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  38097. /** Options for the way items should be displayed.
  38098. @see setStyle, getStyle
  38099. */
  38100. enum ToolbarItemStyle
  38101. {
  38102. iconsOnly, /**< Means that the toolbar should just contain icons. */
  38103. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  38104. textOnly /**< Means that the toolbar only display text labels for each item. */
  38105. };
  38106. /** Returns the toolbar's current style.
  38107. @see ToolbarItemStyle, setStyle
  38108. */
  38109. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  38110. /** Changes the toolbar's current style.
  38111. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  38112. */
  38113. void setStyle (const ToolbarItemStyle& newStyle);
  38114. /** Flags used by the showCustomisationDialog() method. */
  38115. enum CustomisationFlags
  38116. {
  38117. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  38118. show the "icons only" option on its choice of toolbar styles. */
  38119. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  38120. show the "icons with text" option on its choice of toolbar styles. */
  38121. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  38122. show the "text only" option on its choice of toolbar styles. */
  38123. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  38124. show a button to reset the toolbar to its default set of items. */
  38125. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  38126. };
  38127. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  38128. The dialog contains a ToolbarItemPalette and various controls for editing other
  38129. aspects of the toolbar. This method will block and run the dialog box modally,
  38130. returning when the user closes it.
  38131. The factory is used to determine the set of items that will be shown on the
  38132. palette.
  38133. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  38134. enum.
  38135. @see ToolbarItemPalette
  38136. */
  38137. void showCustomisationDialog (ToolbarItemFactory& factory,
  38138. int optionFlags = allCustomisationOptionsEnabled);
  38139. /** Turns on or off the toolbar's editing mode, in which its items can be
  38140. rearranged by the user.
  38141. (In most cases it's easier just to use showCustomisationDialog() instead of
  38142. trying to enable editing directly).
  38143. @see ToolbarItemPalette
  38144. */
  38145. void setEditingActive (bool editingEnabled);
  38146. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  38147. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38148. methods.
  38149. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38150. */
  38151. enum ColourIds
  38152. {
  38153. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  38154. more control over this, override LookAndFeel::paintToolbarBackground(). */
  38155. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  38156. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  38157. over them. */
  38158. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  38159. held down on them. */
  38160. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  38161. when the style is set to iconsWithText or textOnly. */
  38162. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  38163. the customisation dialog is active and the mouse moves over them. */
  38164. };
  38165. /** Returns a string that represents the toolbar's current set of items.
  38166. This lets you later restore the same item layout using restoreFromString().
  38167. @see restoreFromString
  38168. */
  38169. const String toString() const;
  38170. /** Restores a set of items that was previously stored in a string by the toString()
  38171. method.
  38172. The factory object is used to create any item components that are needed.
  38173. @see toString
  38174. */
  38175. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  38176. const String& savedVersion);
  38177. /** @internal */
  38178. void paint (Graphics& g);
  38179. /** @internal */
  38180. void resized();
  38181. /** @internal */
  38182. void buttonClicked (Button*);
  38183. /** @internal */
  38184. void mouseDown (const MouseEvent&);
  38185. /** @internal */
  38186. bool isInterestedInDragSource (const String&, Component*);
  38187. /** @internal */
  38188. void itemDragMove (const String&, Component*, int, int);
  38189. /** @internal */
  38190. void itemDragExit (const String&, Component*);
  38191. /** @internal */
  38192. void itemDropped (const String&, Component*, int, int);
  38193. /** @internal */
  38194. void updateAllItemPositions (bool animate);
  38195. /** @internal */
  38196. static ToolbarItemComponent* createItem (ToolbarItemFactory&, int itemId);
  38197. private:
  38198. ScopedPointer<Button> missingItemsButton;
  38199. bool vertical, isEditingActive;
  38200. ToolbarItemStyle toolbarStyle;
  38201. class MissingItemsComponent;
  38202. friend class MissingItemsComponent;
  38203. OwnedArray <ToolbarItemComponent> items;
  38204. friend class ItemDragAndDropOverlayComponent;
  38205. static const char* const toolbarDragDescriptor;
  38206. void addItemInternal (ToolbarItemFactory& factory, int itemId, int insertIndex);
  38207. ToolbarItemComponent* getNextActiveComponent (int index, int delta) const;
  38208. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Toolbar);
  38209. };
  38210. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  38211. /*** End of inlined file: juce_Toolbar.h ***/
  38212. class ItemDragAndDropOverlayComponent;
  38213. /**
  38214. A component that can be used as one of the items in a Toolbar.
  38215. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  38216. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  38217. class for further info about creating them.
  38218. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  38219. components too. To do this, set the value of isBeingUsedAsAButton to false when
  38220. calling the constructor, and override contentAreaChanged(), in which you can position
  38221. any sub-components you need to add.
  38222. To add basic buttons without writing a special subclass, have a look at the
  38223. ToolbarButton class.
  38224. @see ToolbarButton, Toolbar, ToolbarItemFactory
  38225. */
  38226. class JUCE_API ToolbarItemComponent : public Button
  38227. {
  38228. public:
  38229. /** Constructor.
  38230. @param itemId the ID of the type of toolbar item which this represents
  38231. @param labelText the text to display if the toolbar's style is set to
  38232. Toolbar::iconsWithText or Toolbar::textOnly
  38233. @param isBeingUsedAsAButton set this to false if you don't want the button
  38234. to draw itself with button over/down states when the mouse
  38235. moves over it or clicks
  38236. */
  38237. ToolbarItemComponent (int itemId,
  38238. const String& labelText,
  38239. bool isBeingUsedAsAButton);
  38240. /** Destructor. */
  38241. ~ToolbarItemComponent();
  38242. /** Returns the item type ID that this component represents.
  38243. This value is in the constructor.
  38244. */
  38245. int getItemId() const throw() { return itemId; }
  38246. /** Returns the toolbar that contains this component, or 0 if it's not currently
  38247. inside one.
  38248. */
  38249. Toolbar* getToolbar() const;
  38250. /** Returns true if this component is currently inside a toolbar which is vertical.
  38251. @see Toolbar::isVertical
  38252. */
  38253. bool isToolbarVertical() const;
  38254. /** Returns the current style setting of this item.
  38255. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  38256. @see setStyle, Toolbar::getStyle
  38257. */
  38258. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  38259. /** Changes the current style setting of this item.
  38260. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  38261. by the toolbar that holds this item.
  38262. @see setStyle, Toolbar::setStyle
  38263. */
  38264. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  38265. /** Returns the area of the component that should be used to display the button image or
  38266. other contents of the item.
  38267. This content area may change when the item's style changes, and may leave a space around the
  38268. edge of the component where the text label can be shown.
  38269. @see contentAreaChanged
  38270. */
  38271. const Rectangle<int> getContentArea() const throw() { return contentArea; }
  38272. /** This method must return the size criteria for this item, based on a given toolbar
  38273. size and orientation.
  38274. The preferredSize, minSize and maxSize values must all be set by your implementation
  38275. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  38276. toolbar, they refer to the item's height.
  38277. The preferredSize is the size that the component would like to be, and this must be
  38278. between the min and max sizes. For a fixed-size item, simply set all three variables to
  38279. the same value.
  38280. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  38281. Toolbar::getThickness().
  38282. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  38283. vertically.
  38284. */
  38285. virtual bool getToolbarItemSizes (int toolbarThickness,
  38286. bool isToolbarVertical,
  38287. int& preferredSize,
  38288. int& minSize,
  38289. int& maxSize) = 0;
  38290. /** Your subclass should use this method to draw its content area.
  38291. The graphics object that is passed-in will have been clipped and had its origin
  38292. moved to fit the content area as specified get getContentArea(). The width and height
  38293. parameters are the width and height of the content area.
  38294. If the component you're writing isn't a button, you can just do nothing in this method.
  38295. */
  38296. virtual void paintButtonArea (Graphics& g,
  38297. int width, int height,
  38298. bool isMouseOver, bool isMouseDown) = 0;
  38299. /** Callback to indicate that the content area of this item has changed.
  38300. This might be because the component was resized, or because the style changed and
  38301. the space needed for the text label is different.
  38302. See getContentArea() for a description of what the area is.
  38303. */
  38304. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  38305. /** Editing modes.
  38306. These are used by setEditingMode(), but will be rarely needed in user code.
  38307. */
  38308. enum ToolbarEditingMode
  38309. {
  38310. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  38311. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  38312. customisation mode, and the items can be dragged around. */
  38313. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  38314. dragged onto a toolbar to add it to that bar.*/
  38315. };
  38316. /** Changes the editing mode of this component.
  38317. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  38318. and is unlikely to be of much use in end-user-code.
  38319. */
  38320. void setEditingMode (const ToolbarEditingMode newMode);
  38321. /** Returns the current editing mode of this component.
  38322. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  38323. and is unlikely to be of much use in end-user-code.
  38324. */
  38325. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  38326. /** @internal */
  38327. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  38328. /** @internal */
  38329. void resized();
  38330. private:
  38331. friend class Toolbar;
  38332. friend class ItemDragAndDropOverlayComponent;
  38333. const int itemId;
  38334. ToolbarEditingMode mode;
  38335. Toolbar::ToolbarItemStyle toolbarStyle;
  38336. ScopedPointer <Component> overlayComp;
  38337. int dragOffsetX, dragOffsetY;
  38338. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  38339. Rectangle<int> contentArea;
  38340. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemComponent);
  38341. };
  38342. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  38343. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  38344. /**
  38345. A type of button designed to go on a toolbar.
  38346. This simple button can have two Drawable objects specified - one for normal
  38347. use and another one (optionally) for the button's "on" state if it's a
  38348. toggle button.
  38349. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  38350. */
  38351. class JUCE_API ToolbarButton : public ToolbarItemComponent
  38352. {
  38353. public:
  38354. /** Creates a ToolbarButton.
  38355. @param itemId the ID for this toolbar item type. This is passed through to the
  38356. ToolbarItemComponent constructor
  38357. @param labelText the text to display on the button (if the toolbar is using a style
  38358. that shows text labels). This is passed through to the
  38359. ToolbarItemComponent constructor
  38360. @param normalImage a drawable object that the button should use as its icon. The object
  38361. that is passed-in here will be kept by this object and will be
  38362. deleted when no longer needed or when this button is deleted.
  38363. @param toggledOnImage a drawable object that the button can use as its icon if the button
  38364. is in a toggled-on state (see the Button::getToggleState() method). If
  38365. 0 is passed-in here, then the normal image will be used instead, regardless
  38366. of the toggle state. The object that is passed-in here will be kept by
  38367. this object and will be deleted when no longer needed or when this button
  38368. is deleted.
  38369. */
  38370. ToolbarButton (int itemId,
  38371. const String& labelText,
  38372. Drawable* normalImage,
  38373. Drawable* toggledOnImage);
  38374. /** Destructor. */
  38375. ~ToolbarButton();
  38376. /** @internal */
  38377. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  38378. int& minSize, int& maxSize);
  38379. /** @internal */
  38380. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  38381. /** @internal */
  38382. void contentAreaChanged (const Rectangle<int>& newBounds);
  38383. /** @internal */
  38384. void buttonStateChanged();
  38385. /** @internal */
  38386. void resized();
  38387. /** @internal */
  38388. void enablementChanged();
  38389. private:
  38390. ScopedPointer<Drawable> normalImage, toggledOnImage;
  38391. Drawable* currentImage;
  38392. void updateDrawable();
  38393. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarButton);
  38394. };
  38395. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  38396. /*** End of inlined file: juce_ToolbarButton.h ***/
  38397. #endif
  38398. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  38399. /*** Start of inlined file: juce_CodeDocument.h ***/
  38400. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  38401. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  38402. class CodeDocumentLine;
  38403. /**
  38404. A class for storing and manipulating a source code file.
  38405. When using a CodeEditorComponent, it takes one of these as its source object.
  38406. The CodeDocument stores its content as an array of lines, which makes it
  38407. quick to insert and delete.
  38408. @see CodeEditorComponent
  38409. */
  38410. class JUCE_API CodeDocument
  38411. {
  38412. public:
  38413. /** Creates a new, empty document.
  38414. */
  38415. CodeDocument();
  38416. /** Destructor. */
  38417. ~CodeDocument();
  38418. /** A position in a code document.
  38419. Using this class you can find a position in a code document and quickly get its
  38420. character position, line, and index. By calling setPositionMaintained (true), the
  38421. position is automatically updated when text is inserted or deleted in the document,
  38422. so that it maintains its original place in the text.
  38423. */
  38424. class JUCE_API Position
  38425. {
  38426. public:
  38427. /** Creates an uninitialised postion.
  38428. Don't attempt to call any methods on this until you've given it an owner document
  38429. to refer to!
  38430. */
  38431. Position() throw();
  38432. /** Creates a position based on a line and index in a document.
  38433. Note that this index is NOT the column number, it's the number of characters from the
  38434. start of the line. The "column" number isn't quite the same, because if the line
  38435. contains any tab characters, the relationship of the index to its visual column depends on
  38436. the number of spaces per tab being used!
  38437. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  38438. they will be adjusted to keep them within its limits.
  38439. */
  38440. Position (const CodeDocument* ownerDocument,
  38441. int line, int indexInLine) throw();
  38442. /** Creates a position based on a character index in a document.
  38443. This position is placed at the specified number of characters from the start of the
  38444. document. The line and column are auto-calculated.
  38445. If the position is beyond the range of the document, it'll be adjusted to keep it
  38446. inside.
  38447. */
  38448. Position (const CodeDocument* ownerDocument,
  38449. int charactersFromStartOfDocument) throw();
  38450. /** Creates a copy of another position.
  38451. This will copy the position, but the new object will not be set to maintain its position,
  38452. even if the source object was set to do so.
  38453. */
  38454. Position (const Position& other) throw();
  38455. /** Destructor. */
  38456. ~Position();
  38457. Position& operator= (const Position& other);
  38458. bool operator== (const Position& other) const throw();
  38459. bool operator!= (const Position& other) const throw();
  38460. /** Points this object at a new position within the document.
  38461. If the position is beyond the range of the document, it'll be adjusted to keep it
  38462. inside.
  38463. @see getPosition, setLineAndIndex
  38464. */
  38465. void setPosition (int charactersFromStartOfDocument);
  38466. /** Returns the position as the number of characters from the start of the document.
  38467. @see setPosition, getLineNumber, getIndexInLine
  38468. */
  38469. int getPosition() const throw() { return characterPos; }
  38470. /** Moves the position to a new line and index within the line.
  38471. Note that the index is NOT the column at which the position appears in an editor.
  38472. If the line contains any tab characters, the relationship of the index to its
  38473. visual position depends on the number of spaces per tab being used!
  38474. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  38475. they will be adjusted to keep them within its limits.
  38476. */
  38477. void setLineAndIndex (int newLine, int newIndexInLine);
  38478. /** Returns the line number of this position.
  38479. The first line in the document is numbered zero, not one!
  38480. */
  38481. int getLineNumber() const throw() { return line; }
  38482. /** Returns the number of characters from the start of the line.
  38483. Note that this value is NOT the column at which the position appears in an editor.
  38484. If the line contains any tab characters, the relationship of the index to its
  38485. visual position depends on the number of spaces per tab being used!
  38486. */
  38487. int getIndexInLine() const throw() { return indexInLine; }
  38488. /** Allows the position to be automatically updated when the document changes.
  38489. If this is set to true, the positon will register with its document so that
  38490. when the document has text inserted or deleted, this position will be automatically
  38491. moved to keep it at the same position in the text.
  38492. */
  38493. void setPositionMaintained (bool isMaintained);
  38494. /** Moves the position forwards or backwards by the specified number of characters.
  38495. @see movedBy
  38496. */
  38497. void moveBy (int characterDelta);
  38498. /** Returns a position which is the same as this one, moved by the specified number of
  38499. characters.
  38500. @see moveBy
  38501. */
  38502. const Position movedBy (int characterDelta) const;
  38503. /** Returns a position which is the same as this one, moved up or down by the specified
  38504. number of lines.
  38505. @see movedBy
  38506. */
  38507. const Position movedByLines (int deltaLines) const;
  38508. /** Returns the character in the document at this position.
  38509. @see getLineText
  38510. */
  38511. const juce_wchar getCharacter() const;
  38512. /** Returns the line from the document that this position is within.
  38513. @see getCharacter, getLineNumber
  38514. */
  38515. const String getLineText() const;
  38516. private:
  38517. CodeDocument* owner;
  38518. int characterPos, line, indexInLine;
  38519. bool positionMaintained;
  38520. };
  38521. /** Returns the full text of the document. */
  38522. const String getAllContent() const;
  38523. /** Returns a section of the document's text. */
  38524. const String getTextBetween (const Position& start, const Position& end) const;
  38525. /** Returns a line from the document. */
  38526. const String getLine (int lineIndex) const throw();
  38527. /** Returns the number of characters in the document. */
  38528. int getNumCharacters() const throw();
  38529. /** Returns the number of lines in the document. */
  38530. int getNumLines() const throw() { return lines.size(); }
  38531. /** Returns the number of characters in the longest line of the document. */
  38532. int getMaximumLineLength() throw();
  38533. /** Deletes a section of the text.
  38534. This operation is undoable.
  38535. */
  38536. void deleteSection (const Position& startPosition, const Position& endPosition);
  38537. /** Inserts some text into the document at a given position.
  38538. This operation is undoable.
  38539. */
  38540. void insertText (const Position& position, const String& text);
  38541. /** Clears the document and replaces it with some new text.
  38542. This operation is undoable - if you're trying to completely reset the document, you
  38543. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  38544. */
  38545. void replaceAllContent (const String& newContent);
  38546. /** Replaces the editor's contents with the contents of a stream.
  38547. This will also reset the undo history and save point marker.
  38548. */
  38549. bool loadFromStream (InputStream& stream);
  38550. /** Writes the editor's current contents to a stream. */
  38551. bool writeToStream (OutputStream& stream);
  38552. /** Returns the preferred new-line characters for the document.
  38553. This will be either "\n", "\r\n", or (rarely) "\r".
  38554. @see setNewLineCharacters
  38555. */
  38556. const String getNewLineCharacters() const throw() { return newLineChars; }
  38557. /** Sets the new-line characters that the document should use.
  38558. The string must be either "\n", "\r\n", or (rarely) "\r".
  38559. @see getNewLineCharacters
  38560. */
  38561. void setNewLineCharacters (const String& newLine) throw();
  38562. /** Begins a new undo transaction.
  38563. The document itself will not call this internally, so relies on whatever is using the
  38564. document to periodically call this to break up the undo sequence into sensible chunks.
  38565. @see UndoManager::beginNewTransaction
  38566. */
  38567. void newTransaction();
  38568. /** Undo the last operation.
  38569. @see UndoManager::undo
  38570. */
  38571. void undo();
  38572. /** Redo the last operation.
  38573. @see UndoManager::redo
  38574. */
  38575. void redo();
  38576. /** Clears the undo history.
  38577. @see UndoManager::clearUndoHistory
  38578. */
  38579. void clearUndoHistory();
  38580. /** Returns the document's UndoManager */
  38581. UndoManager& getUndoManager() throw() { return undoManager; }
  38582. /** Makes a note that the document's current state matches the one that is saved.
  38583. After this has been called, hasChangedSinceSavePoint() will return false until
  38584. the document has been altered, and then it'll start returning true. If the document is
  38585. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  38586. will again return false.
  38587. @see hasChangedSinceSavePoint
  38588. */
  38589. void setSavePoint() throw();
  38590. /** Returns true if the state of the document differs from the state it was in when
  38591. setSavePoint() was last called.
  38592. @see setSavePoint
  38593. */
  38594. bool hasChangedSinceSavePoint() const throw();
  38595. /** Searches for a word-break. */
  38596. const Position findWordBreakAfter (const Position& position) const throw();
  38597. /** Searches for a word-break. */
  38598. const Position findWordBreakBefore (const Position& position) const throw();
  38599. /** An object that receives callbacks from the CodeDocument when its text changes.
  38600. @see CodeDocument::addListener, CodeDocument::removeListener
  38601. */
  38602. class JUCE_API Listener
  38603. {
  38604. public:
  38605. Listener() {}
  38606. virtual ~Listener() {}
  38607. /** Called by a CodeDocument when it is altered.
  38608. */
  38609. virtual void codeDocumentChanged (const Position& affectedTextStart,
  38610. const Position& affectedTextEnd) = 0;
  38611. };
  38612. /** Registers a listener object to receive callbacks when the document changes.
  38613. If the listener is already registered, this method has no effect.
  38614. @see removeListener
  38615. */
  38616. void addListener (Listener* listener) throw();
  38617. /** Deregisters a listener.
  38618. @see addListener
  38619. */
  38620. void removeListener (Listener* listener) throw();
  38621. /** Iterates the text in a CodeDocument.
  38622. This class lets you read characters from a CodeDocument. It's designed to be used
  38623. by a SyntaxAnalyser object.
  38624. @see CodeDocument, SyntaxAnalyser
  38625. */
  38626. class JUCE_API Iterator
  38627. {
  38628. public:
  38629. Iterator (CodeDocument* document);
  38630. Iterator (const Iterator& other);
  38631. Iterator& operator= (const Iterator& other) throw();
  38632. ~Iterator() throw();
  38633. /** Reads the next character and returns it.
  38634. @see peekNextChar
  38635. */
  38636. juce_wchar nextChar();
  38637. /** Reads the next character without advancing the current position. */
  38638. juce_wchar peekNextChar() const;
  38639. /** Advances the position by one character. */
  38640. void skip();
  38641. /** Returns the position of the next character as its position within the
  38642. whole document.
  38643. */
  38644. int getPosition() const throw() { return position; }
  38645. /** Skips over any whitespace characters until the next character is non-whitespace. */
  38646. void skipWhitespace();
  38647. /** Skips forward until the next character will be the first character on the next line */
  38648. void skipToEndOfLine();
  38649. /** Returns the line number of the next character. */
  38650. int getLine() const throw() { return line; }
  38651. /** Returns true if the iterator has reached the end of the document. */
  38652. bool isEOF() const throw();
  38653. private:
  38654. CodeDocument* document;
  38655. mutable String::CharPointerType charPointer;
  38656. int line, position;
  38657. };
  38658. private:
  38659. friend class CodeDocumentInsertAction;
  38660. friend class CodeDocumentDeleteAction;
  38661. friend class Iterator;
  38662. friend class Position;
  38663. OwnedArray <CodeDocumentLine> lines;
  38664. Array <Position*> positionsToMaintain;
  38665. UndoManager undoManager;
  38666. int currentActionIndex, indexOfSavedState;
  38667. int maximumLineLength;
  38668. ListenerList <Listener> listeners;
  38669. String newLineChars;
  38670. void sendListenerChangeMessage (int startLine, int endLine);
  38671. void insert (const String& text, int insertPos, bool undoable);
  38672. void remove (int startPos, int endPos, bool undoable);
  38673. void checkLastLineStatus();
  38674. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeDocument);
  38675. };
  38676. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  38677. /*** End of inlined file: juce_CodeDocument.h ***/
  38678. #endif
  38679. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38680. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  38681. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38682. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38683. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  38684. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  38685. #define __JUCE_CODETOKENISER_JUCEHEADER__
  38686. /**
  38687. A base class for tokenising code so that the syntax can be displayed in a
  38688. code editor.
  38689. @see CodeDocument, CodeEditorComponent
  38690. */
  38691. class JUCE_API CodeTokeniser
  38692. {
  38693. public:
  38694. CodeTokeniser() {}
  38695. virtual ~CodeTokeniser() {}
  38696. /** Reads the next token from the source and returns its token type.
  38697. This must leave the source pointing to the first character in the
  38698. next token.
  38699. */
  38700. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  38701. /** Returns a list of the names of the token types this analyser uses.
  38702. The index in this list must match the token type numbers that are
  38703. returned by readNextToken().
  38704. */
  38705. virtual const StringArray getTokenTypes() = 0;
  38706. /** Returns a suggested syntax highlighting colour for a specified
  38707. token type.
  38708. */
  38709. virtual const Colour getDefaultColour (int tokenType) = 0;
  38710. private:
  38711. JUCE_LEAK_DETECTOR (CodeTokeniser);
  38712. };
  38713. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  38714. /*** End of inlined file: juce_CodeTokeniser.h ***/
  38715. /**
  38716. A text editor component designed specifically for source code.
  38717. This is designed to handle syntax highlighting and fast editing of very large
  38718. files.
  38719. */
  38720. class JUCE_API CodeEditorComponent : public Component,
  38721. public TextInputTarget,
  38722. public Timer,
  38723. public ScrollBar::Listener,
  38724. public CodeDocument::Listener,
  38725. public AsyncUpdater
  38726. {
  38727. public:
  38728. /** Creates an editor for a document.
  38729. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  38730. The object that you pass in is not owned or deleted by the editor - you must
  38731. make sure that it doesn't get deleted while this component is still using it.
  38732. @see CodeDocument
  38733. */
  38734. CodeEditorComponent (CodeDocument& document,
  38735. CodeTokeniser* codeTokeniser);
  38736. /** Destructor. */
  38737. ~CodeEditorComponent();
  38738. /** Returns the code document that this component is editing. */
  38739. CodeDocument& getDocument() const throw() { return document; }
  38740. /** Loads the given content into the document.
  38741. This will completely reset the CodeDocument object, clear its undo history,
  38742. and fill it with this text.
  38743. */
  38744. void loadContent (const String& newContent);
  38745. /** Returns the standard character width. */
  38746. float getCharWidth() const throw() { return charWidth; }
  38747. /** Returns the height of a line of text, in pixels. */
  38748. int getLineHeight() const throw() { return lineHeight; }
  38749. /** Returns the number of whole lines visible on the screen,
  38750. This doesn't include a cut-off line that might be visible at the bottom if the
  38751. component's height isn't an exact multiple of the line-height.
  38752. */
  38753. int getNumLinesOnScreen() const throw() { return linesOnScreen; }
  38754. /** Returns the number of whole columns visible on the screen.
  38755. This doesn't include any cut-off columns at the right-hand edge.
  38756. */
  38757. int getNumColumnsOnScreen() const throw() { return columnsOnScreen; }
  38758. /** Returns the current caret position. */
  38759. const CodeDocument::Position getCaretPos() const { return caretPos; }
  38760. /** Moves the caret.
  38761. If selecting is true, the section of the document between the current
  38762. caret position and the new one will become selected. If false, any currently
  38763. selected region will be deselected.
  38764. */
  38765. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  38766. /** Returns the on-screen position of a character in the document.
  38767. The rectangle returned is relative to this component's top-left origin.
  38768. */
  38769. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const;
  38770. /** Finds the character at a given on-screen position.
  38771. The co-ordinates are relative to this component's top-left origin.
  38772. */
  38773. const CodeDocument::Position getPositionAt (int x, int y);
  38774. void cursorLeft (bool moveInWholeWordSteps, bool selecting);
  38775. void cursorRight (bool moveInWholeWordSteps, bool selecting);
  38776. void cursorDown (bool selecting);
  38777. void cursorUp (bool selecting);
  38778. void pageDown (bool selecting);
  38779. void pageUp (bool selecting);
  38780. void scrollDown();
  38781. void scrollUp();
  38782. void scrollToLine (int newFirstLineOnScreen);
  38783. void scrollBy (int deltaLines);
  38784. void scrollToColumn (int newFirstColumnOnScreen);
  38785. void scrollToKeepCaretOnScreen();
  38786. void goToStartOfDocument (bool selecting);
  38787. void goToStartOfLine (bool selecting);
  38788. void goToEndOfDocument (bool selecting);
  38789. void goToEndOfLine (bool selecting);
  38790. void deselectAll();
  38791. void selectAll();
  38792. void insertTextAtCaret (const String& textToInsert);
  38793. void insertTabAtCaret();
  38794. void cut();
  38795. void copy();
  38796. void copyThenCut();
  38797. void paste();
  38798. void backspace (bool moveInWholeWordSteps);
  38799. void deleteForward (bool moveInWholeWordSteps);
  38800. void undo();
  38801. void redo();
  38802. const Range<int> getHighlightedRegion() const;
  38803. void setHighlightedRegion (const Range<int>& newRange);
  38804. const String getTextInRange (const Range<int>& range) const;
  38805. /** Changes the current tab settings.
  38806. This lets you change the tab size and whether pressing the tab key inserts a
  38807. tab character, or its equivalent number of spaces.
  38808. */
  38809. void setTabSize (int numSpacesPerTab, bool insertSpacesInsteadOfTabCharacters);
  38810. /** Returns the current number of spaces per tab.
  38811. @see setTabSize
  38812. */
  38813. int getTabSize() const throw() { return spacesPerTab; }
  38814. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  38815. @see setTabSize
  38816. */
  38817. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  38818. /** Changes the font.
  38819. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  38820. */
  38821. void setFont (const Font& newFont);
  38822. /** Returns the font that the editor is using. */
  38823. const Font& getFont() const throw() { return font; }
  38824. /** Resets the syntax highlighting colours to the default ones provided by the
  38825. code tokeniser.
  38826. @see CodeTokeniser::getDefaultColour
  38827. */
  38828. void resetToDefaultColours();
  38829. /** Changes one of the syntax highlighting colours.
  38830. The token type values are dependent on the tokeniser being used - use
  38831. CodeTokeniser::getTokenTypes() to get a list of the token types.
  38832. @see getColourForTokenType
  38833. */
  38834. void setColourForTokenType (int tokenType, const Colour& colour);
  38835. /** Returns one of the syntax highlighting colours.
  38836. The token type values are dependent on the tokeniser being used - use
  38837. CodeTokeniser::getTokenTypes() to get a list of the token types.
  38838. @see setColourForTokenType
  38839. */
  38840. const Colour getColourForTokenType (int tokenType) const;
  38841. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  38842. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38843. methods.
  38844. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38845. */
  38846. enum ColourIds
  38847. {
  38848. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  38849. caretColourId = 0x1004501, /**< The colour to draw the caret. */
  38850. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  38851. selected text. */
  38852. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  38853. enabled. */
  38854. };
  38855. /** Changes the size of the scrollbars. */
  38856. void setScrollbarThickness (int thickness);
  38857. /** Returns the thickness of the scrollbars. */
  38858. int getScrollbarThickness() const throw() { return scrollbarThickness; }
  38859. /** @internal */
  38860. void resized();
  38861. /** @internal */
  38862. void paint (Graphics& g);
  38863. /** @internal */
  38864. bool keyPressed (const KeyPress& key);
  38865. /** @internal */
  38866. void mouseDown (const MouseEvent& e);
  38867. /** @internal */
  38868. void mouseDrag (const MouseEvent& e);
  38869. /** @internal */
  38870. void mouseUp (const MouseEvent& e);
  38871. /** @internal */
  38872. void mouseDoubleClick (const MouseEvent& e);
  38873. /** @internal */
  38874. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  38875. /** @internal */
  38876. void focusGained (FocusChangeType cause);
  38877. /** @internal */
  38878. void focusLost (FocusChangeType cause);
  38879. /** @internal */
  38880. void timerCallback();
  38881. /** @internal */
  38882. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  38883. /** @internal */
  38884. void handleAsyncUpdate();
  38885. /** @internal */
  38886. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  38887. const CodeDocument::Position& affectedTextEnd);
  38888. /** @internal */
  38889. bool isTextInputActive() const;
  38890. private:
  38891. CodeDocument& document;
  38892. Font font;
  38893. int firstLineOnScreen, gutter, spacesPerTab;
  38894. float charWidth;
  38895. int lineHeight, linesOnScreen, columnsOnScreen;
  38896. int scrollbarThickness, columnToTryToMaintain;
  38897. bool useSpacesForTabs;
  38898. double xOffset;
  38899. CodeDocument::Position caretPos;
  38900. CodeDocument::Position selectionStart, selectionEnd;
  38901. class CaretComponent;
  38902. friend class ScopedPointer <CaretComponent>;
  38903. ScopedPointer<CaretComponent> caret;
  38904. ScrollBar verticalScrollBar, horizontalScrollBar;
  38905. enum DragType
  38906. {
  38907. notDragging,
  38908. draggingSelectionStart,
  38909. draggingSelectionEnd
  38910. };
  38911. DragType dragType;
  38912. CodeTokeniser* codeTokeniser;
  38913. Array <Colour> coloursForTokenCategories;
  38914. class CodeEditorLine;
  38915. OwnedArray <CodeEditorLine> lines;
  38916. void rebuildLineTokens();
  38917. OwnedArray <CodeDocument::Iterator> cachedIterators;
  38918. void clearCachedIterators (int firstLineToBeInvalid);
  38919. void updateCachedIterators (int maxLineNum);
  38920. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  38921. void moveLineDelta (int delta, bool selecting);
  38922. void updateScrollBars();
  38923. void scrollToLineInternal (int line);
  38924. void scrollToColumnInternal (double column);
  38925. void newTransaction();
  38926. int indexToColumn (int line, int index) const throw();
  38927. int columnToIndex (int line, int column) const throw();
  38928. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeEditorComponent);
  38929. };
  38930. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38931. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  38932. #endif
  38933. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  38934. #endif
  38935. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  38936. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  38937. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  38938. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  38939. /**
  38940. A simple lexical analyser for syntax colouring of C++ code.
  38941. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  38942. */
  38943. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  38944. {
  38945. public:
  38946. CPlusPlusCodeTokeniser();
  38947. ~CPlusPlusCodeTokeniser();
  38948. enum TokenType
  38949. {
  38950. tokenType_error = 0,
  38951. tokenType_comment,
  38952. tokenType_builtInKeyword,
  38953. tokenType_identifier,
  38954. tokenType_integerLiteral,
  38955. tokenType_floatLiteral,
  38956. tokenType_stringLiteral,
  38957. tokenType_operator,
  38958. tokenType_bracket,
  38959. tokenType_punctuation,
  38960. tokenType_preprocessor
  38961. };
  38962. int readNextToken (CodeDocument::Iterator& source);
  38963. const StringArray getTokenTypes();
  38964. const Colour getDefaultColour (int tokenType);
  38965. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  38966. static bool isReservedKeyword (const String& token) throw();
  38967. private:
  38968. JUCE_LEAK_DETECTOR (CPlusPlusCodeTokeniser);
  38969. };
  38970. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  38971. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  38972. #endif
  38973. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  38974. #endif
  38975. #ifndef __JUCE_LABEL_JUCEHEADER__
  38976. #endif
  38977. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  38978. #endif
  38979. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  38980. /*** Start of inlined file: juce_ProgressBar.h ***/
  38981. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  38982. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  38983. /**
  38984. A progress bar component.
  38985. To use this, just create one and make it visible. It'll run its own timer
  38986. to keep an eye on a variable that you give it, and will automatically
  38987. redraw itself when the variable changes.
  38988. For an easy way of running a background task with a dialog box showing its
  38989. progress, see the ThreadWithProgressWindow class.
  38990. @see ThreadWithProgressWindow
  38991. */
  38992. class JUCE_API ProgressBar : public Component,
  38993. public SettableTooltipClient,
  38994. private Timer
  38995. {
  38996. public:
  38997. /** Creates a ProgressBar.
  38998. @param progress pass in a reference to a double that you're going to
  38999. update with your task's progress. The ProgressBar will
  39000. monitor the value of this variable and will redraw itself
  39001. when the value changes. The range is from 0 to 1.0. Obviously
  39002. you'd better be careful not to delete this variable while the
  39003. ProgressBar still exists!
  39004. */
  39005. explicit ProgressBar (double& progress);
  39006. /** Destructor. */
  39007. ~ProgressBar();
  39008. /** Turns the percentage display on or off.
  39009. By default this is on, and the progress bar will display a text string showing
  39010. its current percentage.
  39011. */
  39012. void setPercentageDisplay (bool shouldDisplayPercentage);
  39013. /** Gives the progress bar a string to display inside it.
  39014. If you call this, it will turn off the percentage display.
  39015. @see setPercentageDisplay
  39016. */
  39017. void setTextToDisplay (const String& text);
  39018. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  39019. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39020. methods.
  39021. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39022. */
  39023. enum ColourIds
  39024. {
  39025. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  39026. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  39027. classes will probably use variations on this colour. */
  39028. };
  39029. protected:
  39030. /** @internal */
  39031. void paint (Graphics& g);
  39032. /** @internal */
  39033. void lookAndFeelChanged();
  39034. /** @internal */
  39035. void visibilityChanged();
  39036. /** @internal */
  39037. void colourChanged();
  39038. private:
  39039. double& progress;
  39040. double currentValue;
  39041. bool displayPercentage;
  39042. String displayedMessage, currentMessage;
  39043. uint32 lastCallbackTime;
  39044. void timerCallback();
  39045. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProgressBar);
  39046. };
  39047. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  39048. /*** End of inlined file: juce_ProgressBar.h ***/
  39049. #endif
  39050. #ifndef __JUCE_SLIDER_JUCEHEADER__
  39051. /*** Start of inlined file: juce_Slider.h ***/
  39052. #ifndef __JUCE_SLIDER_JUCEHEADER__
  39053. #define __JUCE_SLIDER_JUCEHEADER__
  39054. #if JUCE_VC6
  39055. #define Listener LabelListener
  39056. #endif
  39057. /**
  39058. A slider control for changing a value.
  39059. The slider can be horizontal, vertical, or rotary, and can optionally have
  39060. a text-box inside it to show an editable display of the current value.
  39061. To use it, create a Slider object and use the setSliderStyle() method
  39062. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  39063. To define the values that it can be set to, see the setRange() and setValue() methods.
  39064. There are also lots of custom tweaks you can do by subclassing and overriding
  39065. some of the virtual methods, such as changing the scaling, changing the format of
  39066. the text display, custom ways of limiting the values, etc.
  39067. You can register Slider::Listener objects with a slider, and they'll be called when
  39068. the value changes.
  39069. @see Slider::Listener
  39070. */
  39071. class JUCE_API Slider : public Component,
  39072. public SettableTooltipClient,
  39073. public AsyncUpdater,
  39074. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  39075. public LabelListener,
  39076. public ValueListener
  39077. {
  39078. public:
  39079. /** Creates a slider.
  39080. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  39081. setRange(), etc.
  39082. */
  39083. explicit Slider (const String& componentName = String::empty);
  39084. /** Destructor. */
  39085. ~Slider();
  39086. /** The types of slider available.
  39087. @see setSliderStyle, setRotaryParameters
  39088. */
  39089. enum SliderStyle
  39090. {
  39091. LinearHorizontal, /**< A traditional horizontal slider. */
  39092. LinearVertical, /**< A traditional vertical slider. */
  39093. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  39094. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  39095. @see setRotaryParameters */
  39096. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  39097. @see setRotaryParameters */
  39098. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  39099. @see setRotaryParameters */
  39100. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  39101. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  39102. @see setMinValue, setMaxValue */
  39103. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  39104. @see setMinValue, setMaxValue */
  39105. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  39106. value, with the current value being somewhere between them.
  39107. @see setMinValue, setMaxValue */
  39108. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  39109. value, with the current value being somewhere between them.
  39110. @see setMinValue, setMaxValue */
  39111. };
  39112. /** Changes the type of slider interface being used.
  39113. @param newStyle the type of interface
  39114. @see setRotaryParameters, setVelocityBasedMode,
  39115. */
  39116. void setSliderStyle (SliderStyle newStyle);
  39117. /** Returns the slider's current style.
  39118. @see setSliderStyle
  39119. */
  39120. SliderStyle getSliderStyle() const throw() { return style; }
  39121. /** Changes the properties of a rotary slider.
  39122. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  39123. the slider's minimum value is represented
  39124. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  39125. the slider's maximum value is represented. This must be
  39126. greater than startAngleRadians
  39127. @param stopAtEnd if true, then when the slider is dragged around past the
  39128. minimum or maximum, it'll stop there; if false, it'll wrap
  39129. back to the opposite value
  39130. */
  39131. void setRotaryParameters (float startAngleRadians,
  39132. float endAngleRadians,
  39133. bool stopAtEnd);
  39134. /** Sets the distance the mouse has to move to drag the slider across
  39135. the full extent of its range.
  39136. This only applies when in modes like RotaryHorizontalDrag, where it's using
  39137. relative mouse movements to adjust the slider.
  39138. */
  39139. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  39140. /** Returns the current sensitivity value set by setMouseDragSensitivity(). */
  39141. int getMouseDragSensitivity() const throw() { return pixelsForFullDragExtent; }
  39142. /** Changes the way the the mouse is used when dragging the slider.
  39143. If true, this will turn on velocity-sensitive dragging, so that
  39144. the faster the mouse moves, the bigger the movement to the slider. This
  39145. helps when making accurate adjustments if the slider's range is quite large.
  39146. If false, the slider will just try to snap to wherever the mouse is.
  39147. */
  39148. void setVelocityBasedMode (bool isVelocityBased);
  39149. /** Returns true if velocity-based mode is active.
  39150. @see setVelocityBasedMode
  39151. */
  39152. bool getVelocityBasedMode() const throw() { return isVelocityBased; }
  39153. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  39154. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  39155. or if you're holding down ctrl.
  39156. @param sensitivity higher values than 1.0 increase the range of acceleration used
  39157. @param threshold the minimum number of pixels that the mouse needs to move for it
  39158. to be treated as a movement
  39159. @param offset values greater than 0.0 increase the minimum speed that will be used when
  39160. the threshold is reached
  39161. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  39162. key to toggle velocity-sensitive mode
  39163. */
  39164. void setVelocityModeParameters (double sensitivity = 1.0,
  39165. int threshold = 1,
  39166. double offset = 0.0,
  39167. bool userCanPressKeyToSwapMode = true);
  39168. /** Returns the velocity sensitivity setting.
  39169. @see setVelocityModeParameters
  39170. */
  39171. double getVelocitySensitivity() const throw() { return velocityModeSensitivity; }
  39172. /** Returns the velocity threshold setting.
  39173. @see setVelocityModeParameters
  39174. */
  39175. int getVelocityThreshold() const throw() { return velocityModeThreshold; }
  39176. /** Returns the velocity offset setting.
  39177. @see setVelocityModeParameters
  39178. */
  39179. double getVelocityOffset() const throw() { return velocityModeOffset; }
  39180. /** Returns the velocity user key setting.
  39181. @see setVelocityModeParameters
  39182. */
  39183. bool getVelocityModeIsSwappable() const throw() { return userKeyOverridesVelocity; }
  39184. /** Sets up a skew factor to alter the way values are distributed.
  39185. You may want to use a range of values on the slider where more accuracy
  39186. is required towards one end of the range, so this will logarithmically
  39187. spread the values across the length of the slider.
  39188. If the factor is < 1.0, the lower end of the range will fill more of the
  39189. slider's length; if the factor is > 1.0, the upper end of the range
  39190. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  39191. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  39192. method instead.
  39193. @see getSkewFactor, setSkewFactorFromMidPoint
  39194. */
  39195. void setSkewFactor (double factor);
  39196. /** Sets up a skew factor to alter the way values are distributed.
  39197. This allows you to specify the slider value that should appear in the
  39198. centre of the slider's visible range.
  39199. @see setSkewFactor, getSkewFactor
  39200. */
  39201. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  39202. /** Returns the current skew factor.
  39203. See setSkewFactor for more info.
  39204. @see setSkewFactor, setSkewFactorFromMidPoint
  39205. */
  39206. double getSkewFactor() const throw() { return skewFactor; }
  39207. /** Used by setIncDecButtonsMode().
  39208. */
  39209. enum IncDecButtonMode
  39210. {
  39211. incDecButtonsNotDraggable,
  39212. incDecButtonsDraggable_AutoDirection,
  39213. incDecButtonsDraggable_Horizontal,
  39214. incDecButtonsDraggable_Vertical
  39215. };
  39216. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  39217. can be dragged on the buttons to drag the values.
  39218. By default this is turned off. When enabled, clicking on the buttons still works
  39219. them as normal, but by holding down the mouse on a button and dragging it a little
  39220. distance, it flips into a mode where the value can be dragged. The drag direction can
  39221. either be set explicitly to be vertical or horizontal, or can be set to
  39222. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  39223. are side-by-side or above each other.
  39224. */
  39225. void setIncDecButtonsMode (IncDecButtonMode mode);
  39226. /** The position of the slider's text-entry box.
  39227. @see setTextBoxStyle
  39228. */
  39229. enum TextEntryBoxPosition
  39230. {
  39231. NoTextBox, /**< Doesn't display a text box. */
  39232. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  39233. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  39234. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  39235. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  39236. };
  39237. /** Changes the location and properties of the text-entry box.
  39238. @param newPosition where it should go (or NoTextBox to not have one at all)
  39239. @param isReadOnly if true, it's a read-only display
  39240. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  39241. room for the slider as well!
  39242. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  39243. room for the slider as well!
  39244. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  39245. */
  39246. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  39247. bool isReadOnly,
  39248. int textEntryBoxWidth,
  39249. int textEntryBoxHeight);
  39250. /** Returns the status of the text-box.
  39251. @see setTextBoxStyle
  39252. */
  39253. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  39254. /** Returns the width used for the text-box.
  39255. @see setTextBoxStyle
  39256. */
  39257. int getTextBoxWidth() const throw() { return textBoxWidth; }
  39258. /** Returns the height used for the text-box.
  39259. @see setTextBoxStyle
  39260. */
  39261. int getTextBoxHeight() const throw() { return textBoxHeight; }
  39262. /** Makes the text-box editable.
  39263. By default this is true, and the user can enter values into the textbox,
  39264. but it can be turned off if that's not suitable.
  39265. @see setTextBoxStyle, getValueFromText, getTextFromValue
  39266. */
  39267. void setTextBoxIsEditable (bool shouldBeEditable);
  39268. /** Returns true if the text-box is read-only.
  39269. @see setTextBoxStyle
  39270. */
  39271. bool isTextBoxEditable() const { return editableText; }
  39272. /** If the text-box is editable, this will give it the focus so that the user can
  39273. type directly into it.
  39274. This is basically the effect as the user clicking on it.
  39275. */
  39276. void showTextBox();
  39277. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  39278. focus away from it.
  39279. @param discardCurrentEditorContents if true, the slider's value will be left
  39280. unchanged; if false, the current contents of the
  39281. text editor will be used to set the slider position
  39282. before it is hidden.
  39283. */
  39284. void hideTextBox (bool discardCurrentEditorContents);
  39285. /** Changes the slider's current value.
  39286. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  39287. that are registered, and will synchronously call the valueChanged() method in case subclasses
  39288. want to handle it.
  39289. @param newValue the new value to set - this will be restricted by the
  39290. minimum and maximum range, and will be snapped to the
  39291. nearest interval if one has been set
  39292. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  39293. any Slider::Listeners or the valueChanged() method
  39294. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  39295. synchronously; if false, it will be asynchronous
  39296. */
  39297. void setValue (double newValue,
  39298. bool sendUpdateMessage = true,
  39299. bool sendMessageSynchronously = false);
  39300. /** Returns the slider's current value. */
  39301. double getValue() const;
  39302. /** Returns the Value object that represents the slider's current position.
  39303. You can use this Value object to connect the slider's position to external values or setters,
  39304. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  39305. your own Value object.
  39306. @see Value, getMaxValue, getMinValueObject
  39307. */
  39308. Value& getValueObject() { return currentValue; }
  39309. /** Sets the limits that the slider's value can take.
  39310. @param newMinimum the lowest value allowed
  39311. @param newMaximum the highest value allowed
  39312. @param newInterval the steps in which the value is allowed to increase - if this
  39313. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  39314. */
  39315. void setRange (double newMinimum,
  39316. double newMaximum,
  39317. double newInterval = 0);
  39318. /** Returns the current maximum value.
  39319. @see setRange
  39320. */
  39321. double getMaximum() const { return maximum; }
  39322. /** Returns the current minimum value.
  39323. @see setRange
  39324. */
  39325. double getMinimum() const { return minimum; }
  39326. /** Returns the current step-size for values.
  39327. @see setRange
  39328. */
  39329. double getInterval() const { return interval; }
  39330. /** For a slider with two or three thumbs, this returns the lower of its values.
  39331. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  39332. A slider with three values also uses the normal getValue() and setValue() methods to
  39333. control the middle value.
  39334. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  39335. */
  39336. double getMinValue() const;
  39337. /** For a slider with two or three thumbs, this returns the lower of its values.
  39338. You can use this Value object to connect the slider's position to external values or setters,
  39339. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  39340. your own Value object.
  39341. @see Value, getMinValue, getMaxValueObject
  39342. */
  39343. Value& getMinValueObject() throw() { return valueMin; }
  39344. /** For a slider with two or three thumbs, this sets the lower of its values.
  39345. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  39346. that are registered, and will synchronously call the valueChanged() method in case subclasses
  39347. want to handle it.
  39348. @param newValue the new value to set - this will be restricted by the
  39349. minimum and maximum range, and will be snapped to the nearest
  39350. interval if one has been set.
  39351. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  39352. any Slider::Listeners or the valueChanged() method
  39353. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  39354. synchronously; if false, it will be asynchronous
  39355. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  39356. max value (in a two-value slider) or the mid value (in a three-value
  39357. slider). If false, then if this value goes beyond those values,
  39358. it will push them along with it.
  39359. @see getMinValue, setMaxValue, setValue
  39360. */
  39361. void setMinValue (double newValue,
  39362. bool sendUpdateMessage = true,
  39363. bool sendMessageSynchronously = false,
  39364. bool allowNudgingOfOtherValues = false);
  39365. /** For a slider with two or three thumbs, this returns the higher of its values.
  39366. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  39367. A slider with three values also uses the normal getValue() and setValue() methods to
  39368. control the middle value.
  39369. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  39370. */
  39371. double getMaxValue() const;
  39372. /** For a slider with two or three thumbs, this returns the higher of its values.
  39373. You can use this Value object to connect the slider's position to external values or setters,
  39374. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  39375. your own Value object.
  39376. @see Value, getMaxValue, getMinValueObject
  39377. */
  39378. Value& getMaxValueObject() throw() { return valueMax; }
  39379. /** For a slider with two or three thumbs, this sets the lower of its values.
  39380. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  39381. that are registered, and will synchronously call the valueChanged() method in case subclasses
  39382. want to handle it.
  39383. @param newValue the new value to set - this will be restricted by the
  39384. minimum and maximum range, and will be snapped to the nearest
  39385. interval if one has been set.
  39386. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  39387. any Slider::Listeners or the valueChanged() method
  39388. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  39389. synchronously; if false, it will be asynchronous
  39390. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  39391. min value (in a two-value slider) or the mid value (in a three-value
  39392. slider). If false, then if this value goes beyond those values,
  39393. it will push them along with it.
  39394. @see getMaxValue, setMinValue, setValue
  39395. */
  39396. void setMaxValue (double newValue,
  39397. bool sendUpdateMessage = true,
  39398. bool sendMessageSynchronously = false,
  39399. bool allowNudgingOfOtherValues = false);
  39400. /** For a slider with two or three thumbs, this sets the minimum and maximum thumb positions.
  39401. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  39402. that are registered, and will synchronously call the valueChanged() method in case subclasses
  39403. want to handle it.
  39404. @param newMinValue the new minimum value to set - this will be snapped to the
  39405. nearest interval if one has been set.
  39406. @param newMaxValue the new minimum value to set - this will be snapped to the
  39407. nearest interval if one has been set.
  39408. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  39409. any Slider::Listeners or the valueChanged() method
  39410. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  39411. synchronously; if false, it will be asynchronous
  39412. @see setMaxValue, setMinValue, setValue
  39413. */
  39414. void setMinAndMaxValues (double newMinValue, double newMaxValue,
  39415. bool sendUpdateMessage = true,
  39416. bool sendMessageSynchronously = false);
  39417. /** A class for receiving callbacks from a Slider.
  39418. To be told when a slider's value changes, you can register a Slider::Listener
  39419. object using Slider::addListener().
  39420. @see Slider::addListener, Slider::removeListener
  39421. */
  39422. class JUCE_API Listener
  39423. {
  39424. public:
  39425. /** Destructor. */
  39426. virtual ~Listener() {}
  39427. /** Called when the slider's value is changed.
  39428. This may be caused by dragging it, or by typing in its text entry box,
  39429. or by a call to Slider::setValue().
  39430. You can find out the new value using Slider::getValue().
  39431. @see Slider::valueChanged
  39432. */
  39433. virtual void sliderValueChanged (Slider* slider) = 0;
  39434. /** Called when the slider is about to be dragged.
  39435. This is called when a drag begins, then it's followed by multiple calls
  39436. to sliderValueChanged(), and then sliderDragEnded() is called after the
  39437. user lets go.
  39438. @see sliderDragEnded, Slider::startedDragging
  39439. */
  39440. virtual void sliderDragStarted (Slider* slider);
  39441. /** Called after a drag operation has finished.
  39442. @see sliderDragStarted, Slider::stoppedDragging
  39443. */
  39444. virtual void sliderDragEnded (Slider* slider);
  39445. };
  39446. /** Adds a listener to be called when this slider's value changes. */
  39447. void addListener (Listener* listener);
  39448. /** Removes a previously-registered listener. */
  39449. void removeListener (Listener* listener);
  39450. /** This lets you choose whether double-clicking moves the slider to a given position.
  39451. By default this is turned off, but it's handy if you want a double-click to act
  39452. as a quick way of resetting a slider. Just pass in the value you want it to
  39453. go to when double-clicked.
  39454. @see getDoubleClickReturnValue
  39455. */
  39456. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  39457. double valueToSetOnDoubleClick);
  39458. /** Returns the values last set by setDoubleClickReturnValue() method.
  39459. Sets isEnabled to true if double-click is enabled, and returns the value
  39460. that was set.
  39461. @see setDoubleClickReturnValue
  39462. */
  39463. double getDoubleClickReturnValue (bool& isEnabled) const;
  39464. /** Tells the slider whether to keep sending change messages while the user
  39465. is dragging the slider.
  39466. If set to true, a change message will only be sent when the user has
  39467. dragged the slider and let go. If set to false (the default), then messages
  39468. will be continuously sent as they drag it while the mouse button is still
  39469. held down.
  39470. */
  39471. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  39472. /** This lets you change whether the slider thumb jumps to the mouse position
  39473. when you click.
  39474. By default, this is true. If it's false, then the slider moves with relative
  39475. motion when you drag it.
  39476. This only applies to linear bars, and won't affect two- or three- value
  39477. sliders.
  39478. */
  39479. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  39480. /** If enabled, this gives the slider a pop-up bubble which appears while the
  39481. slider is being dragged.
  39482. This can be handy if your slider doesn't have a text-box, so that users can
  39483. see the value just when they're changing it.
  39484. If you pass a component as the parentComponentToUse parameter, the pop-up
  39485. bubble will be added as a child of that component when it's needed. If you
  39486. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  39487. transparent window, so if you're using an OS that can't do transparent windows
  39488. you'll have to add it to a parent component instead).
  39489. */
  39490. void setPopupDisplayEnabled (bool isEnabled,
  39491. Component* parentComponentToUse);
  39492. /** If this is set to true, then right-clicking on the slider will pop-up
  39493. a menu to let the user change the way it works.
  39494. By default this is turned off, but when turned on, the menu will include
  39495. things like velocity sensitivity, and for rotary sliders, whether they
  39496. use a linear or rotary mouse-drag to move them.
  39497. */
  39498. void setPopupMenuEnabled (bool menuEnabled);
  39499. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  39500. By default it's enabled.
  39501. */
  39502. void setScrollWheelEnabled (bool enabled);
  39503. /** Returns a number to indicate which thumb is currently being dragged by the
  39504. mouse.
  39505. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  39506. the maximum-value thumb, or -1 if none is currently down.
  39507. */
  39508. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  39509. /** Callback to indicate that the user is about to start dragging the slider.
  39510. @see Slider::Listener::sliderDragStarted
  39511. */
  39512. virtual void startedDragging();
  39513. /** Callback to indicate that the user has just stopped dragging the slider.
  39514. @see Slider::Listener::sliderDragEnded
  39515. */
  39516. virtual void stoppedDragging();
  39517. /** Callback to indicate that the user has just moved the slider.
  39518. @see Slider::Listener::sliderValueChanged
  39519. */
  39520. virtual void valueChanged();
  39521. /** Subclasses can override this to convert a text string to a value.
  39522. When the user enters something into the text-entry box, this method is
  39523. called to convert it to a value.
  39524. The default routine just tries to convert it to a double.
  39525. @see getTextFromValue
  39526. */
  39527. virtual double getValueFromText (const String& text);
  39528. /** Turns the slider's current value into a text string.
  39529. Subclasses can override this to customise the formatting of the text-entry box.
  39530. The default implementation just turns the value into a string, using
  39531. a number of decimal places based on the range interval. If a suffix string
  39532. has been set using setTextValueSuffix(), this will be appended to the text.
  39533. @see getValueFromText
  39534. */
  39535. virtual const String getTextFromValue (double value);
  39536. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  39537. a string.
  39538. This is used by the default implementation of getTextFromValue(), and is just
  39539. appended to the numeric value. For more advanced formatting, you can override
  39540. getTextFromValue() and do something else.
  39541. */
  39542. void setTextValueSuffix (const String& suffix);
  39543. /** Returns the suffix that was set by setTextValueSuffix(). */
  39544. const String getTextValueSuffix() const;
  39545. /** Allows a user-defined mapping of distance along the slider to its value.
  39546. The default implementation for this performs the skewing operation that
  39547. can be set up in the setSkewFactor() method. Override it if you need
  39548. some kind of custom mapping instead, but make sure you also implement the
  39549. inverse function in valueToProportionOfLength().
  39550. @param proportion a value 0 to 1.0, indicating a distance along the slider
  39551. @returns the slider value that is represented by this position
  39552. @see valueToProportionOfLength
  39553. */
  39554. virtual double proportionOfLengthToValue (double proportion);
  39555. /** Allows a user-defined mapping of value to the position of the slider along its length.
  39556. The default implementation for this performs the skewing operation that
  39557. can be set up in the setSkewFactor() method. Override it if you need
  39558. some kind of custom mapping instead, but make sure you also implement the
  39559. inverse function in proportionOfLengthToValue().
  39560. @param value a valid slider value, between the range of values specified in
  39561. setRange()
  39562. @returns a value 0 to 1.0 indicating the distance along the slider that
  39563. represents this value
  39564. @see proportionOfLengthToValue
  39565. */
  39566. virtual double valueToProportionOfLength (double value);
  39567. /** Returns the X or Y coordinate of a value along the slider's length.
  39568. If the slider is horizontal, this will be the X coordinate of the given
  39569. value, relative to the left of the slider. If it's vertical, then this will
  39570. be the Y coordinate, relative to the top of the slider.
  39571. If the slider is rotary, this will throw an assertion and return 0. If the
  39572. value is out-of-range, it will be constrained to the length of the slider.
  39573. */
  39574. float getPositionOfValue (double value);
  39575. /** This can be overridden to allow the slider to snap to user-definable values.
  39576. If overridden, it will be called when the user tries to move the slider to
  39577. a given position, and allows a subclass to sanity-check this value, possibly
  39578. returning a different value to use instead.
  39579. @param attemptedValue the value the user is trying to enter
  39580. @param userIsDragging true if the user is dragging with the mouse; false if
  39581. they are entering the value using the text box
  39582. @returns the value to use instead
  39583. */
  39584. virtual double snapValue (double attemptedValue, bool userIsDragging);
  39585. /** This can be called to force the text box to update its contents.
  39586. (Not normally needed, as this is done automatically).
  39587. */
  39588. void updateText();
  39589. /** True if the slider moves horizontally. */
  39590. bool isHorizontal() const;
  39591. /** True if the slider moves vertically. */
  39592. bool isVertical() const;
  39593. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  39594. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39595. methods.
  39596. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39597. */
  39598. enum ColourIds
  39599. {
  39600. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  39601. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  39602. and feel class how this is used. */
  39603. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  39604. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  39605. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  39606. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  39607. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  39608. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  39609. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  39610. };
  39611. protected:
  39612. /** @internal */
  39613. void labelTextChanged (Label*);
  39614. /** @internal */
  39615. void paint (Graphics& g);
  39616. /** @internal */
  39617. void resized();
  39618. /** @internal */
  39619. void mouseDown (const MouseEvent& e);
  39620. /** @internal */
  39621. void mouseUp (const MouseEvent& e);
  39622. /** @internal */
  39623. void mouseDrag (const MouseEvent& e);
  39624. /** @internal */
  39625. void mouseDoubleClick (const MouseEvent& e);
  39626. /** @internal */
  39627. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39628. /** @internal */
  39629. void modifierKeysChanged (const ModifierKeys& modifiers);
  39630. /** @internal */
  39631. void buttonClicked (Button* button);
  39632. /** @internal */
  39633. void lookAndFeelChanged();
  39634. /** @internal */
  39635. void enablementChanged();
  39636. /** @internal */
  39637. void focusOfChildComponentChanged (FocusChangeType cause);
  39638. /** @internal */
  39639. void handleAsyncUpdate();
  39640. /** @internal */
  39641. void colourChanged();
  39642. /** @internal */
  39643. void valueChanged (Value& value);
  39644. /** Returns the best number of decimal places to use when displaying numbers.
  39645. This is calculated from the slider's interval setting.
  39646. */
  39647. int getNumDecimalPlacesToDisplay() const throw() { return numDecimalPlaces; }
  39648. private:
  39649. ListenerList <Listener> listeners;
  39650. Value currentValue, valueMin, valueMax;
  39651. double lastCurrentValue, lastValueMin, lastValueMax;
  39652. double minimum, maximum, interval, doubleClickReturnValue;
  39653. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  39654. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  39655. int velocityModeThreshold;
  39656. float rotaryStart, rotaryEnd;
  39657. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  39658. int mouseDragStartX, mouseDragStartY;
  39659. int sliderRegionStart, sliderRegionSize;
  39660. int sliderBeingDragged;
  39661. int pixelsForFullDragExtent;
  39662. Rectangle<int> sliderRect;
  39663. String textSuffix;
  39664. SliderStyle style;
  39665. TextEntryBoxPosition textBoxPos;
  39666. int textBoxWidth, textBoxHeight;
  39667. IncDecButtonMode incDecButtonMode;
  39668. bool editableText : 1, doubleClickToValue : 1;
  39669. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  39670. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  39671. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  39672. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  39673. ScopedPointer<Label> valueBox;
  39674. ScopedPointer<Button> incButton, decButton;
  39675. class PopupDisplayComponent;
  39676. friend class PopupDisplayComponent;
  39677. friend class ScopedPointer <PopupDisplayComponent>;
  39678. ScopedPointer <PopupDisplayComponent> popupDisplay;
  39679. Component* parentForPopupDisplay;
  39680. float getLinearSliderPos (double value);
  39681. void restoreMouseIfHidden();
  39682. void sendDragStart();
  39683. void sendDragEnd();
  39684. double constrainedValue (double value) const;
  39685. void triggerChangeMessage (bool synchronous);
  39686. bool incDecDragDirectionIsHorizontal() const;
  39687. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Slider);
  39688. };
  39689. /** This typedef is just for compatibility with old code - newer code should use the Slider::Listener class directly. */
  39690. typedef Slider::Listener SliderListener;
  39691. #if JUCE_VC6
  39692. #undef Listener
  39693. #endif
  39694. #endif // __JUCE_SLIDER_JUCEHEADER__
  39695. /*** End of inlined file: juce_Slider.h ***/
  39696. #endif
  39697. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  39698. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  39699. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  39700. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  39701. /**
  39702. A component that displays a strip of column headings for a table, and allows these
  39703. to be resized, dragged around, etc.
  39704. This is just the component that goes at the top of a table. You can use it
  39705. directly for custom components, or to create a simple table, use the
  39706. TableListBox class.
  39707. To use one of these, create it and use addColumn() to add all the columns that you need.
  39708. Each column must be given a unique ID number that's used to refer to it.
  39709. @see TableListBox, TableHeaderComponent::Listener
  39710. */
  39711. class JUCE_API TableHeaderComponent : public Component,
  39712. private AsyncUpdater
  39713. {
  39714. public:
  39715. /** Creates an empty table header.
  39716. */
  39717. TableHeaderComponent();
  39718. /** Destructor. */
  39719. ~TableHeaderComponent();
  39720. /** A combination of these flags are passed into the addColumn() method to specify
  39721. the properties of a column.
  39722. */
  39723. enum ColumnPropertyFlags
  39724. {
  39725. 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. */
  39726. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  39727. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  39728. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  39729. 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. */
  39730. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  39731. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  39732. /** This set of default flags is used as the default parameter value in addColumn(). */
  39733. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  39734. /** A quick way of combining flags for a column that's not resizable. */
  39735. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  39736. /** A quick way of combining flags for a column that's not resizable or sortable. */
  39737. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  39738. /** A quick way of combining flags for a column that's not sortable. */
  39739. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  39740. };
  39741. /** Adds a column to the table.
  39742. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  39743. registered listeners.
  39744. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  39745. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  39746. a unique ID. This is used to identify the column later on, after the user may have
  39747. changed the order that they appear in
  39748. @param width the initial width of the column, in pixels
  39749. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  39750. if the 'resizable' flag is specified for this column
  39751. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  39752. if the 'resizable' flag is specified for this column
  39753. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  39754. properties of this column
  39755. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  39756. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  39757. all columns, not just the index amongst those that are currently visible
  39758. */
  39759. void addColumn (const String& columnName,
  39760. int columnId,
  39761. int width,
  39762. int minimumWidth = 30,
  39763. int maximumWidth = -1,
  39764. int propertyFlags = defaultFlags,
  39765. int insertIndex = -1);
  39766. /** Removes a column with the given ID.
  39767. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  39768. registered listeners.
  39769. */
  39770. void removeColumn (int columnIdToRemove);
  39771. /** Deletes all columns from the table.
  39772. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  39773. registered listeners.
  39774. */
  39775. void removeAllColumns();
  39776. /** Returns the number of columns in the table.
  39777. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  39778. return the total number of columns, including hidden ones.
  39779. @see isColumnVisible
  39780. */
  39781. int getNumColumns (bool onlyCountVisibleColumns) const;
  39782. /** Returns the name for a column.
  39783. @see setColumnName
  39784. */
  39785. const String getColumnName (int columnId) const;
  39786. /** Changes the name of a column. */
  39787. void setColumnName (int columnId, const String& newName);
  39788. /** Moves a column to a different index in the table.
  39789. @param columnId the column to move
  39790. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  39791. */
  39792. void moveColumn (int columnId, int newVisibleIndex);
  39793. /** Returns the width of one of the columns.
  39794. */
  39795. int getColumnWidth (int columnId) const;
  39796. /** Changes the width of a column.
  39797. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  39798. */
  39799. void setColumnWidth (int columnId, int newWidth);
  39800. /** Shows or hides a column.
  39801. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  39802. @see isColumnVisible
  39803. */
  39804. void setColumnVisible (int columnId, bool shouldBeVisible);
  39805. /** Returns true if this column is currently visible.
  39806. @see setColumnVisible
  39807. */
  39808. bool isColumnVisible (int columnId) const;
  39809. /** Changes the column which is the sort column.
  39810. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  39811. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  39812. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  39813. @see getSortColumnId, isSortedForwards, reSortTable
  39814. */
  39815. void setSortColumnId (int columnId, bool sortForwards);
  39816. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  39817. @see setSortColumnId, isSortedForwards
  39818. */
  39819. int getSortColumnId() const;
  39820. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  39821. @see setSortColumnId
  39822. */
  39823. bool isSortedForwards() const;
  39824. /** Triggers a re-sort of the table according to the current sort-column.
  39825. If you modifiy the table's contents, you can call this to signal that the table needs
  39826. to be re-sorted.
  39827. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  39828. tableSortOrderChanged() method of any listeners).
  39829. */
  39830. void reSortTable();
  39831. /** Returns the total width of all the visible columns in the table.
  39832. */
  39833. int getTotalWidth() const;
  39834. /** Returns the index of a given column.
  39835. If there's no such column ID, this will return -1.
  39836. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  39837. otherwise it'll return the index amongst all the columns, including any hidden ones.
  39838. */
  39839. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  39840. /** Returns the ID of the column at a given index.
  39841. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  39842. otherwise it'll count it amongst all the columns, including any hidden ones.
  39843. If the index is out-of-range, it'll return 0.
  39844. */
  39845. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  39846. /** Returns the rectangle containing of one of the columns.
  39847. The index is an index from 0 to the number of columns that are currently visible (hidden
  39848. ones are not counted). It returns a rectangle showing the position of the column relative
  39849. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  39850. */
  39851. const Rectangle<int> getColumnPosition (int index) const;
  39852. /** Finds the column ID at a given x-position in the component.
  39853. If there is a column at this point this returns its ID, or if not, it will return 0.
  39854. */
  39855. int getColumnIdAtX (int xToFind) const;
  39856. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  39857. entire width of the component.
  39858. By default this is disabled. Turning it on also means that when resizing a column, those
  39859. on the right will be squashed to fit.
  39860. */
  39861. void setStretchToFitActive (bool shouldStretchToFit);
  39862. /** Returns true if stretch-to-fit has been enabled.
  39863. @see setStretchToFitActive
  39864. */
  39865. bool isStretchToFitActive() const;
  39866. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  39867. specified width, keeping their relative proportions the same.
  39868. If the minimum widths of the columns are too wide to fit into this space, it may
  39869. actually end up wider.
  39870. */
  39871. void resizeAllColumnsToFit (int targetTotalWidth);
  39872. /** Enables or disables the pop-up menu.
  39873. The default menu allows the user to show or hide columns. You can add custom
  39874. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  39875. By default the menu is enabled.
  39876. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  39877. */
  39878. void setPopupMenuActive (bool hasMenu);
  39879. /** Returns true if the pop-up menu is enabled.
  39880. @see setPopupMenuActive
  39881. */
  39882. bool isPopupMenuActive() const;
  39883. /** Returns a string that encapsulates the table's current layout.
  39884. This can be restored later using restoreFromString(). It saves the order of
  39885. the columns, the currently-sorted column, and the widths.
  39886. @see restoreFromString
  39887. */
  39888. const String toString() const;
  39889. /** Restores the state of the table, based on a string previously created with
  39890. toString().
  39891. @see toString
  39892. */
  39893. void restoreFromString (const String& storedVersion);
  39894. /**
  39895. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  39896. You can register one of these objects for table events using TableHeaderComponent::addListener()
  39897. and TableHeaderComponent::removeListener().
  39898. @see TableHeaderComponent
  39899. */
  39900. class JUCE_API Listener
  39901. {
  39902. public:
  39903. Listener() {}
  39904. /** Destructor. */
  39905. virtual ~Listener() {}
  39906. /** This is called when some of the table's columns are added, removed, hidden,
  39907. or rearranged.
  39908. */
  39909. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  39910. /** This is called when one or more of the table's columns are resized.
  39911. */
  39912. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  39913. /** This is called when the column by which the table should be sorted is changed.
  39914. */
  39915. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  39916. /** This is called when the user begins or ends dragging one of the columns around.
  39917. When the user starts dragging a column, this is called with the ID of that
  39918. column. When they finish dragging, it is called again with 0 as the ID.
  39919. */
  39920. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  39921. int columnIdNowBeingDragged);
  39922. };
  39923. /** Adds a listener to be informed about things that happen to the header. */
  39924. void addListener (Listener* newListener);
  39925. /** Removes a previously-registered listener. */
  39926. void removeListener (Listener* listenerToRemove);
  39927. /** This can be overridden to handle a mouse-click on one of the column headers.
  39928. The default implementation will use this click to call getSortColumnId() and
  39929. change the sort order.
  39930. */
  39931. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  39932. /** This can be overridden to add custom items to the pop-up menu.
  39933. If you override this, you should call the superclass's method to add its
  39934. column show/hide items, if you want them on the menu as well.
  39935. Then to handle the result, override reactToMenuItem().
  39936. @see reactToMenuItem
  39937. */
  39938. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  39939. /** Override this to handle any custom items that you have added to the
  39940. pop-up menu with an addMenuItems() override.
  39941. If the menuReturnId isn't one of your own custom menu items, you'll need to
  39942. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  39943. handle the items that it had added.
  39944. @see addMenuItems
  39945. */
  39946. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  39947. /** @internal */
  39948. void paint (Graphics& g);
  39949. /** @internal */
  39950. void resized();
  39951. /** @internal */
  39952. void mouseMove (const MouseEvent&);
  39953. /** @internal */
  39954. void mouseEnter (const MouseEvent&);
  39955. /** @internal */
  39956. void mouseExit (const MouseEvent&);
  39957. /** @internal */
  39958. void mouseDown (const MouseEvent&);
  39959. /** @internal */
  39960. void mouseDrag (const MouseEvent&);
  39961. /** @internal */
  39962. void mouseUp (const MouseEvent&);
  39963. /** @internal */
  39964. const MouseCursor getMouseCursor();
  39965. /** Can be overridden for more control over the pop-up menu behaviour. */
  39966. virtual void showColumnChooserMenu (int columnIdClicked);
  39967. private:
  39968. struct ColumnInfo
  39969. {
  39970. String name;
  39971. int id, propertyFlags, width, minimumWidth, maximumWidth;
  39972. double lastDeliberateWidth;
  39973. bool isVisible() const;
  39974. };
  39975. OwnedArray <ColumnInfo> columns;
  39976. Array <Listener*> listeners;
  39977. ScopedPointer <Component> dragOverlayComp;
  39978. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  39979. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  39980. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  39981. ColumnInfo* getInfoForId (int columnId) const;
  39982. int visibleIndexToTotalIndex (int visibleIndex) const;
  39983. void sendColumnsChanged();
  39984. void handleAsyncUpdate();
  39985. void beginDrag (const MouseEvent&);
  39986. void endDrag (int finalIndex);
  39987. int getResizeDraggerAt (int mouseX) const;
  39988. void updateColumnUnderMouse (int x, int y);
  39989. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  39990. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableHeaderComponent);
  39991. };
  39992. /** This typedef is just for compatibility with old code - newer code should use the TableHeaderComponent::Listener class directly. */
  39993. typedef TableHeaderComponent::Listener TableHeaderListener;
  39994. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  39995. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  39996. #endif
  39997. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  39998. /*** Start of inlined file: juce_TableListBox.h ***/
  39999. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  40000. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  40001. /**
  40002. One of these is used by a TableListBox as the data model for the table's contents.
  40003. The virtual methods that you override in this class take care of drawing the
  40004. table cells, and reacting to events.
  40005. @see TableListBox
  40006. */
  40007. class JUCE_API TableListBoxModel
  40008. {
  40009. public:
  40010. TableListBoxModel() {}
  40011. /** Destructor. */
  40012. virtual ~TableListBoxModel() {}
  40013. /** This must return the number of rows currently in the table.
  40014. If the number of rows changes, you must call TableListBox::updateContent() to
  40015. cause it to refresh the list.
  40016. */
  40017. virtual int getNumRows() = 0;
  40018. /** This must draw the background behind one of the rows in the table.
  40019. The graphics context has its origin at the row's top-left, and your method
  40020. should fill the area specified by the width and height parameters.
  40021. */
  40022. virtual void paintRowBackground (Graphics& g,
  40023. int rowNumber,
  40024. int width, int height,
  40025. bool rowIsSelected) = 0;
  40026. /** This must draw one of the cells.
  40027. The graphics context's origin will already be set to the top-left of the cell,
  40028. whose size is specified by (width, height).
  40029. */
  40030. virtual void paintCell (Graphics& g,
  40031. int rowNumber,
  40032. int columnId,
  40033. int width, int height,
  40034. bool rowIsSelected) = 0;
  40035. /** This is used to create or update a custom component to go in a cell.
  40036. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  40037. and handle mouse clicks with cellClicked().
  40038. This method will be called whenever a custom component might need to be updated - e.g.
  40039. when the table is changed, or TableListBox::updateContent() is called.
  40040. If you don't need a custom component for the specified cell, then return 0.
  40041. If you do want a custom component, and the existingComponentToUpdate is null, then
  40042. this method must create a new component suitable for the cell, and return it.
  40043. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  40044. by this method. In this case, the method must either update it to make sure it's correctly representing
  40045. the given cell (which may be different from the one that the component was created for), or it can
  40046. delete this component and return a new one.
  40047. */
  40048. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  40049. Component* existingComponentToUpdate);
  40050. /** This callback is made when the user clicks on one of the cells in the table.
  40051. The mouse event's coordinates will be relative to the entire table row.
  40052. @see cellDoubleClicked, backgroundClicked
  40053. */
  40054. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  40055. /** This callback is made when the user clicks on one of the cells in the table.
  40056. The mouse event's coordinates will be relative to the entire table row.
  40057. @see cellClicked, backgroundClicked
  40058. */
  40059. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  40060. /** This can be overridden to react to the user double-clicking on a part of the list where
  40061. there are no rows.
  40062. @see cellClicked
  40063. */
  40064. virtual void backgroundClicked();
  40065. /** This callback is made when the table's sort order is changed.
  40066. This could be because the user has clicked a column header, or because the
  40067. TableHeaderComponent::setSortColumnId() method was called.
  40068. If you implement this, your method should re-sort the table using the given
  40069. column as the key.
  40070. */
  40071. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  40072. /** Returns the best width for one of the columns.
  40073. If you implement this method, you should measure the width of all the items
  40074. in this column, and return the best size.
  40075. Returning 0 means that the column shouldn't be changed.
  40076. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  40077. */
  40078. virtual int getColumnAutoSizeWidth (int columnId);
  40079. /** Returns a tooltip for a particular cell in the table.
  40080. */
  40081. virtual const String getCellTooltip (int rowNumber, int columnId);
  40082. /** Override this to be informed when rows are selected or deselected.
  40083. @see ListBox::selectedRowsChanged()
  40084. */
  40085. virtual void selectedRowsChanged (int lastRowSelected);
  40086. /** Override this to be informed when the delete key is pressed.
  40087. @see ListBox::deleteKeyPressed()
  40088. */
  40089. virtual void deleteKeyPressed (int lastRowSelected);
  40090. /** Override this to be informed when the return key is pressed.
  40091. @see ListBox::returnKeyPressed()
  40092. */
  40093. virtual void returnKeyPressed (int lastRowSelected);
  40094. /** Override this to be informed when the list is scrolled.
  40095. This might be caused by the user moving the scrollbar, or by programmatic changes
  40096. to the list position.
  40097. */
  40098. virtual void listWasScrolled();
  40099. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  40100. If this returns a non-empty name then when the user drags a row, the table will try to
  40101. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  40102. drag-and-drop operation, using this string as the source description, and the listbox
  40103. itself as the source component.
  40104. @see DragAndDropContainer::startDragging
  40105. */
  40106. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  40107. };
  40108. /**
  40109. A table of cells, using a TableHeaderComponent as its header.
  40110. This component makes it easy to create a table by providing a TableListBoxModel as
  40111. the data source.
  40112. @see TableListBoxModel, TableHeaderComponent
  40113. */
  40114. class JUCE_API TableListBox : public ListBox,
  40115. private ListBoxModel,
  40116. private TableHeaderComponent::Listener
  40117. {
  40118. public:
  40119. /** Creates a TableListBox.
  40120. The model pointer passed-in can be null, in which case you can set it later
  40121. with setModel().
  40122. */
  40123. TableListBox (const String& componentName = String::empty,
  40124. TableListBoxModel* model = 0);
  40125. /** Destructor. */
  40126. ~TableListBox();
  40127. /** Changes the TableListBoxModel that is being used for this table.
  40128. */
  40129. void setModel (TableListBoxModel* newModel);
  40130. /** Returns the model currently in use. */
  40131. TableListBoxModel* getModel() const { return model; }
  40132. /** Returns the header component being used in this table. */
  40133. TableHeaderComponent& getHeader() const { return *header; }
  40134. /** Sets the header component to use for the table.
  40135. The table will take ownership of the component that you pass in, and will delete it
  40136. when it's no longer needed.
  40137. */
  40138. void setHeader (TableHeaderComponent* newHeader);
  40139. /** Changes the height of the table header component.
  40140. @see getHeaderHeight
  40141. */
  40142. void setHeaderHeight (int newHeight);
  40143. /** Returns the height of the table header.
  40144. @see setHeaderHeight
  40145. */
  40146. int getHeaderHeight() const;
  40147. /** Resizes a column to fit its contents.
  40148. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  40149. and applies that to the column.
  40150. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  40151. */
  40152. void autoSizeColumn (int columnId);
  40153. /** Calls autoSizeColumn() for all columns in the table. */
  40154. void autoSizeAllColumns();
  40155. /** Enables or disables the auto size options on the popup menu.
  40156. By default, these are enabled.
  40157. */
  40158. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  40159. /** True if the auto-size options should be shown on the menu.
  40160. @see setAutoSizeMenuOptionsShown
  40161. */
  40162. bool isAutoSizeMenuOptionShown() const;
  40163. /** Returns the position of one of the cells in the table.
  40164. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  40165. the table component's top-left. The row number isn't checked to see if it's
  40166. in-range, but the column ID must exist or this will return an empty rectangle.
  40167. If relativeToComponentTopLeft is false, the co-ords are relative to the
  40168. top-left of the table's top-left cell.
  40169. */
  40170. const Rectangle<int> getCellPosition (int columnId, int rowNumber,
  40171. bool relativeToComponentTopLeft) const;
  40172. /** Returns the component that currently represents a given cell.
  40173. If the component for this cell is off-screen or if the position is out-of-range,
  40174. this may return 0.
  40175. @see getCellPosition
  40176. */
  40177. Component* getCellComponent (int columnId, int rowNumber) const;
  40178. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  40179. @see ListBox::scrollToEnsureRowIsOnscreen
  40180. */
  40181. void scrollToEnsureColumnIsOnscreen (int columnId);
  40182. /** @internal */
  40183. int getNumRows();
  40184. /** @internal */
  40185. void paintListBoxItem (int, Graphics&, int, int, bool);
  40186. /** @internal */
  40187. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  40188. /** @internal */
  40189. void selectedRowsChanged (int lastRowSelected);
  40190. /** @internal */
  40191. void deleteKeyPressed (int currentSelectedRow);
  40192. /** @internal */
  40193. void returnKeyPressed (int currentSelectedRow);
  40194. /** @internal */
  40195. void backgroundClicked();
  40196. /** @internal */
  40197. void listWasScrolled();
  40198. /** @internal */
  40199. void tableColumnsChanged (TableHeaderComponent*);
  40200. /** @internal */
  40201. void tableColumnsResized (TableHeaderComponent*);
  40202. /** @internal */
  40203. void tableSortOrderChanged (TableHeaderComponent*);
  40204. /** @internal */
  40205. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  40206. /** @internal */
  40207. void resized();
  40208. private:
  40209. TableHeaderComponent* header;
  40210. TableListBoxModel* model;
  40211. int columnIdNowBeingDragged;
  40212. bool autoSizeOptionsShown;
  40213. void updateColumnComponents() const;
  40214. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBox);
  40215. };
  40216. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  40217. /*** End of inlined file: juce_TableListBox.h ***/
  40218. #endif
  40219. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  40220. #endif
  40221. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  40222. #endif
  40223. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  40224. #endif
  40225. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40226. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  40227. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40228. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40229. /**
  40230. A factory object which can create ToolbarItemComponent objects.
  40231. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  40232. that it can create.
  40233. Each type of item is identified by a unique ID, and multiple instances of an
  40234. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  40235. bars).
  40236. @see Toolbar, ToolbarItemComponent, ToolbarButton
  40237. */
  40238. class JUCE_API ToolbarItemFactory
  40239. {
  40240. public:
  40241. ToolbarItemFactory();
  40242. /** Destructor. */
  40243. virtual ~ToolbarItemFactory();
  40244. /** A set of reserved item ID values, used for the built-in item types.
  40245. */
  40246. enum SpecialItemIds
  40247. {
  40248. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  40249. can be placed between sets of items to break them into groups. */
  40250. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  40251. items.*/
  40252. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  40253. either side of it, filling any available space. */
  40254. };
  40255. /** Must return a list of the IDs for all the item types that this factory can create.
  40256. The ids should be added to the array that is passed-in.
  40257. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  40258. and the predefined IDs in the SpecialItemIds enum.
  40259. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  40260. to this list if you want your toolbar to be able to contain those items.
  40261. The list returned here is used by the ToolbarItemPalette class to obtain its list
  40262. of available items, and their order on the palette will reflect the order in which
  40263. they appear on this list.
  40264. @see ToolbarItemPalette
  40265. */
  40266. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  40267. /** Must return the set of items that should be added to a toolbar as its default set.
  40268. This method is used by Toolbar::addDefaultItems() to determine which items to
  40269. create.
  40270. The items that your method adds to the array that is passed-in will be added to the
  40271. toolbar in the same order. Items can appear in the list more than once.
  40272. */
  40273. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  40274. /** Must create an instance of one of the items that the factory lists in its
  40275. getAllToolbarItemIds() method.
  40276. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  40277. method, except for the built-in item types from the SpecialItemIds enum, which
  40278. are created internally by the toolbar code.
  40279. Try not to keep a pointer to the object that is returned, as it will be deleted
  40280. automatically by the toolbar, and remember that multiple instances of the same
  40281. item type are likely to exist at the same time.
  40282. */
  40283. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  40284. };
  40285. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  40286. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  40287. #endif
  40288. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  40289. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  40290. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  40291. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  40292. /**
  40293. A component containing a list of toolbar items, which the user can drag onto
  40294. a toolbar to add them.
  40295. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  40296. which automatically shows one of these in a dialog box with lots of extra controls.
  40297. @see Toolbar
  40298. */
  40299. class JUCE_API ToolbarItemPalette : public Component,
  40300. public DragAndDropContainer
  40301. {
  40302. public:
  40303. /** Creates a palette of items for a given factory, with the aim of adding them
  40304. to the specified toolbar.
  40305. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  40306. set of items that are shown in this palette.
  40307. The toolbar and factory must not be deleted while this object exists.
  40308. */
  40309. ToolbarItemPalette (ToolbarItemFactory& factory,
  40310. Toolbar* toolbar);
  40311. /** Destructor. */
  40312. ~ToolbarItemPalette();
  40313. /** @internal */
  40314. void resized();
  40315. private:
  40316. ToolbarItemFactory& factory;
  40317. Toolbar* toolbar;
  40318. Viewport viewport;
  40319. OwnedArray <ToolbarItemComponent> items;
  40320. friend class Toolbar;
  40321. void replaceComponent (ToolbarItemComponent* comp);
  40322. void addComponent (int itemId, int index);
  40323. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemPalette);
  40324. };
  40325. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  40326. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  40327. #endif
  40328. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  40329. /*** Start of inlined file: juce_TreeView.h ***/
  40330. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  40331. #define __JUCE_TREEVIEW_JUCEHEADER__
  40332. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  40333. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  40334. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  40335. /**
  40336. Components derived from this class can have files dropped onto them by an external application.
  40337. @see DragAndDropContainer
  40338. */
  40339. class JUCE_API FileDragAndDropTarget
  40340. {
  40341. public:
  40342. /** Destructor. */
  40343. virtual ~FileDragAndDropTarget() {}
  40344. /** Callback to check whether this target is interested in the set of files being offered.
  40345. Note that this will be called repeatedly when the user is dragging the mouse around over your
  40346. component, so don't do anything time-consuming in here, like opening the files to have a look
  40347. inside them!
  40348. @param files the set of (absolute) pathnames of the files that the user is dragging
  40349. @returns true if this component wants to receive the other callbacks regarging this
  40350. type of object; if it returns false, no other callbacks will be made.
  40351. */
  40352. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  40353. /** Callback to indicate that some files are being dragged over this component.
  40354. This gets called when the user moves the mouse into this component while dragging.
  40355. Use this callback as a trigger to make your component repaint itself to give the
  40356. user feedback about whether the files can be dropped here or not.
  40357. @param files the set of (absolute) pathnames of the files that the user is dragging
  40358. @param x the mouse x position, relative to this component
  40359. @param y the mouse y position, relative to this component
  40360. */
  40361. virtual void fileDragEnter (const StringArray& files, int x, int y);
  40362. /** Callback to indicate that the user is dragging some files over this component.
  40363. This gets called when the user moves the mouse over this component while dragging.
  40364. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  40365. this lets you know what happens in-between.
  40366. @param files the set of (absolute) pathnames of the files that the user is dragging
  40367. @param x the mouse x position, relative to this component
  40368. @param y the mouse y position, relative to this component
  40369. */
  40370. virtual void fileDragMove (const StringArray& files, int x, int y);
  40371. /** Callback to indicate that the mouse has moved away from this component.
  40372. This gets called when the user moves the mouse out of this component while dragging
  40373. the files.
  40374. If you've used fileDragEnter() to repaint your component and give feedback, use this
  40375. as a signal to repaint it in its normal state.
  40376. @param files the set of (absolute) pathnames of the files that the user is dragging
  40377. */
  40378. virtual void fileDragExit (const StringArray& files);
  40379. /** Callback to indicate that the user has dropped the files onto this component.
  40380. When the user drops the files, this get called, and you can use the files in whatever
  40381. way is appropriate.
  40382. Note that after this is called, the fileDragExit method may not be called, so you should
  40383. clean up in here if there's anything you need to do when the drag finishes.
  40384. @param files the set of (absolute) pathnames of the files that the user is dragging
  40385. @param x the mouse x position, relative to this component
  40386. @param y the mouse y position, relative to this component
  40387. */
  40388. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  40389. };
  40390. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  40391. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  40392. class TreeView;
  40393. /**
  40394. An item in a treeview.
  40395. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  40396. own sub-items.
  40397. To implement an item that contains sub-items, override the itemOpennessChanged()
  40398. method so that when it is opened, it adds the new sub-items to itself using the
  40399. addSubItem method. Depending on the nature of the item it might choose to only
  40400. do this the first time it's opened, or it might want to refresh itself each time.
  40401. It also has the option of deleting its sub-items when it is closed, or leaving them
  40402. in place.
  40403. */
  40404. class JUCE_API TreeViewItem
  40405. {
  40406. public:
  40407. /** Constructor. */
  40408. TreeViewItem();
  40409. /** Destructor. */
  40410. virtual ~TreeViewItem();
  40411. /** Returns the number of sub-items that have been added to this item.
  40412. Note that this doesn't mean much if the node isn't open.
  40413. @see getSubItem, mightContainSubItems, addSubItem
  40414. */
  40415. int getNumSubItems() const throw();
  40416. /** Returns one of the item's sub-items.
  40417. Remember that the object returned might get deleted at any time when its parent
  40418. item is closed or refreshed, depending on the nature of the items you're using.
  40419. @see getNumSubItems
  40420. */
  40421. TreeViewItem* getSubItem (int index) const throw();
  40422. /** Removes any sub-items. */
  40423. void clearSubItems();
  40424. /** Adds a sub-item.
  40425. @param newItem the object to add to the item's sub-item list. Once added, these can be
  40426. found using getSubItem(). When the items are later removed with
  40427. removeSubItem() (or when this item is deleted), they will be deleted.
  40428. @param insertPosition the index which the new item should have when it's added. If this
  40429. value is less than 0, the item will be added to the end of the list.
  40430. */
  40431. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  40432. /** Removes one of the sub-items.
  40433. @param index the item to remove
  40434. @param deleteItem if true, the item that is removed will also be deleted.
  40435. */
  40436. void removeSubItem (int index, bool deleteItem = true);
  40437. /** Returns the TreeView to which this item belongs. */
  40438. TreeView* getOwnerView() const throw() { return ownerView; }
  40439. /** Returns the item within which this item is contained. */
  40440. TreeViewItem* getParentItem() const throw() { return parentItem; }
  40441. /** True if this item is currently open in the treeview. */
  40442. bool isOpen() const throw();
  40443. /** Opens or closes the item.
  40444. When opened or closed, the item's itemOpennessChanged() method will be called,
  40445. and a subclass should use this callback to create and add any sub-items that
  40446. it needs to.
  40447. @see itemOpennessChanged, mightContainSubItems
  40448. */
  40449. void setOpen (bool shouldBeOpen);
  40450. /** True if this item is currently selected.
  40451. Use this when painting the node, to decide whether to draw it as selected or not.
  40452. */
  40453. bool isSelected() const throw();
  40454. /** Selects or deselects the item.
  40455. This will cause a callback to itemSelectionChanged()
  40456. */
  40457. void setSelected (bool shouldBeSelected,
  40458. bool deselectOtherItemsFirst);
  40459. /** Returns the rectangle that this item occupies.
  40460. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  40461. top-left of the TreeView comp, so this will depend on the scroll-position of
  40462. the tree. If false, it is relative to the top-left of the topmost item in the
  40463. tree (so this would be unaffected by scrolling the view).
  40464. */
  40465. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const throw();
  40466. /** Sends a signal to the treeview to make it refresh itself.
  40467. Call this if your items have changed and you want the tree to update to reflect
  40468. this.
  40469. */
  40470. void treeHasChanged() const throw();
  40471. /** Sends a repaint message to redraw just this item.
  40472. Note that you should only call this if you want to repaint a superficial change. If
  40473. you're altering the tree's nodes, you should instead call treeHasChanged().
  40474. */
  40475. void repaintItem() const;
  40476. /** Returns the row number of this item in the tree.
  40477. The row number of an item will change according to which items are open.
  40478. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  40479. */
  40480. int getRowNumberInTree() const throw();
  40481. /** Returns true if all the item's parent nodes are open.
  40482. This is useful to check whether the item might actually be visible or not.
  40483. */
  40484. bool areAllParentsOpen() const throw();
  40485. /** Changes whether lines are drawn to connect any sub-items to this item.
  40486. By default, line-drawing is turned on.
  40487. */
  40488. void setLinesDrawnForSubItems (bool shouldDrawLines) throw();
  40489. /** Tells the tree whether this item can potentially be opened.
  40490. If your item could contain sub-items, this should return true; if it returns
  40491. false then the tree will not try to open the item. This determines whether or
  40492. not the item will be drawn with a 'plus' button next to it.
  40493. */
  40494. virtual bool mightContainSubItems() = 0;
  40495. /** Returns a string to uniquely identify this item.
  40496. If you're planning on using the TreeView::getOpennessState() method, then
  40497. these strings will be used to identify which nodes are open. The string
  40498. should be unique amongst the item's sibling items, but it's ok for there
  40499. to be duplicates at other levels of the tree.
  40500. If you're not going to store the state, then it's ok not to bother implementing
  40501. this method.
  40502. */
  40503. virtual const String getUniqueName() const;
  40504. /** Called when an item is opened or closed.
  40505. When setOpen() is called and the item has specified that it might
  40506. have sub-items with the mightContainSubItems() method, this method
  40507. is called to let the item create or manage its sub-items.
  40508. So when this is called with isNowOpen set to true (i.e. when the item is being
  40509. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  40510. refresh its sub-item list.
  40511. When this is called with isNowOpen set to false, the subclass might want
  40512. to use clearSubItems() to save on space, or it might choose to leave them,
  40513. depending on the nature of the tree.
  40514. You could also use this callback as a trigger to start a background process
  40515. which asynchronously creates sub-items and adds them, if that's more
  40516. appropriate for the task in hand.
  40517. @see mightContainSubItems
  40518. */
  40519. virtual void itemOpennessChanged (bool isNowOpen);
  40520. /** Must return the width required by this item.
  40521. If your item needs to have a particular width in pixels, return that value; if
  40522. you'd rather have it just fill whatever space is available in the treeview,
  40523. return -1.
  40524. If all your items return -1, no horizontal scrollbar will be shown, but if any
  40525. items have fixed widths and extend beyond the width of the treeview, a
  40526. scrollbar will appear.
  40527. Each item can be a different width, but if they change width, you should call
  40528. treeHasChanged() to update the tree.
  40529. */
  40530. virtual int getItemWidth() const { return -1; }
  40531. /** Must return the height required by this item.
  40532. This is the height in pixels that the item will take up. Items in the tree
  40533. can be different heights, but if they change height, you should call
  40534. treeHasChanged() to update the tree.
  40535. */
  40536. virtual int getItemHeight() const { return 20; }
  40537. /** You can override this method to return false if you don't want to allow the
  40538. user to select this item.
  40539. */
  40540. virtual bool canBeSelected() const { return true; }
  40541. /** Creates a component that will be used to represent this item.
  40542. You don't have to implement this method - if it returns 0 then no component
  40543. will be used for the item, and you can just draw it using the paintItem()
  40544. callback. But if you do return a component, it will be positioned in the
  40545. treeview so that it can be used to represent this item.
  40546. The component returned will be managed by the treeview, so always return
  40547. a new component, and don't keep a reference to it, as the treeview will
  40548. delete it later when it goes off the screen or is no longer needed. Also
  40549. bear in mind that if the component keeps a reference to the item that
  40550. created it, that item could be deleted before the component. Its position
  40551. and size will be completely managed by the tree, so don't attempt to move it
  40552. around.
  40553. Something you may want to do with your component is to give it a pointer to
  40554. the TreeView that created it. This is perfectly safe, and there's no danger
  40555. of it becoming a dangling pointer because the TreeView will always delete
  40556. the component before it is itself deleted.
  40557. As long as you stick to these rules you can return whatever kind of
  40558. component you like. It's most useful if you're doing things like drag-and-drop
  40559. of items, or want to use a Label component to edit item names, etc.
  40560. */
  40561. virtual Component* createItemComponent() { return 0; }
  40562. /** Draws the item's contents.
  40563. You can choose to either implement this method and draw each item, or you
  40564. can use createItemComponent() to create a component that will represent the
  40565. item.
  40566. If all you need in your tree is to be able to draw the items and detect when
  40567. the user selects or double-clicks one of them, it's probably enough to
  40568. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  40569. complicated interactions, you may need to use createItemComponent() instead.
  40570. @param g the graphics context to draw into
  40571. @param width the width of the area available for drawing
  40572. @param height the height of the area available for drawing
  40573. */
  40574. virtual void paintItem (Graphics& g, int width, int height);
  40575. /** Draws the item's open/close button.
  40576. If you don't implement this method, the default behaviour is to
  40577. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  40578. it for custom effects.
  40579. */
  40580. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  40581. /** Called when the user clicks on this item.
  40582. If you're using createItemComponent() to create a custom component for the
  40583. item, the mouse-clicks might not make it through to the treeview, but this
  40584. is how you find out about clicks when just drawing each item individually.
  40585. The associated mouse-event details are passed in, so you can find out about
  40586. which button, where it was, etc.
  40587. @see itemDoubleClicked
  40588. */
  40589. virtual void itemClicked (const MouseEvent& e);
  40590. /** Called when the user double-clicks on this item.
  40591. If you're using createItemComponent() to create a custom component for the
  40592. item, the mouse-clicks might not make it through to the treeview, but this
  40593. is how you find out about clicks when just drawing each item individually.
  40594. The associated mouse-event details are passed in, so you can find out about
  40595. which button, where it was, etc.
  40596. If not overridden, the base class method here will open or close the item as
  40597. if the 'plus' button had been clicked.
  40598. @see itemClicked
  40599. */
  40600. virtual void itemDoubleClicked (const MouseEvent& e);
  40601. /** Called when the item is selected or deselected.
  40602. Use this if you want to do something special when the item's selectedness
  40603. changes. By default it'll get repainted when this happens.
  40604. */
  40605. virtual void itemSelectionChanged (bool isNowSelected);
  40606. /** The item can return a tool tip string here if it wants to.
  40607. @see TooltipClient
  40608. */
  40609. virtual const String getTooltip();
  40610. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  40611. If this returns a non-empty name then when the user drags an item, the treeview will
  40612. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  40613. a drag-and-drop operation, using this string as the source description, with the treeview
  40614. itself as the source component.
  40615. If you need more complex drag-and-drop behaviour, you can use custom components for
  40616. the items, and use those to trigger the drag.
  40617. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  40618. isInterestedInFileDrag(), etc.
  40619. @see DragAndDropContainer::startDragging
  40620. */
  40621. virtual const String getDragSourceDescription();
  40622. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  40623. method and return true.
  40624. If you return true and allow some files to be dropped, you'll also need to implement the
  40625. filesDropped() method to do something with them.
  40626. Note that this will be called often, so make your implementation very quick! There's
  40627. certainly no time to try opening the files and having a think about what's inside them!
  40628. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  40629. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  40630. */
  40631. virtual bool isInterestedInFileDrag (const StringArray& files);
  40632. /** When files are dropped into this item, this callback is invoked.
  40633. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  40634. The insertIndex value indicates where in the list of sub-items the files were dropped.
  40635. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  40636. */
  40637. virtual void filesDropped (const StringArray& files, int insertIndex);
  40638. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  40639. If you implement this method, you'll also need to implement itemDropped() in order to handle
  40640. the items when they are dropped.
  40641. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  40642. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  40643. */
  40644. virtual bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  40645. /** When a things are dropped into this item, this callback is invoked.
  40646. For this to work, you need to have also implemented isInterestedInDragSource().
  40647. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  40648. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  40649. */
  40650. virtual void itemDropped (const String& sourceDescription, Component* sourceComponent, int insertIndex);
  40651. /** Sets a flag to indicate that the item wants to be allowed
  40652. to draw all the way across to the left edge of the treeview.
  40653. By default this is false, which means that when the paintItem()
  40654. method is called, its graphics context is clipped to only allow
  40655. drawing within the item's rectangle. If this flag is set to true,
  40656. then the graphics context isn't clipped on its left side, so it
  40657. can draw all the way across to the left margin. Note that the
  40658. context will still have its origin in the same place though, so
  40659. the coordinates of anything to its left will be negative. It's
  40660. mostly useful if you want to draw a wider bar behind the
  40661. highlighted item.
  40662. */
  40663. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  40664. /** Saves the current state of open/closed nodes so it can be restored later.
  40665. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  40666. and records it as XML. To identify node objects it uses the
  40667. TreeViewItem::getUniqueName() method to create named paths. This
  40668. means that the same state of open/closed nodes can be restored to a
  40669. completely different instance of the tree, as long as it contains nodes
  40670. whose unique names are the same.
  40671. You'd normally want to use TreeView::getOpennessState() rather than call it
  40672. for a specific item, but this can be handy if you need to briefly save the state
  40673. for a section of the tree.
  40674. The caller is responsible for deleting the object that is returned.
  40675. @see TreeView::getOpennessState, restoreOpennessState
  40676. */
  40677. XmlElement* getOpennessState() const throw();
  40678. /** Restores the openness of this item and all its sub-items from a saved state.
  40679. See TreeView::restoreOpennessState for more details.
  40680. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  40681. for a specific item, but this can be handy if you need to briefly save the state
  40682. for a section of the tree.
  40683. @see TreeView::restoreOpennessState, getOpennessState
  40684. */
  40685. void restoreOpennessState (const XmlElement& xml) throw();
  40686. /** Returns the index of this item in its parent's sub-items. */
  40687. int getIndexInParent() const throw();
  40688. /** Returns true if this item is the last of its parent's sub-itens. */
  40689. bool isLastOfSiblings() const throw();
  40690. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  40691. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  40692. The string takes the form of a path, constructed from the getUniqueName() of this
  40693. item and all its parents, so these must all be correctly implemented for it to work.
  40694. @see TreeView::findItemFromIdentifierString, getUniqueName
  40695. */
  40696. const String getItemIdentifierString() const;
  40697. /**
  40698. This handy class takes a copy of a TreeViewItem's openness when you create it,
  40699. and restores that openness state when its destructor is called.
  40700. This can very handy when you're refreshing sub-items - e.g.
  40701. @code
  40702. void MyTreeViewItem::updateChildItems()
  40703. {
  40704. OpennessRestorer openness (*this); // saves the openness state here..
  40705. clearSubItems();
  40706. // add a bunch of sub-items here which may or may not be the same as the ones that
  40707. // were previously there
  40708. addSubItem (...
  40709. // ..and at this point, the old openness is restored, so any items that haven't
  40710. // changed will have their old openness retained.
  40711. }
  40712. @endcode
  40713. */
  40714. class OpennessRestorer
  40715. {
  40716. public:
  40717. OpennessRestorer (TreeViewItem& treeViewItem);
  40718. ~OpennessRestorer();
  40719. private:
  40720. TreeViewItem& treeViewItem;
  40721. ScopedPointer <XmlElement> oldOpenness;
  40722. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpennessRestorer);
  40723. };
  40724. private:
  40725. TreeView* ownerView;
  40726. TreeViewItem* parentItem;
  40727. OwnedArray <TreeViewItem> subItems;
  40728. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  40729. int uid;
  40730. bool selected : 1;
  40731. bool redrawNeeded : 1;
  40732. bool drawLinesInside : 1;
  40733. bool drawsInLeftMargin : 1;
  40734. unsigned int openness : 2;
  40735. friend class TreeView;
  40736. friend class TreeViewContentComponent;
  40737. void updatePositions (int newY);
  40738. int getIndentX() const throw();
  40739. void setOwnerView (TreeView* newOwner) throw();
  40740. void paintRecursively (Graphics& g, int width);
  40741. TreeViewItem* getTopLevelItem() throw();
  40742. TreeViewItem* findItemRecursively (int y) throw();
  40743. TreeViewItem* getDeepestOpenParentItem() throw();
  40744. int getNumRows() const throw();
  40745. TreeViewItem* getItemOnRow (int index) throw();
  40746. void deselectAllRecursively();
  40747. int countSelectedItemsRecursively (int depth) const throw();
  40748. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  40749. TreeViewItem* getNextVisibleItem (bool recurse) const throw();
  40750. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  40751. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewItem);
  40752. };
  40753. /**
  40754. A tree-view component.
  40755. Use one of these to hold and display a structure of TreeViewItem objects.
  40756. */
  40757. class JUCE_API TreeView : public Component,
  40758. public SettableTooltipClient,
  40759. public FileDragAndDropTarget,
  40760. public DragAndDropTarget,
  40761. private AsyncUpdater
  40762. {
  40763. public:
  40764. /** Creates an empty treeview.
  40765. Once you've got a treeview component, you'll need to give it something to
  40766. display, using the setRootItem() method.
  40767. */
  40768. TreeView (const String& componentName = String::empty);
  40769. /** Destructor. */
  40770. ~TreeView();
  40771. /** Sets the item that is displayed in the treeview.
  40772. A tree has a single root item which contains as many sub-items as it needs. If
  40773. you want the tree to contain a number of root items, you should still use a single
  40774. root item above these, but hide it using setRootItemVisible().
  40775. You can pass in 0 to this method to clear the tree and remove its current root item.
  40776. The object passed in will not be deleted by the treeview, it's up to the caller
  40777. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  40778. this item until you've removed it from the tree, either by calling setRootItem (0),
  40779. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  40780. to delete it.
  40781. */
  40782. void setRootItem (TreeViewItem* newRootItem);
  40783. /** Returns the tree's root item.
  40784. This will be the last object passed to setRootItem(), or 0 if none has been set.
  40785. */
  40786. TreeViewItem* getRootItem() const throw() { return rootItem; }
  40787. /** This will remove and delete the current root item.
  40788. It's a convenient way of deleting the item and calling setRootItem (0).
  40789. */
  40790. void deleteRootItem();
  40791. /** Changes whether the tree's root item is shown or not.
  40792. If the root item is hidden, only its sub-items will be shown in the treeview - this
  40793. lets you make the tree look as if it's got many root items. If it's hidden, this call
  40794. will also make sure the root item is open (otherwise the treeview would look empty).
  40795. */
  40796. void setRootItemVisible (bool shouldBeVisible);
  40797. /** Returns true if the root item is visible.
  40798. @see setRootItemVisible
  40799. */
  40800. bool isRootItemVisible() const throw() { return rootItemVisible; }
  40801. /** Sets whether items are open or closed by default.
  40802. Normally, items are closed until the user opens them, but you can use this
  40803. to make them default to being open until explicitly closed.
  40804. @see areItemsOpenByDefault
  40805. */
  40806. void setDefaultOpenness (bool isOpenByDefault);
  40807. /** Returns true if the tree's items default to being open.
  40808. @see setDefaultOpenness
  40809. */
  40810. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  40811. /** This sets a flag to indicate that the tree can be used for multi-selection.
  40812. You can always select multiple items internally by calling the
  40813. TreeViewItem::setSelected() method, but this flag indicates whether the user
  40814. is allowed to multi-select by clicking on the tree.
  40815. By default it is disabled.
  40816. @see isMultiSelectEnabled
  40817. */
  40818. void setMultiSelectEnabled (bool canMultiSelect);
  40819. /** Returns whether multi-select has been enabled for the tree.
  40820. @see setMultiSelectEnabled
  40821. */
  40822. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  40823. /** Sets a flag to indicate whether to hide the open/close buttons.
  40824. @see areOpenCloseButtonsVisible
  40825. */
  40826. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  40827. /** Returns whether open/close buttons are shown.
  40828. @see setOpenCloseButtonsVisible
  40829. */
  40830. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  40831. /** Deselects any items that are currently selected. */
  40832. void clearSelectedItems();
  40833. /** Returns the number of items that are currently selected.
  40834. If maximumDepthToSearchTo is >= 0, it lets you specify a maximum depth to which the
  40835. tree will be recursed.
  40836. @see getSelectedItem, clearSelectedItems
  40837. */
  40838. int getNumSelectedItems (int maximumDepthToSearchTo = -1) const throw();
  40839. /** Returns one of the selected items in the tree.
  40840. @param index the index, 0 to (getNumSelectedItems() - 1)
  40841. */
  40842. TreeViewItem* getSelectedItem (int index) const throw();
  40843. /** Returns the number of rows the tree is using.
  40844. This will depend on which items are open.
  40845. @see TreeViewItem::getRowNumberInTree()
  40846. */
  40847. int getNumRowsInTree() const;
  40848. /** Returns the item on a particular row of the tree.
  40849. If the index is out of range, this will return 0.
  40850. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  40851. */
  40852. TreeViewItem* getItemOnRow (int index) const;
  40853. /** Returns the item that contains a given y position.
  40854. The y is relative to the top of the TreeView component.
  40855. */
  40856. TreeViewItem* getItemAt (int yPosition) const throw();
  40857. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  40858. void scrollToKeepItemVisible (TreeViewItem* item);
  40859. /** Returns the treeview's Viewport object. */
  40860. Viewport* getViewport() const throw();
  40861. /** Returns the number of pixels by which each nested level of the tree is indented.
  40862. @see setIndentSize
  40863. */
  40864. int getIndentSize() const throw() { return indentSize; }
  40865. /** Changes the distance by which each nested level of the tree is indented.
  40866. @see getIndentSize
  40867. */
  40868. void setIndentSize (int newIndentSize);
  40869. /** Searches the tree for an item with the specified identifier.
  40870. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  40871. If no such item exists, this will return false. If the item is found, all of its items
  40872. will be automatically opened.
  40873. */
  40874. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  40875. /** Saves the current state of open/closed nodes so it can be restored later.
  40876. This takes a snapshot of which nodes have been explicitly opened or closed,
  40877. and records it as XML. To identify node objects it uses the
  40878. TreeViewItem::getUniqueName() method to create named paths. This
  40879. means that the same state of open/closed nodes can be restored to a
  40880. completely different instance of the tree, as long as it contains nodes
  40881. whose unique names are the same.
  40882. The caller is responsible for deleting the object that is returned.
  40883. @param alsoIncludeScrollPosition if this is true, the state will also
  40884. include information about where the
  40885. tree has been scrolled to vertically,
  40886. so this can also be restored
  40887. @see restoreOpennessState
  40888. */
  40889. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  40890. /** Restores a previously saved arrangement of open/closed nodes.
  40891. This will try to restore a snapshot of the tree's state that was created by
  40892. the getOpennessState() method. If any of the nodes named in the original
  40893. XML aren't present in this tree, they will be ignored.
  40894. @see getOpennessState
  40895. */
  40896. void restoreOpennessState (const XmlElement& newState);
  40897. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  40898. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40899. methods.
  40900. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40901. */
  40902. enum ColourIds
  40903. {
  40904. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  40905. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  40906. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  40907. };
  40908. /** @internal */
  40909. void paint (Graphics& g);
  40910. /** @internal */
  40911. void resized();
  40912. /** @internal */
  40913. bool keyPressed (const KeyPress& key);
  40914. /** @internal */
  40915. void colourChanged();
  40916. /** @internal */
  40917. void enablementChanged();
  40918. /** @internal */
  40919. bool isInterestedInFileDrag (const StringArray& files);
  40920. /** @internal */
  40921. void fileDragEnter (const StringArray& files, int x, int y);
  40922. /** @internal */
  40923. void fileDragMove (const StringArray& files, int x, int y);
  40924. /** @internal */
  40925. void fileDragExit (const StringArray& files);
  40926. /** @internal */
  40927. void filesDropped (const StringArray& files, int x, int y);
  40928. /** @internal */
  40929. bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  40930. /** @internal */
  40931. void itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y);
  40932. /** @internal */
  40933. void itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y);
  40934. /** @internal */
  40935. void itemDragExit (const String& sourceDescription, Component* sourceComponent);
  40936. /** @internal */
  40937. void itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y);
  40938. private:
  40939. friend class TreeViewItem;
  40940. friend class TreeViewContentComponent;
  40941. class TreeViewport;
  40942. class InsertPointHighlight;
  40943. class TargetGroupHighlight;
  40944. friend class ScopedPointer<TreeViewport>;
  40945. friend class ScopedPointer<InsertPointHighlight>;
  40946. friend class ScopedPointer<TargetGroupHighlight>;
  40947. ScopedPointer<TreeViewport> viewport;
  40948. CriticalSection nodeAlterationLock;
  40949. TreeViewItem* rootItem;
  40950. ScopedPointer<InsertPointHighlight> dragInsertPointHighlight;
  40951. ScopedPointer<TargetGroupHighlight> dragTargetGroupHighlight;
  40952. int indentSize;
  40953. bool defaultOpenness : 1;
  40954. bool needsRecalculating : 1;
  40955. bool rootItemVisible : 1;
  40956. bool multiSelectEnabled : 1;
  40957. bool openCloseButtonsVisible : 1;
  40958. void itemsChanged() throw();
  40959. void handleAsyncUpdate();
  40960. void moveSelectedRow (int delta);
  40961. void updateButtonUnderMouse (const MouseEvent& e);
  40962. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw();
  40963. void hideDragHighlight() throw();
  40964. void handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  40965. void handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  40966. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  40967. const StringArray& files, const String& sourceDescription,
  40968. Component* sourceComponent) const throw();
  40969. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeView);
  40970. };
  40971. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  40972. /*** End of inlined file: juce_TreeView.h ***/
  40973. #endif
  40974. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  40975. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  40976. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  40977. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  40978. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  40979. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  40980. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  40981. /*** Start of inlined file: juce_FileFilter.h ***/
  40982. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  40983. #define __JUCE_FILEFILTER_JUCEHEADER__
  40984. /**
  40985. Interface for deciding which files are suitable for something.
  40986. For example, this is used by DirectoryContentsList to select which files
  40987. go into the list.
  40988. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  40989. */
  40990. class JUCE_API FileFilter
  40991. {
  40992. public:
  40993. /** Creates a filter with the given description.
  40994. The description can be returned later with the getDescription() method.
  40995. */
  40996. FileFilter (const String& filterDescription);
  40997. /** Destructor. */
  40998. virtual ~FileFilter();
  40999. /** Returns the description that the filter was created with. */
  41000. const String& getDescription() const throw();
  41001. /** Should return true if this file is suitable for inclusion in whatever context
  41002. the object is being used.
  41003. */
  41004. virtual bool isFileSuitable (const File& file) const = 0;
  41005. /** Should return true if this directory is suitable for inclusion in whatever context
  41006. the object is being used.
  41007. */
  41008. virtual bool isDirectorySuitable (const File& file) const = 0;
  41009. protected:
  41010. String description;
  41011. };
  41012. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  41013. /*** End of inlined file: juce_FileFilter.h ***/
  41014. /**
  41015. A class to asynchronously scan for details about the files in a directory.
  41016. This keeps a list of files and some information about them, using a background
  41017. thread to scan for more files. As files are found, it broadcasts change messages
  41018. to tell any listeners.
  41019. @see FileListComponent, FileBrowserComponent
  41020. */
  41021. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  41022. public TimeSliceClient
  41023. {
  41024. public:
  41025. /** Creates a directory list.
  41026. To set the directory it should point to, use setDirectory(), which will
  41027. also start it scanning for files on the background thread.
  41028. When the background thread finds and adds new files to this list, the
  41029. ChangeBroadcaster class will send a change message, so you can register
  41030. listeners and update them when the list changes.
  41031. @param fileFilter an optional filter to select which files are
  41032. included in the list. If this is 0, then all files
  41033. and directories are included. Make sure that the
  41034. filter doesn't get deleted during the lifetime of this
  41035. object
  41036. @param threadToUse a thread object that this list can use
  41037. to scan for files as a background task. Make sure
  41038. that the thread you give it has been started, or you
  41039. won't get any files!
  41040. */
  41041. DirectoryContentsList (const FileFilter* fileFilter,
  41042. TimeSliceThread& threadToUse);
  41043. /** Destructor. */
  41044. ~DirectoryContentsList();
  41045. /** Sets the directory to look in for files.
  41046. If the directory that's passed in is different to the current one, this will
  41047. also start the background thread scanning it for files.
  41048. */
  41049. void setDirectory (const File& directory,
  41050. bool includeDirectories,
  41051. bool includeFiles);
  41052. /** Returns the directory that's currently being used. */
  41053. const File& getDirectory() const;
  41054. /** Clears the list, and stops the thread scanning for files. */
  41055. void clear();
  41056. /** Clears the list and restarts scanning the directory for files. */
  41057. void refresh();
  41058. /** True if the background thread hasn't yet finished scanning for files. */
  41059. bool isStillLoading() const;
  41060. /** Tells the list whether or not to ignore hidden files.
  41061. By default these are ignored.
  41062. */
  41063. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  41064. /** Returns true if hidden files are ignored.
  41065. @see setIgnoresHiddenFiles
  41066. */
  41067. bool ignoresHiddenFiles() const;
  41068. /** Contains cached information about one of the files in a DirectoryContentsList.
  41069. */
  41070. struct FileInfo
  41071. {
  41072. /** The filename.
  41073. This isn't a full pathname, it's just the last part of the path, same as you'd
  41074. get from File::getFileName().
  41075. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  41076. */
  41077. String filename;
  41078. /** File size in bytes. */
  41079. int64 fileSize;
  41080. /** File modification time.
  41081. As supplied by File::getLastModificationTime().
  41082. */
  41083. Time modificationTime;
  41084. /** File creation time.
  41085. As supplied by File::getCreationTime().
  41086. */
  41087. Time creationTime;
  41088. /** True if the file is a directory. */
  41089. bool isDirectory;
  41090. /** True if the file is read-only. */
  41091. bool isReadOnly;
  41092. };
  41093. /** Returns the number of files currently available in the list.
  41094. The info about one of these files can be retrieved with getFileInfo() or
  41095. getFile().
  41096. Obviously as the background thread runs and scans the directory for files, this
  41097. number will change.
  41098. @see getFileInfo, getFile
  41099. */
  41100. int getNumFiles() const;
  41101. /** Returns the cached information about one of the files in the list.
  41102. If the index is in-range, this will return true and will copy the file's details
  41103. to the structure that is passed-in.
  41104. If it returns false, then the index wasn't in range, and the structure won't
  41105. be affected.
  41106. @see getNumFiles, getFile
  41107. */
  41108. bool getFileInfo (int index, FileInfo& resultInfo) const;
  41109. /** Returns one of the files in the list.
  41110. @param index should be less than getNumFiles(). If this is out-of-range, the
  41111. return value will be File::nonexistent
  41112. @see getNumFiles, getFileInfo
  41113. */
  41114. const File getFile (int index) const;
  41115. /** Returns the file filter being used.
  41116. The filter is specified in the constructor.
  41117. */
  41118. const FileFilter* getFilter() const { return fileFilter; }
  41119. /** @internal */
  41120. int useTimeSlice();
  41121. /** @internal */
  41122. TimeSliceThread& getTimeSliceThread() { return thread; }
  41123. /** @internal */
  41124. static int compareElements (const DirectoryContentsList::FileInfo* first,
  41125. const DirectoryContentsList::FileInfo* second);
  41126. private:
  41127. File root;
  41128. const FileFilter* fileFilter;
  41129. TimeSliceThread& thread;
  41130. int fileTypeFlags;
  41131. CriticalSection fileListLock;
  41132. OwnedArray <FileInfo> files;
  41133. ScopedPointer <DirectoryIterator> fileFindHandle;
  41134. bool volatile shouldStop;
  41135. void changed();
  41136. bool checkNextFile (bool& hasChanged);
  41137. bool addFile (const File& file, bool isDir,
  41138. const int64 fileSize, const Time& modTime,
  41139. const Time& creationTime, bool isReadOnly);
  41140. void setTypeFlags (int newFlags);
  41141. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsList);
  41142. };
  41143. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41144. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  41145. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  41146. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41147. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41148. /**
  41149. A listener for user selection events in a file browser.
  41150. This is used by a FileBrowserComponent or FileListComponent.
  41151. */
  41152. class JUCE_API FileBrowserListener
  41153. {
  41154. public:
  41155. /** Destructor. */
  41156. virtual ~FileBrowserListener();
  41157. /** Callback when the user selects a different file in the browser. */
  41158. virtual void selectionChanged() = 0;
  41159. /** Callback when the user clicks on a file in the browser. */
  41160. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  41161. /** Callback when the user double-clicks on a file in the browser. */
  41162. virtual void fileDoubleClicked (const File& file) = 0;
  41163. };
  41164. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41165. /*** End of inlined file: juce_FileBrowserListener.h ***/
  41166. /**
  41167. A base class for components that display a list of the files in a directory.
  41168. @see DirectoryContentsList
  41169. */
  41170. class JUCE_API DirectoryContentsDisplayComponent
  41171. {
  41172. public:
  41173. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  41174. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  41175. /** Destructor. */
  41176. virtual ~DirectoryContentsDisplayComponent();
  41177. /** Returns the number of files the user has got selected.
  41178. @see getSelectedFile
  41179. */
  41180. virtual int getNumSelectedFiles() const = 0;
  41181. /** Returns one of the files that the user has currently selected.
  41182. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  41183. @see getNumSelectedFiles
  41184. */
  41185. virtual const File getSelectedFile (int index) const = 0;
  41186. /** Deselects any selected files. */
  41187. virtual void deselectAllFiles() = 0;
  41188. /** Scrolls this view to the top. */
  41189. virtual void scrollToTop() = 0;
  41190. /** Adds a listener to be told when files are selected or clicked.
  41191. @see removeListener
  41192. */
  41193. void addListener (FileBrowserListener* listener);
  41194. /** Removes a listener.
  41195. @see addListener
  41196. */
  41197. void removeListener (FileBrowserListener* listener);
  41198. /** A set of colour IDs to use to change the colour of various aspects of the list.
  41199. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41200. methods.
  41201. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41202. */
  41203. enum ColourIds
  41204. {
  41205. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  41206. textColourId = 0x1000541, /**< The colour for the text. */
  41207. };
  41208. /** @internal */
  41209. void sendSelectionChangeMessage();
  41210. /** @internal */
  41211. void sendDoubleClickMessage (const File& file);
  41212. /** @internal */
  41213. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  41214. protected:
  41215. DirectoryContentsList& fileList;
  41216. ListenerList <FileBrowserListener> listeners;
  41217. private:
  41218. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsDisplayComponent);
  41219. };
  41220. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  41221. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  41222. #endif
  41223. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  41224. #endif
  41225. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  41226. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  41227. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  41228. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  41229. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  41230. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  41231. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  41232. /**
  41233. Base class for components that live inside a file chooser dialog box and
  41234. show previews of the files that get selected.
  41235. One of these allows special extra information to be displayed for files
  41236. in a dialog box as the user selects them. Each time the current file or
  41237. directory is changed, the selectedFileChanged() method will be called
  41238. to allow it to update itself appropriately.
  41239. @see FileChooser, ImagePreviewComponent
  41240. */
  41241. class JUCE_API FilePreviewComponent : public Component
  41242. {
  41243. public:
  41244. /** Creates a FilePreviewComponent. */
  41245. FilePreviewComponent();
  41246. /** Destructor. */
  41247. ~FilePreviewComponent();
  41248. /** Called to indicate that the user's currently selected file has changed.
  41249. @param newSelectedFile the newly selected file or directory, which may be
  41250. File::nonexistent if none is selected.
  41251. */
  41252. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  41253. private:
  41254. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilePreviewComponent);
  41255. };
  41256. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  41257. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  41258. /**
  41259. A component for browsing and selecting a file or directory to open or save.
  41260. This contains a FileListComponent and adds various boxes and controls for
  41261. navigating and selecting a file. It can work in different modes so that it can
  41262. be used for loading or saving a file, or for choosing a directory.
  41263. @see FileChooserDialogBox, FileChooser, FileListComponent
  41264. */
  41265. class JUCE_API FileBrowserComponent : public Component,
  41266. public ChangeBroadcaster,
  41267. private FileBrowserListener,
  41268. private TextEditorListener,
  41269. private ButtonListener,
  41270. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  41271. private FileFilter
  41272. {
  41273. public:
  41274. /** Various options for the browser.
  41275. A combination of these is passed into the FileBrowserComponent constructor.
  41276. */
  41277. enum FileChooserFlags
  41278. {
  41279. openMode = 1, /**< specifies that the component should allow the user to
  41280. choose an existing file with the intention of opening it. */
  41281. saveMode = 2, /**< specifies that the component should allow the user to specify
  41282. the name of a file that will be used to save something. */
  41283. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  41284. conjunction with canSelectDirectories). */
  41285. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  41286. conjuction with canSelectFiles). */
  41287. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  41288. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  41289. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  41290. };
  41291. /** Creates a FileBrowserComponent.
  41292. @param flags A combination of flags from the FileChooserFlags enumeration,
  41293. used to specify the component's behaviour. The flags must contain
  41294. either openMode or saveMode, and canSelectFiles and/or
  41295. canSelectDirectories.
  41296. @param initialFileOrDirectory The file or directory that should be selected when
  41297. the component begins. If this is File::nonexistent,
  41298. a default directory will be chosen.
  41299. @param fileFilter an optional filter to use to determine which files
  41300. are shown. If this is 0 then all files are displayed. Note
  41301. that a pointer is kept internally to this object, so
  41302. make sure that it is not deleted before the browser object
  41303. is deleted.
  41304. @param previewComp an optional preview component that will be used to
  41305. show previews of files that the user selects
  41306. */
  41307. FileBrowserComponent (int flags,
  41308. const File& initialFileOrDirectory,
  41309. const FileFilter* fileFilter,
  41310. FilePreviewComponent* previewComp);
  41311. /** Destructor. */
  41312. ~FileBrowserComponent();
  41313. /** Returns the number of files that the user has got selected.
  41314. If multiple select isn't active, this will only be 0 or 1. To get the complete
  41315. list of files they've chosen, pass an index to getCurrentFile().
  41316. */
  41317. int getNumSelectedFiles() const throw();
  41318. /** Returns one of the files that the user has chosen.
  41319. If the box has multi-select enabled, the index lets you specify which of the files
  41320. to get - see getNumSelectedFiles() to find out how many files were chosen.
  41321. @see getHighlightedFile
  41322. */
  41323. const File getSelectedFile (int index) const throw();
  41324. /** Deselects any files that are currently selected.
  41325. */
  41326. void deselectAllFiles();
  41327. /** Returns true if the currently selected file(s) are usable.
  41328. This can be used to decide whether the user can press "ok" for the
  41329. current file. What it does depends on the mode, so for example in an "open"
  41330. mode, this only returns true if a file has been selected and if it exists.
  41331. In a "save" mode, a non-existent file would also be valid.
  41332. */
  41333. bool currentFileIsValid() const;
  41334. /** This returns the last item in the view that the user has highlighted.
  41335. This may be different from getCurrentFile(), which returns the value
  41336. that is shown in the filename box, and if there are multiple selections,
  41337. this will only return one of them.
  41338. @see getSelectedFile
  41339. */
  41340. const File getHighlightedFile() const throw();
  41341. /** Returns the directory whose contents are currently being shown in the listbox. */
  41342. const File getRoot() const;
  41343. /** Changes the directory that's being shown in the listbox. */
  41344. void setRoot (const File& newRootDirectory);
  41345. /** Equivalent to pressing the "up" button to browse the parent directory. */
  41346. void goUp();
  41347. /** Refreshes the directory that's currently being listed. */
  41348. void refresh();
  41349. /** Changes the filter that's being used to sift the files. */
  41350. void setFileFilter (const FileFilter* newFileFilter);
  41351. /** Returns a verb to describe what should happen when the file is accepted.
  41352. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  41353. mode, it'll be "Save", etc.
  41354. */
  41355. virtual const String getActionVerb() const;
  41356. /** Returns true if the saveMode flag was set when this component was created.
  41357. */
  41358. bool isSaveMode() const throw();
  41359. /** Adds a listener to be told when the user selects and clicks on files.
  41360. @see removeListener
  41361. */
  41362. void addListener (FileBrowserListener* listener);
  41363. /** Removes a listener.
  41364. @see addListener
  41365. */
  41366. void removeListener (FileBrowserListener* listener);
  41367. /** @internal */
  41368. void resized();
  41369. /** @internal */
  41370. void buttonClicked (Button* b);
  41371. /** @internal */
  41372. void comboBoxChanged (ComboBox*);
  41373. /** @internal */
  41374. void textEditorTextChanged (TextEditor& editor);
  41375. /** @internal */
  41376. void textEditorReturnKeyPressed (TextEditor& editor);
  41377. /** @internal */
  41378. void textEditorEscapeKeyPressed (TextEditor& editor);
  41379. /** @internal */
  41380. void textEditorFocusLost (TextEditor& editor);
  41381. /** @internal */
  41382. bool keyPressed (const KeyPress& key);
  41383. /** @internal */
  41384. void selectionChanged();
  41385. /** @internal */
  41386. void fileClicked (const File& f, const MouseEvent& e);
  41387. /** @internal */
  41388. void fileDoubleClicked (const File& f);
  41389. /** @internal */
  41390. bool isFileSuitable (const File& file) const;
  41391. /** @internal */
  41392. bool isDirectorySuitable (const File&) const;
  41393. /** @internal */
  41394. FilePreviewComponent* getPreviewComponent() const throw();
  41395. protected:
  41396. /** Returns a list of names and paths for the default places the user might want to look.
  41397. Use an empty string to indicate a section break.
  41398. */
  41399. virtual void getRoots (StringArray& rootNames, StringArray& rootPaths);
  41400. private:
  41401. ScopedPointer <DirectoryContentsList> fileList;
  41402. const FileFilter* fileFilter;
  41403. int flags;
  41404. File currentRoot;
  41405. Array<File> chosenFiles;
  41406. ListenerList <FileBrowserListener> listeners;
  41407. ScopedPointer<DirectoryContentsDisplayComponent> fileListComponent;
  41408. FilePreviewComponent* previewComp;
  41409. ComboBox currentPathBox;
  41410. TextEditor filenameBox;
  41411. Label fileLabel;
  41412. ScopedPointer<Button> goUpButton;
  41413. TimeSliceThread thread;
  41414. void sendListenerChangeMessage();
  41415. bool isFileOrDirSuitable (const File& f) const;
  41416. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBrowserComponent);
  41417. };
  41418. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  41419. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  41420. #endif
  41421. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  41422. #endif
  41423. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  41424. /*** Start of inlined file: juce_FileChooser.h ***/
  41425. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  41426. #define __JUCE_FILECHOOSER_JUCEHEADER__
  41427. /**
  41428. Creates a dialog box to choose a file or directory to load or save.
  41429. To use a FileChooser:
  41430. - create one (as a local stack variable is the neatest way)
  41431. - call one of its browseFor.. methods
  41432. - if this returns true, the user has selected a file, so you can retrieve it
  41433. with the getResult() method.
  41434. e.g. @code
  41435. void loadMooseFile()
  41436. {
  41437. FileChooser myChooser ("Please select the moose you want to load...",
  41438. File::getSpecialLocation (File::userHomeDirectory),
  41439. "*.moose");
  41440. if (myChooser.browseForFileToOpen())
  41441. {
  41442. File mooseFile (myChooser.getResult());
  41443. loadMoose (mooseFile);
  41444. }
  41445. }
  41446. @endcode
  41447. */
  41448. class JUCE_API FileChooser
  41449. {
  41450. public:
  41451. /** Creates a FileChooser.
  41452. After creating one of these, use one of the browseFor... methods to display it.
  41453. @param dialogBoxTitle a text string to display in the dialog box to
  41454. tell the user what's going on
  41455. @param initialFileOrDirectory the file or directory that should be selected when
  41456. the dialog box opens. If this parameter is set to
  41457. File::nonexistent, a sensible default directory
  41458. will be used instead.
  41459. @param filePatternsAllowed a set of file patterns to specify which files can be
  41460. selected - each pattern should be separated by a
  41461. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  41462. empty string means that all files are allowed
  41463. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  41464. possible; if false, then a Juce-based browser dialog
  41465. box will always be used
  41466. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  41467. */
  41468. FileChooser (const String& dialogBoxTitle,
  41469. const File& initialFileOrDirectory = File::nonexistent,
  41470. const String& filePatternsAllowed = String::empty,
  41471. bool useOSNativeDialogBox = true);
  41472. /** Destructor. */
  41473. ~FileChooser();
  41474. /** Shows a dialog box to choose a file to open.
  41475. This will display the dialog box modally, using an "open file" mode, so that
  41476. it won't allow non-existent files or directories to be chosen.
  41477. @param previewComponent an optional component to display inside the dialog
  41478. box to show special info about the files that the user
  41479. is browsing. The component will not be deleted by this
  41480. object, so the caller must take care of it.
  41481. @returns true if the user selected a file, in which case, use the getResult()
  41482. method to find out what it was. Returns false if they cancelled instead.
  41483. @see browseForFileToSave, browseForDirectory
  41484. */
  41485. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  41486. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  41487. The files that are returned can be obtained by calling getResults(). See
  41488. browseForFileToOpen() for more info about the behaviour of this method.
  41489. */
  41490. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  41491. /** Shows a dialog box to choose a file to save.
  41492. This will display the dialog box modally, using an "save file" mode, so it
  41493. will allow non-existent files to be chosen, but not directories.
  41494. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  41495. the user if they're sure they want to overwrite a file that already
  41496. exists
  41497. @returns true if the user chose a file and pressed 'ok', in which case, use
  41498. the getResult() method to find out what the file was. Returns false
  41499. if they cancelled instead.
  41500. @see browseForFileToOpen, browseForDirectory
  41501. */
  41502. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  41503. /** Shows a dialog box to choose a directory.
  41504. This will display the dialog box modally, using an "open directory" mode, so it
  41505. will only allow directories to be returned, not files.
  41506. @returns true if the user chose a directory and pressed 'ok', in which case, use
  41507. the getResult() method to find out what they chose. Returns false
  41508. if they cancelled instead.
  41509. @see browseForFileToOpen, browseForFileToSave
  41510. */
  41511. bool browseForDirectory();
  41512. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  41513. The files that are returned can be obtained by calling getResults(). See
  41514. browseForFileToOpen() for more info about the behaviour of this method.
  41515. */
  41516. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  41517. /** Returns the last file that was chosen by one of the browseFor methods.
  41518. After calling the appropriate browseFor... method, this method lets you
  41519. find out what file or directory they chose.
  41520. Note that the file returned is only valid if the browse method returned true (i.e.
  41521. if the user pressed 'ok' rather than cancelling).
  41522. If you're using a multiple-file select, then use the getResults() method instead,
  41523. to obtain the list of all files chosen.
  41524. @see getResults
  41525. */
  41526. const File getResult() const;
  41527. /** Returns a list of all the files that were chosen during the last call to a
  41528. browse method.
  41529. This array may be empty if no files were chosen, or can contain multiple entries
  41530. if multiple files were chosen.
  41531. @see getResult
  41532. */
  41533. const Array<File>& getResults() const;
  41534. private:
  41535. String title, filters;
  41536. File startingFile;
  41537. Array<File> results;
  41538. bool useNativeDialogBox;
  41539. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  41540. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  41541. FilePreviewComponent* previewComponent);
  41542. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  41543. const String& filters, bool selectsDirectories, bool selectsFiles,
  41544. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  41545. FilePreviewComponent* previewComponent);
  41546. JUCE_LEAK_DETECTOR (FileChooser);
  41547. };
  41548. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  41549. /*** End of inlined file: juce_FileChooser.h ***/
  41550. #endif
  41551. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  41552. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  41553. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  41554. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  41555. /*** Start of inlined file: juce_ResizableWindow.h ***/
  41556. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  41557. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  41558. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  41559. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  41560. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  41561. /*** Start of inlined file: juce_DropShadower.h ***/
  41562. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  41563. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  41564. /**
  41565. Adds a drop-shadow to a component.
  41566. This object creates and manages a set of components which sit around a
  41567. component, creating a gaussian shadow around it. The components will track
  41568. the position of the component and if it's brought to the front they'll also
  41569. follow this.
  41570. For desktop windows you don't need to use this class directly - just
  41571. set the Component::windowHasDropShadow flag when calling
  41572. Component::addToDesktop(), and the system will create one of these if it's
  41573. needed (which it obviously isn't on the Mac, for example).
  41574. */
  41575. class JUCE_API DropShadower : public ComponentListener
  41576. {
  41577. public:
  41578. /** Creates a DropShadower.
  41579. @param alpha the opacity of the shadows, from 0 to 1.0
  41580. @param xOffset the horizontal displacement of the shadow, in pixels
  41581. @param yOffset the vertical displacement of the shadow, in pixels
  41582. @param blurRadius the radius of the blur to use for creating the shadow
  41583. */
  41584. DropShadower (float alpha = 0.5f,
  41585. int xOffset = 1,
  41586. int yOffset = 5,
  41587. float blurRadius = 10.0f);
  41588. /** Destructor. */
  41589. virtual ~DropShadower();
  41590. /** Attaches the DropShadower to the component you want to shadow. */
  41591. void setOwner (Component* componentToFollow);
  41592. /** @internal */
  41593. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  41594. /** @internal */
  41595. void componentBroughtToFront (Component& component);
  41596. /** @internal */
  41597. void componentParentHierarchyChanged (Component& component);
  41598. /** @internal */
  41599. void componentVisibilityChanged (Component& component);
  41600. private:
  41601. Component* owner;
  41602. OwnedArray<Component> shadowWindows;
  41603. Image shadowImageSections[12];
  41604. const int xOffset, yOffset;
  41605. const float alpha, blurRadius;
  41606. bool reentrant;
  41607. void updateShadows();
  41608. void setShadowImage (const Image& src, int num, int w, int h, int sx, int sy);
  41609. void bringShadowWindowsToFront();
  41610. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DropShadower);
  41611. };
  41612. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  41613. /*** End of inlined file: juce_DropShadower.h ***/
  41614. /**
  41615. A base class for top-level windows.
  41616. This class is used for components that are considered a major part of your
  41617. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  41618. etc. Things like menus that pop up briefly aren't derived from it.
  41619. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  41620. could itself be the child of another component.
  41621. The class manages a list of all instances of top-level windows that are in use,
  41622. and each one is also given the concept of being "active". The active window is
  41623. one that is actively being used by the user. This isn't quite the same as the
  41624. component with the keyboard focus, because there may be a popup menu or other
  41625. temporary window which gets keyboard focus while the active top level window is
  41626. unchanged.
  41627. A top-level window also has an optional drop-shadow.
  41628. @see ResizableWindow, DocumentWindow, DialogWindow
  41629. */
  41630. class JUCE_API TopLevelWindow : public Component
  41631. {
  41632. public:
  41633. /** Creates a TopLevelWindow.
  41634. @param name the name to give the component
  41635. @param addToDesktop if true, the window will be automatically added to the
  41636. desktop; if false, you can use it as a child component
  41637. */
  41638. TopLevelWindow (const String& name, bool addToDesktop);
  41639. /** Destructor. */
  41640. ~TopLevelWindow();
  41641. /** True if this is currently the TopLevelWindow that is actively being used.
  41642. This isn't quite the same as having keyboard focus, because the focus may be
  41643. on a child component or a temporary pop-up menu, etc, while this window is
  41644. still considered to be active.
  41645. @see activeWindowStatusChanged
  41646. */
  41647. bool isActiveWindow() const throw() { return windowIsActive_; }
  41648. /** This will set the bounds of the window so that it's centred in front of another
  41649. window.
  41650. If your app has a few windows open and want to pop up a dialog box for one of
  41651. them, you can use this to show it in front of the relevent parent window, which
  41652. is a bit neater than just having it appear in the middle of the screen.
  41653. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  41654. be used instead. If no window is focused, it'll just default to the middle of the
  41655. screen.
  41656. */
  41657. void centreAroundComponent (Component* componentToCentreAround,
  41658. int width, int height);
  41659. /** Turns the drop-shadow on and off. */
  41660. void setDropShadowEnabled (bool useShadow);
  41661. /** Sets whether an OS-native title bar will be used, or a Juce one.
  41662. @see isUsingNativeTitleBar
  41663. */
  41664. void setUsingNativeTitleBar (bool useNativeTitleBar);
  41665. /** Returns true if the window is currently using an OS-native title bar.
  41666. @see setUsingNativeTitleBar
  41667. */
  41668. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  41669. /** Returns the number of TopLevelWindow objects currently in use.
  41670. @see getTopLevelWindow
  41671. */
  41672. static int getNumTopLevelWindows() throw();
  41673. /** Returns one of the TopLevelWindow objects currently in use.
  41674. The index is 0 to (getNumTopLevelWindows() - 1).
  41675. */
  41676. static TopLevelWindow* getTopLevelWindow (int index) throw();
  41677. /** Returns the currently-active top level window.
  41678. There might not be one, of course, so this can return 0.
  41679. */
  41680. static TopLevelWindow* getActiveTopLevelWindow() throw();
  41681. /** @internal */
  41682. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  41683. protected:
  41684. /** This callback happens when this window becomes active or inactive.
  41685. @see isActiveWindow
  41686. */
  41687. virtual void activeWindowStatusChanged();
  41688. /** @internal */
  41689. void focusOfChildComponentChanged (FocusChangeType cause);
  41690. /** @internal */
  41691. void parentHierarchyChanged();
  41692. /** @internal */
  41693. virtual int getDesktopWindowStyleFlags() const;
  41694. /** @internal */
  41695. void recreateDesktopWindow();
  41696. /** @internal */
  41697. void visibilityChanged();
  41698. private:
  41699. friend class TopLevelWindowManager;
  41700. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  41701. ScopedPointer <DropShadower> shadower;
  41702. void setWindowActive (bool isNowActive);
  41703. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TopLevelWindow);
  41704. };
  41705. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  41706. /*** End of inlined file: juce_TopLevelWindow.h ***/
  41707. /*** Start of inlined file: juce_ComponentDragger.h ***/
  41708. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  41709. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  41710. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  41711. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  41712. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  41713. /**
  41714. A class that imposes restrictions on a Component's size or position.
  41715. This is used by classes such as ResizableCornerComponent,
  41716. ResizableBorderComponent and ResizableWindow.
  41717. The base class can impose some basic size and position limits, but you can
  41718. also subclass this for custom uses.
  41719. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  41720. */
  41721. class JUCE_API ComponentBoundsConstrainer
  41722. {
  41723. public:
  41724. /** When first created, the object will not impose any restrictions on the components. */
  41725. ComponentBoundsConstrainer() throw();
  41726. /** Destructor. */
  41727. virtual ~ComponentBoundsConstrainer();
  41728. /** Imposes a minimum width limit. */
  41729. void setMinimumWidth (int minimumWidth) throw();
  41730. /** Returns the current minimum width. */
  41731. int getMinimumWidth() const throw() { return minW; }
  41732. /** Imposes a maximum width limit. */
  41733. void setMaximumWidth (int maximumWidth) throw();
  41734. /** Returns the current maximum width. */
  41735. int getMaximumWidth() const throw() { return maxW; }
  41736. /** Imposes a minimum height limit. */
  41737. void setMinimumHeight (int minimumHeight) throw();
  41738. /** Returns the current minimum height. */
  41739. int getMinimumHeight() const throw() { return minH; }
  41740. /** Imposes a maximum height limit. */
  41741. void setMaximumHeight (int maximumHeight) throw();
  41742. /** Returns the current maximum height. */
  41743. int getMaximumHeight() const throw() { return maxH; }
  41744. /** Imposes a minimum width and height limit. */
  41745. void setMinimumSize (int minimumWidth,
  41746. int minimumHeight) throw();
  41747. /** Imposes a maximum width and height limit. */
  41748. void setMaximumSize (int maximumWidth,
  41749. int maximumHeight) throw();
  41750. /** Set all the maximum and minimum dimensions. */
  41751. void setSizeLimits (int minimumWidth,
  41752. int minimumHeight,
  41753. int maximumWidth,
  41754. int maximumHeight) throw();
  41755. /** Sets the amount by which the component is allowed to go off-screen.
  41756. The values indicate how many pixels must remain on-screen when dragged off
  41757. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  41758. when the component goes off the top of the screen, its y-position will be
  41759. clipped so that there are always at least 10 pixels on-screen. In other words,
  41760. the lowest y-position it can take would be (10 - the component's height).
  41761. If you pass 0 or less for one of these amounts, the component is allowed
  41762. to move beyond that edge completely, with no restrictions at all.
  41763. If you pass a very large number (i.e. larger that the dimensions of the
  41764. component itself), then the component won't be allowed to overlap that
  41765. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  41766. the component will bump into the left side of the screen and go no further.
  41767. */
  41768. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  41769. int minimumWhenOffTheLeft,
  41770. int minimumWhenOffTheBottom,
  41771. int minimumWhenOffTheRight) throw();
  41772. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  41773. int getMinimumWhenOffTheTop() const throw() { return minOffTop; }
  41774. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  41775. int getMinimumWhenOffTheLeft() const throw() { return minOffLeft; }
  41776. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  41777. int getMinimumWhenOffTheBottom() const throw() { return minOffBottom; }
  41778. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  41779. int getMinimumWhenOffTheRight() const throw() { return minOffRight; }
  41780. /** Specifies a width-to-height ratio that the resizer should always maintain.
  41781. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  41782. will always be maintained as this multiple of the height.
  41783. @see setResizeLimits
  41784. */
  41785. void setFixedAspectRatio (double widthOverHeight) throw();
  41786. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  41787. If no aspect ratio is being enforced, this will return 0.
  41788. */
  41789. double getFixedAspectRatio() const throw();
  41790. /** This callback changes the given co-ordinates to impose whatever the current
  41791. constraints are set to be.
  41792. @param bounds the target position that should be examined and adjusted
  41793. @param previousBounds the component's current size
  41794. @param limits the region in which the component can be positioned
  41795. @param isStretchingTop whether the top edge of the component is being resized
  41796. @param isStretchingLeft whether the left edge of the component is being resized
  41797. @param isStretchingBottom whether the bottom edge of the component is being resized
  41798. @param isStretchingRight whether the right edge of the component is being resized
  41799. */
  41800. virtual void checkBounds (Rectangle<int>& bounds,
  41801. const Rectangle<int>& previousBounds,
  41802. const Rectangle<int>& limits,
  41803. bool isStretchingTop,
  41804. bool isStretchingLeft,
  41805. bool isStretchingBottom,
  41806. bool isStretchingRight);
  41807. /** This callback happens when the resizer is about to start dragging. */
  41808. virtual void resizeStart();
  41809. /** This callback happens when the resizer has finished dragging. */
  41810. virtual void resizeEnd();
  41811. /** Checks the given bounds, and then sets the component to the corrected size. */
  41812. void setBoundsForComponent (Component* component,
  41813. const Rectangle<int>& bounds,
  41814. bool isStretchingTop,
  41815. bool isStretchingLeft,
  41816. bool isStretchingBottom,
  41817. bool isStretchingRight);
  41818. /** Performs a check on the current size of a component, and moves or resizes
  41819. it if it fails the constraints.
  41820. */
  41821. void checkComponentBounds (Component* component);
  41822. /** Called by setBoundsForComponent() to apply a new constrained size to a
  41823. component.
  41824. By default this just calls setBounds(), but it virtual in case it's needed for
  41825. extremely cunning purposes.
  41826. */
  41827. virtual void applyBoundsToComponent (Component* component,
  41828. const Rectangle<int>& bounds);
  41829. private:
  41830. int minW, maxW, minH, maxH;
  41831. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  41832. double aspectRatio;
  41833. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBoundsConstrainer);
  41834. };
  41835. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  41836. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  41837. /**
  41838. An object to take care of the logic for dragging components around with the mouse.
  41839. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  41840. then in your mouseDrag() callback, call dragComponent().
  41841. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  41842. to limit the component's position and keep it on-screen.
  41843. e.g. @code
  41844. class MyDraggableComp
  41845. {
  41846. ComponentDragger myDragger;
  41847. void mouseDown (const MouseEvent& e)
  41848. {
  41849. myDragger.startDraggingComponent (this, e);
  41850. }
  41851. void mouseDrag (const MouseEvent& e)
  41852. {
  41853. myDragger.dragComponent (this, e, 0);
  41854. }
  41855. };
  41856. @endcode
  41857. */
  41858. class JUCE_API ComponentDragger
  41859. {
  41860. public:
  41861. /** Creates a ComponentDragger. */
  41862. ComponentDragger();
  41863. /** Destructor. */
  41864. virtual ~ComponentDragger();
  41865. /** Call this from your component's mouseDown() method, to prepare for dragging.
  41866. @param componentToDrag the component that you want to drag
  41867. @param e the mouse event that is triggering the drag
  41868. @see dragComponent
  41869. */
  41870. void startDraggingComponent (Component* componentToDrag,
  41871. const MouseEvent& e);
  41872. /** Call this from your mouseDrag() callback to move the component.
  41873. This will move the component, but will first check the validity of the
  41874. component's new position using the checkPosition() method, which you
  41875. can override if you need to enforce special positioning limits on the
  41876. component.
  41877. @param componentToDrag the component that you want to drag
  41878. @param e the current mouse-drag event
  41879. @param constrainer an optional constrainer object that should be used
  41880. to apply limits to the component's position. Pass
  41881. null if you don't want to contrain the movement.
  41882. @see startDraggingComponent
  41883. */
  41884. void dragComponent (Component* componentToDrag,
  41885. const MouseEvent& e,
  41886. ComponentBoundsConstrainer* constrainer);
  41887. private:
  41888. Point<int> mouseDownWithinTarget;
  41889. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentDragger);
  41890. };
  41891. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  41892. /*** End of inlined file: juce_ComponentDragger.h ***/
  41893. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  41894. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  41895. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  41896. /**
  41897. A component that resizes its parent component when dragged.
  41898. This component forms a frame around the edge of a component, allowing it to
  41899. be dragged by the edges or corners to resize it - like the way windows are
  41900. resized in MSWindows or Linux.
  41901. To use it, just add it to your component, making it fill the entire parent component
  41902. (there's a mouse hit-test that only traps mouse-events which land around the
  41903. edge of the component, so it's even ok to put it on top of any other components
  41904. you're using). Make sure you rescale the resizer component to fill the parent
  41905. each time the parent's size changes.
  41906. @see ResizableCornerComponent
  41907. */
  41908. class JUCE_API ResizableBorderComponent : public Component
  41909. {
  41910. public:
  41911. /** Creates a resizer.
  41912. Pass in the target component which you want to be resized when this one is
  41913. dragged.
  41914. The target component will usually be a parent of the resizer component, but this
  41915. isn't mandatory.
  41916. Remember that when the target component is resized, it'll need to move and
  41917. resize this component to keep it in place, as this won't happen automatically.
  41918. If the constrainer parameter is non-zero, then this object will be used to enforce
  41919. limits on the size and position that the component can be stretched to. Make sure
  41920. that the constrainer isn't deleted while still in use by this object.
  41921. @see ComponentBoundsConstrainer
  41922. */
  41923. ResizableBorderComponent (Component* componentToResize,
  41924. ComponentBoundsConstrainer* constrainer);
  41925. /** Destructor. */
  41926. ~ResizableBorderComponent();
  41927. /** Specifies how many pixels wide the draggable edges of this component are.
  41928. @see getBorderThickness
  41929. */
  41930. void setBorderThickness (const BorderSize<int>& newBorderSize);
  41931. /** Returns the number of pixels wide that the draggable edges of this component are.
  41932. @see setBorderThickness
  41933. */
  41934. const BorderSize<int> getBorderThickness() const;
  41935. /** Represents the different sections of a resizable border, which allow it to
  41936. resized in different ways.
  41937. */
  41938. class Zone
  41939. {
  41940. public:
  41941. enum Zones
  41942. {
  41943. centre = 0,
  41944. left = 1,
  41945. top = 2,
  41946. right = 4,
  41947. bottom = 8
  41948. };
  41949. /** Creates a Zone from a combination of the flags in \enum Zones. */
  41950. explicit Zone (int zoneFlags = 0) throw();
  41951. Zone (const Zone& other) throw();
  41952. Zone& operator= (const Zone& other) throw();
  41953. bool operator== (const Zone& other) const throw();
  41954. bool operator!= (const Zone& other) const throw();
  41955. /** Given a point within a rectangle with a resizable border, this returns the
  41956. zone that the point lies within.
  41957. */
  41958. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  41959. const BorderSize<int>& border,
  41960. const Point<int>& position);
  41961. /** Returns an appropriate mouse-cursor for this resize zone. */
  41962. const MouseCursor getMouseCursor() const throw();
  41963. /** Returns true if dragging this zone will move the enire object without resizing it. */
  41964. bool isDraggingWholeObject() const throw() { return zone == centre; }
  41965. /** Returns true if dragging this zone will move the object's left edge. */
  41966. bool isDraggingLeftEdge() const throw() { return (zone & left) != 0; }
  41967. /** Returns true if dragging this zone will move the object's right edge. */
  41968. bool isDraggingRightEdge() const throw() { return (zone & right) != 0; }
  41969. /** Returns true if dragging this zone will move the object's top edge. */
  41970. bool isDraggingTopEdge() const throw() { return (zone & top) != 0; }
  41971. /** Returns true if dragging this zone will move the object's bottom edge. */
  41972. bool isDraggingBottomEdge() const throw() { return (zone & bottom) != 0; }
  41973. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  41974. applies to.
  41975. */
  41976. template <typename ValueType>
  41977. const Rectangle<ValueType> resizeRectangleBy (Rectangle<ValueType> original,
  41978. const Point<ValueType>& distance) const throw()
  41979. {
  41980. if (isDraggingWholeObject())
  41981. return original + distance;
  41982. if (isDraggingLeftEdge())
  41983. original.setLeft (jmin (original.getRight(), original.getX() + distance.getX()));
  41984. if (isDraggingRightEdge())
  41985. original.setWidth (jmax (ValueType(), original.getWidth() + distance.getX()));
  41986. if (isDraggingTopEdge())
  41987. original.setTop (jmin (original.getBottom(), original.getY() + distance.getY()));
  41988. if (isDraggingBottomEdge())
  41989. original.setHeight (jmax (ValueType(), original.getHeight() + distance.getY()));
  41990. return original;
  41991. }
  41992. /** Returns the raw flags for this zone. */
  41993. int getZoneFlags() const throw() { return zone; }
  41994. private:
  41995. int zone;
  41996. };
  41997. protected:
  41998. /** @internal */
  41999. void paint (Graphics& g);
  42000. /** @internal */
  42001. void mouseEnter (const MouseEvent& e);
  42002. /** @internal */
  42003. void mouseMove (const MouseEvent& e);
  42004. /** @internal */
  42005. void mouseDown (const MouseEvent& e);
  42006. /** @internal */
  42007. void mouseDrag (const MouseEvent& e);
  42008. /** @internal */
  42009. void mouseUp (const MouseEvent& e);
  42010. /** @internal */
  42011. bool hitTest (int x, int y);
  42012. private:
  42013. WeakReference<Component> component;
  42014. ComponentBoundsConstrainer* constrainer;
  42015. BorderSize<int> borderSize;
  42016. Rectangle<int> originalBounds;
  42017. Zone mouseZone;
  42018. void updateMouseZone (const MouseEvent& e);
  42019. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableBorderComponent);
  42020. };
  42021. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  42022. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  42023. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  42024. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  42025. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  42026. /** A component that resizes a parent component when dragged.
  42027. This is the small triangular stripey resizer component you get in the bottom-right
  42028. of windows (more commonly on the Mac than Windows). Put one in the corner of
  42029. a larger component and it will automatically resize its parent when it gets dragged
  42030. around.
  42031. @see ResizableFrameComponent
  42032. */
  42033. class JUCE_API ResizableCornerComponent : public Component
  42034. {
  42035. public:
  42036. /** Creates a resizer.
  42037. Pass in the target component which you want to be resized when this one is
  42038. dragged.
  42039. The target component will usually be a parent of the resizer component, but this
  42040. isn't mandatory.
  42041. Remember that when the target component is resized, it'll need to move and
  42042. resize this component to keep it in place, as this won't happen automatically.
  42043. If the constrainer parameter is non-zero, then this object will be used to enforce
  42044. limits on the size and position that the component can be stretched to. Make sure
  42045. that the constrainer isn't deleted while still in use by this object. If you
  42046. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  42047. @see ComponentBoundsConstrainer
  42048. */
  42049. ResizableCornerComponent (Component* componentToResize,
  42050. ComponentBoundsConstrainer* constrainer);
  42051. /** Destructor. */
  42052. ~ResizableCornerComponent();
  42053. protected:
  42054. /** @internal */
  42055. void paint (Graphics& g);
  42056. /** @internal */
  42057. void mouseDown (const MouseEvent& e);
  42058. /** @internal */
  42059. void mouseDrag (const MouseEvent& e);
  42060. /** @internal */
  42061. void mouseUp (const MouseEvent& e);
  42062. /** @internal */
  42063. bool hitTest (int x, int y);
  42064. private:
  42065. WeakReference<Component> component;
  42066. ComponentBoundsConstrainer* constrainer;
  42067. Rectangle<int> originalBounds;
  42068. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableCornerComponent);
  42069. };
  42070. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  42071. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  42072. /**
  42073. A base class for top-level windows that can be dragged around and resized.
  42074. To add content to the window, use its setContentOwned() or setContentNonOwned() methods
  42075. to give it a component that will remain positioned inside it (leaving a gap around
  42076. the edges for a border).
  42077. It's not advisable to add child components directly to a ResizableWindow: put them
  42078. inside your content component instead. And overriding methods like resized(), moved(), etc
  42079. is also not recommended - instead override these methods for your content component.
  42080. (If for some obscure reason you do need to override these methods, always remember to
  42081. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  42082. decorations correctly).
  42083. By default resizing isn't enabled - use the setResizable() method to enable it and
  42084. to choose the style of resizing to use.
  42085. @see TopLevelWindow
  42086. */
  42087. class JUCE_API ResizableWindow : public TopLevelWindow
  42088. {
  42089. public:
  42090. /** Creates a ResizableWindow.
  42091. This constructor doesn't specify a background colour, so the LookAndFeel's default
  42092. background colour will be used.
  42093. @param name the name to give the component
  42094. @param addToDesktop if true, the window will be automatically added to the
  42095. desktop; if false, you can use it as a child component
  42096. */
  42097. ResizableWindow (const String& name,
  42098. bool addToDesktop);
  42099. /** Creates a ResizableWindow.
  42100. @param name the name to give the component
  42101. @param backgroundColour the colour to use for filling the window's background.
  42102. @param addToDesktop if true, the window will be automatically added to the
  42103. desktop; if false, you can use it as a child component
  42104. */
  42105. ResizableWindow (const String& name,
  42106. const Colour& backgroundColour,
  42107. bool addToDesktop);
  42108. /** Destructor.
  42109. If a content component has been set with setContentOwned(), it will be deleted.
  42110. */
  42111. ~ResizableWindow();
  42112. /** Returns the colour currently being used for the window's background.
  42113. As a convenience the window will fill itself with this colour, but you
  42114. can override the paint() method if you need more customised behaviour.
  42115. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  42116. @see setBackgroundColour
  42117. */
  42118. const Colour getBackgroundColour() const throw();
  42119. /** Changes the colour currently being used for the window's background.
  42120. As a convenience the window will fill itself with this colour, but you
  42121. can override the paint() method if you need more customised behaviour.
  42122. Note that the opaque state of this window is altered by this call to reflect
  42123. the opacity of the colour passed-in. On window systems which can't support
  42124. semi-transparent windows this might cause problems, (though it's unlikely you'll
  42125. be using this class as a base for a semi-transparent component anyway).
  42126. You can also use the ResizableWindow::backgroundColourId colour id to set
  42127. this colour.
  42128. @see getBackgroundColour
  42129. */
  42130. void setBackgroundColour (const Colour& newColour);
  42131. /** Make the window resizable or fixed.
  42132. @param shouldBeResizable whether it's resizable at all
  42133. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  42134. bottom-right; if false, it'll use a ResizableBorderComponent
  42135. around the edge
  42136. @see setResizeLimits, isResizable
  42137. */
  42138. void setResizable (bool shouldBeResizable,
  42139. bool useBottomRightCornerResizer);
  42140. /** True if resizing is enabled.
  42141. @see setResizable
  42142. */
  42143. bool isResizable() const throw();
  42144. /** This sets the maximum and minimum sizes for the window.
  42145. If the window's current size is outside these limits, it will be resized to
  42146. make sure it's within them.
  42147. Calling setBounds() on the component will bypass any size checking - it's only when
  42148. the window is being resized by the user that these values are enforced.
  42149. @see setResizable, setFixedAspectRatio
  42150. */
  42151. void setResizeLimits (int newMinimumWidth,
  42152. int newMinimumHeight,
  42153. int newMaximumWidth,
  42154. int newMaximumHeight) throw();
  42155. /** Returns the bounds constrainer object that this window is using.
  42156. You can access this to change its properties.
  42157. */
  42158. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  42159. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  42160. A pointer to the object you pass in will be kept, but it won't be deleted
  42161. by this object, so it's the caller's responsiblity to manage it.
  42162. If you pass 0, then no contraints will be placed on the positioning of the window.
  42163. */
  42164. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  42165. /** Calls the window's setBounds method, after first checking these bounds
  42166. with the current constrainer.
  42167. @see setConstrainer
  42168. */
  42169. void setBoundsConstrained (const Rectangle<int>& bounds);
  42170. /** Returns true if the window is currently in full-screen mode.
  42171. @see setFullScreen
  42172. */
  42173. bool isFullScreen() const;
  42174. /** Puts the window into full-screen mode, or restores it to its normal size.
  42175. If true, the window will become full-screen; if false, it will return to the
  42176. last size it was before being made full-screen.
  42177. @see isFullScreen
  42178. */
  42179. void setFullScreen (bool shouldBeFullScreen);
  42180. /** Returns true if the window is currently minimised.
  42181. @see setMinimised
  42182. */
  42183. bool isMinimised() const;
  42184. /** Minimises the window, or restores it to its previous position and size.
  42185. When being un-minimised, it'll return to the last position and size it
  42186. was in before being minimised.
  42187. @see isMinimised
  42188. */
  42189. void setMinimised (bool shouldMinimise);
  42190. /** Returns a string which encodes the window's current size and position.
  42191. This string will encapsulate the window's size, position, and whether it's
  42192. in full-screen mode. It's intended for letting your application save and
  42193. restore a window's position.
  42194. Use the restoreWindowStateFromString() to restore from a saved state.
  42195. @see restoreWindowStateFromString
  42196. */
  42197. const String getWindowStateAsString();
  42198. /** Restores the window to a previously-saved size and position.
  42199. This restores the window's size, positon and full-screen status from an
  42200. string that was previously created with the getWindowStateAsString()
  42201. method.
  42202. @returns false if the string wasn't a valid window state
  42203. @see getWindowStateAsString
  42204. */
  42205. bool restoreWindowStateFromString (const String& previousState);
  42206. /** Returns the current content component.
  42207. This will be the component set by setContentOwned() or setContentNonOwned, or 0 if none
  42208. has yet been specified.
  42209. @see setContentOwned, setContentNonOwned
  42210. */
  42211. Component* getContentComponent() const throw() { return contentComponent; }
  42212. /** Changes the current content component.
  42213. This sets a component that will be placed in the centre of the ResizableWindow,
  42214. (leaving a space around the edge for the border).
  42215. You should never add components directly to a ResizableWindow (or any of its subclasses)
  42216. with addChildComponent(). Instead, add them to the content component.
  42217. @param newContentComponent the new component to use - this component will be deleted when it's
  42218. no longer needed (i.e. when the window is deleted or a new content
  42219. component is set for it). To set a component that this window will not
  42220. delete, call setContentNonOwned() instead.
  42221. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  42222. such that it always fits around the size of the content component. If false,
  42223. the new content will be resized to fit the current space available.
  42224. */
  42225. void setContentOwned (Component* newContentComponent,
  42226. bool resizeToFitWhenContentChangesSize);
  42227. /** Changes the current content component.
  42228. This sets a component that will be placed in the centre of the ResizableWindow,
  42229. (leaving a space around the edge for the border).
  42230. You should never add components directly to a ResizableWindow (or any of its subclasses)
  42231. with addChildComponent(). Instead, add them to the content component.
  42232. @param newContentComponent the new component to use - this component will NOT be deleted by this
  42233. component, so it's the caller's responsibility to manage its lifetime (it's
  42234. ok to delete it while this window is still using it). To set a content
  42235. component that the window will delete, call setContentOwned() instead.
  42236. @param resizeToFitWhenContentChangesSize if true, then the ResizableWindow will maintain its size
  42237. such that it always fits around the size of the content component. If false,
  42238. the new content will be resized to fit the current space available.
  42239. */
  42240. void setContentNonOwned (Component* newContentComponent,
  42241. bool resizeToFitWhenContentChangesSize);
  42242. /** Removes the current content component.
  42243. If the previous content component was added with setContentOwned(), it will also be deleted. If
  42244. it was added with setContentNonOwned(), it will simply be removed from this component.
  42245. */
  42246. void clearContentComponent();
  42247. /** Changes the window so that the content component ends up with the specified size.
  42248. This is basically a setSize call on the window, but which adds on the borders,
  42249. so you can specify the content component's target size.
  42250. */
  42251. void setContentComponentSize (int width, int height);
  42252. /** Returns the width of the frame to use around the window.
  42253. @see getContentComponentBorder
  42254. */
  42255. virtual const BorderSize<int> getBorderThickness();
  42256. /** Returns the insets to use when positioning the content component.
  42257. @see getBorderThickness
  42258. */
  42259. virtual const BorderSize<int> getContentComponentBorder();
  42260. /** A set of colour IDs to use to change the colour of various aspects of the window.
  42261. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42262. methods.
  42263. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42264. */
  42265. enum ColourIds
  42266. {
  42267. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  42268. };
  42269. /** @deprecated - use setContentOwned() and setContentNonOwned() instead. */
  42270. JUCE_DEPRECATED (void setContentComponent (Component* newContentComponent,
  42271. bool deleteOldOne = true,
  42272. bool resizeToFit = false));
  42273. protected:
  42274. /** @internal */
  42275. void paint (Graphics& g);
  42276. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  42277. void moved();
  42278. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  42279. void resized();
  42280. /** @internal */
  42281. void mouseDown (const MouseEvent& e);
  42282. /** @internal */
  42283. void mouseDrag (const MouseEvent& e);
  42284. /** @internal */
  42285. void lookAndFeelChanged();
  42286. /** @internal */
  42287. void childBoundsChanged (Component* child);
  42288. /** @internal */
  42289. void parentSizeChanged();
  42290. /** @internal */
  42291. void visibilityChanged();
  42292. /** @internal */
  42293. void activeWindowStatusChanged();
  42294. /** @internal */
  42295. int getDesktopWindowStyleFlags() const;
  42296. #if JUCE_DEBUG
  42297. /** Overridden to warn people about adding components directly to this component
  42298. instead of using setContentOwned().
  42299. If you know what you're doing and are sure you really want to add a component, specify
  42300. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  42301. */
  42302. void addChildComponent (Component* child, int zOrder = -1);
  42303. /** Overridden to warn people about adding components directly to this component
  42304. instead of using setContentOwned().
  42305. If you know what you're doing and are sure you really want to add a component, specify
  42306. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  42307. */
  42308. void addAndMakeVisible (Component* child, int zOrder = -1);
  42309. #endif
  42310. ScopedPointer <ResizableCornerComponent> resizableCorner;
  42311. ScopedPointer <ResizableBorderComponent> resizableBorder;
  42312. private:
  42313. Component::SafePointer <Component> contentComponent;
  42314. bool ownsContentComponent, resizeToFitContent, fullscreen;
  42315. ComponentDragger dragger;
  42316. Rectangle<int> lastNonFullScreenPos;
  42317. ComponentBoundsConstrainer defaultConstrainer;
  42318. ComponentBoundsConstrainer* constrainer;
  42319. #if JUCE_DEBUG
  42320. bool hasBeenResized;
  42321. #endif
  42322. void updateLastPos();
  42323. void setContent (Component* newComp, bool takeOwnership, bool resizeToFit);
  42324. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  42325. // The parameters for these methods have changed - please update your code!
  42326. JUCE_DEPRECATED (void getBorderThickness (int& left, int& top, int& right, int& bottom));
  42327. JUCE_DEPRECATED (void getContentComponentBorder (int& left, int& top, int& right, int& bottom));
  42328. #endif
  42329. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableWindow);
  42330. };
  42331. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  42332. /*** End of inlined file: juce_ResizableWindow.h ***/
  42333. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  42334. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  42335. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  42336. /**
  42337. A glyph from a particular font, with a particular size, style,
  42338. typeface and position.
  42339. @see GlyphArrangement, Font
  42340. */
  42341. class JUCE_API PositionedGlyph
  42342. {
  42343. public:
  42344. PositionedGlyph (const PositionedGlyph& other);
  42345. /** Returns the character the glyph represents. */
  42346. juce_wchar getCharacter() const { return character; }
  42347. /** Checks whether the glyph is actually empty. */
  42348. bool isWhitespace() const { return CharacterFunctions::isWhitespace (character); }
  42349. /** Returns the position of the glyph's left-hand edge. */
  42350. float getLeft() const { return x; }
  42351. /** Returns the position of the glyph's right-hand edge. */
  42352. float getRight() const { return x + w; }
  42353. /** Returns the y position of the glyph's baseline. */
  42354. float getBaselineY() const { return y; }
  42355. /** Returns the y position of the top of the glyph. */
  42356. float getTop() const { return y - font.getAscent(); }
  42357. /** Returns the y position of the bottom of the glyph. */
  42358. float getBottom() const { return y + font.getDescent(); }
  42359. /** Returns the bounds of the glyph. */
  42360. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  42361. /** Shifts the glyph's position by a relative amount. */
  42362. void moveBy (float deltaX, float deltaY);
  42363. /** Draws the glyph into a graphics context. */
  42364. void draw (const Graphics& g) const;
  42365. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  42366. void draw (const Graphics& g, const AffineTransform& transform) const;
  42367. /** Returns the path for this glyph.
  42368. @param path the glyph's outline will be appended to this path
  42369. */
  42370. void createPath (Path& path) const;
  42371. /** Checks to see if a point lies within this glyph. */
  42372. bool hitTest (float x, float y) const;
  42373. private:
  42374. friend class GlyphArrangement;
  42375. float x, y, w;
  42376. Font font;
  42377. juce_wchar character;
  42378. int glyph;
  42379. PositionedGlyph (float x, float y, float w, const Font& font, juce_wchar character, int glyph);
  42380. JUCE_LEAK_DETECTOR (PositionedGlyph);
  42381. };
  42382. /**
  42383. A set of glyphs, each with a position.
  42384. You can create a GlyphArrangement, text to it and then draw it onto a
  42385. graphics context. It's used internally by the text methods in the
  42386. Graphics class, but can be used directly if more control is needed.
  42387. @see Font, PositionedGlyph
  42388. */
  42389. class JUCE_API GlyphArrangement
  42390. {
  42391. public:
  42392. /** Creates an empty arrangement. */
  42393. GlyphArrangement();
  42394. /** Takes a copy of another arrangement. */
  42395. GlyphArrangement (const GlyphArrangement& other);
  42396. /** Copies another arrangement onto this one.
  42397. To add another arrangement without clearing this one, use addGlyphArrangement().
  42398. */
  42399. GlyphArrangement& operator= (const GlyphArrangement& other);
  42400. /** Destructor. */
  42401. ~GlyphArrangement();
  42402. /** Returns the total number of glyphs in the arrangement. */
  42403. int getNumGlyphs() const throw() { return glyphs.size(); }
  42404. /** Returns one of the glyphs from the arrangement.
  42405. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  42406. careful not to pass an out-of-range index here, as it
  42407. doesn't do any bounds-checking.
  42408. */
  42409. PositionedGlyph& getGlyph (int index) const;
  42410. /** Clears all text from the arrangement and resets it.
  42411. */
  42412. void clear();
  42413. /** Appends a line of text to the arrangement.
  42414. This will add the text as a single line, where x is the left-hand edge of the
  42415. first character, and y is the position for the text's baseline.
  42416. If the text contains new-lines or carriage-returns, this will ignore them - use
  42417. addJustifiedText() to add multi-line arrangements.
  42418. */
  42419. void addLineOfText (const Font& font,
  42420. const String& text,
  42421. float x, float y);
  42422. /** Adds a line of text, truncating it if it's wider than a specified size.
  42423. This is the same as addLineOfText(), but if the line's width exceeds the value
  42424. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  42425. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  42426. */
  42427. void addCurtailedLineOfText (const Font& font,
  42428. const String& text,
  42429. float x, float y,
  42430. float maxWidthPixels,
  42431. bool useEllipsis);
  42432. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  42433. This will add text to the arrangement, breaking it into new lines either where there
  42434. is a new-line or carriage-return character in the text, or where a line's width
  42435. exceeds the value set in maxLineWidth.
  42436. Each line that is added will be laid out using the flags set in horizontalLayout, so
  42437. the lines can be left- or right-justified, or centred horizontally in the space
  42438. between x and (x + maxLineWidth).
  42439. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  42440. lines will be placed below it, separated by a distance of font.getHeight().
  42441. */
  42442. void addJustifiedText (const Font& font,
  42443. const String& text,
  42444. float x, float y,
  42445. float maxLineWidth,
  42446. const Justification& horizontalLayout);
  42447. /** Tries to fit some text withing a given space.
  42448. This does its best to make the given text readable within the specified rectangle,
  42449. so it useful for labelling things.
  42450. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  42451. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  42452. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  42453. it's been truncated.
  42454. A Justification parameter lets you specify how the text is laid out within the rectangle,
  42455. both horizontally and vertically.
  42456. @see Graphics::drawFittedText
  42457. */
  42458. void addFittedText (const Font& font,
  42459. const String& text,
  42460. float x, float y, float width, float height,
  42461. const Justification& layout,
  42462. int maximumLinesToUse,
  42463. float minimumHorizontalScale = 0.7f);
  42464. /** Appends another glyph arrangement to this one. */
  42465. void addGlyphArrangement (const GlyphArrangement& other);
  42466. /** Draws this glyph arrangement to a graphics context.
  42467. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  42468. method, which renders the glyphs as filled vectors.
  42469. */
  42470. void draw (const Graphics& g) const;
  42471. /** Draws this glyph arrangement to a graphics context.
  42472. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  42473. method for non-transformed arrangements.
  42474. */
  42475. void draw (const Graphics& g, const AffineTransform& transform) const;
  42476. /** Converts the set of glyphs into a path.
  42477. @param path the glyphs' outlines will be appended to this path
  42478. */
  42479. void createPath (Path& path) const;
  42480. /** Looks for a glyph that contains the given co-ordinate.
  42481. @returns the index of the glyph, or -1 if none were found.
  42482. */
  42483. int findGlyphIndexAt (float x, float y) const;
  42484. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  42485. @param startIndex the first glyph to test
  42486. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  42487. startIndex will be included
  42488. @param includeWhitespace if true, the extent of any whitespace characters will also
  42489. be taken into account
  42490. */
  42491. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  42492. /** Shifts a set of glyphs by a given amount.
  42493. @param startIndex the first glyph to transform
  42494. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  42495. startIndex will be used
  42496. @param deltaX the amount to add to their x-positions
  42497. @param deltaY the amount to add to their y-positions
  42498. */
  42499. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  42500. float deltaX, float deltaY);
  42501. /** Removes a set of glyphs from the arrangement.
  42502. @param startIndex the first glyph to remove
  42503. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  42504. startIndex will be deleted
  42505. */
  42506. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  42507. /** Expands or compresses a set of glyphs horizontally.
  42508. @param startIndex the first glyph to transform
  42509. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  42510. startIndex will be used
  42511. @param horizontalScaleFactor how much to scale their horizontal width by
  42512. */
  42513. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  42514. float horizontalScaleFactor);
  42515. /** Justifies a set of glyphs within a given space.
  42516. This moves the glyphs as a block so that the whole thing is located within the
  42517. given rectangle with the specified layout.
  42518. If the Justification::horizontallyJustified flag is specified, each line will
  42519. be stretched out to fill the specified width.
  42520. */
  42521. void justifyGlyphs (int startIndex, int numGlyphs,
  42522. float x, float y, float width, float height,
  42523. const Justification& justification);
  42524. private:
  42525. OwnedArray <PositionedGlyph> glyphs;
  42526. int insertEllipsis (const Font& font, float maxXPos, int startIndex, int endIndex);
  42527. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  42528. const Justification& justification, float minimumHorizontalScale);
  42529. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  42530. JUCE_LEAK_DETECTOR (GlyphArrangement);
  42531. };
  42532. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  42533. /*** End of inlined file: juce_GlyphArrangement.h ***/
  42534. /*** Start of inlined file: juce_AlertWindow.h ***/
  42535. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  42536. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  42537. /*** Start of inlined file: juce_TextLayout.h ***/
  42538. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  42539. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  42540. class Graphics;
  42541. /**
  42542. A laid-out arrangement of text.
  42543. You can add text in different fonts to a TextLayout object, then call its
  42544. layout() method to word-wrap it into lines. The layout can then be drawn
  42545. using a graphics context.
  42546. It's handy if you've got a message to display, because you can format it,
  42547. measure the extent of the layout, and then create a suitably-sized window
  42548. to show it in.
  42549. @see Font, Graphics::drawFittedText, GlyphArrangement
  42550. */
  42551. class JUCE_API TextLayout
  42552. {
  42553. public:
  42554. /** Creates an empty text layout.
  42555. Text can then be appended using the appendText() method.
  42556. */
  42557. TextLayout();
  42558. /** Creates a copy of another layout object. */
  42559. TextLayout (const TextLayout& other);
  42560. /** Creates a text layout from an initial string and font. */
  42561. TextLayout (const String& text, const Font& font);
  42562. /** Destructor. */
  42563. ~TextLayout();
  42564. /** Copies another layout onto this one. */
  42565. TextLayout& operator= (const TextLayout& layoutToCopy);
  42566. /** Clears the layout, removing all its text. */
  42567. void clear();
  42568. /** Adds a string to the end of the arrangement.
  42569. The string will be broken onto new lines wherever it contains
  42570. carriage-returns or linefeeds. After adding it, you can call layout()
  42571. to wrap long lines into a paragraph and justify it.
  42572. */
  42573. void appendText (const String& textToAppend,
  42574. const Font& fontToUse);
  42575. /** Replaces all the text with a new string.
  42576. This is equivalent to calling clear() followed by appendText().
  42577. */
  42578. void setText (const String& newText,
  42579. const Font& fontToUse);
  42580. /** Returns true if the layout has not had any text added yet. */
  42581. bool isEmpty() const;
  42582. /** Breaks the text up to form a paragraph with the given width.
  42583. @param maximumWidth any text wider than this will be split
  42584. across multiple lines
  42585. @param justification how the lines are to be laid-out horizontally
  42586. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  42587. width that keeps all the lines of text at a
  42588. similar length - this is good when you're displaying
  42589. a short message and don't want it to get split
  42590. onto two lines with only a couple of words on
  42591. the second line, which looks untidy.
  42592. */
  42593. void layout (int maximumWidth,
  42594. const Justification& justification,
  42595. bool attemptToBalanceLineLengths);
  42596. /** Returns the overall width of the entire text layout. */
  42597. int getWidth() const;
  42598. /** Returns the overall height of the entire text layout. */
  42599. int getHeight() const;
  42600. /** Returns the total number of lines of text. */
  42601. int getNumLines() const { return totalLines; }
  42602. /** Returns the width of a particular line of text.
  42603. @param lineNumber the line, from 0 to (getNumLines() - 1)
  42604. */
  42605. int getLineWidth (int lineNumber) const;
  42606. /** Renders the text at a specified position using a graphics context.
  42607. */
  42608. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  42609. /** Renders the text within a specified rectangle using a graphics context.
  42610. The justification flags dictate how the block of text should be positioned
  42611. within the rectangle.
  42612. */
  42613. void drawWithin (Graphics& g,
  42614. int x, int y, int w, int h,
  42615. const Justification& layoutFlags) const;
  42616. private:
  42617. class Token;
  42618. friend class OwnedArray <Token>;
  42619. OwnedArray <Token> tokens;
  42620. int totalLines;
  42621. JUCE_LEAK_DETECTOR (TextLayout);
  42622. };
  42623. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  42624. /*** End of inlined file: juce_TextLayout.h ***/
  42625. /** A window that displays a message and has buttons for the user to react to it.
  42626. For simple dialog boxes with just a couple of buttons on them, there are
  42627. some static methods for running these.
  42628. For more complex dialogs, an AlertWindow can be created, then it can have some
  42629. buttons and components added to it, and its runModalLoop() method is then used to
  42630. show it. The value returned by runModalLoop() shows which button the
  42631. user pressed to dismiss the box.
  42632. @see ThreadWithProgressWindow
  42633. */
  42634. class JUCE_API AlertWindow : public TopLevelWindow,
  42635. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  42636. {
  42637. public:
  42638. /** The type of icon to show in the dialog box. */
  42639. enum AlertIconType
  42640. {
  42641. NoIcon, /**< No icon will be shown on the dialog box. */
  42642. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  42643. user to answer a question. */
  42644. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  42645. warning about something and shouldn't be ignored. */
  42646. InfoIcon /**< An icon that indicates that the dialog box is just
  42647. giving the user some information, which doesn't require
  42648. a response from them. */
  42649. };
  42650. /** Creates an AlertWindow.
  42651. @param title the headline to show at the top of the dialog box
  42652. @param message a longer, more descriptive message to show underneath the
  42653. headline
  42654. @param iconType the type of icon to display
  42655. @param associatedComponent if this is non-null, it specifies the component that the
  42656. alert window should be associated with. Depending on the look
  42657. and feel, this might be used for positioning of the alert window.
  42658. */
  42659. AlertWindow (const String& title,
  42660. const String& message,
  42661. AlertIconType iconType,
  42662. Component* associatedComponent = 0);
  42663. /** Destroys the AlertWindow */
  42664. ~AlertWindow();
  42665. /** Returns the type of alert icon that was specified when the window
  42666. was created. */
  42667. AlertIconType getAlertType() const throw() { return alertIconType; }
  42668. /** Changes the dialog box's message.
  42669. This will also resize the window to fit the new message if required.
  42670. */
  42671. void setMessage (const String& message);
  42672. /** Adds a button to the window.
  42673. @param name the text to show on the button
  42674. @param returnValue the value that should be returned from runModalLoop()
  42675. if this is the button that the user presses.
  42676. @param shortcutKey1 an optional key that can be pressed to trigger this button
  42677. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  42678. */
  42679. void addButton (const String& name,
  42680. int returnValue,
  42681. const KeyPress& shortcutKey1 = KeyPress(),
  42682. const KeyPress& shortcutKey2 = KeyPress());
  42683. /** Returns the number of buttons that the window currently has. */
  42684. int getNumButtons() const;
  42685. /** Invokes a click of one of the buttons. */
  42686. void triggerButtonClick (const String& buttonName);
  42687. /** Adds a textbox to the window for entering strings.
  42688. @param name an internal name for the text-box. This is the name to pass to
  42689. the getTextEditorContents() method to find out what the
  42690. user typed-in.
  42691. @param initialContents a string to show in the text box when it's first shown
  42692. @param onScreenLabel if this is non-empty, it will be displayed next to the
  42693. text-box to label it.
  42694. @param isPasswordBox if true, the text editor will display asterisks instead of
  42695. the actual text
  42696. @see getTextEditorContents
  42697. */
  42698. void addTextEditor (const String& name,
  42699. const String& initialContents,
  42700. const String& onScreenLabel = String::empty,
  42701. bool isPasswordBox = false);
  42702. /** Returns the contents of a named textbox.
  42703. After showing an AlertWindow that contains a text editor, this can be
  42704. used to find out what the user has typed into it.
  42705. @param nameOfTextEditor the name of the text box that you're interested in
  42706. @see addTextEditor
  42707. */
  42708. const String getTextEditorContents (const String& nameOfTextEditor) const;
  42709. /** Returns a pointer to a textbox that was added with addTextEditor(). */
  42710. TextEditor* getTextEditor (const String& nameOfTextEditor) const;
  42711. /** Adds a drop-down list of choices to the box.
  42712. After the box has been shown, the getComboBoxComponent() method can
  42713. be used to find out which item the user picked.
  42714. @param name the label to use for the drop-down list
  42715. @param items the list of items to show in it
  42716. @param onScreenLabel if this is non-empty, it will be displayed next to the
  42717. combo-box to label it.
  42718. @see getComboBoxComponent
  42719. */
  42720. void addComboBox (const String& name,
  42721. const StringArray& items,
  42722. const String& onScreenLabel = String::empty);
  42723. /** Returns a drop-down list that was added to the AlertWindow.
  42724. @param nameOfList the name that was passed into the addComboBox() method
  42725. when creating the drop-down
  42726. @returns the ComboBox component, or 0 if none was found for the given name.
  42727. */
  42728. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  42729. /** Adds a block of text.
  42730. This is handy for adding a multi-line note next to a textbox or combo-box,
  42731. to provide more details about what's going on.
  42732. */
  42733. void addTextBlock (const String& text);
  42734. /** Adds a progress-bar to the window.
  42735. @param progressValue a variable that will be repeatedly checked while the
  42736. dialog box is visible, to see how far the process has
  42737. got. The value should be in the range 0 to 1.0
  42738. */
  42739. void addProgressBarComponent (double& progressValue);
  42740. /** Adds a user-defined component to the dialog box.
  42741. @param component the component to add - its size should be set up correctly
  42742. before it is passed in. The caller is responsible for deleting
  42743. the component later on - the AlertWindow won't delete it.
  42744. */
  42745. void addCustomComponent (Component* component);
  42746. /** Returns the number of custom components in the dialog box.
  42747. @see getCustomComponent, addCustomComponent
  42748. */
  42749. int getNumCustomComponents() const;
  42750. /** Returns one of the custom components in the dialog box.
  42751. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  42752. will return 0
  42753. @see getNumCustomComponents, addCustomComponent
  42754. */
  42755. Component* getCustomComponent (int index) const;
  42756. /** Removes one of the custom components in the dialog box.
  42757. Note that this won't delete it, it just removes the component from the window
  42758. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  42759. will return 0
  42760. @returns the component that was removed (or null)
  42761. @see getNumCustomComponents, addCustomComponent
  42762. */
  42763. Component* removeCustomComponent (int index);
  42764. /** Returns true if the window contains any components other than just buttons.*/
  42765. bool containsAnyExtraComponents() const;
  42766. // easy-to-use message box functions:
  42767. /** Shows a dialog box that just has a message and a single button to get rid of it.
  42768. If the callback parameter is null, the box is shown modally, and the method will
  42769. block until the user has clicked the button (or pressed the escape or return keys).
  42770. If the callback parameter is non-null, the box will be displayed and placed into a
  42771. modal state, but this method will return immediately, and the callback will be invoked
  42772. later when the user dismisses the box.
  42773. @param iconType the type of icon to show
  42774. @param title the headline to show at the top of the box
  42775. @param message a longer, more descriptive message to show underneath the
  42776. headline
  42777. @param buttonText the text to show in the button - if this string is empty, the
  42778. default string "ok" (or a localised version) will be used.
  42779. @param associatedComponent if this is non-null, it specifies the component that the
  42780. alert window should be associated with. Depending on the look
  42781. and feel, this might be used for positioning of the alert window.
  42782. */
  42783. #if JUCE_MODAL_LOOPS_PERMITTED
  42784. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  42785. const String& title,
  42786. const String& message,
  42787. const String& buttonText = String::empty,
  42788. Component* associatedComponent = 0);
  42789. #endif
  42790. /** Shows a dialog box that just has a message and a single button to get rid of it.
  42791. If the callback parameter is null, the box is shown modally, and the method will
  42792. block until the user has clicked the button (or pressed the escape or return keys).
  42793. If the callback parameter is non-null, the box will be displayed and placed into a
  42794. modal state, but this method will return immediately, and the callback will be invoked
  42795. later when the user dismisses the box.
  42796. @param iconType the type of icon to show
  42797. @param title the headline to show at the top of the box
  42798. @param message a longer, more descriptive message to show underneath the
  42799. headline
  42800. @param buttonText the text to show in the button - if this string is empty, the
  42801. default string "ok" (or a localised version) will be used.
  42802. @param associatedComponent if this is non-null, it specifies the component that the
  42803. alert window should be associated with. Depending on the look
  42804. and feel, this might be used for positioning of the alert window.
  42805. */
  42806. static void JUCE_CALLTYPE showMessageBoxAsync (AlertIconType iconType,
  42807. const String& title,
  42808. const String& message,
  42809. const String& buttonText = String::empty,
  42810. Component* associatedComponent = 0);
  42811. /** Shows a dialog box with two buttons.
  42812. Ideal for ok/cancel or yes/no choices. The return key can also be used
  42813. to trigger the first button, and the escape key for the second button.
  42814. If the callback parameter is null, the box is shown modally, and the method will
  42815. block until the user has clicked the button (or pressed the escape or return keys).
  42816. If the callback parameter is non-null, the box will be displayed and placed into a
  42817. modal state, but this method will return immediately, and the callback will be invoked
  42818. later when the user dismisses the box.
  42819. @param iconType the type of icon to show
  42820. @param title the headline to show at the top of the box
  42821. @param message a longer, more descriptive message to show underneath the
  42822. headline
  42823. @param button1Text the text to show in the first button - if this string is
  42824. empty, the default string "ok" (or a localised version of it)
  42825. will be used.
  42826. @param button2Text the text to show in the second button - if this string is
  42827. empty, the default string "cancel" (or a localised version of it)
  42828. will be used.
  42829. @param associatedComponent if this is non-null, it specifies the component that the
  42830. alert window should be associated with. Depending on the look
  42831. and feel, this might be used for positioning of the alert window.
  42832. @param callback if this is non-null, the menu will be launched asynchronously,
  42833. returning immediately, and the callback will receive a call to its
  42834. modalStateFinished() when the box is dismissed, with its parameter
  42835. being 1 if the ok button was pressed, or 0 for cancel, The callback object
  42836. will be owned and deleted by the system, so make sure that it works
  42837. safely and doesn't keep any references to objects that might be deleted
  42838. before it gets called.
  42839. @returns true if button 1 was clicked, false if it was button 2. If the callback parameter
  42840. is not null, the method always returns false, and the user's choice is delivered
  42841. later by the callback.
  42842. */
  42843. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  42844. const String& title,
  42845. const String& message,
  42846. #if JUCE_MODAL_LOOPS_PERMITTED
  42847. const String& button1Text = String::empty,
  42848. const String& button2Text = String::empty,
  42849. Component* associatedComponent = 0,
  42850. ModalComponentManager::Callback* callback = 0);
  42851. #else
  42852. const String& button1Text,
  42853. const String& button2Text,
  42854. Component* associatedComponent,
  42855. ModalComponentManager::Callback* callback);
  42856. #endif
  42857. /** Shows a dialog box with three buttons.
  42858. Ideal for yes/no/cancel boxes.
  42859. The escape key can be used to trigger the third button.
  42860. If the callback parameter is null, the box is shown modally, and the method will
  42861. block until the user has clicked the button (or pressed the escape or return keys).
  42862. If the callback parameter is non-null, the box will be displayed and placed into a
  42863. modal state, but this method will return immediately, and the callback will be invoked
  42864. later when the user dismisses the box.
  42865. @param iconType the type of icon to show
  42866. @param title the headline to show at the top of the box
  42867. @param message a longer, more descriptive message to show underneath the
  42868. headline
  42869. @param button1Text the text to show in the first button - if an empty string, then
  42870. "yes" will be used (or a localised version of it)
  42871. @param button2Text the text to show in the first button - if an empty string, then
  42872. "no" will be used (or a localised version of it)
  42873. @param button3Text the text to show in the first button - if an empty string, then
  42874. "cancel" will be used (or a localised version of it)
  42875. @param associatedComponent if this is non-null, it specifies the component that the
  42876. alert window should be associated with. Depending on the look
  42877. and feel, this might be used for positioning of the alert window.
  42878. @param callback if this is non-null, the menu will be launched asynchronously,
  42879. returning immediately, and the callback will receive a call to its
  42880. modalStateFinished() when the box is dismissed, with its parameter
  42881. being 1 if the "yes" button was pressed, 2 for the "no" button, or 0
  42882. if it was cancelled, The callback object will be owned and deleted by the
  42883. system, so make sure that it works safely and doesn't keep any references
  42884. to objects that might be deleted before it gets called.
  42885. @returns If the callback parameter has been set, this returns 0. Otherwise, it
  42886. returns one of the following values:
  42887. - 0 if the third button was pressed (normally used for 'cancel')
  42888. - 1 if the first button was pressed (normally used for 'yes')
  42889. - 2 if the middle button was pressed (normally used for 'no')
  42890. */
  42891. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  42892. const String& title,
  42893. const String& message,
  42894. #if JUCE_MODAL_LOOPS_PERMITTED
  42895. const String& button1Text = String::empty,
  42896. const String& button2Text = String::empty,
  42897. const String& button3Text = String::empty,
  42898. Component* associatedComponent = 0,
  42899. ModalComponentManager::Callback* callback = 0);
  42900. #else
  42901. const String& button1Text,
  42902. const String& button2Text,
  42903. const String& button3Text,
  42904. Component* associatedComponent,
  42905. ModalComponentManager::Callback* callback);
  42906. #endif
  42907. /** Shows an operating-system native dialog box.
  42908. @param title the title to use at the top
  42909. @param bodyText the longer message to show
  42910. @param isOkCancel if true, this will show an ok/cancel box, if false,
  42911. it'll show a box with just an ok button
  42912. @returns true if the ok button was pressed, false if they pressed cancel.
  42913. */
  42914. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  42915. const String& bodyText,
  42916. bool isOkCancel);
  42917. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  42918. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42919. methods.
  42920. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42921. */
  42922. enum ColourIds
  42923. {
  42924. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  42925. textColourId = 0x1001810, /**< The colour for the text. */
  42926. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  42927. };
  42928. protected:
  42929. /** @internal */
  42930. void paint (Graphics& g);
  42931. /** @internal */
  42932. void mouseDown (const MouseEvent& e);
  42933. /** @internal */
  42934. void mouseDrag (const MouseEvent& e);
  42935. /** @internal */
  42936. bool keyPressed (const KeyPress& key);
  42937. /** @internal */
  42938. void buttonClicked (Button* button);
  42939. /** @internal */
  42940. void lookAndFeelChanged();
  42941. /** @internal */
  42942. void userTriedToCloseWindow();
  42943. /** @internal */
  42944. int getDesktopWindowStyleFlags() const;
  42945. private:
  42946. String text;
  42947. TextLayout textLayout;
  42948. AlertIconType alertIconType;
  42949. ComponentBoundsConstrainer constrainer;
  42950. ComponentDragger dragger;
  42951. Rectangle<int> textArea;
  42952. OwnedArray<TextButton> buttons;
  42953. OwnedArray<TextEditor> textBoxes;
  42954. OwnedArray<ComboBox> comboBoxes;
  42955. OwnedArray<ProgressBar> progressBars;
  42956. Array<Component*> customComps;
  42957. OwnedArray<Component> textBlocks;
  42958. Array<Component*> allComps;
  42959. StringArray textboxNames, comboBoxNames;
  42960. Font font;
  42961. Component* associatedComponent;
  42962. void updateLayout (bool onlyIncreaseSize);
  42963. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AlertWindow);
  42964. };
  42965. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  42966. /*** End of inlined file: juce_AlertWindow.h ***/
  42967. /**
  42968. A file open/save dialog box.
  42969. This is a Juce-based file dialog box; to use a native file chooser, see the
  42970. FileChooser class.
  42971. To use one of these, create it and call its show() method. e.g.
  42972. @code
  42973. {
  42974. WildcardFileFilter wildcardFilter ("*.foo", "Foo files");
  42975. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  42976. File::nonexistent,
  42977. &wildcardFilter,
  42978. 0);
  42979. FileChooserDialogBox dialogBox ("Open some kind of file",
  42980. "Please choose some kind of file that you want to open...",
  42981. browser,
  42982. getLookAndFeel().alertWindowBackground);
  42983. if (dialogBox.show())
  42984. {
  42985. File selectedFile = browser.getCurrentFile();
  42986. ...
  42987. }
  42988. }
  42989. @endcode
  42990. @see FileChooser
  42991. */
  42992. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  42993. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  42994. public FileBrowserListener
  42995. {
  42996. public:
  42997. /** Creates a file chooser box.
  42998. @param title the main title to show at the top of the box
  42999. @param instructions an optional longer piece of text to show below the title in
  43000. a smaller font, describing in more detail what's required.
  43001. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  43002. box. Make sure you delete this after (but not before!) the
  43003. dialog box has been deleted.
  43004. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  43005. if they try to select a file that already exists. (This
  43006. flag is only used when saving files)
  43007. @param backgroundColour the background colour for the top level window
  43008. @see FileBrowserComponent, FilePreviewComponent
  43009. */
  43010. FileChooserDialogBox (const String& title,
  43011. const String& instructions,
  43012. FileBrowserComponent& browserComponent,
  43013. bool warnAboutOverwritingExistingFiles,
  43014. const Colour& backgroundColour);
  43015. /** Destructor. */
  43016. ~FileChooserDialogBox();
  43017. #if JUCE_MODAL_LOOPS_PERMITTED
  43018. /** Displays and runs the dialog box modally.
  43019. This will show the box with the specified size, returning true if the user
  43020. pressed 'ok', or false if they cancelled.
  43021. Leave the width or height as 0 to use the default size
  43022. */
  43023. bool show (int width = 0, int height = 0);
  43024. /** Displays and runs the dialog box modally.
  43025. This will show the box with the specified size at the specified location,
  43026. returning true if the user pressed 'ok', or false if they cancelled.
  43027. Leave the width or height as 0 to use the default size.
  43028. */
  43029. bool showAt (int x, int y, int width, int height);
  43030. #endif
  43031. /** Sets the size of this dialog box to its default and positions it either in the
  43032. centre of the screen, or centred around a component that is provided.
  43033. */
  43034. void centreWithDefaultSize (Component* componentToCentreAround = 0);
  43035. /** A set of colour IDs to use to change the colour of various aspects of the box.
  43036. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43037. methods.
  43038. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43039. */
  43040. enum ColourIds
  43041. {
  43042. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  43043. };
  43044. /** @internal */
  43045. void buttonClicked (Button* button);
  43046. /** @internal */
  43047. void closeButtonPressed();
  43048. /** @internal */
  43049. void selectionChanged();
  43050. /** @internal */
  43051. void fileClicked (const File& file, const MouseEvent& e);
  43052. /** @internal */
  43053. void fileDoubleClicked (const File& file);
  43054. private:
  43055. class ContentComponent;
  43056. ContentComponent* content;
  43057. const bool warnAboutOverwritingExistingFiles;
  43058. void okButtonPressed();
  43059. void createNewFolder();
  43060. void createNewFolderConfirmed (const String& name);
  43061. static void okToOverwriteFileCallback (int result, FileChooserDialogBox*);
  43062. static void createNewFolderCallback (int result, FileChooserDialogBox*, Component::SafePointer<AlertWindow>);
  43063. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileChooserDialogBox);
  43064. };
  43065. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  43066. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  43067. #endif
  43068. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  43069. #endif
  43070. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43071. /*** Start of inlined file: juce_FileListComponent.h ***/
  43072. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43073. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43074. /**
  43075. A component that displays the files in a directory as a listbox.
  43076. This implements the DirectoryContentsDisplayComponent base class so that
  43077. it can be used in a FileBrowserComponent.
  43078. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  43079. class and the FileBrowserListener class.
  43080. @see DirectoryContentsList, FileTreeComponent
  43081. */
  43082. class JUCE_API FileListComponent : public ListBox,
  43083. public DirectoryContentsDisplayComponent,
  43084. private ListBoxModel,
  43085. private ChangeListener
  43086. {
  43087. public:
  43088. /** Creates a listbox to show the contents of a specified directory.
  43089. */
  43090. FileListComponent (DirectoryContentsList& listToShow);
  43091. /** Destructor. */
  43092. ~FileListComponent();
  43093. /** Returns the number of files the user has got selected.
  43094. @see getSelectedFile
  43095. */
  43096. int getNumSelectedFiles() const;
  43097. /** Returns one of the files that the user has currently selected.
  43098. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  43099. @see getNumSelectedFiles
  43100. */
  43101. const File getSelectedFile (int index = 0) const;
  43102. /** Deselects any files that are currently selected. */
  43103. void deselectAllFiles();
  43104. /** Scrolls to the top of the list. */
  43105. void scrollToTop();
  43106. /** @internal */
  43107. void changeListenerCallback (ChangeBroadcaster*);
  43108. /** @internal */
  43109. int getNumRows();
  43110. /** @internal */
  43111. void paintListBoxItem (int, Graphics&, int, int, bool);
  43112. /** @internal */
  43113. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  43114. /** @internal */
  43115. void selectedRowsChanged (int lastRowSelected);
  43116. /** @internal */
  43117. void deleteKeyPressed (int currentSelectedRow);
  43118. /** @internal */
  43119. void returnKeyPressed (int currentSelectedRow);
  43120. private:
  43121. File lastDirectory;
  43122. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListComponent);
  43123. };
  43124. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  43125. /*** End of inlined file: juce_FileListComponent.h ***/
  43126. #endif
  43127. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43128. /*** Start of inlined file: juce_FilenameComponent.h ***/
  43129. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43130. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43131. class FilenameComponent;
  43132. /**
  43133. Listens for events happening to a FilenameComponent.
  43134. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  43135. register one of these objects for event callbacks when the filename is changed.
  43136. @see FilenameComponent
  43137. */
  43138. class JUCE_API FilenameComponentListener
  43139. {
  43140. public:
  43141. /** Destructor. */
  43142. virtual ~FilenameComponentListener() {}
  43143. /** This method is called after the FilenameComponent's file has been changed. */
  43144. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  43145. };
  43146. /**
  43147. Shows a filename as an editable text box, with a 'browse' button and a
  43148. drop-down list for recently selected files.
  43149. A handy component for dialogue boxes where you want the user to be able to
  43150. select a file or directory.
  43151. Attach an FilenameComponentListener using the addListener() method, and it will
  43152. get called each time the user changes the filename, either by browsing for a file
  43153. and clicking 'ok', or by typing a new filename into the box and pressing return.
  43154. @see FileChooser, ComboBox
  43155. */
  43156. class JUCE_API FilenameComponent : public Component,
  43157. public SettableTooltipClient,
  43158. public FileDragAndDropTarget,
  43159. private AsyncUpdater,
  43160. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  43161. private ComboBoxListener
  43162. {
  43163. public:
  43164. /** Creates a FilenameComponent.
  43165. @param name the name for this component.
  43166. @param currentFile the file to initially show in the box
  43167. @param canEditFilename if true, the user can manually edit the filename; if false,
  43168. they can only change it by browsing for a new file
  43169. @param isDirectory if true, the file will be treated as a directory, and
  43170. an appropriate directory browser used
  43171. @param isForSaving if true, the file browser will allow non-existent files to
  43172. be picked, as the file is assumed to be used for saving rather
  43173. than loading
  43174. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  43175. If an empty string is passed in, then the pattern is assumed to be "*"
  43176. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  43177. to any filenames that are entered or chosen
  43178. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  43179. will only appear if the initial file isn't valid)
  43180. */
  43181. FilenameComponent (const String& name,
  43182. const File& currentFile,
  43183. bool canEditFilename,
  43184. bool isDirectory,
  43185. bool isForSaving,
  43186. const String& fileBrowserWildcard,
  43187. const String& enforcedSuffix,
  43188. const String& textWhenNothingSelected);
  43189. /** Destructor. */
  43190. ~FilenameComponent();
  43191. /** Returns the currently displayed filename. */
  43192. const File getCurrentFile() const;
  43193. /** Changes the current filename.
  43194. If addToRecentlyUsedList is true, the filename will also be added to the
  43195. drop-down list of recent files.
  43196. If sendChangeNotification is false, then the listeners won't be told of the
  43197. change.
  43198. */
  43199. void setCurrentFile (File newFile,
  43200. bool addToRecentlyUsedList,
  43201. bool sendChangeNotification = true);
  43202. /** Changes whether the use can type into the filename box.
  43203. */
  43204. void setFilenameIsEditable (bool shouldBeEditable);
  43205. /** Sets a file or directory to be the default starting point for the browser to show.
  43206. This is only used if the current file hasn't been set.
  43207. */
  43208. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  43209. /** Returns all the entries on the recent files list.
  43210. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  43211. state of this list.
  43212. @see setRecentlyUsedFilenames
  43213. */
  43214. const StringArray getRecentlyUsedFilenames() const;
  43215. /** Sets all the entries on the recent files list.
  43216. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  43217. state of this list.
  43218. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  43219. */
  43220. void setRecentlyUsedFilenames (const StringArray& filenames);
  43221. /** Adds an entry to the recently-used files dropdown list.
  43222. If the file is already in the list, it will be moved to the top. A limit
  43223. is also placed on the number of items that are kept in the list.
  43224. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  43225. */
  43226. void addRecentlyUsedFile (const File& file);
  43227. /** Changes the limit for the number of files that will be stored in the recent-file list.
  43228. */
  43229. void setMaxNumberOfRecentFiles (int newMaximum);
  43230. /** Changes the text shown on the 'browse' button.
  43231. By default this button just says "..." but you can change it. The button itself
  43232. can be changed using the look-and-feel classes, so it might not actually have any
  43233. text on it.
  43234. */
  43235. void setBrowseButtonText (const String& browseButtonText);
  43236. /** Adds a listener that will be called when the selected file is changed. */
  43237. void addListener (FilenameComponentListener* listener);
  43238. /** Removes a previously-registered listener. */
  43239. void removeListener (FilenameComponentListener* listener);
  43240. /** Gives the component a tooltip. */
  43241. void setTooltip (const String& newTooltip);
  43242. /** @internal */
  43243. void paintOverChildren (Graphics& g);
  43244. /** @internal */
  43245. void resized();
  43246. /** @internal */
  43247. void lookAndFeelChanged();
  43248. /** @internal */
  43249. bool isInterestedInFileDrag (const StringArray& files);
  43250. /** @internal */
  43251. void filesDropped (const StringArray& files, int, int);
  43252. /** @internal */
  43253. void fileDragEnter (const StringArray& files, int, int);
  43254. /** @internal */
  43255. void fileDragExit (const StringArray& files);
  43256. private:
  43257. ComboBox filenameBox;
  43258. String lastFilename;
  43259. ScopedPointer<Button> browseButton;
  43260. int maxRecentFiles;
  43261. bool isDir, isSaving, isFileDragOver;
  43262. String wildcard, enforcedSuffix, browseButtonText;
  43263. ListenerList <FilenameComponentListener> listeners;
  43264. File defaultBrowseFile;
  43265. void comboBoxChanged (ComboBox*);
  43266. void buttonClicked (Button* button);
  43267. void handleAsyncUpdate();
  43268. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilenameComponent);
  43269. };
  43270. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  43271. /*** End of inlined file: juce_FilenameComponent.h ***/
  43272. #endif
  43273. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  43274. #endif
  43275. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  43276. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  43277. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  43278. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  43279. /**
  43280. Shows a set of file paths in a list, allowing them to be added, removed or
  43281. re-ordered.
  43282. @see FileSearchPath
  43283. */
  43284. class JUCE_API FileSearchPathListComponent : public Component,
  43285. public SettableTooltipClient,
  43286. public FileDragAndDropTarget,
  43287. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  43288. private ListBoxModel
  43289. {
  43290. public:
  43291. /** Creates an empty FileSearchPathListComponent. */
  43292. FileSearchPathListComponent();
  43293. /** Destructor. */
  43294. ~FileSearchPathListComponent();
  43295. /** Returns the path as it is currently shown. */
  43296. const FileSearchPath& getPath() const throw() { return path; }
  43297. /** Changes the current path. */
  43298. void setPath (const FileSearchPath& newPath);
  43299. /** Sets a file or directory to be the default starting point for the browser to show.
  43300. This is only used if the current file hasn't been set.
  43301. */
  43302. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  43303. /** A set of colour IDs to use to change the colour of various aspects of the label.
  43304. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43305. methods.
  43306. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43307. */
  43308. enum ColourIds
  43309. {
  43310. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  43311. Make this transparent if you don't want the background to be filled. */
  43312. };
  43313. /** @internal */
  43314. int getNumRows();
  43315. /** @internal */
  43316. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  43317. /** @internal */
  43318. void deleteKeyPressed (int lastRowSelected);
  43319. /** @internal */
  43320. void returnKeyPressed (int lastRowSelected);
  43321. /** @internal */
  43322. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  43323. /** @internal */
  43324. void selectedRowsChanged (int lastRowSelected);
  43325. /** @internal */
  43326. void resized();
  43327. /** @internal */
  43328. void paint (Graphics& g);
  43329. /** @internal */
  43330. bool isInterestedInFileDrag (const StringArray& files);
  43331. /** @internal */
  43332. void filesDropped (const StringArray& files, int, int);
  43333. /** @internal */
  43334. void buttonClicked (Button* button);
  43335. private:
  43336. FileSearchPath path;
  43337. File defaultBrowseTarget;
  43338. ListBox listBox;
  43339. TextButton addButton, removeButton, changeButton;
  43340. DrawableButton upButton, downButton;
  43341. void changed();
  43342. void updateButtons();
  43343. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileSearchPathListComponent);
  43344. };
  43345. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  43346. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  43347. #endif
  43348. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  43349. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  43350. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  43351. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  43352. /**
  43353. A component that displays the files in a directory as a treeview.
  43354. This implements the DirectoryContentsDisplayComponent base class so that
  43355. it can be used in a FileBrowserComponent.
  43356. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  43357. class and the FileBrowserListener class.
  43358. @see DirectoryContentsList, FileListComponent
  43359. */
  43360. class JUCE_API FileTreeComponent : public TreeView,
  43361. public DirectoryContentsDisplayComponent
  43362. {
  43363. public:
  43364. /** Creates a listbox to show the contents of a specified directory.
  43365. */
  43366. FileTreeComponent (DirectoryContentsList& listToShow);
  43367. /** Destructor. */
  43368. ~FileTreeComponent();
  43369. /** Returns the number of files the user has got selected.
  43370. @see getSelectedFile
  43371. */
  43372. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  43373. /** Returns one of the files that the user has currently selected.
  43374. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  43375. @see getNumSelectedFiles
  43376. */
  43377. const File getSelectedFile (int index = 0) const;
  43378. /** Deselects any files that are currently selected. */
  43379. void deselectAllFiles();
  43380. /** Scrolls the list to the top. */
  43381. void scrollToTop();
  43382. /** Setting a name for this allows tree items to be dragged.
  43383. The string that you pass in here will be returned by the getDragSourceDescription()
  43384. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  43385. */
  43386. void setDragAndDropDescription (const String& description);
  43387. /** Returns the last value that was set by setDragAndDropDescription().
  43388. */
  43389. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  43390. private:
  43391. String dragAndDropDescription;
  43392. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileTreeComponent);
  43393. };
  43394. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  43395. /*** End of inlined file: juce_FileTreeComponent.h ***/
  43396. #endif
  43397. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  43398. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  43399. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  43400. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  43401. /**
  43402. A simple preview component that shows thumbnails of image files.
  43403. @see FileChooserDialogBox, FilePreviewComponent
  43404. */
  43405. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  43406. private Timer
  43407. {
  43408. public:
  43409. /** Creates an ImagePreviewComponent. */
  43410. ImagePreviewComponent();
  43411. /** Destructor. */
  43412. ~ImagePreviewComponent();
  43413. /** @internal */
  43414. void selectedFileChanged (const File& newSelectedFile);
  43415. /** @internal */
  43416. void paint (Graphics& g);
  43417. /** @internal */
  43418. void timerCallback();
  43419. private:
  43420. File fileToLoad;
  43421. Image currentThumbnail;
  43422. String currentDetails;
  43423. void getThumbSize (int& w, int& h) const;
  43424. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImagePreviewComponent);
  43425. };
  43426. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  43427. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  43428. #endif
  43429. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  43430. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  43431. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  43432. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  43433. /**
  43434. A type of FileFilter that works by wildcard pattern matching.
  43435. This filter only allows files that match one of the specified patterns, but
  43436. allows all directories through.
  43437. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  43438. */
  43439. class JUCE_API WildcardFileFilter : public FileFilter
  43440. {
  43441. public:
  43442. /**
  43443. Creates a wildcard filter for one or more patterns.
  43444. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  43445. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  43446. or .aiff.
  43447. The description is a name to show the user in a list of possible patterns, so
  43448. for the wav/aiff example, your description might be "audio files".
  43449. */
  43450. WildcardFileFilter (const String& fileWildcardPatterns,
  43451. const String& directoryWildcardPatterns,
  43452. const String& description);
  43453. /** Destructor. */
  43454. ~WildcardFileFilter();
  43455. /** Returns true if the filename matches one of the patterns specified. */
  43456. bool isFileSuitable (const File& file) const;
  43457. /** This always returns true. */
  43458. bool isDirectorySuitable (const File& file) const;
  43459. private:
  43460. StringArray fileWildcards, directoryWildcards;
  43461. static void parse (const String& pattern, StringArray& result);
  43462. static bool match (const File& file, const StringArray& wildcards);
  43463. JUCE_LEAK_DETECTOR (WildcardFileFilter);
  43464. };
  43465. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  43466. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  43467. #endif
  43468. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  43469. #endif
  43470. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  43471. #endif
  43472. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  43473. #endif
  43474. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  43475. #endif
  43476. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  43477. #endif
  43478. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  43479. #endif
  43480. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  43481. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  43482. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  43483. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  43484. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  43485. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  43486. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  43487. /**
  43488. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  43489. command in a ApplicationCommandManager.
  43490. Normally, you won't actually create a KeyPressMappingSet directly, because
  43491. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  43492. you'd create yourself an ApplicationCommandManager, and call its
  43493. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  43494. KeyPressMappingSet.
  43495. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  43496. to the top-level component for which you want to handle keystrokes. So for example:
  43497. @code
  43498. class MyMainWindow : public Component
  43499. {
  43500. ApplicationCommandManager* myCommandManager;
  43501. public:
  43502. MyMainWindow()
  43503. {
  43504. myCommandManager = new ApplicationCommandManager();
  43505. // first, make sure the command manager has registered all the commands that its
  43506. // targets can perform..
  43507. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  43508. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  43509. // this will use the command manager to initialise the KeyPressMappingSet with
  43510. // the default keypresses that were specified when the targets added their commands
  43511. // to the manager.
  43512. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  43513. // having set up the default key-mappings, you might now want to load the last set
  43514. // of mappings that the user configured.
  43515. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  43516. // Now tell our top-level window to send any keypresses that arrive to the
  43517. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  43518. addKeyListener (myCommandManager->getKeyMappings());
  43519. }
  43520. ...
  43521. }
  43522. @endcode
  43523. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  43524. register to be told when a command or mapping is added, removed, etc.
  43525. There's also a UI component called KeyMappingEditorComponent that can be used
  43526. to easily edit the key mappings.
  43527. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  43528. */
  43529. class JUCE_API KeyPressMappingSet : public KeyListener,
  43530. public ChangeBroadcaster,
  43531. public FocusChangeListener
  43532. {
  43533. public:
  43534. /** Creates a KeyPressMappingSet for a given command manager.
  43535. Normally, you won't actually create a KeyPressMappingSet directly, because
  43536. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  43537. best thing to do is to create your ApplicationCommandManager, and use the
  43538. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  43539. When a suitable keypress happens, the manager's invoke() method will be
  43540. used to invoke the appropriate command.
  43541. @see ApplicationCommandManager
  43542. */
  43543. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  43544. /** Creates an copy of a KeyPressMappingSet. */
  43545. KeyPressMappingSet (const KeyPressMappingSet& other);
  43546. /** Destructor. */
  43547. ~KeyPressMappingSet();
  43548. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  43549. /** Returns a list of keypresses that are assigned to a particular command.
  43550. @param commandID the command's ID
  43551. */
  43552. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  43553. /** Assigns a keypress to a command.
  43554. If the keypress is already assigned to a different command, it will first be
  43555. removed from that command, to avoid it triggering multiple functions.
  43556. @param commandID the ID of the command that you want to add a keypress to. If
  43557. this is 0, the keypress will be removed from anything that it
  43558. was previously assigned to, but not re-assigned
  43559. @param newKeyPress the new key-press
  43560. @param insertIndex if this is less than zero, the key will be appended to the
  43561. end of the list of keypresses; otherwise the new keypress will
  43562. be inserted into the existing list at this index
  43563. */
  43564. void addKeyPress (CommandID commandID,
  43565. const KeyPress& newKeyPress,
  43566. int insertIndex = -1);
  43567. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  43568. @see resetToDefaultMapping
  43569. */
  43570. void resetToDefaultMappings();
  43571. /** Resets all key-mappings to the defaults for a particular command.
  43572. @see resetToDefaultMappings
  43573. */
  43574. void resetToDefaultMapping (CommandID commandID);
  43575. /** Removes all keypresses that are assigned to any commands. */
  43576. void clearAllKeyPresses();
  43577. /** Removes all keypresses that are assigned to a particular command. */
  43578. void clearAllKeyPresses (CommandID commandID);
  43579. /** Removes one of the keypresses that are assigned to a command.
  43580. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  43581. which the keyPressIndex refers.
  43582. */
  43583. void removeKeyPress (CommandID commandID, int keyPressIndex);
  43584. /** Removes a keypress from any command that it may be assigned to.
  43585. */
  43586. void removeKeyPress (const KeyPress& keypress);
  43587. /** Returns true if the given command is linked to this key. */
  43588. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const throw();
  43589. /** Looks for a command that corresponds to a keypress.
  43590. @returns the UID of the command or 0 if none was found
  43591. */
  43592. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  43593. /** Tries to recreate the mappings from a previously stored state.
  43594. The XML passed in must have been created by the createXml() method.
  43595. If the stored state makes any reference to commands that aren't
  43596. currently available, these will be ignored.
  43597. If the set of mappings being loaded was a set of differences (using createXml (true)),
  43598. then this will call resetToDefaultMappings() and then merge the saved mappings
  43599. on top. If the saved set was created with createXml (false), then this method
  43600. will first clear all existing mappings and load the saved ones as a complete set.
  43601. @returns true if it manages to load the XML correctly
  43602. @see createXml
  43603. */
  43604. bool restoreFromXml (const XmlElement& xmlVersion);
  43605. /** Creates an XML representation of the current mappings.
  43606. This will produce a lump of XML that can be later reloaded using
  43607. restoreFromXml() to recreate the current mapping state.
  43608. The object that is returned must be deleted by the caller.
  43609. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  43610. will be saved into the XML. If it's true, then the XML will
  43611. only store the differences between the current mappings and
  43612. the default mappings you'd get from calling resetToDefaultMappings().
  43613. The advantage of saving a set of differences from the default is that
  43614. if you change the default mappings (in a new version of your app, for
  43615. example), then these will be merged into a user's saved preferences.
  43616. @see restoreFromXml
  43617. */
  43618. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  43619. /** @internal */
  43620. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  43621. /** @internal */
  43622. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  43623. /** @internal */
  43624. void globalFocusChanged (Component* focusedComponent);
  43625. private:
  43626. ApplicationCommandManager* commandManager;
  43627. struct CommandMapping
  43628. {
  43629. CommandID commandID;
  43630. Array <KeyPress> keypresses;
  43631. bool wantsKeyUpDownCallbacks;
  43632. };
  43633. OwnedArray <CommandMapping> mappings;
  43634. struct KeyPressTime
  43635. {
  43636. KeyPress key;
  43637. uint32 timeWhenPressed;
  43638. };
  43639. OwnedArray <KeyPressTime> keysDown;
  43640. void handleMessage (const Message& message);
  43641. void invokeCommand (const CommandID commandID,
  43642. const KeyPress& keyPress,
  43643. const bool isKeyDown,
  43644. const int millisecsSinceKeyPressed,
  43645. Component* const originatingComponent) const;
  43646. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  43647. JUCE_LEAK_DETECTOR (KeyPressMappingSet);
  43648. };
  43649. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  43650. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  43651. /**
  43652. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  43653. object.
  43654. @see KeyPressMappingSet
  43655. */
  43656. class JUCE_API KeyMappingEditorComponent : public Component
  43657. {
  43658. public:
  43659. /** Creates a KeyMappingEditorComponent.
  43660. @param mappingSet this is the set of mappings to display and edit. Make sure the
  43661. mappings object is not deleted before this component!
  43662. @param showResetToDefaultButton if true, then at the bottom of the list, the
  43663. component will include a 'reset to defaults' button.
  43664. */
  43665. KeyMappingEditorComponent (KeyPressMappingSet& mappingSet,
  43666. bool showResetToDefaultButton);
  43667. /** Destructor. */
  43668. virtual ~KeyMappingEditorComponent();
  43669. /** Sets up the colours to use for parts of the component.
  43670. @param mainBackground colour to use for most of the background
  43671. @param textColour colour to use for the text
  43672. */
  43673. void setColours (const Colour& mainBackground,
  43674. const Colour& textColour);
  43675. /** Returns the KeyPressMappingSet that this component is acting upon. */
  43676. KeyPressMappingSet& getMappings() const throw() { return mappings; }
  43677. /** Can be overridden if some commands need to be excluded from the list.
  43678. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  43679. method to decide what to return, but you can override it to handle special cases.
  43680. */
  43681. virtual bool shouldCommandBeIncluded (CommandID commandID);
  43682. /** Can be overridden to indicate that some commands are shown as read-only.
  43683. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  43684. method to decide what to return, but you can override it to handle special cases.
  43685. */
  43686. virtual bool isCommandReadOnly (CommandID commandID);
  43687. /** This can be overridden to let you change the format of the string used
  43688. to describe a keypress.
  43689. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  43690. keys that are triggered by something else externally. If you override the
  43691. method, be sure to let the base class's method handle keys you're not
  43692. interested in.
  43693. */
  43694. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  43695. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  43696. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43697. methods.
  43698. To change the colours of the menu that pops up
  43699. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43700. */
  43701. enum ColourIds
  43702. {
  43703. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  43704. textColourId = 0x100ad01, /**< The colour for the text. */
  43705. };
  43706. /** @internal */
  43707. void parentHierarchyChanged();
  43708. /** @internal */
  43709. void resized();
  43710. private:
  43711. KeyPressMappingSet& mappings;
  43712. TreeView tree;
  43713. TextButton resetButton;
  43714. class TopLevelItem;
  43715. class ChangeKeyButton;
  43716. class MappingItem;
  43717. class CategoryItem;
  43718. class ItemComponent;
  43719. friend class TopLevelItem;
  43720. friend class OwnedArray <ChangeKeyButton>;
  43721. friend class ScopedPointer<TopLevelItem>;
  43722. ScopedPointer<TopLevelItem> treeItem;
  43723. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KeyMappingEditorComponent);
  43724. };
  43725. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  43726. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  43727. #endif
  43728. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  43729. #endif
  43730. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  43731. #endif
  43732. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  43733. #endif
  43734. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  43735. #endif
  43736. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  43737. #endif
  43738. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  43739. #endif
  43740. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  43741. #endif
  43742. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  43743. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  43744. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  43745. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  43746. /** An object that watches for any movement of a component or any of its parent components.
  43747. This makes it easy to check when a component is moved relative to its top-level
  43748. peer window. The normal Component::moved() method is only called when a component
  43749. moves relative to its immediate parent, and sometimes you want to know if any of
  43750. components higher up the tree have moved (which of course will affect the overall
  43751. position of all their sub-components).
  43752. It also includes a callback that lets you know when the top-level peer is changed.
  43753. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  43754. because they need to keep their custom windows in the right place and respond to
  43755. changes in the peer.
  43756. */
  43757. class JUCE_API ComponentMovementWatcher : public ComponentListener
  43758. {
  43759. public:
  43760. /** Creates a ComponentMovementWatcher to watch a given target component. */
  43761. ComponentMovementWatcher (Component* component);
  43762. /** Destructor. */
  43763. ~ComponentMovementWatcher();
  43764. /** This callback happens when the component that is being watched is moved
  43765. relative to its top-level peer window, or when it is resized. */
  43766. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  43767. /** This callback happens when the component's top-level peer is changed. */
  43768. virtual void componentPeerChanged() = 0;
  43769. /** This callback happens when the component's visibility state changes, possibly due to
  43770. one of its parents being made visible or invisible.
  43771. */
  43772. virtual void componentVisibilityChanged() = 0;
  43773. /** @internal */
  43774. void componentParentHierarchyChanged (Component& component);
  43775. /** @internal */
  43776. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  43777. /** @internal */
  43778. void componentBeingDeleted (Component& component);
  43779. /** @internal */
  43780. void componentVisibilityChanged (Component& component);
  43781. private:
  43782. WeakReference<Component> component;
  43783. ComponentPeer* lastPeer;
  43784. Array <Component*> registeredParentComps;
  43785. bool reentrant, wasShowing;
  43786. Rectangle<int> lastBounds;
  43787. void unregister();
  43788. void registerWithParentComps();
  43789. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentMovementWatcher);
  43790. };
  43791. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  43792. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  43793. #endif
  43794. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  43795. /*** Start of inlined file: juce_GroupComponent.h ***/
  43796. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  43797. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  43798. /**
  43799. A component that draws an outline around itself and has an optional title at
  43800. the top, for drawing an outline around a group of controls.
  43801. */
  43802. class JUCE_API GroupComponent : public Component
  43803. {
  43804. public:
  43805. /** Creates a GroupComponent.
  43806. @param componentName the name to give the component
  43807. @param labelText the text to show at the top of the outline
  43808. */
  43809. GroupComponent (const String& componentName = String::empty,
  43810. const String& labelText = String::empty);
  43811. /** Destructor. */
  43812. ~GroupComponent();
  43813. /** Changes the text that's shown at the top of the component. */
  43814. void setText (const String& newText);
  43815. /** Returns the currently displayed text label. */
  43816. const String getText() const;
  43817. /** Sets the positioning of the text label.
  43818. (The default is Justification::left)
  43819. @see getTextLabelPosition
  43820. */
  43821. void setTextLabelPosition (const Justification& justification);
  43822. /** Returns the current text label position.
  43823. @see setTextLabelPosition
  43824. */
  43825. const Justification getTextLabelPosition() const throw() { return justification; }
  43826. /** A set of colour IDs to use to change the colour of various aspects of the component.
  43827. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43828. methods.
  43829. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43830. */
  43831. enum ColourIds
  43832. {
  43833. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  43834. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  43835. };
  43836. /** @internal */
  43837. void paint (Graphics& g);
  43838. /** @internal */
  43839. void enablementChanged();
  43840. /** @internal */
  43841. void colourChanged();
  43842. private:
  43843. String text;
  43844. Justification justification;
  43845. JUCE_DECLARE_NON_COPYABLE (GroupComponent);
  43846. };
  43847. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  43848. /*** End of inlined file: juce_GroupComponent.h ***/
  43849. #endif
  43850. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  43851. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  43852. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  43853. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  43854. /*** Start of inlined file: juce_TabbedComponent.h ***/
  43855. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  43856. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  43857. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  43858. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  43859. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  43860. class TabbedButtonBar;
  43861. /** In a TabbedButtonBar, this component is used for each of the buttons.
  43862. If you want to create a TabbedButtonBar with custom tab components, derive
  43863. your component from this class, and override the TabbedButtonBar::createTabButton()
  43864. method to create it instead of the default one.
  43865. @see TabbedButtonBar
  43866. */
  43867. class JUCE_API TabBarButton : public Button
  43868. {
  43869. public:
  43870. /** Creates the tab button. */
  43871. TabBarButton (const String& name, TabbedButtonBar& ownerBar);
  43872. /** Destructor. */
  43873. ~TabBarButton();
  43874. /** Chooses the best length for the tab, given the specified depth.
  43875. If the tab is horizontal, this should return its width, and the depth
  43876. specifies its height. If it's vertical, it should return the height, and
  43877. the depth is actually its width.
  43878. */
  43879. virtual int getBestTabLength (int depth);
  43880. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  43881. void clicked (const ModifierKeys& mods);
  43882. bool hitTest (int x, int y);
  43883. protected:
  43884. friend class TabbedButtonBar;
  43885. TabbedButtonBar& owner;
  43886. int overlapPixels;
  43887. DropShadowEffect shadow;
  43888. /** Returns an area of the component that's safe to draw in.
  43889. This deals with the orientation of the tabs, which affects which side is
  43890. touching the tabbed box's content component.
  43891. */
  43892. const Rectangle<int> getActiveArea();
  43893. /** Returns this tab's index in its tab bar. */
  43894. int getIndex() const;
  43895. private:
  43896. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabBarButton);
  43897. };
  43898. /**
  43899. A vertical or horizontal bar containing tabs that you can select.
  43900. You can use one of these to generate things like a dialog box that has
  43901. tabbed pages you can flip between. Attach a ChangeListener to the
  43902. button bar to be told when the user changes the page.
  43903. An easier method than doing this is to use a TabbedComponent, which
  43904. contains its own TabbedButtonBar and which takes care of the layout
  43905. and other housekeeping.
  43906. @see TabbedComponent
  43907. */
  43908. class JUCE_API TabbedButtonBar : public Component,
  43909. public ChangeBroadcaster
  43910. {
  43911. public:
  43912. /** The placement of the tab-bar
  43913. @see setOrientation, getOrientation
  43914. */
  43915. enum Orientation
  43916. {
  43917. TabsAtTop,
  43918. TabsAtBottom,
  43919. TabsAtLeft,
  43920. TabsAtRight
  43921. };
  43922. /** Creates a TabbedButtonBar with a given placement.
  43923. You can change the orientation later if you need to.
  43924. */
  43925. TabbedButtonBar (Orientation orientation);
  43926. /** Destructor. */
  43927. ~TabbedButtonBar();
  43928. /** Changes the bar's orientation.
  43929. This won't change the bar's actual size - you'll need to do that yourself,
  43930. but this determines which direction the tabs go in, and which side they're
  43931. stuck to.
  43932. */
  43933. void setOrientation (Orientation orientation);
  43934. /** Returns the current orientation.
  43935. @see setOrientation
  43936. */
  43937. Orientation getOrientation() const throw() { return orientation; }
  43938. /** Changes the minimum scale factor to which the tabs can be compressed when trying to
  43939. fit a lot of tabs on-screen.
  43940. */
  43941. void setMinimumTabScaleFactor (double newMinimumScale);
  43942. /** Deletes all the tabs from the bar.
  43943. @see addTab
  43944. */
  43945. void clearTabs();
  43946. /** Adds a tab to the bar.
  43947. Tabs are added in left-to-right reading order.
  43948. If this is the first tab added, it'll also be automatically selected.
  43949. */
  43950. void addTab (const String& tabName,
  43951. const Colour& tabBackgroundColour,
  43952. int insertIndex = -1);
  43953. /** Changes the name of one of the tabs. */
  43954. void setTabName (int tabIndex,
  43955. const String& newName);
  43956. /** Gets rid of one of the tabs. */
  43957. void removeTab (int tabIndex);
  43958. /** Moves a tab to a new index in the list.
  43959. Pass -1 as the index to move it to the end of the list.
  43960. */
  43961. void moveTab (int currentIndex, int newIndex);
  43962. /** Returns the number of tabs in the bar. */
  43963. int getNumTabs() const;
  43964. /** Returns a list of all the tab names in the bar. */
  43965. const StringArray getTabNames() const;
  43966. /** Changes the currently selected tab.
  43967. This will send a change message and cause a synchronous callback to
  43968. the currentTabChanged() method. (But if the given tab is already selected,
  43969. nothing will be done).
  43970. To deselect all the tabs, use an index of -1.
  43971. */
  43972. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  43973. /** Returns the name of the currently selected tab.
  43974. This could be an empty string if none are selected.
  43975. */
  43976. const String getCurrentTabName() const;
  43977. /** Returns the index of the currently selected tab.
  43978. This could return -1 if none are selected.
  43979. */
  43980. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  43981. /** Returns the button for a specific tab.
  43982. The button that is returned may be deleted later by this component, so don't hang
  43983. on to the pointer that is returned. A null pointer may be returned if the index is
  43984. out of range.
  43985. */
  43986. TabBarButton* getTabButton (int index) const;
  43987. /** Returns the index of a TabBarButton if it belongs to this bar. */
  43988. int indexOfTabButton (const TabBarButton* button) const;
  43989. /** Callback method to indicate the selected tab has been changed.
  43990. @see setCurrentTabIndex
  43991. */
  43992. virtual void currentTabChanged (int newCurrentTabIndex,
  43993. const String& newCurrentTabName);
  43994. /** Callback method to indicate that the user has right-clicked on a tab.
  43995. (Or ctrl-clicked on the Mac)
  43996. */
  43997. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  43998. /** Returns the colour of a tab.
  43999. This is the colour that was specified in addTab().
  44000. */
  44001. const Colour getTabBackgroundColour (int tabIndex);
  44002. /** Changes the background colour of a tab.
  44003. @see addTab, getTabBackgroundColour
  44004. */
  44005. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  44006. /** A set of colour IDs to use to change the colour of various aspects of the component.
  44007. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44008. methods.
  44009. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44010. */
  44011. enum ColourIds
  44012. {
  44013. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  44014. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  44015. the look and feel will choose an appropriate colour. */
  44016. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  44017. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  44018. this isn't specified, the look and feel will choose an appropriate
  44019. colour. */
  44020. };
  44021. /** @internal */
  44022. void resized();
  44023. /** @internal */
  44024. void lookAndFeelChanged();
  44025. protected:
  44026. /** This creates one of the tabs.
  44027. If you need to use custom tab components, you can override this method and
  44028. return your own class instead of the default.
  44029. */
  44030. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  44031. private:
  44032. Orientation orientation;
  44033. struct TabInfo
  44034. {
  44035. ScopedPointer<TabBarButton> component;
  44036. String name;
  44037. Colour colour;
  44038. };
  44039. OwnedArray <TabInfo> tabs;
  44040. double minimumScale;
  44041. int currentTabIndex;
  44042. class BehindFrontTabComp;
  44043. friend class BehindFrontTabComp;
  44044. friend class ScopedPointer<BehindFrontTabComp>;
  44045. ScopedPointer<BehindFrontTabComp> behindFrontTab;
  44046. ScopedPointer<Button> extraTabsButton;
  44047. void showExtraItemsMenu();
  44048. static void extraItemsMenuCallback (int, TabbedButtonBar*);
  44049. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedButtonBar);
  44050. };
  44051. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  44052. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  44053. /**
  44054. A component with a TabbedButtonBar along one of its sides.
  44055. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  44056. with addTab(), and this will take care of showing the pages for you when the
  44057. user clicks on a different tab.
  44058. @see TabbedButtonBar
  44059. */
  44060. class JUCE_API TabbedComponent : public Component
  44061. {
  44062. public:
  44063. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  44064. Once created, add some tabs with the addTab() method.
  44065. */
  44066. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  44067. /** Destructor. */
  44068. ~TabbedComponent();
  44069. /** Changes the placement of the tabs.
  44070. This will rearrange the layout to place the tabs along the appropriate
  44071. side of this component, and will shift the content component accordingly.
  44072. @see TabbedButtonBar::setOrientation
  44073. */
  44074. void setOrientation (TabbedButtonBar::Orientation orientation);
  44075. /** Returns the current tab placement.
  44076. @see setOrientation, TabbedButtonBar::getOrientation
  44077. */
  44078. TabbedButtonBar::Orientation getOrientation() const throw();
  44079. /** Specifies how many pixels wide or high the tab-bar should be.
  44080. If the tabs are placed along the top or bottom, this specified the height
  44081. of the bar; if they're along the left or right edges, it'll be the width
  44082. of the bar.
  44083. */
  44084. void setTabBarDepth (int newDepth);
  44085. /** Returns the current thickness of the tab bar.
  44086. @see setTabBarDepth
  44087. */
  44088. int getTabBarDepth() const throw() { return tabDepth; }
  44089. /** Specifies the thickness of an outline that should be drawn around the content component.
  44090. If this thickness is > 0, a line will be drawn around the three sides of the content
  44091. component which don't touch the tab-bar, and the content component will be inset by this amount.
  44092. To set the colour of the line, use setColour (outlineColourId, ...).
  44093. */
  44094. void setOutline (int newThickness);
  44095. /** Specifies a gap to leave around the edge of the content component.
  44096. Each edge of the content component will be indented by the given number of pixels.
  44097. */
  44098. void setIndent (int indentThickness);
  44099. /** Removes all the tabs from the bar.
  44100. @see TabbedButtonBar::clearTabs
  44101. */
  44102. void clearTabs();
  44103. /** Adds a tab to the tab-bar.
  44104. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  44105. is true, it will be deleted when the tab is removed or when this object is
  44106. deleted.
  44107. @see TabbedButtonBar::addTab
  44108. */
  44109. void addTab (const String& tabName,
  44110. const Colour& tabBackgroundColour,
  44111. Component* contentComponent,
  44112. bool deleteComponentWhenNotNeeded,
  44113. int insertIndex = -1);
  44114. /** Changes the name of one of the tabs. */
  44115. void setTabName (int tabIndex, const String& newName);
  44116. /** Gets rid of one of the tabs. */
  44117. void removeTab (int tabIndex);
  44118. /** Returns the number of tabs in the bar. */
  44119. int getNumTabs() const;
  44120. /** Returns a list of all the tab names in the bar. */
  44121. const StringArray getTabNames() const;
  44122. /** Returns the content component that was added for the given index.
  44123. Be sure not to use or delete the components that are returned, as this may interfere
  44124. with the TabbedComponent's use of them.
  44125. */
  44126. Component* getTabContentComponent (int tabIndex) const throw();
  44127. /** Returns the colour of one of the tabs. */
  44128. const Colour getTabBackgroundColour (int tabIndex) const throw();
  44129. /** Changes the background colour of one of the tabs. */
  44130. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  44131. /** Changes the currently-selected tab.
  44132. To deselect all the tabs, pass -1 as the index.
  44133. @see TabbedButtonBar::setCurrentTabIndex
  44134. */
  44135. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  44136. /** Returns the index of the currently selected tab.
  44137. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  44138. */
  44139. int getCurrentTabIndex() const;
  44140. /** Returns the name of the currently selected tab.
  44141. @see addTab, TabbedButtonBar::getCurrentTabName()
  44142. */
  44143. const String getCurrentTabName() const;
  44144. /** Returns the current component that's filling the panel.
  44145. This will return 0 if there isn't one.
  44146. */
  44147. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  44148. /** Callback method to indicate the selected tab has been changed.
  44149. @see setCurrentTabIndex
  44150. */
  44151. virtual void currentTabChanged (int newCurrentTabIndex,
  44152. const String& newCurrentTabName);
  44153. /** Callback method to indicate that the user has right-clicked on a tab.
  44154. (Or ctrl-clicked on the Mac)
  44155. */
  44156. virtual void popupMenuClickOnTab (int tabIndex,
  44157. const String& tabName);
  44158. /** Returns the tab button bar component that is being used.
  44159. */
  44160. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  44161. /** A set of colour IDs to use to change the colour of various aspects of the component.
  44162. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44163. methods.
  44164. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44165. */
  44166. enum ColourIds
  44167. {
  44168. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  44169. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  44170. (See setOutline) */
  44171. };
  44172. /** @internal */
  44173. void paint (Graphics& g);
  44174. /** @internal */
  44175. void resized();
  44176. /** @internal */
  44177. void lookAndFeelChanged();
  44178. protected:
  44179. /** This creates one of the tab buttons.
  44180. If you need to use custom tab components, you can override this method and
  44181. return your own class instead of the default.
  44182. */
  44183. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  44184. /** @internal */
  44185. ScopedPointer<TabbedButtonBar> tabs;
  44186. private:
  44187. Array <WeakReference<Component> > contentComponents;
  44188. WeakReference<Component> panelComponent;
  44189. int tabDepth;
  44190. int outlineThickness, edgeIndent;
  44191. class ButtonBar;
  44192. friend class ButtonBar;
  44193. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  44194. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedComponent);
  44195. };
  44196. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  44197. /*** End of inlined file: juce_TabbedComponent.h ***/
  44198. /*** Start of inlined file: juce_DocumentWindow.h ***/
  44199. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  44200. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  44201. /*** Start of inlined file: juce_MenuBarModel.h ***/
  44202. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  44203. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  44204. /**
  44205. A class for controlling MenuBar components.
  44206. This class is used to tell a MenuBar what menus to show, and to respond
  44207. to a menu being selected.
  44208. @see MenuBarModel::Listener, MenuBarComponent, PopupMenu
  44209. */
  44210. class JUCE_API MenuBarModel : private AsyncUpdater,
  44211. private ApplicationCommandManagerListener
  44212. {
  44213. public:
  44214. MenuBarModel() throw();
  44215. /** Destructor. */
  44216. virtual ~MenuBarModel();
  44217. /** Call this when some of your menu items have changed.
  44218. This method will cause a callback to any MenuBarListener objects that
  44219. are registered with this model.
  44220. If this model is displaying items from an ApplicationCommandManager, you
  44221. can use the setApplicationCommandManagerToWatch() method to cause
  44222. change messages to be sent automatically when the ApplicationCommandManager
  44223. is changed.
  44224. @see addListener, removeListener, MenuBarListener
  44225. */
  44226. void menuItemsChanged();
  44227. /** Tells the menu bar to listen to the specified command manager, and to update
  44228. itself when the commands change.
  44229. This will also allow it to flash a menu name when a command from that menu
  44230. is invoked using a keystroke.
  44231. */
  44232. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) throw();
  44233. /** A class to receive callbacks when a MenuBarModel changes.
  44234. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  44235. */
  44236. class JUCE_API Listener
  44237. {
  44238. public:
  44239. /** Destructor. */
  44240. virtual ~Listener() {}
  44241. /** This callback is made when items are changed in the menu bar model.
  44242. */
  44243. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  44244. /** This callback is made when an application command is invoked that
  44245. is represented by one of the items in the menu bar model.
  44246. */
  44247. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  44248. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  44249. };
  44250. /** Registers a listener for callbacks when the menu items in this model change.
  44251. The listener object will get callbacks when this object's menuItemsChanged()
  44252. method is called.
  44253. @see removeListener
  44254. */
  44255. void addListener (Listener* listenerToAdd) throw();
  44256. /** Removes a listener.
  44257. @see addListener
  44258. */
  44259. void removeListener (Listener* listenerToRemove) throw();
  44260. /** This method must return a list of the names of the menus. */
  44261. virtual const StringArray getMenuBarNames() = 0;
  44262. /** This should return the popup menu to display for a given top-level menu.
  44263. @param topLevelMenuIndex the index of the top-level menu to show
  44264. @param menuName the name of the top-level menu item to show
  44265. */
  44266. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  44267. const String& menuName) = 0;
  44268. /** This is called when a menu item has been clicked on.
  44269. @param menuItemID the item ID of the PopupMenu item that was selected
  44270. @param topLevelMenuIndex the index of the top-level menu from which the item was
  44271. chosen (just in case you've used duplicate ID numbers
  44272. on more than one of the popup menus)
  44273. */
  44274. virtual void menuItemSelected (int menuItemID,
  44275. int topLevelMenuIndex) = 0;
  44276. #if JUCE_MAC || DOXYGEN
  44277. /** MAC ONLY - Sets the model that is currently being shown as the main
  44278. menu bar at the top of the screen on the Mac.
  44279. You can pass 0 to stop the current model being displayed. Be careful
  44280. not to delete a model while it is being used.
  44281. An optional extra menu can be specified, containing items to add to the top of
  44282. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  44283. an apple, it's the one next to it, with your application's name at the top
  44284. and the services menu etc on it). When one of these items is selected, the
  44285. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  44286. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  44287. object then newMenuBarModel must be non-null.
  44288. */
  44289. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  44290. const PopupMenu* extraAppleMenuItems = 0);
  44291. /** MAC ONLY - Returns the menu model that is currently being shown as
  44292. the main menu bar.
  44293. */
  44294. static MenuBarModel* getMacMainMenu();
  44295. #endif
  44296. /** @internal */
  44297. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  44298. /** @internal */
  44299. void applicationCommandListChanged();
  44300. /** @internal */
  44301. void handleAsyncUpdate();
  44302. private:
  44303. ApplicationCommandManager* manager;
  44304. ListenerList <Listener> listeners;
  44305. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarModel);
  44306. };
  44307. /** This typedef is just for compatibility with old code - newer code should use the MenuBarModel::Listener class directly. */
  44308. typedef MenuBarModel::Listener MenuBarModelListener;
  44309. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  44310. /*** End of inlined file: juce_MenuBarModel.h ***/
  44311. /**
  44312. A resizable window with a title bar and maximise, minimise and close buttons.
  44313. This subclass of ResizableWindow creates a fairly standard type of window with
  44314. a title bar and various buttons. The name of the component is shown in the
  44315. title bar, and an icon can optionally be specified with setIcon().
  44316. All the methods available to a ResizableWindow are also available to this,
  44317. so it can easily be made resizable, minimised, maximised, etc.
  44318. It's not advisable to add child components directly to a DocumentWindow: put them
  44319. inside your content component instead. And overriding methods like resized(), moved(), etc
  44320. is also not recommended - instead override these methods for your content component.
  44321. (If for some obscure reason you do need to override these methods, always remember to
  44322. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  44323. decorations correctly).
  44324. You can also automatically add a menu bar to the window, using the setMenuBar()
  44325. method.
  44326. @see ResizableWindow, DialogWindow
  44327. */
  44328. class JUCE_API DocumentWindow : public ResizableWindow
  44329. {
  44330. public:
  44331. /** The set of available button-types that can be put on the title bar.
  44332. @see setTitleBarButtonsRequired
  44333. */
  44334. enum TitleBarButtons
  44335. {
  44336. minimiseButton = 1,
  44337. maximiseButton = 2,
  44338. closeButton = 4,
  44339. /** A combination of all the buttons above. */
  44340. allButtons = 7
  44341. };
  44342. /** Creates a DocumentWindow.
  44343. @param name the name to give the component - this is also
  44344. the title shown at the top of the window. To change
  44345. this later, use setName()
  44346. @param backgroundColour the colour to use for filling the window's background.
  44347. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  44348. should be shown on the title bar. This value is a bitwise
  44349. combination of values from the TitleBarButtons enum. Note
  44350. that it can be "allButtons" to get them all. You
  44351. can change this later with the setTitleBarButtonsRequired()
  44352. method, which can also specify where they are positioned.
  44353. @param addToDesktop if true, the window will be automatically added to the
  44354. desktop; if false, you can use it as a child component
  44355. @see TitleBarButtons
  44356. */
  44357. DocumentWindow (const String& name,
  44358. const Colour& backgroundColour,
  44359. int requiredButtons,
  44360. bool addToDesktop = true);
  44361. /** Destructor.
  44362. If a content component has been set with setContentOwned(), it will be deleted.
  44363. */
  44364. ~DocumentWindow();
  44365. /** Changes the component's name.
  44366. (This is overridden from Component::setName() to cause a repaint, as
  44367. the name is what gets drawn across the window's title bar).
  44368. */
  44369. void setName (const String& newName);
  44370. /** Sets an icon to show in the title bar, next to the title.
  44371. A copy is made internally of the image, so the caller can delete the
  44372. image after calling this. If 0 is passed-in, any existing icon will be
  44373. removed.
  44374. */
  44375. void setIcon (const Image& imageToUse);
  44376. /** Changes the height of the title-bar. */
  44377. void setTitleBarHeight (int newHeight);
  44378. /** Returns the current title bar height. */
  44379. int getTitleBarHeight() const;
  44380. /** Changes the set of title-bar buttons being shown.
  44381. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  44382. should be shown on the title bar. This value is a bitwise
  44383. combination of values from the TitleBarButtons enum. Note
  44384. that it can be "allButtons" to get them all.
  44385. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  44386. left side of the bar; if false, they'll be placed at the right
  44387. */
  44388. void setTitleBarButtonsRequired (int requiredButtons,
  44389. bool positionTitleBarButtonsOnLeft);
  44390. /** Sets whether the title should be centred within the window.
  44391. If true, the title text is shown in the middle of the title-bar; if false,
  44392. it'll be shown at the left of the bar.
  44393. */
  44394. void setTitleBarTextCentred (bool textShouldBeCentred);
  44395. /** Creates a menu inside this window.
  44396. @param menuBarModel this specifies a MenuBarModel that should be used to
  44397. generate the contents of a menu bar that will be placed
  44398. just below the title bar, and just above any content
  44399. component. If this value is zero, any existing menu bar
  44400. will be removed from the component; if non-zero, one will
  44401. be added if it's required.
  44402. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  44403. or less to use the look-and-feel's default size.
  44404. */
  44405. void setMenuBar (MenuBarModel* menuBarModel,
  44406. int menuBarHeight = 0);
  44407. /** Returns the current menu bar component, or null if there isn't one.
  44408. This is probably a MenuBarComponent, unless a custom one has been set using
  44409. setMenuBarComponent().
  44410. */
  44411. Component* getMenuBarComponent() const throw();
  44412. /** Replaces the current menu bar with a custom component.
  44413. The component will be owned and deleted by the document window.
  44414. */
  44415. void setMenuBarComponent (Component* newMenuBarComponent);
  44416. /** This method is called when the user tries to close the window.
  44417. This is triggered by the user clicking the close button, or using some other
  44418. OS-specific key shortcut or OS menu for getting rid of a window.
  44419. If the window is just a pop-up, you should override this closeButtonPressed()
  44420. method and make it delete the window in whatever way is appropriate for your
  44421. app. E.g. you might just want to call "delete this".
  44422. If your app is centred around this window such that the whole app should quit when
  44423. the window is closed, then you will probably want to use this method as an opportunity
  44424. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  44425. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  44426. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  44427. or closing it via the taskbar icon on Windows).
  44428. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  44429. redirects it to call this method, so any methods of closing the window that are
  44430. caught by userTriedToCloseWindow() will also end up here).
  44431. */
  44432. virtual void closeButtonPressed();
  44433. /** Callback that is triggered when the minimise button is pressed.
  44434. The default implementation of this calls ResizableWindow::setMinimised(), but
  44435. you can override it to do more customised behaviour.
  44436. */
  44437. virtual void minimiseButtonPressed();
  44438. /** Callback that is triggered when the maximise button is pressed, or when the
  44439. title-bar is double-clicked.
  44440. The default implementation of this calls ResizableWindow::setFullScreen(), but
  44441. you can override it to do more customised behaviour.
  44442. */
  44443. virtual void maximiseButtonPressed();
  44444. /** Returns the close button, (or 0 if there isn't one). */
  44445. Button* getCloseButton() const throw();
  44446. /** Returns the minimise button, (or 0 if there isn't one). */
  44447. Button* getMinimiseButton() const throw();
  44448. /** Returns the maximise button, (or 0 if there isn't one). */
  44449. Button* getMaximiseButton() const throw();
  44450. /** A set of colour IDs to use to change the colour of various aspects of the window.
  44451. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44452. methods.
  44453. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44454. */
  44455. enum ColourIds
  44456. {
  44457. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  44458. and feel class how this is used. */
  44459. };
  44460. /** @internal */
  44461. void paint (Graphics& g);
  44462. /** @internal */
  44463. void resized();
  44464. /** @internal */
  44465. void lookAndFeelChanged();
  44466. /** @internal */
  44467. const BorderSize<int> getBorderThickness();
  44468. /** @internal */
  44469. const BorderSize<int> getContentComponentBorder();
  44470. /** @internal */
  44471. void mouseDoubleClick (const MouseEvent& e);
  44472. /** @internal */
  44473. void userTriedToCloseWindow();
  44474. /** @internal */
  44475. void activeWindowStatusChanged();
  44476. /** @internal */
  44477. int getDesktopWindowStyleFlags() const;
  44478. /** @internal */
  44479. void parentHierarchyChanged();
  44480. /** @internal */
  44481. const Rectangle<int> getTitleBarArea();
  44482. private:
  44483. int titleBarHeight, menuBarHeight, requiredButtons;
  44484. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  44485. ScopedPointer <Button> titleBarButtons [3];
  44486. Image titleBarIcon;
  44487. ScopedPointer <Component> menuBar;
  44488. MenuBarModel* menuBarModel;
  44489. class ButtonListenerProxy;
  44490. friend class ScopedPointer <ButtonListenerProxy>;
  44491. ScopedPointer <ButtonListenerProxy> buttonListener;
  44492. void repaintTitleBar();
  44493. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DocumentWindow);
  44494. };
  44495. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  44496. /*** End of inlined file: juce_DocumentWindow.h ***/
  44497. class MultiDocumentPanel;
  44498. class MDITabbedComponentInternal;
  44499. /**
  44500. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  44501. component.
  44502. It's like a normal DocumentWindow but has some extra functionality to make sure
  44503. everything works nicely inside a MultiDocumentPanel.
  44504. @see MultiDocumentPanel
  44505. */
  44506. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  44507. {
  44508. public:
  44509. /**
  44510. */
  44511. MultiDocumentPanelWindow (const Colour& backgroundColour);
  44512. /** Destructor. */
  44513. ~MultiDocumentPanelWindow();
  44514. /** @internal */
  44515. void maximiseButtonPressed();
  44516. /** @internal */
  44517. void closeButtonPressed();
  44518. /** @internal */
  44519. void activeWindowStatusChanged();
  44520. /** @internal */
  44521. void broughtToFront();
  44522. private:
  44523. void updateOrder();
  44524. MultiDocumentPanel* getOwner() const throw();
  44525. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanelWindow);
  44526. };
  44527. /**
  44528. A component that contains a set of other components either in floating windows
  44529. or tabs.
  44530. This acts as a panel that can be used to hold a set of open document windows, with
  44531. different layout modes.
  44532. Use addDocument() and closeDocument() to add or remove components from the
  44533. panel - never use any of the Component methods to access the panel's child
  44534. components directly, as these are managed internally.
  44535. */
  44536. class JUCE_API MultiDocumentPanel : public Component,
  44537. private ComponentListener
  44538. {
  44539. public:
  44540. /** Creates an empty panel.
  44541. Use addDocument() and closeDocument() to add or remove components from the
  44542. panel - never use any of the Component methods to access the panel's child
  44543. components directly, as these are managed internally.
  44544. */
  44545. MultiDocumentPanel();
  44546. /** Destructor.
  44547. When deleted, this will call closeAllDocuments (false) to make sure all its
  44548. components are deleted. If you need to make sure all documents are saved
  44549. before closing, then you should call closeAllDocuments (true) and check that
  44550. it returns true before deleting the panel.
  44551. */
  44552. ~MultiDocumentPanel();
  44553. /** Tries to close all the documents.
  44554. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  44555. be called for each open document, and any of these calls fails, this method
  44556. will stop and return false, leaving some documents still open.
  44557. If checkItsOkToCloseFirst is false, then all documents will be closed
  44558. unconditionally.
  44559. @see closeDocument
  44560. */
  44561. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  44562. /** Adds a document component to the panel.
  44563. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  44564. this will fail and return false. (If it does fail, the component passed-in will not be
  44565. deleted, even if deleteWhenRemoved was set to true).
  44566. The MultiDocumentPanel will deal with creating a window border to go around your component,
  44567. so just pass in the bare content component here, no need to give it a ResizableWindow
  44568. or DocumentWindow.
  44569. @param component the component to add
  44570. @param backgroundColour the background colour to use to fill the component's
  44571. window or tab
  44572. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  44573. or closeAllDocuments(), then it will be deleted. If false, then
  44574. the caller must handle the component's deletion
  44575. */
  44576. bool addDocument (Component* component,
  44577. const Colour& backgroundColour,
  44578. bool deleteWhenRemoved);
  44579. /** Closes one of the documents.
  44580. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  44581. be called, and if it fails, this method will return false without closing the
  44582. document.
  44583. If checkItsOkToCloseFirst is false, then the documents will be closed
  44584. unconditionally.
  44585. The component will be deleted if the deleteWhenRemoved parameter was set to
  44586. true when it was added with addDocument.
  44587. @see addDocument, closeAllDocuments
  44588. */
  44589. bool closeDocument (Component* component,
  44590. bool checkItsOkToCloseFirst);
  44591. /** Returns the number of open document windows.
  44592. @see getDocument
  44593. */
  44594. int getNumDocuments() const throw();
  44595. /** Returns one of the open documents.
  44596. The order of the documents in this array may change when they are added, removed
  44597. or moved around.
  44598. @see getNumDocuments
  44599. */
  44600. Component* getDocument (int index) const throw();
  44601. /** Returns the document component that is currently focused or on top.
  44602. If currently using floating windows, then this will be the component in the currently
  44603. active window, or the top component if none are active.
  44604. If it's currently in tabbed mode, then it'll return the component in the active tab.
  44605. @see setActiveDocument
  44606. */
  44607. Component* getActiveDocument() const throw();
  44608. /** Makes one of the components active and brings it to the top.
  44609. @see getActiveDocument
  44610. */
  44611. void setActiveDocument (Component* component);
  44612. /** Callback which gets invoked when the currently-active document changes. */
  44613. virtual void activeDocumentChanged();
  44614. /** Sets a limit on how many windows can be open at once.
  44615. If this is zero or less there's no limit (the default). addDocument() will fail
  44616. if this number is exceeded.
  44617. */
  44618. void setMaximumNumDocuments (int maximumNumDocuments);
  44619. /** Sets an option to make the document fullscreen if there's only one document open.
  44620. If set to true, then if there's only one document, it'll fill the whole of this
  44621. component without tabs or a window border. If false, then tabs or a window
  44622. will always be shown, even if there's only one document. If there's more than
  44623. one document open, then this option makes no difference.
  44624. */
  44625. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  44626. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  44627. */
  44628. bool isFullscreenWhenOneDocument() const throw();
  44629. /** The different layout modes available. */
  44630. enum LayoutMode
  44631. {
  44632. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  44633. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  44634. };
  44635. /** Changes the panel's mode.
  44636. @see LayoutMode, getLayoutMode
  44637. */
  44638. void setLayoutMode (LayoutMode newLayoutMode);
  44639. /** Returns the current layout mode. */
  44640. LayoutMode getLayoutMode() const throw() { return mode; }
  44641. /** Sets the background colour for the whole panel.
  44642. Each document has its own background colour, but this is the one used to fill the areas
  44643. behind them.
  44644. */
  44645. void setBackgroundColour (const Colour& newBackgroundColour);
  44646. /** Returns the current background colour.
  44647. @see setBackgroundColour
  44648. */
  44649. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  44650. /** A subclass must override this to say whether its currently ok for a document
  44651. to be closed.
  44652. This method is called by closeDocument() and closeAllDocuments() to indicate that
  44653. a document should be saved if possible, ready for it to be closed.
  44654. If this method returns true, then it means the document is ok and can be closed.
  44655. If it returns false, then it means that the closeDocument() method should stop
  44656. and not close.
  44657. Normally, you'd use this method to ask the user if they want to save any changes,
  44658. then return true if the save operation went ok. If the user cancelled the save
  44659. operation you could return false here to abort the close operation.
  44660. If your component is based on the FileBasedDocument class, then you'd probably want
  44661. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  44662. FileBasedDocument::savedOk
  44663. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  44664. */
  44665. virtual bool tryToCloseDocument (Component* component) = 0;
  44666. /** Creates a new window to be used for a document.
  44667. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  44668. but you might want to override it to return a custom component.
  44669. */
  44670. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  44671. /** @internal */
  44672. void paint (Graphics& g);
  44673. /** @internal */
  44674. void resized();
  44675. /** @internal */
  44676. void componentNameChanged (Component&);
  44677. private:
  44678. LayoutMode mode;
  44679. Array <Component*> components;
  44680. ScopedPointer<TabbedComponent> tabComponent;
  44681. Colour backgroundColour;
  44682. int maximumNumDocuments, numDocsBeforeTabsUsed;
  44683. friend class MultiDocumentPanelWindow;
  44684. friend class MDITabbedComponentInternal;
  44685. Component* getContainerComp (Component* c) const;
  44686. void updateOrder();
  44687. void addWindow (Component* component);
  44688. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanel);
  44689. };
  44690. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  44691. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  44692. #endif
  44693. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  44694. #endif
  44695. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  44696. #endif
  44697. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  44698. /*** Start of inlined file: juce_ResizableEdgeComponent.h ***/
  44699. #ifndef __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  44700. #define __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  44701. /**
  44702. A component that resizes its parent component when dragged.
  44703. This component forms a bar along one edge of a component, allowing it to
  44704. be dragged by that edges to resize it.
  44705. To use it, just add it to your component, positioning it along the appropriate
  44706. edge. Make sure you reposition the resizer component each time the parent's size
  44707. changes, to keep it in the correct position.
  44708. @see ResizbleBorderComponent, ResizableCornerComponent
  44709. */
  44710. class JUCE_API ResizableEdgeComponent : public Component
  44711. {
  44712. public:
  44713. enum Edge
  44714. {
  44715. leftEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's left-hand edge. */
  44716. rightEdge, /**< Indicates a vertical bar that can be dragged left/right to move the component's right-hand edge. */
  44717. topEdge, /**< Indicates a horizontal bar that can be dragged up/down to move the top of the component. */
  44718. bottomEdge /**< Indicates a horizontal bar that can be dragged up/down to move the bottom of the component. */
  44719. };
  44720. /** Creates a resizer bar.
  44721. Pass in the target component which you want to be resized when this one is
  44722. dragged. The target component will usually be this component's parent, but this
  44723. isn't mandatory.
  44724. Remember that when the target component is resized, it'll need to move and
  44725. resize this component to keep it in place, as this won't happen automatically.
  44726. If the constrainer parameter is non-zero, then this object will be used to enforce
  44727. limits on the size and position that the component can be stretched to. Make sure
  44728. that the constrainer isn't deleted while still in use by this object.
  44729. @see ComponentBoundsConstrainer
  44730. */
  44731. ResizableEdgeComponent (Component* componentToResize,
  44732. ComponentBoundsConstrainer* constrainer,
  44733. Edge edgeToResize);
  44734. /** Destructor. */
  44735. ~ResizableEdgeComponent();
  44736. bool isVertical() const throw();
  44737. protected:
  44738. /** @internal */
  44739. void paint (Graphics& g);
  44740. /** @internal */
  44741. void mouseDown (const MouseEvent& e);
  44742. /** @internal */
  44743. void mouseDrag (const MouseEvent& e);
  44744. /** @internal */
  44745. void mouseUp (const MouseEvent& e);
  44746. private:
  44747. WeakReference<Component> component;
  44748. ComponentBoundsConstrainer* constrainer;
  44749. Rectangle<int> originalBounds;
  44750. const Edge edge;
  44751. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableEdgeComponent);
  44752. };
  44753. #endif // __JUCE_RESIZABLEEDGECOMPONENT_JUCEHEADER__
  44754. /*** End of inlined file: juce_ResizableEdgeComponent.h ***/
  44755. #endif
  44756. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  44757. #endif
  44758. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  44759. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  44760. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  44761. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  44762. /**
  44763. For laying out a set of components, where the components have preferred sizes
  44764. and size limits, but where they are allowed to stretch to fill the available
  44765. space.
  44766. For example, if you have a component containing several other components, and
  44767. each one should be given a share of the total size, you could use one of these
  44768. to resize the child components when the parent component is resized. Then
  44769. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  44770. A StretchableLayoutManager operates only in one dimension, so if you have a set
  44771. of components stacked vertically on top of each other, you'd use one to manage their
  44772. heights. To build up complex arrangements of components, e.g. for applications
  44773. with multiple nested panels, you would use more than one StretchableLayoutManager.
  44774. E.g. by using two (one vertical, one horizontal), you could create a resizable
  44775. spreadsheet-style table.
  44776. E.g.
  44777. @code
  44778. class MyComp : public Component
  44779. {
  44780. StretchableLayoutManager myLayout;
  44781. MyComp()
  44782. {
  44783. myLayout.setItemLayout (0, // for item 0
  44784. 50, 100, // must be between 50 and 100 pixels in size
  44785. -0.6); // and its preferred size is 60% of the total available space
  44786. myLayout.setItemLayout (1, // for item 1
  44787. -0.2, -0.6, // size must be between 20% and 60% of the available space
  44788. 50); // and its preferred size is 50 pixels
  44789. }
  44790. void resized()
  44791. {
  44792. // make a list of two of our child components that we want to reposition
  44793. Component* comps[] = { myComp1, myComp2 };
  44794. // this will position the 2 components, one above the other, to fit
  44795. // vertically into the rectangle provided.
  44796. myLayout.layOutComponents (comps, 2,
  44797. 0, 0, getWidth(), getHeight(),
  44798. true);
  44799. }
  44800. };
  44801. @endcode
  44802. @see StretchableLayoutResizerBar
  44803. */
  44804. class JUCE_API StretchableLayoutManager
  44805. {
  44806. public:
  44807. /** Creates an empty layout.
  44808. You'll need to add some item properties to the layout before it can be used
  44809. to resize things - see setItemLayout().
  44810. */
  44811. StretchableLayoutManager();
  44812. /** Destructor. */
  44813. ~StretchableLayoutManager();
  44814. /** For a numbered item, this sets its size limits and preferred size.
  44815. @param itemIndex the index of the item to change.
  44816. @param minimumSize the minimum size that this item is allowed to be - a positive number
  44817. indicates an absolute size in pixels. A negative number indicates a
  44818. proportion of the available space (e.g -0.5 is 50%)
  44819. @param maximumSize the maximum size that this item is allowed to be - a positive number
  44820. indicates an absolute size in pixels. A negative number indicates a
  44821. proportion of the available space
  44822. @param preferredSize the size that this item would like to be, if there's enough room. A
  44823. positive number indicates an absolute size in pixels. A negative number
  44824. indicates a proportion of the available space
  44825. @see getItemLayout
  44826. */
  44827. void setItemLayout (int itemIndex,
  44828. double minimumSize,
  44829. double maximumSize,
  44830. double preferredSize);
  44831. /** For a numbered item, this returns its size limits and preferred size.
  44832. @param itemIndex the index of the item.
  44833. @param minimumSize the minimum size that this item is allowed to be - a positive number
  44834. indicates an absolute size in pixels. A negative number indicates a
  44835. proportion of the available space (e.g -0.5 is 50%)
  44836. @param maximumSize the maximum size that this item is allowed to be - a positive number
  44837. indicates an absolute size in pixels. A negative number indicates a
  44838. proportion of the available space
  44839. @param preferredSize the size that this item would like to be, if there's enough room. A
  44840. positive number indicates an absolute size in pixels. A negative number
  44841. indicates a proportion of the available space
  44842. @returns false if the item's properties hadn't been set
  44843. @see setItemLayout
  44844. */
  44845. bool getItemLayout (int itemIndex,
  44846. double& minimumSize,
  44847. double& maximumSize,
  44848. double& preferredSize) const;
  44849. /** Clears all the properties that have been set with setItemLayout() and resets
  44850. this object to its initial state.
  44851. */
  44852. void clearAllItems();
  44853. /** Takes a set of components that correspond to the layout's items, and positions
  44854. them to fill a space.
  44855. This will try to give each item its preferred size, whether that's a relative size
  44856. or an absolute one.
  44857. @param components an array of components that correspond to each of the
  44858. numbered items that the StretchableLayoutManager object
  44859. has been told about with setItemLayout()
  44860. @param numComponents the number of components in the array that is passed-in. This
  44861. should be the same as the number of items this object has been
  44862. told about.
  44863. @param x the left of the rectangle in which the components should
  44864. be laid out
  44865. @param y the top of the rectangle in which the components should
  44866. be laid out
  44867. @param width the width of the rectangle in which the components should
  44868. be laid out
  44869. @param height the height of the rectangle in which the components should
  44870. be laid out
  44871. @param vertically if true, the components will be positioned in a vertical stack,
  44872. so that they fill the height of the rectangle. If false, they
  44873. will be placed side-by-side in a horizontal line, filling the
  44874. available width
  44875. @param resizeOtherDimension if true, this means that the components will have their
  44876. other dimension resized to fit the space - i.e. if the 'vertically'
  44877. parameter is true, their x-positions and widths are adjusted to fit
  44878. the x and width parameters; if 'vertically' is false, their y-positions
  44879. and heights are adjusted to fit the y and height parameters.
  44880. */
  44881. void layOutComponents (Component** components,
  44882. int numComponents,
  44883. int x, int y, int width, int height,
  44884. bool vertically,
  44885. bool resizeOtherDimension);
  44886. /** Returns the current position of one of the items.
  44887. This is only a valid call after layOutComponents() has been called, as it
  44888. returns the last position that this item was placed at. If the layout was
  44889. vertical, the value returned will be the y position of the top of the item,
  44890. relative to the top of the rectangle in which the items were placed (so for
  44891. example, item 0 will always have position of 0, even in the rectangle passed
  44892. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  44893. the position returned is the item's left-hand position, again relative to the
  44894. x position of the rectangle used.
  44895. @see getItemCurrentSize, setItemPosition
  44896. */
  44897. int getItemCurrentPosition (int itemIndex) const;
  44898. /** Returns the current size of one of the items.
  44899. This is only meaningful after layOutComponents() has been called, as it
  44900. returns the last size that this item was given. If the layout was done
  44901. vertically, it'll return the item's height in pixels; if it was horizontal,
  44902. it'll return its width.
  44903. @see getItemCurrentRelativeSize
  44904. */
  44905. int getItemCurrentAbsoluteSize (int itemIndex) const;
  44906. /** Returns the current size of one of the items.
  44907. This is only meaningful after layOutComponents() has been called, as it
  44908. returns the last size that this item was given. If the layout was done
  44909. vertically, it'll return a negative value representing the item's height relative
  44910. to the last size used for laying the components out; if the layout was done
  44911. horizontally it'll be the proportion of its width.
  44912. @see getItemCurrentAbsoluteSize
  44913. */
  44914. double getItemCurrentRelativeSize (int itemIndex) const;
  44915. /** Moves one of the items, shifting along any other items as necessary in
  44916. order to get it to the desired position.
  44917. Calling this method will also update the preferred sizes of the items it
  44918. shuffles along, so that they reflect their new positions.
  44919. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  44920. about when it's dragged).
  44921. @param itemIndex the item to move
  44922. @param newPosition the absolute position that you'd like this item to move
  44923. to. The item might not be able to always reach exactly this position,
  44924. because other items may have minimum sizes that constrain how
  44925. far it can go
  44926. */
  44927. void setItemPosition (int itemIndex,
  44928. int newPosition);
  44929. private:
  44930. struct ItemLayoutProperties
  44931. {
  44932. int itemIndex;
  44933. int currentSize;
  44934. double minSize, maxSize, preferredSize;
  44935. };
  44936. OwnedArray <ItemLayoutProperties> items;
  44937. int totalSize;
  44938. static int sizeToRealSize (double size, int totalSpace);
  44939. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  44940. void setTotalSize (int newTotalSize);
  44941. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  44942. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  44943. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  44944. void updatePrefSizesToMatchCurrentPositions();
  44945. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutManager);
  44946. };
  44947. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  44948. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  44949. #endif
  44950. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  44951. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  44952. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  44953. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  44954. /**
  44955. A component that acts as one of the vertical or horizontal bars you see being
  44956. used to resize panels in a window.
  44957. One of these acts with a StretchableLayoutManager to resize the other components.
  44958. @see StretchableLayoutManager
  44959. */
  44960. class JUCE_API StretchableLayoutResizerBar : public Component
  44961. {
  44962. public:
  44963. /** Creates a resizer bar for use on a specified layout.
  44964. @param layoutToUse the layout that will be affected when this bar
  44965. is dragged
  44966. @param itemIndexInLayout the item index in the layout that corresponds to
  44967. this bar component. You'll need to set up the item
  44968. properties in a suitable way for a divider bar, e.g.
  44969. for an 8-pixel wide bar which, you could call
  44970. myLayout->setItemLayout (barIndex, 8, 8, 8)
  44971. @param isBarVertical true if it's an upright bar that you drag left and
  44972. right; false for a horizontal one that you drag up and
  44973. down
  44974. */
  44975. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  44976. int itemIndexInLayout,
  44977. bool isBarVertical);
  44978. /** Destructor. */
  44979. ~StretchableLayoutResizerBar();
  44980. /** This is called when the bar is dragged.
  44981. This method must update the positions of any components whose position is
  44982. determined by the StretchableLayoutManager, because they might have just
  44983. moved.
  44984. The default implementation calls the resized() method of this component's
  44985. parent component, because that's often where you're likely to apply the
  44986. layout, but it can be overridden for more specific needs.
  44987. */
  44988. virtual void hasBeenMoved();
  44989. /** @internal */
  44990. void paint (Graphics& g);
  44991. /** @internal */
  44992. void mouseDown (const MouseEvent& e);
  44993. /** @internal */
  44994. void mouseDrag (const MouseEvent& e);
  44995. private:
  44996. StretchableLayoutManager* layout;
  44997. int itemIndex, mouseDownPos;
  44998. bool isVertical;
  44999. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutResizerBar);
  45000. };
  45001. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  45002. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  45003. #endif
  45004. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45005. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  45006. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45007. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45008. /**
  45009. A utility class for fitting a set of objects whose sizes can vary between
  45010. a minimum and maximum size, into a space.
  45011. This is a trickier algorithm than it would first seem, so I've put it in this
  45012. class to allow it to be shared by various bits of code.
  45013. To use it, create one of these objects, call addItem() to add the list of items
  45014. you need, then call resizeToFit(), which will change all their sizes. You can
  45015. then retrieve the new sizes with getItemSize() and getNumItems().
  45016. It's currently used by the TableHeaderComponent for stretching out the table
  45017. headings to fill the table's width.
  45018. */
  45019. class StretchableObjectResizer
  45020. {
  45021. public:
  45022. /** Creates an empty object resizer. */
  45023. StretchableObjectResizer();
  45024. /** Destructor. */
  45025. ~StretchableObjectResizer();
  45026. /** Adds an item to the list.
  45027. The order parameter lets you specify groups of items that are resized first when some
  45028. space needs to be found. Those items with an order of 0 will be the first ones to be
  45029. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  45030. will then try resizing the items with an order of 1, then 2, and so on.
  45031. */
  45032. void addItem (double currentSize,
  45033. double minSize,
  45034. double maxSize,
  45035. int order = 0);
  45036. /** Resizes all the items to fit this amount of space.
  45037. This will attempt to fit them in without exceeding each item's miniumum and
  45038. maximum sizes. In cases where none of the items can be expanded or enlarged any
  45039. further, the final size may be greater or less than the size passed in.
  45040. After calling this method, you can retrieve the new sizes with the getItemSize()
  45041. method.
  45042. */
  45043. void resizeToFit (double targetSize);
  45044. /** Returns the number of items that have been added. */
  45045. int getNumItems() const throw() { return items.size(); }
  45046. /** Returns the size of one of the items. */
  45047. double getItemSize (int index) const throw();
  45048. private:
  45049. struct Item
  45050. {
  45051. double size;
  45052. double minSize;
  45053. double maxSize;
  45054. int order;
  45055. };
  45056. OwnedArray <Item> items;
  45057. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableObjectResizer);
  45058. };
  45059. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  45060. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  45061. #endif
  45062. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  45063. #endif
  45064. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  45065. #endif
  45066. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  45067. #endif
  45068. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  45069. /*** Start of inlined file: juce_LookAndFeel.h ***/
  45070. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  45071. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  45072. class ToggleButton;
  45073. class TextButton;
  45074. class AlertWindow;
  45075. class TextLayout;
  45076. class ScrollBar;
  45077. class BubbleComponent;
  45078. class ComboBox;
  45079. class Button;
  45080. class FilenameComponent;
  45081. class DocumentWindow;
  45082. class ResizableWindow;
  45083. class GroupComponent;
  45084. class MenuBarComponent;
  45085. class DropShadower;
  45086. class GlyphArrangement;
  45087. class PropertyComponent;
  45088. class TableHeaderComponent;
  45089. class Toolbar;
  45090. class ToolbarItemComponent;
  45091. class PopupMenu;
  45092. class ProgressBar;
  45093. class FileBrowserComponent;
  45094. class DirectoryContentsDisplayComponent;
  45095. class FilePreviewComponent;
  45096. class ImageButton;
  45097. class CallOutBox;
  45098. class Drawable;
  45099. /**
  45100. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  45101. can be used to apply different 'skins' to the application.
  45102. */
  45103. class JUCE_API LookAndFeel
  45104. {
  45105. public:
  45106. /** Creates the default JUCE look and feel. */
  45107. LookAndFeel();
  45108. /** Destructor. */
  45109. virtual ~LookAndFeel();
  45110. /** Returns the current default look-and-feel for a component to use when it
  45111. hasn't got one explicitly set.
  45112. @see setDefaultLookAndFeel
  45113. */
  45114. static LookAndFeel& getDefaultLookAndFeel() throw();
  45115. /** Changes the default look-and-feel.
  45116. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  45117. set to 0, it will revert to using the default one. The
  45118. object passed-in must be deleted by the caller when
  45119. it's no longer needed.
  45120. @see getDefaultLookAndFeel
  45121. */
  45122. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  45123. /** Looks for a colour that has been registered with the given colour ID number.
  45124. If a colour has been set for this ID number using setColour(), then it is
  45125. returned. If none has been set, it will just return Colours::black.
  45126. The colour IDs for various purposes are stored as enums in the components that
  45127. they are relevent to - for an example, see Slider::ColourIds,
  45128. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  45129. If you're looking up a colour for use in drawing a component, it's usually
  45130. best not to call this directly, but to use the Component::findColour() method
  45131. instead. That will first check whether a suitable colour has been registered
  45132. directly with the component, and will fall-back on calling the component's
  45133. LookAndFeel's findColour() method if none is found.
  45134. @see setColour, Component::findColour, Component::setColour
  45135. */
  45136. const Colour findColour (int colourId) const throw();
  45137. /** Registers a colour to be used for a particular purpose.
  45138. For more details, see the comments for findColour().
  45139. @see findColour, Component::findColour, Component::setColour
  45140. */
  45141. void setColour (int colourId, const Colour& colour) throw();
  45142. /** Returns true if the specified colour ID has been explicitly set using the
  45143. setColour() method.
  45144. */
  45145. bool isColourSpecified (int colourId) const throw();
  45146. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  45147. /** Allows you to change the default sans-serif font.
  45148. If you need to supply your own Typeface object for any of the default fonts, rather
  45149. than just supplying the name (e.g. if you want to use an embedded font), then
  45150. you should instead override getTypefaceForFont() to create and return the typeface.
  45151. */
  45152. void setDefaultSansSerifTypefaceName (const String& newName);
  45153. /** Override this to get the chance to swap a component's mouse cursor for a
  45154. customised one.
  45155. */
  45156. virtual const MouseCursor getMouseCursorFor (Component& component);
  45157. /** Draws the lozenge-shaped background for a standard button. */
  45158. virtual void drawButtonBackground (Graphics& g,
  45159. Button& button,
  45160. const Colour& backgroundColour,
  45161. bool isMouseOverButton,
  45162. bool isButtonDown);
  45163. virtual const Font getFontForTextButton (TextButton& button);
  45164. /** Draws the text for a TextButton. */
  45165. virtual void drawButtonText (Graphics& g,
  45166. TextButton& button,
  45167. bool isMouseOverButton,
  45168. bool isButtonDown);
  45169. /** Draws the contents of a standard ToggleButton. */
  45170. virtual void drawToggleButton (Graphics& g,
  45171. ToggleButton& button,
  45172. bool isMouseOverButton,
  45173. bool isButtonDown);
  45174. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  45175. virtual void drawTickBox (Graphics& g,
  45176. Component& component,
  45177. float x, float y, float w, float h,
  45178. bool ticked,
  45179. bool isEnabled,
  45180. bool isMouseOverButton,
  45181. bool isButtonDown);
  45182. /* AlertWindow handling..
  45183. */
  45184. virtual AlertWindow* createAlertWindow (const String& title,
  45185. const String& message,
  45186. const String& button1,
  45187. const String& button2,
  45188. const String& button3,
  45189. AlertWindow::AlertIconType iconType,
  45190. int numButtons,
  45191. Component* associatedComponent);
  45192. virtual void drawAlertBox (Graphics& g,
  45193. AlertWindow& alert,
  45194. const Rectangle<int>& textArea,
  45195. TextLayout& textLayout);
  45196. virtual int getAlertBoxWindowFlags();
  45197. virtual int getAlertWindowButtonHeight();
  45198. virtual const Font getAlertWindowMessageFont();
  45199. virtual const Font getAlertWindowFont();
  45200. /** Draws a progress bar.
  45201. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  45202. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  45203. isn't known). It can use the current time as a basis for playing an animation.
  45204. (Used by progress bars in AlertWindow).
  45205. */
  45206. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  45207. int width, int height,
  45208. double progress, const String& textToShow);
  45209. // Draws a small image that spins to indicate that something's happening..
  45210. // This method should use the current time to animate itself, so just keep
  45211. // repainting it every so often.
  45212. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  45213. int x, int y, int w, int h);
  45214. /** Draws one of the buttons on a scrollbar.
  45215. @param g the context to draw into
  45216. @param scrollbar the bar itself
  45217. @param width the width of the button
  45218. @param height the height of the button
  45219. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  45220. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  45221. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  45222. @param isButtonDown whether the mouse button's held down
  45223. */
  45224. virtual void drawScrollbarButton (Graphics& g,
  45225. ScrollBar& scrollbar,
  45226. int width, int height,
  45227. int buttonDirection,
  45228. bool isScrollbarVertical,
  45229. bool isMouseOverButton,
  45230. bool isButtonDown);
  45231. /** Draws the thumb area of a scrollbar.
  45232. @param g the context to draw into
  45233. @param scrollbar the bar itself
  45234. @param x the x position of the left edge of the thumb area to draw in
  45235. @param y the y position of the top edge of the thumb area to draw in
  45236. @param width the width of the thumb area to draw in
  45237. @param height the height of the thumb area to draw in
  45238. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  45239. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  45240. thumb, or its x position for horizontal bars
  45241. @param thumbSize for vertical bars, the height of the thumb, or its width for
  45242. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  45243. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  45244. currently dragging the thumb
  45245. @param isMouseDown whether the mouse is currently dragging the scrollbar
  45246. */
  45247. virtual void drawScrollbar (Graphics& g,
  45248. ScrollBar& scrollbar,
  45249. int x, int y,
  45250. int width, int height,
  45251. bool isScrollbarVertical,
  45252. int thumbStartPosition,
  45253. int thumbSize,
  45254. bool isMouseOver,
  45255. bool isMouseDown);
  45256. /** Returns the component effect to use for a scrollbar */
  45257. virtual ImageEffectFilter* getScrollbarEffect();
  45258. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  45259. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  45260. /** Returns the default thickness to use for a scrollbar. */
  45261. virtual int getDefaultScrollbarWidth();
  45262. /** Returns the length in pixels to use for a scrollbar button. */
  45263. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  45264. /** Returns a tick shape for use in yes/no boxes, etc. */
  45265. virtual const Path getTickShape (float height);
  45266. /** Returns a cross shape for use in yes/no boxes, etc. */
  45267. virtual const Path getCrossShape (float height);
  45268. /** Draws the + or - box in a treeview. */
  45269. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  45270. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  45271. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  45272. // These return a pointer to an internally cached drawable - make sure you don't keep
  45273. // a copy of this pointer anywhere, as it may become invalid in the future.
  45274. virtual const Drawable* getDefaultFolderImage();
  45275. virtual const Drawable* getDefaultDocumentFileImage();
  45276. virtual void createFileChooserHeaderText (const String& title,
  45277. const String& instructions,
  45278. GlyphArrangement& destArrangement,
  45279. int width);
  45280. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  45281. const String& filename, Image* icon,
  45282. const String& fileSizeDescription,
  45283. const String& fileTimeDescription,
  45284. bool isDirectory,
  45285. bool isItemSelected,
  45286. int itemIndex,
  45287. DirectoryContentsDisplayComponent& component);
  45288. virtual Button* createFileBrowserGoUpButton();
  45289. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  45290. DirectoryContentsDisplayComponent* fileListComponent,
  45291. FilePreviewComponent* previewComp,
  45292. ComboBox* currentPathBox,
  45293. TextEditor* filenameBox,
  45294. Button* goUpButton);
  45295. virtual void drawBubble (Graphics& g,
  45296. float tipX, float tipY,
  45297. float boxX, float boxY, float boxW, float boxH);
  45298. /** Fills the background of a popup menu component. */
  45299. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  45300. /** Draws one of the items in a popup menu. */
  45301. virtual void drawPopupMenuItem (Graphics& g,
  45302. int width, int height,
  45303. bool isSeparator,
  45304. bool isActive,
  45305. bool isHighlighted,
  45306. bool isTicked,
  45307. bool hasSubMenu,
  45308. const String& text,
  45309. const String& shortcutKeyText,
  45310. Image* image,
  45311. const Colour* const textColour);
  45312. /** Returns the size and style of font to use in popup menus. */
  45313. virtual const Font getPopupMenuFont();
  45314. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  45315. int width, int height,
  45316. bool isScrollUpArrow);
  45317. /** Finds the best size for an item in a popup menu. */
  45318. virtual void getIdealPopupMenuItemSize (const String& text,
  45319. bool isSeparator,
  45320. int standardMenuItemHeight,
  45321. int& idealWidth,
  45322. int& idealHeight);
  45323. virtual int getMenuWindowFlags();
  45324. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  45325. bool isMouseOverBar,
  45326. MenuBarComponent& menuBar);
  45327. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  45328. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  45329. virtual void drawMenuBarItem (Graphics& g,
  45330. int width, int height,
  45331. int itemIndex,
  45332. const String& itemText,
  45333. bool isMouseOverItem,
  45334. bool isMenuOpen,
  45335. bool isMouseOverBar,
  45336. MenuBarComponent& menuBar);
  45337. virtual void drawComboBox (Graphics& g, int width, int height,
  45338. bool isButtonDown,
  45339. int buttonX, int buttonY,
  45340. int buttonW, int buttonH,
  45341. ComboBox& box);
  45342. virtual const Font getComboBoxFont (ComboBox& box);
  45343. virtual Label* createComboBoxTextBox (ComboBox& box);
  45344. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  45345. virtual void drawLabel (Graphics& g, Label& label);
  45346. virtual void drawLinearSlider (Graphics& g,
  45347. int x, int y,
  45348. int width, int height,
  45349. float sliderPos,
  45350. float minSliderPos,
  45351. float maxSliderPos,
  45352. const Slider::SliderStyle style,
  45353. Slider& slider);
  45354. virtual void drawLinearSliderBackground (Graphics& g,
  45355. int x, int y,
  45356. int width, int height,
  45357. float sliderPos,
  45358. float minSliderPos,
  45359. float maxSliderPos,
  45360. const Slider::SliderStyle style,
  45361. Slider& slider);
  45362. virtual void drawLinearSliderThumb (Graphics& g,
  45363. int x, int y,
  45364. int width, int height,
  45365. float sliderPos,
  45366. float minSliderPos,
  45367. float maxSliderPos,
  45368. const Slider::SliderStyle style,
  45369. Slider& slider);
  45370. virtual int getSliderThumbRadius (Slider& slider);
  45371. virtual void drawRotarySlider (Graphics& g,
  45372. int x, int y,
  45373. int width, int height,
  45374. float sliderPosProportional,
  45375. float rotaryStartAngle,
  45376. float rotaryEndAngle,
  45377. Slider& slider);
  45378. virtual Button* createSliderButton (bool isIncrement);
  45379. virtual Label* createSliderTextBox (Slider& slider);
  45380. virtual ImageEffectFilter* getSliderEffect();
  45381. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  45382. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  45383. virtual Button* createFilenameComponentBrowseButton (const String& text);
  45384. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  45385. ComboBox* filenameBox, Button* browseButton);
  45386. virtual void drawCornerResizer (Graphics& g,
  45387. int w, int h,
  45388. bool isMouseOver,
  45389. bool isMouseDragging);
  45390. virtual void drawResizableFrame (Graphics& g,
  45391. int w, int h,
  45392. const BorderSize<int>& borders);
  45393. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  45394. const BorderSize<int>& border,
  45395. ResizableWindow& window);
  45396. virtual void drawResizableWindowBorder (Graphics& g,
  45397. int w, int h,
  45398. const BorderSize<int>& border,
  45399. ResizableWindow& window);
  45400. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  45401. Graphics& g, int w, int h,
  45402. int titleSpaceX, int titleSpaceW,
  45403. const Image* icon,
  45404. bool drawTitleTextOnLeft);
  45405. virtual Button* createDocumentWindowButton (int buttonType);
  45406. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  45407. int titleBarX, int titleBarY,
  45408. int titleBarW, int titleBarH,
  45409. Button* minimiseButton,
  45410. Button* maximiseButton,
  45411. Button* closeButton,
  45412. bool positionTitleBarButtonsOnLeft);
  45413. virtual int getDefaultMenuBarHeight();
  45414. virtual DropShadower* createDropShadowerForComponent (Component* component);
  45415. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  45416. int w, int h,
  45417. bool isVerticalBar,
  45418. bool isMouseOver,
  45419. bool isMouseDragging);
  45420. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  45421. const String& text,
  45422. const Justification& position,
  45423. GroupComponent& group);
  45424. virtual void createTabButtonShape (Path& p,
  45425. int width, int height,
  45426. int tabIndex,
  45427. const String& text,
  45428. Button& button,
  45429. TabbedButtonBar::Orientation orientation,
  45430. bool isMouseOver,
  45431. bool isMouseDown,
  45432. bool isFrontTab);
  45433. virtual void fillTabButtonShape (Graphics& g,
  45434. const Path& path,
  45435. const Colour& preferredBackgroundColour,
  45436. int tabIndex,
  45437. const String& text,
  45438. Button& button,
  45439. TabbedButtonBar::Orientation orientation,
  45440. bool isMouseOver,
  45441. bool isMouseDown,
  45442. bool isFrontTab);
  45443. virtual void drawTabButtonText (Graphics& g,
  45444. int x, int y, int w, int h,
  45445. const Colour& preferredBackgroundColour,
  45446. int tabIndex,
  45447. const String& text,
  45448. Button& button,
  45449. TabbedButtonBar::Orientation orientation,
  45450. bool isMouseOver,
  45451. bool isMouseDown,
  45452. bool isFrontTab);
  45453. virtual int getTabButtonOverlap (int tabDepth);
  45454. virtual int getTabButtonSpaceAroundImage();
  45455. virtual int getTabButtonBestWidth (int tabIndex,
  45456. const String& text,
  45457. int tabDepth,
  45458. Button& button);
  45459. virtual void drawTabButton (Graphics& g,
  45460. int w, int h,
  45461. const Colour& preferredColour,
  45462. int tabIndex,
  45463. const String& text,
  45464. Button& button,
  45465. TabbedButtonBar::Orientation orientation,
  45466. bool isMouseOver,
  45467. bool isMouseDown,
  45468. bool isFrontTab);
  45469. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  45470. int w, int h,
  45471. TabbedButtonBar& tabBar,
  45472. TabbedButtonBar::Orientation orientation);
  45473. virtual Button* createTabBarExtrasButton();
  45474. virtual void drawImageButton (Graphics& g, Image* image,
  45475. int imageX, int imageY, int imageW, int imageH,
  45476. const Colour& overlayColour,
  45477. float imageOpacity,
  45478. ImageButton& button);
  45479. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  45480. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  45481. int width, int height,
  45482. bool isMouseOver, bool isMouseDown,
  45483. int columnFlags);
  45484. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  45485. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  45486. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  45487. bool isMouseOver, bool isMouseDown,
  45488. ToolbarItemComponent& component);
  45489. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  45490. const String& text, ToolbarItemComponent& component);
  45491. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  45492. bool isOpen, int width, int height);
  45493. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  45494. PropertyComponent& component);
  45495. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  45496. PropertyComponent& component);
  45497. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  45498. void drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path);
  45499. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  45500. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  45501. /**
  45502. */
  45503. virtual void playAlertSound();
  45504. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  45505. static void drawGlassSphere (Graphics& g,
  45506. float x, float y,
  45507. float diameter,
  45508. const Colour& colour,
  45509. float outlineThickness) throw();
  45510. static void drawGlassPointer (Graphics& g,
  45511. float x, float y,
  45512. float diameter,
  45513. const Colour& colour, float outlineThickness,
  45514. int direction) throw();
  45515. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  45516. static void drawGlassLozenge (Graphics& g,
  45517. float x, float y,
  45518. float width, float height,
  45519. const Colour& colour,
  45520. float outlineThickness,
  45521. float cornerSize,
  45522. bool flatOnLeft, bool flatOnRight,
  45523. bool flatOnTop, bool flatOnBottom) throw();
  45524. static Drawable* loadDrawableFromData (const void* data, size_t numBytes);
  45525. private:
  45526. friend JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  45527. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  45528. Array <int> colourIds;
  45529. Array <Colour> colours;
  45530. // default typeface names
  45531. String defaultSans, defaultSerif, defaultFixed;
  45532. ScopedPointer<Drawable> folderImage, documentImage;
  45533. void drawShinyButtonShape (Graphics& g,
  45534. float x, float y, float w, float h, float maxCornerSize,
  45535. const Colour& baseColour,
  45536. float strokeWidth,
  45537. bool flatOnLeft,
  45538. bool flatOnRight,
  45539. bool flatOnTop,
  45540. bool flatOnBottom) throw();
  45541. // This has been deprecated - see the new parameter list..
  45542. virtual int drawFileBrowserRow (Graphics&, int, int, const String&, Image*, const String&, const String&, bool, bool, int) { return 0; }
  45543. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LookAndFeel);
  45544. };
  45545. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  45546. /*** End of inlined file: juce_LookAndFeel.h ***/
  45547. #endif
  45548. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  45549. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  45550. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  45551. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  45552. /**
  45553. The original Juce look-and-feel.
  45554. */
  45555. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  45556. {
  45557. public:
  45558. /** Creates the default JUCE look and feel. */
  45559. OldSchoolLookAndFeel();
  45560. /** Destructor. */
  45561. virtual ~OldSchoolLookAndFeel();
  45562. /** Draws the lozenge-shaped background for a standard button. */
  45563. virtual void drawButtonBackground (Graphics& g,
  45564. Button& button,
  45565. const Colour& backgroundColour,
  45566. bool isMouseOverButton,
  45567. bool isButtonDown);
  45568. /** Draws the contents of a standard ToggleButton. */
  45569. virtual void drawToggleButton (Graphics& g,
  45570. ToggleButton& button,
  45571. bool isMouseOverButton,
  45572. bool isButtonDown);
  45573. virtual void drawTickBox (Graphics& g,
  45574. Component& component,
  45575. float x, float y, float w, float h,
  45576. bool ticked,
  45577. bool isEnabled,
  45578. bool isMouseOverButton,
  45579. bool isButtonDown);
  45580. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  45581. int width, int height,
  45582. double progress, const String& textToShow);
  45583. virtual void drawScrollbarButton (Graphics& g,
  45584. ScrollBar& scrollbar,
  45585. int width, int height,
  45586. int buttonDirection,
  45587. bool isScrollbarVertical,
  45588. bool isMouseOverButton,
  45589. bool isButtonDown);
  45590. virtual void drawScrollbar (Graphics& g,
  45591. ScrollBar& scrollbar,
  45592. int x, int y,
  45593. int width, int height,
  45594. bool isScrollbarVertical,
  45595. int thumbStartPosition,
  45596. int thumbSize,
  45597. bool isMouseOver,
  45598. bool isMouseDown);
  45599. virtual ImageEffectFilter* getScrollbarEffect();
  45600. virtual void drawTextEditorOutline (Graphics& g,
  45601. int width, int height,
  45602. TextEditor& textEditor);
  45603. /** Fills the background of a popup menu component. */
  45604. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  45605. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  45606. bool isMouseOverBar,
  45607. MenuBarComponent& menuBar);
  45608. virtual void drawComboBox (Graphics& g, int width, int height,
  45609. bool isButtonDown,
  45610. int buttonX, int buttonY,
  45611. int buttonW, int buttonH,
  45612. ComboBox& box);
  45613. virtual const Font getComboBoxFont (ComboBox& box);
  45614. virtual void drawLinearSlider (Graphics& g,
  45615. int x, int y,
  45616. int width, int height,
  45617. float sliderPos,
  45618. float minSliderPos,
  45619. float maxSliderPos,
  45620. const Slider::SliderStyle style,
  45621. Slider& slider);
  45622. virtual int getSliderThumbRadius (Slider& slider);
  45623. virtual Button* createSliderButton (bool isIncrement);
  45624. virtual ImageEffectFilter* getSliderEffect();
  45625. virtual void drawCornerResizer (Graphics& g,
  45626. int w, int h,
  45627. bool isMouseOver,
  45628. bool isMouseDragging);
  45629. virtual Button* createDocumentWindowButton (int buttonType);
  45630. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  45631. int titleBarX, int titleBarY,
  45632. int titleBarW, int titleBarH,
  45633. Button* minimiseButton,
  45634. Button* maximiseButton,
  45635. Button* closeButton,
  45636. bool positionTitleBarButtonsOnLeft);
  45637. private:
  45638. DropShadowEffect scrollbarShadow;
  45639. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OldSchoolLookAndFeel);
  45640. };
  45641. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  45642. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  45643. #endif
  45644. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  45645. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  45646. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  45647. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  45648. /**
  45649. A menu bar component.
  45650. @see MenuBarModel
  45651. */
  45652. class JUCE_API MenuBarComponent : public Component,
  45653. private MenuBarModel::Listener,
  45654. private Timer
  45655. {
  45656. public:
  45657. /** Creates a menu bar.
  45658. @param model the model object to use to control this bar. You can
  45659. pass 0 into this if you like, and set the model later
  45660. using the setModel() method
  45661. */
  45662. MenuBarComponent (MenuBarModel* model);
  45663. /** Destructor. */
  45664. ~MenuBarComponent();
  45665. /** Changes the model object to use to control the bar.
  45666. This can be 0, in which case the bar will be empty. Don't delete the object
  45667. that is passed-in while it's still being used by this MenuBar.
  45668. */
  45669. void setModel (MenuBarModel* newModel);
  45670. /** Returns the current menu bar model being used.
  45671. */
  45672. MenuBarModel* getModel() const throw();
  45673. /** Pops up one of the menu items.
  45674. This lets you manually open one of the menus - it could be triggered by a
  45675. key shortcut, for example.
  45676. */
  45677. void showMenu (int menuIndex);
  45678. /** @internal */
  45679. void paint (Graphics& g);
  45680. /** @internal */
  45681. void resized();
  45682. /** @internal */
  45683. void mouseEnter (const MouseEvent& e);
  45684. /** @internal */
  45685. void mouseExit (const MouseEvent& e);
  45686. /** @internal */
  45687. void mouseDown (const MouseEvent& e);
  45688. /** @internal */
  45689. void mouseDrag (const MouseEvent& e);
  45690. /** @internal */
  45691. void mouseUp (const MouseEvent& e);
  45692. /** @internal */
  45693. void mouseMove (const MouseEvent& e);
  45694. /** @internal */
  45695. void handleCommandMessage (int commandId);
  45696. /** @internal */
  45697. bool keyPressed (const KeyPress& key);
  45698. /** @internal */
  45699. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  45700. /** @internal */
  45701. void menuCommandInvoked (MenuBarModel* menuBarModel,
  45702. const ApplicationCommandTarget::InvocationInfo& info);
  45703. private:
  45704. MenuBarModel* model;
  45705. StringArray menuNames;
  45706. Array <int> xPositions;
  45707. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked;
  45708. int lastMouseX, lastMouseY;
  45709. int getItemAt (int x, int y);
  45710. void setItemUnderMouse (int index);
  45711. void setOpenItem (int index);
  45712. void updateItemUnderMouse (int x, int y);
  45713. void timerCallback();
  45714. void repaintMenuItem (int index);
  45715. void menuDismissed (int topLevelIndex, int itemId);
  45716. static void menuBarMenuDismissedCallback (int, MenuBarComponent*, int);
  45717. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarComponent);
  45718. };
  45719. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  45720. /*** End of inlined file: juce_MenuBarComponent.h ***/
  45721. #endif
  45722. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  45723. #endif
  45724. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  45725. #endif
  45726. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  45727. #endif
  45728. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  45729. #endif
  45730. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  45731. #endif
  45732. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  45733. #endif
  45734. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  45735. /*** Start of inlined file: juce_LassoComponent.h ***/
  45736. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  45737. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  45738. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  45739. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  45740. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  45741. /** Manages a list of selectable items.
  45742. Use one of these to keep a track of things that the user has highlighted, like
  45743. icons or things in a list.
  45744. The class is templated so that you can use it to hold either a set of pointers
  45745. to objects, or a set of ID numbers or handles, for cases where each item may
  45746. not always have a corresponding object.
  45747. To be informed when items are selected/deselected, register a ChangeListener with
  45748. this object.
  45749. @see SelectableObject
  45750. */
  45751. template <class SelectableItemType>
  45752. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  45753. {
  45754. public:
  45755. typedef SelectableItemType ItemType;
  45756. typedef PARAMETER_TYPE (SelectableItemType) ParameterType;
  45757. /** Creates an empty set. */
  45758. SelectedItemSet()
  45759. {
  45760. }
  45761. /** Creates a set based on an array of items. */
  45762. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  45763. : selectedItems (items)
  45764. {
  45765. }
  45766. /** Creates a copy of another set. */
  45767. SelectedItemSet (const SelectedItemSet& other)
  45768. : selectedItems (other.selectedItems)
  45769. {
  45770. }
  45771. /** Creates a copy of another set. */
  45772. SelectedItemSet& operator= (const SelectedItemSet& other)
  45773. {
  45774. if (selectedItems != other.selectedItems)
  45775. {
  45776. selectedItems = other.selectedItems;
  45777. changed();
  45778. }
  45779. return *this;
  45780. }
  45781. /** Clears any other currently selected items, and selects this item.
  45782. If this item is already the only thing selected, no change notification
  45783. will be sent out.
  45784. @see addToSelection, addToSelectionBasedOnModifiers
  45785. */
  45786. void selectOnly (ParameterType item)
  45787. {
  45788. if (isSelected (item))
  45789. {
  45790. for (int i = selectedItems.size(); --i >= 0;)
  45791. {
  45792. if (selectedItems.getUnchecked(i) != item)
  45793. {
  45794. deselect (selectedItems.getUnchecked(i));
  45795. i = jmin (i, selectedItems.size());
  45796. }
  45797. }
  45798. }
  45799. else
  45800. {
  45801. deselectAll();
  45802. changed();
  45803. selectedItems.add (item);
  45804. itemSelected (item);
  45805. }
  45806. }
  45807. /** Selects an item.
  45808. If the item is already selected, no change notification will be sent out.
  45809. @see selectOnly, addToSelectionBasedOnModifiers
  45810. */
  45811. void addToSelection (ParameterType item)
  45812. {
  45813. if (! isSelected (item))
  45814. {
  45815. changed();
  45816. selectedItems.add (item);
  45817. itemSelected (item);
  45818. }
  45819. }
  45820. /** Selects or deselects an item.
  45821. This will use the modifier keys to decide whether to deselect other items
  45822. first.
  45823. So if the shift key is held down, the item will be added without deselecting
  45824. anything (same as calling addToSelection() )
  45825. If no modifiers are down, the current selection will be cleared first (same
  45826. as calling selectOnly() )
  45827. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  45828. so it'll be added to the set unless it's already there, in which case it'll be
  45829. deselected.
  45830. If the items that you're selecting can also be dragged, you may need to use the
  45831. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  45832. subtleties of this kind of usage.
  45833. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  45834. */
  45835. void addToSelectionBasedOnModifiers (ParameterType item,
  45836. const ModifierKeys& modifiers)
  45837. {
  45838. if (modifiers.isShiftDown())
  45839. {
  45840. addToSelection (item);
  45841. }
  45842. else if (modifiers.isCommandDown())
  45843. {
  45844. if (isSelected (item))
  45845. deselect (item);
  45846. else
  45847. addToSelection (item);
  45848. }
  45849. else
  45850. {
  45851. selectOnly (item);
  45852. }
  45853. }
  45854. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  45855. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  45856. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  45857. makes it easy to handle multiple-selection of sets of objects that can also
  45858. be dragged.
  45859. For example, if you have several items already selected, and you click on
  45860. one of them (without dragging), then you'd expect this to deselect the other, and
  45861. just select the item you clicked on. But if you had clicked on this item and
  45862. dragged it, you'd have expected them all to stay selected.
  45863. When you call this method, you'll need to store the boolean result, because the
  45864. addToSelectionOnMouseUp() method will need to be know this value.
  45865. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  45866. */
  45867. bool addToSelectionOnMouseDown (ParameterType item,
  45868. const ModifierKeys& modifiers)
  45869. {
  45870. if (isSelected (item))
  45871. {
  45872. return ! modifiers.isPopupMenu();
  45873. }
  45874. else
  45875. {
  45876. addToSelectionBasedOnModifiers (item, modifiers);
  45877. return false;
  45878. }
  45879. }
  45880. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  45881. Call this during a mouseUp callback, when you have previously called the
  45882. addToSelectionOnMouseDown() method during your mouseDown event.
  45883. See addToSelectionOnMouseDown() for more info
  45884. @param item the item to select (or deselect)
  45885. @param modifiers the modifiers from the mouse-up event
  45886. @param wasItemDragged true if your item was dragged during the mouse click
  45887. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  45888. back from the addToSelectionOnMouseDown() call that you
  45889. should have made during the matching mouseDown event
  45890. */
  45891. void addToSelectionOnMouseUp (ParameterType item,
  45892. const ModifierKeys& modifiers,
  45893. const bool wasItemDragged,
  45894. const bool resultOfMouseDownSelectMethod)
  45895. {
  45896. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  45897. addToSelectionBasedOnModifiers (item, modifiers);
  45898. }
  45899. /** Deselects an item. */
  45900. void deselect (ParameterType item)
  45901. {
  45902. const int i = selectedItems.indexOf (item);
  45903. if (i >= 0)
  45904. {
  45905. changed();
  45906. itemDeselected (selectedItems.remove (i));
  45907. }
  45908. }
  45909. /** Deselects all items. */
  45910. void deselectAll()
  45911. {
  45912. if (selectedItems.size() > 0)
  45913. {
  45914. changed();
  45915. for (int i = selectedItems.size(); --i >= 0;)
  45916. {
  45917. itemDeselected (selectedItems.remove (i));
  45918. i = jmin (i, selectedItems.size());
  45919. }
  45920. }
  45921. }
  45922. /** Returns the number of currently selected items.
  45923. @see getSelectedItem
  45924. */
  45925. int getNumSelected() const throw()
  45926. {
  45927. return selectedItems.size();
  45928. }
  45929. /** Returns one of the currently selected items.
  45930. Returns 0 if the index is out-of-range.
  45931. @see getNumSelected
  45932. */
  45933. SelectableItemType getSelectedItem (const int index) const throw()
  45934. {
  45935. return selectedItems [index];
  45936. }
  45937. /** True if this item is currently selected. */
  45938. bool isSelected (ParameterType item) const throw()
  45939. {
  45940. return selectedItems.contains (item);
  45941. }
  45942. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  45943. /** Can be overridden to do special handling when an item is selected.
  45944. For example, if the item is an object, you might want to call it and tell
  45945. it that it's being selected.
  45946. */
  45947. virtual void itemSelected (SelectableItemType item) { (void) item; }
  45948. /** Can be overridden to do special handling when an item is deselected.
  45949. For example, if the item is an object, you might want to call it and tell
  45950. it that it's being deselected.
  45951. */
  45952. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  45953. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  45954. */
  45955. void changed (const bool synchronous = false)
  45956. {
  45957. if (synchronous)
  45958. sendSynchronousChangeMessage();
  45959. else
  45960. sendChangeMessage();
  45961. }
  45962. private:
  45963. Array <SelectableItemType> selectedItems;
  45964. JUCE_LEAK_DETECTOR (SelectedItemSet <SelectableItemType>);
  45965. };
  45966. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  45967. /*** End of inlined file: juce_SelectedItemSet.h ***/
  45968. /**
  45969. A class used by the LassoComponent to manage the things that it selects.
  45970. This allows the LassoComponent to find out which items are within the lasso,
  45971. and to change the list of selected items.
  45972. @see LassoComponent, SelectedItemSet
  45973. */
  45974. template <class SelectableItemType>
  45975. class LassoSource
  45976. {
  45977. public:
  45978. /** Destructor. */
  45979. virtual ~LassoSource() {}
  45980. /** Returns the set of items that lie within a given lassoable region.
  45981. Your implementation of this method must find all the relevent items that lie
  45982. within the given rectangle. and add them to the itemsFound array.
  45983. The co-ordinates are relative to the top-left of the lasso component's parent
  45984. component. (i.e. they are the same as the size and position of the lasso
  45985. component itself).
  45986. */
  45987. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  45988. const Rectangle<int>& area) = 0;
  45989. /** Returns the SelectedItemSet that the lasso should update.
  45990. This set will be continuously updated by the LassoComponent as it gets
  45991. dragged around, so make sure that you've got a ChangeListener attached to
  45992. the set so that your UI objects will know when the selection changes and
  45993. be able to update themselves appropriately.
  45994. */
  45995. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  45996. };
  45997. /**
  45998. A component that acts as a rectangular selection region, which you drag with
  45999. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  46000. To use one of these:
  46001. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  46002. component, and call its beginLasso() method, giving it a
  46003. suitable LassoSource object that it can use to find out which items are in
  46004. the active area.
  46005. - Each time your parent component gets a mouseDrag event, call dragLasso()
  46006. to update the lasso's position - it will use its LassoSource to calculate and
  46007. update the current selection.
  46008. - After the drag has finished and you get a mouseUp callback, you should call
  46009. endLasso() to clean up. This will make the lasso component invisible, and you
  46010. can remove it from the parent component, or delete it.
  46011. The class takes into account the modifier keys that are being held down while
  46012. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  46013. be added to the original selection; if ctrl or command is pressed, they will be
  46014. xor'ed with any previously selected items.
  46015. @see LassoSource, SelectedItemSet
  46016. */
  46017. template <class SelectableItemType>
  46018. class LassoComponent : public Component
  46019. {
  46020. public:
  46021. /** Creates a Lasso component.
  46022. The fill colour is used to fill the lasso'ed rectangle, and the outline
  46023. colour is used to draw a line around its edge.
  46024. */
  46025. explicit LassoComponent (const int outlineThickness_ = 1)
  46026. : source (0),
  46027. outlineThickness (outlineThickness_)
  46028. {
  46029. }
  46030. /** Destructor. */
  46031. ~LassoComponent()
  46032. {
  46033. }
  46034. /** Call this in your mouseDown event, to initialise a drag.
  46035. Pass in a suitable LassoSource object which the lasso will use to find
  46036. the items and change the selection.
  46037. After using this method to initialise the lasso, repeatedly call dragLasso()
  46038. in your component's mouseDrag callback.
  46039. @see dragLasso, endLasso, LassoSource
  46040. */
  46041. void beginLasso (const MouseEvent& e,
  46042. LassoSource <SelectableItemType>* const lassoSource)
  46043. {
  46044. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  46045. jassert (lassoSource != 0); // the source can't be null!
  46046. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  46047. source = lassoSource;
  46048. if (lassoSource != 0)
  46049. originalSelection = lassoSource->getLassoSelection().getItemArray();
  46050. setSize (0, 0);
  46051. dragStartPos = e.getMouseDownPosition();
  46052. }
  46053. /** Call this in your mouseDrag event, to update the lasso's position.
  46054. This must be repeatedly calling when the mouse is dragged, after you've
  46055. first initialised the lasso with beginLasso().
  46056. This method takes into account the modifier keys that are being held down, so
  46057. if shift is pressed, then the lassoed items will be added to any that were
  46058. previously selected; if ctrl or command is pressed, then they will be xor'ed
  46059. with previously selected items.
  46060. @see beginLasso, endLasso
  46061. */
  46062. void dragLasso (const MouseEvent& e)
  46063. {
  46064. if (source != 0)
  46065. {
  46066. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  46067. setVisible (true);
  46068. Array <SelectableItemType> itemsInLasso;
  46069. source->findLassoItemsInArea (itemsInLasso, getBounds());
  46070. if (e.mods.isShiftDown())
  46071. {
  46072. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  46073. itemsInLasso.addArray (originalSelection);
  46074. }
  46075. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  46076. {
  46077. Array <SelectableItemType> originalMinusNew (originalSelection);
  46078. originalMinusNew.removeValuesIn (itemsInLasso);
  46079. itemsInLasso.removeValuesIn (originalSelection);
  46080. itemsInLasso.addArray (originalMinusNew);
  46081. }
  46082. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  46083. }
  46084. }
  46085. /** Call this in your mouseUp event, after the lasso has been dragged.
  46086. @see beginLasso, dragLasso
  46087. */
  46088. void endLasso()
  46089. {
  46090. source = 0;
  46091. originalSelection.clear();
  46092. setVisible (false);
  46093. }
  46094. /** A set of colour IDs to use to change the colour of various aspects of the label.
  46095. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  46096. methods.
  46097. Note that you can also use the constants from TextEditor::ColourIds to change the
  46098. colour of the text editor that is opened when a label is editable.
  46099. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  46100. */
  46101. enum ColourIds
  46102. {
  46103. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  46104. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  46105. };
  46106. /** @internal */
  46107. void paint (Graphics& g)
  46108. {
  46109. g.fillAll (findColour (lassoFillColourId));
  46110. g.setColour (findColour (lassoOutlineColourId));
  46111. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  46112. // this suggests that you've left a lasso comp lying around after the
  46113. // mouse drag has finished.. Be careful to call endLasso() when you get a
  46114. // mouse-up event.
  46115. jassert (isMouseButtonDownAnywhere());
  46116. }
  46117. /** @internal */
  46118. bool hitTest (int, int) { return false; }
  46119. private:
  46120. Array <SelectableItemType> originalSelection;
  46121. LassoSource <SelectableItemType>* source;
  46122. int outlineThickness;
  46123. Point<int> dragStartPos;
  46124. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LassoComponent);
  46125. };
  46126. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  46127. /*** End of inlined file: juce_LassoComponent.h ***/
  46128. #endif
  46129. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  46130. #endif
  46131. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  46132. #endif
  46133. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46134. /*** Start of inlined file: juce_MouseInputSource.h ***/
  46135. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46136. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46137. class MouseInputSourceInternal;
  46138. /**
  46139. Represents a linear source of mouse events from a mouse device or individual finger
  46140. in a multi-touch environment.
  46141. Each MouseEvent object contains a reference to the MouseInputSource that generated
  46142. it. In an environment with a single mouse for input, all events will come from the
  46143. same source, but in a multi-touch system, there may be multiple MouseInputSource
  46144. obects active, each representing a stream of events coming from a particular finger.
  46145. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  46146. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  46147. the only events that can happen between a mouseDown and its corresponding mouseUp are
  46148. mouseDrags, etc.
  46149. When there are multiple touches arriving from multiple MouseInputSources, their
  46150. event streams may arrive in an interleaved order, so you should use the getIndex()
  46151. method to find out which finger each event came from.
  46152. @see MouseEvent
  46153. */
  46154. class JUCE_API MouseInputSource
  46155. {
  46156. public:
  46157. /** Creates a MouseInputSource.
  46158. You should never actually create a MouseInputSource in your own code - the
  46159. library takes care of managing these objects.
  46160. */
  46161. MouseInputSource (int index, bool isMouseDevice);
  46162. /** Destructor. */
  46163. ~MouseInputSource();
  46164. /** Returns true if this object represents a normal desk-based mouse device. */
  46165. bool isMouse() const;
  46166. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  46167. bool isTouch() const;
  46168. /** Returns true if this source has an on-screen pointer that can hover over
  46169. items without clicking them.
  46170. */
  46171. bool canHover() const;
  46172. /** Returns true if this source may have a scroll wheel. */
  46173. bool hasMouseWheel() const;
  46174. /** Returns this source's index in the global list of possible sources.
  46175. If the system only has a single mouse, there will only be a single MouseInputSource
  46176. with an index of 0.
  46177. If the system supports multi-touch input, then the index will represent a finger
  46178. number, starting from 0. When the first touch event begins, it will have finger
  46179. number 0, and then if a second touch happens while the first is still down, it
  46180. will have index 1, etc.
  46181. */
  46182. int getIndex() const;
  46183. /** Returns true if this device is currently being pressed. */
  46184. bool isDragging() const;
  46185. /** Returns the last-known screen position of this source. */
  46186. const Point<int> getScreenPosition() const;
  46187. /** Returns a set of modifiers that indicate which buttons are currently
  46188. held down on this device.
  46189. */
  46190. const ModifierKeys getCurrentModifiers() const;
  46191. /** Returns the component that was last known to be under this pointer. */
  46192. Component* getComponentUnderMouse() const;
  46193. /** Tells the device to dispatch a mouse-move or mouse-drag event.
  46194. This is asynchronous - the event will occur on the message thread.
  46195. */
  46196. void triggerFakeMove() const;
  46197. /** Returns the number of clicks that should be counted as belonging to the
  46198. current mouse event.
  46199. So the mouse is currently down and it's the second click of a double-click, this
  46200. will return 2.
  46201. */
  46202. int getNumberOfMultipleClicks() const throw();
  46203. /** Returns the time at which the last mouse-down occurred. */
  46204. const Time getLastMouseDownTime() const throw();
  46205. /** Returns the screen position at which the last mouse-down occurred. */
  46206. const Point<int> getLastMouseDownPosition() const throw();
  46207. /** Returns true if this mouse is currently down, and if it has been dragged more
  46208. than a couple of pixels from the place it was pressed.
  46209. */
  46210. bool hasMouseMovedSignificantlySincePressed() const throw();
  46211. /** Returns true if this input source uses a visible mouse cursor. */
  46212. bool hasMouseCursor() const throw();
  46213. /** Changes the mouse cursor, (if there is one). */
  46214. void showMouseCursor (const MouseCursor& cursor);
  46215. /** Hides the mouse cursor (if there is one). */
  46216. void hideCursor();
  46217. /** Un-hides the mouse cursor if it was hidden by hideCursor(). */
  46218. void revealCursor();
  46219. /** Forces an update of the mouse cursor for whatever component it's currently over. */
  46220. void forceMouseCursorUpdate();
  46221. /** Returns true if this mouse can be moved indefinitely in any direction without running out of space. */
  46222. bool canDoUnboundedMovement() const throw();
  46223. /** Allows the mouse to move beyond the edges of the screen.
  46224. Calling this method when the mouse button is currently pressed will remove the cursor
  46225. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  46226. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  46227. can be used for things like custom slider controls or dragging objects around, where
  46228. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  46229. The unbounded mode is automatically turned off when the mouse button is released, or
  46230. it can be turned off explicitly by calling this method again.
  46231. @param isEnabled whether to turn this mode on or off
  46232. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  46233. hidden; if true, it will only be hidden when it
  46234. is moved beyond the edge of the screen
  46235. */
  46236. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  46237. /** @internal */
  46238. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  46239. /** @internal */
  46240. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  46241. private:
  46242. friend class Desktop;
  46243. friend class ComponentPeer;
  46244. friend class MouseInputSourceInternal;
  46245. ScopedPointer<MouseInputSourceInternal> pimpl;
  46246. static const Point<int> getCurrentMousePosition();
  46247. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseInputSource);
  46248. };
  46249. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  46250. /*** End of inlined file: juce_MouseInputSource.h ***/
  46251. #endif
  46252. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  46253. #endif
  46254. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  46255. #endif
  46256. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  46257. #endif
  46258. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  46259. #endif
  46260. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  46261. #endif
  46262. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46263. /*** Start of inlined file: juce_RelativeParallelogram.h ***/
  46264. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46265. #define __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46266. /**
  46267. A parallelogram defined by three RelativePoint positions.
  46268. @see RelativePoint, RelativeCoordinate
  46269. */
  46270. class JUCE_API RelativeParallelogram
  46271. {
  46272. public:
  46273. RelativeParallelogram();
  46274. RelativeParallelogram (const Rectangle<float>& simpleRectangle);
  46275. RelativeParallelogram (const RelativePoint& topLeft, const RelativePoint& topRight, const RelativePoint& bottomLeft);
  46276. RelativeParallelogram (const String& topLeft, const String& topRight, const String& bottomLeft);
  46277. ~RelativeParallelogram();
  46278. void resolveThreePoints (Point<float>* points, Expression::Scope* scope) const;
  46279. void resolveFourCorners (Point<float>* points, Expression::Scope* scope) const;
  46280. const Rectangle<float> getBounds (Expression::Scope* scope) const;
  46281. void getPath (Path& path, Expression::Scope* scope) const;
  46282. const AffineTransform resetToPerpendicular (Expression::Scope* scope);
  46283. bool isDynamic() const;
  46284. bool operator== (const RelativeParallelogram& other) const throw();
  46285. bool operator!= (const RelativeParallelogram& other) const throw();
  46286. static const Point<float> getInternalCoordForPoint (const Point<float>* parallelogramCorners, Point<float> point) throw();
  46287. static const Point<float> getPointForInternalCoord (const Point<float>* parallelogramCorners, const Point<float>& internalPoint) throw();
  46288. static const Rectangle<float> getBoundingBox (const Point<float>* parallelogramCorners) throw();
  46289. RelativePoint topLeft, topRight, bottomLeft;
  46290. };
  46291. #endif // __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  46292. /*** End of inlined file: juce_RelativeParallelogram.h ***/
  46293. #endif
  46294. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  46295. #endif
  46296. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  46297. /*** Start of inlined file: juce_RelativePointPath.h ***/
  46298. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  46299. #define __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  46300. class DrawablePath;
  46301. /**
  46302. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  46303. One of these paths can be converted into a Path object for drawing and manipulation, but
  46304. unlike a Path, its points can be dynamic instead of just fixed.
  46305. @see RelativePoint, RelativeCoordinate
  46306. */
  46307. class JUCE_API RelativePointPath
  46308. {
  46309. public:
  46310. RelativePointPath();
  46311. RelativePointPath (const RelativePointPath& other);
  46312. explicit RelativePointPath (const Path& path);
  46313. ~RelativePointPath();
  46314. bool operator== (const RelativePointPath& other) const throw();
  46315. bool operator!= (const RelativePointPath& other) const throw();
  46316. /** Resolves this points in this path and adds them to a normal Path object. */
  46317. void createPath (Path& path, Expression::Scope* scope) const;
  46318. /** Returns true if the path contains any non-fixed points. */
  46319. bool containsAnyDynamicPoints() const;
  46320. /** Quickly swaps the contents of this path with another. */
  46321. void swapWith (RelativePointPath& other) throw();
  46322. /** The types of element that may be contained in this path.
  46323. @see RelativePointPath::ElementBase
  46324. */
  46325. enum ElementType
  46326. {
  46327. nullElement,
  46328. startSubPathElement,
  46329. closeSubPathElement,
  46330. lineToElement,
  46331. quadraticToElement,
  46332. cubicToElement
  46333. };
  46334. /** Base class for the elements that make up a RelativePointPath.
  46335. */
  46336. class JUCE_API ElementBase
  46337. {
  46338. public:
  46339. ElementBase (ElementType type);
  46340. virtual ~ElementBase() {}
  46341. virtual const ValueTree createTree() const = 0;
  46342. virtual void addToPath (Path& path, Expression::Scope*) const = 0;
  46343. virtual RelativePoint* getControlPoints (int& numPoints) = 0;
  46344. virtual ElementBase* clone() const = 0;
  46345. bool isDynamic();
  46346. const ElementType type;
  46347. private:
  46348. JUCE_DECLARE_NON_COPYABLE (ElementBase);
  46349. };
  46350. class JUCE_API StartSubPath : public ElementBase
  46351. {
  46352. public:
  46353. StartSubPath (const RelativePoint& pos);
  46354. const ValueTree createTree() const;
  46355. void addToPath (Path& path, Expression::Scope*) const;
  46356. RelativePoint* getControlPoints (int& numPoints);
  46357. ElementBase* clone() const;
  46358. RelativePoint startPos;
  46359. private:
  46360. JUCE_DECLARE_NON_COPYABLE (StartSubPath);
  46361. };
  46362. class JUCE_API CloseSubPath : public ElementBase
  46363. {
  46364. public:
  46365. CloseSubPath();
  46366. const ValueTree createTree() const;
  46367. void addToPath (Path& path, Expression::Scope*) const;
  46368. RelativePoint* getControlPoints (int& numPoints);
  46369. ElementBase* clone() const;
  46370. private:
  46371. JUCE_DECLARE_NON_COPYABLE (CloseSubPath);
  46372. };
  46373. class JUCE_API LineTo : public ElementBase
  46374. {
  46375. public:
  46376. LineTo (const RelativePoint& endPoint);
  46377. const ValueTree createTree() const;
  46378. void addToPath (Path& path, Expression::Scope*) const;
  46379. RelativePoint* getControlPoints (int& numPoints);
  46380. ElementBase* clone() const;
  46381. RelativePoint endPoint;
  46382. private:
  46383. JUCE_DECLARE_NON_COPYABLE (LineTo);
  46384. };
  46385. class JUCE_API QuadraticTo : public ElementBase
  46386. {
  46387. public:
  46388. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  46389. const ValueTree createTree() const;
  46390. void addToPath (Path& path, Expression::Scope*) const;
  46391. RelativePoint* getControlPoints (int& numPoints);
  46392. ElementBase* clone() const;
  46393. RelativePoint controlPoints[2];
  46394. private:
  46395. JUCE_DECLARE_NON_COPYABLE (QuadraticTo);
  46396. };
  46397. class JUCE_API CubicTo : public ElementBase
  46398. {
  46399. public:
  46400. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  46401. const ValueTree createTree() const;
  46402. void addToPath (Path& path, Expression::Scope*) const;
  46403. RelativePoint* getControlPoints (int& numPoints);
  46404. ElementBase* clone() const;
  46405. RelativePoint controlPoints[3];
  46406. private:
  46407. JUCE_DECLARE_NON_COPYABLE (CubicTo);
  46408. };
  46409. void addElement (ElementBase* newElement);
  46410. OwnedArray <ElementBase> elements;
  46411. bool usesNonZeroWinding;
  46412. private:
  46413. class Positioner;
  46414. friend class Positioner;
  46415. bool containsDynamicPoints;
  46416. void applyTo (DrawablePath& path) const;
  46417. RelativePointPath& operator= (const RelativePointPath&);
  46418. JUCE_LEAK_DETECTOR (RelativePointPath);
  46419. };
  46420. #endif // __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  46421. /*** End of inlined file: juce_RelativePointPath.h ***/
  46422. #endif
  46423. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  46424. /*** Start of inlined file: juce_RelativeRectangle.h ***/
  46425. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  46426. #define __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  46427. class Component;
  46428. /**
  46429. An rectangle stored as a set of RelativeCoordinate values.
  46430. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  46431. @see RelativeCoordinate, RelativePoint
  46432. */
  46433. class JUCE_API RelativeRectangle
  46434. {
  46435. public:
  46436. /** Creates a zero-size rectangle at the origin. */
  46437. RelativeRectangle();
  46438. /** Creates an absolute rectangle, relative to the origin. */
  46439. explicit RelativeRectangle (const Rectangle<float>& rect);
  46440. /** Creates a rectangle from four coordinates. */
  46441. RelativeRectangle (const RelativeCoordinate& left, const RelativeCoordinate& right,
  46442. const RelativeCoordinate& top, const RelativeCoordinate& bottom);
  46443. /** Creates a rectangle from a stringified representation.
  46444. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  46445. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  46446. RelativeCoordinate class.
  46447. @see toString
  46448. */
  46449. explicit RelativeRectangle (const String& stringVersion);
  46450. bool operator== (const RelativeRectangle& other) const throw();
  46451. bool operator!= (const RelativeRectangle& other) const throw();
  46452. /** Calculates the absolute position of this rectangle.
  46453. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  46454. be needed to calculate the result.
  46455. */
  46456. const Rectangle<float> resolve (const Expression::Scope* scope) const;
  46457. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  46458. Calling this will leave any anchor points unchanged, but will set any absolute
  46459. or relative positions to whatever values are necessary to make the resultant position
  46460. match the position that is provided.
  46461. */
  46462. void moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope);
  46463. /** Returns true if this rectangle depends on any external symbols for its position.
  46464. Coordinates that refer to symbols based on "this" are assumed not to be dynamic.
  46465. */
  46466. bool isDynamic() const;
  46467. /** Returns a string which represents this point.
  46468. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  46469. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  46470. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  46471. */
  46472. const String toString() const;
  46473. /** Renames a symbol if it is used by any of the coordinates.
  46474. This calls Expression::withRenamedSymbol() on the rectangle's coordinates.
  46475. */
  46476. void renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope);
  46477. /** Creates and sets an appropriate Component::Positioner object for the given component, which will
  46478. keep it positioned with this rectangle.
  46479. */
  46480. void applyToComponent (Component& component) const;
  46481. // The actual rectangle coords...
  46482. RelativeCoordinate left, right, top, bottom;
  46483. };
  46484. #endif // __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  46485. /*** End of inlined file: juce_RelativeRectangle.h ***/
  46486. #endif
  46487. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  46488. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  46489. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  46490. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  46491. /**
  46492. A PropertyComponent that contains an on/off toggle button.
  46493. This type of property component can be used if you have a boolean value to
  46494. toggle on/off.
  46495. @see PropertyComponent
  46496. */
  46497. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  46498. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  46499. {
  46500. protected:
  46501. /** Creates a button component.
  46502. If you use this constructor, you must override the getState() and setState()
  46503. methods.
  46504. @param propertyName the property name to be passed to the PropertyComponent
  46505. @param buttonTextWhenTrue the text shown in the button when the value is true
  46506. @param buttonTextWhenFalse the text shown in the button when the value is false
  46507. */
  46508. BooleanPropertyComponent (const String& propertyName,
  46509. const String& buttonTextWhenTrue,
  46510. const String& buttonTextWhenFalse);
  46511. public:
  46512. /** Creates a button component.
  46513. @param valueToControl a Value object that this property should refer to.
  46514. @param propertyName the property name to be passed to the PropertyComponent
  46515. @param buttonText the text shown in the ToggleButton component
  46516. */
  46517. BooleanPropertyComponent (const Value& valueToControl,
  46518. const String& propertyName,
  46519. const String& buttonText);
  46520. /** Destructor. */
  46521. ~BooleanPropertyComponent();
  46522. /** Called to change the state of the boolean value. */
  46523. virtual void setState (bool newState);
  46524. /** Must return the current value of the property. */
  46525. virtual bool getState() const;
  46526. /** @internal */
  46527. void paint (Graphics& g);
  46528. /** @internal */
  46529. void refresh();
  46530. /** @internal */
  46531. void buttonClicked (Button*);
  46532. private:
  46533. ToggleButton button;
  46534. String onText, offText;
  46535. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BooleanPropertyComponent);
  46536. };
  46537. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  46538. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  46539. #endif
  46540. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  46541. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  46542. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  46543. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  46544. /**
  46545. A PropertyComponent that contains a button.
  46546. This type of property component can be used if you need a button to trigger some
  46547. kind of action.
  46548. @see PropertyComponent
  46549. */
  46550. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  46551. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  46552. {
  46553. public:
  46554. /** Creates a button component.
  46555. @param propertyName the property name to be passed to the PropertyComponent
  46556. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  46557. */
  46558. ButtonPropertyComponent (const String& propertyName,
  46559. bool triggerOnMouseDown);
  46560. /** Destructor. */
  46561. ~ButtonPropertyComponent();
  46562. /** Called when the user clicks the button.
  46563. */
  46564. virtual void buttonClicked() = 0;
  46565. /** Returns the string that should be displayed in the button.
  46566. If you need to change this string, call refresh() to update the component.
  46567. */
  46568. virtual const String getButtonText() const = 0;
  46569. /** @internal */
  46570. void refresh();
  46571. /** @internal */
  46572. void buttonClicked (Button*);
  46573. private:
  46574. TextButton button;
  46575. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonPropertyComponent);
  46576. };
  46577. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  46578. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  46579. #endif
  46580. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  46581. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  46582. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  46583. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  46584. /**
  46585. A PropertyComponent that shows its value as a combo box.
  46586. This type of property component contains a list of options and has a
  46587. combo box to choose one.
  46588. Your subclass's constructor must add some strings to the choices StringArray
  46589. and these are shown in the list.
  46590. The getIndex() method will be called to find out which option is the currently
  46591. selected one. If you call refresh() it will call getIndex() to check whether
  46592. the value has changed, and will update the combo box if needed.
  46593. If the user selects a different item from the list, setIndex() will be
  46594. called to let your class process this.
  46595. @see PropertyComponent, PropertyPanel
  46596. */
  46597. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  46598. private ComboBoxListener // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  46599. {
  46600. protected:
  46601. /** Creates the component.
  46602. Your subclass's constructor must add a list of options to the choices
  46603. member variable.
  46604. */
  46605. ChoicePropertyComponent (const String& propertyName);
  46606. public:
  46607. /** Creates the component.
  46608. @param valueToControl the value that the combo box will read and control
  46609. @param propertyName the name of the property
  46610. @param choices the list of possible values that the drop-down list will contain
  46611. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  46612. These are the values that will be read and written to the
  46613. valueToControl value. This array must contain the same number of items
  46614. as the choices array
  46615. */
  46616. ChoicePropertyComponent (const Value& valueToControl,
  46617. const String& propertyName,
  46618. const StringArray& choices,
  46619. const Array <var>& correspondingValues);
  46620. /** Destructor. */
  46621. ~ChoicePropertyComponent();
  46622. /** Called when the user selects an item from the combo box.
  46623. Your subclass must use this callback to update the value that this component
  46624. represents. The index is the index of the chosen item in the choices
  46625. StringArray.
  46626. */
  46627. virtual void setIndex (int newIndex);
  46628. /** Returns the index of the item that should currently be shown.
  46629. This is the index of the item in the choices StringArray that will be
  46630. shown.
  46631. */
  46632. virtual int getIndex() const;
  46633. /** Returns the list of options. */
  46634. const StringArray& getChoices() const;
  46635. /** @internal */
  46636. void refresh();
  46637. /** @internal */
  46638. void comboBoxChanged (ComboBox*);
  46639. protected:
  46640. /** The list of options that will be shown in the combo box.
  46641. Your subclass must populate this array in its constructor. If any empty
  46642. strings are added, these will be replaced with horizontal separators (see
  46643. ComboBox::addSeparator() for more info).
  46644. */
  46645. StringArray choices;
  46646. private:
  46647. ComboBox comboBox;
  46648. bool isCustomClass;
  46649. class RemapperValueSource;
  46650. void createComboBox();
  46651. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChoicePropertyComponent);
  46652. };
  46653. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  46654. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  46655. #endif
  46656. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  46657. #endif
  46658. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  46659. #endif
  46660. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  46661. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  46662. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  46663. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  46664. /**
  46665. A PropertyComponent that shows its value as a slider.
  46666. @see PropertyComponent, Slider
  46667. */
  46668. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  46669. private SliderListener // (can't use Slider::Listener due to idiotic VC2005 bug)
  46670. {
  46671. protected:
  46672. /** Creates the property component.
  46673. The ranges, interval and skew factor are passed to the Slider component.
  46674. If you need to customise the slider in other ways, your constructor can
  46675. access the slider member variable and change it directly.
  46676. */
  46677. SliderPropertyComponent (const String& propertyName,
  46678. double rangeMin,
  46679. double rangeMax,
  46680. double interval,
  46681. double skewFactor = 1.0);
  46682. public:
  46683. /** Creates the property component.
  46684. The ranges, interval and skew factor are passed to the Slider component.
  46685. If you need to customise the slider in other ways, your constructor can
  46686. access the slider member variable and change it directly.
  46687. */
  46688. SliderPropertyComponent (const Value& valueToControl,
  46689. const String& propertyName,
  46690. double rangeMin,
  46691. double rangeMax,
  46692. double interval,
  46693. double skewFactor = 1.0);
  46694. /** Destructor. */
  46695. ~SliderPropertyComponent();
  46696. /** Called when the user moves the slider to change its value.
  46697. Your subclass must use this method to update whatever item this property
  46698. represents.
  46699. */
  46700. virtual void setValue (double newValue);
  46701. /** Returns the value that the slider should show. */
  46702. virtual double getValue() const;
  46703. /** @internal */
  46704. void refresh();
  46705. /** @internal */
  46706. void sliderValueChanged (Slider*);
  46707. protected:
  46708. /** The slider component being used in this component.
  46709. Your subclass has access to this in case it needs to customise it in some way.
  46710. */
  46711. Slider slider;
  46712. private:
  46713. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPropertyComponent);
  46714. };
  46715. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  46716. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  46717. #endif
  46718. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  46719. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  46720. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  46721. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  46722. /**
  46723. A PropertyComponent that shows its value as editable text.
  46724. @see PropertyComponent
  46725. */
  46726. class JUCE_API TextPropertyComponent : public PropertyComponent
  46727. {
  46728. protected:
  46729. /** Creates a text property component.
  46730. The maxNumChars is used to set the length of string allowable, and isMultiLine
  46731. sets whether the text editor allows carriage returns.
  46732. @see TextEditor
  46733. */
  46734. TextPropertyComponent (const String& propertyName,
  46735. int maxNumChars,
  46736. bool isMultiLine);
  46737. public:
  46738. /** Creates a text property component.
  46739. The maxNumChars is used to set the length of string allowable, and isMultiLine
  46740. sets whether the text editor allows carriage returns.
  46741. @see TextEditor
  46742. */
  46743. TextPropertyComponent (const Value& valueToControl,
  46744. const String& propertyName,
  46745. int maxNumChars,
  46746. bool isMultiLine);
  46747. /** Destructor. */
  46748. ~TextPropertyComponent();
  46749. /** Called when the user edits the text.
  46750. Your subclass must use this callback to change the value of whatever item
  46751. this property component represents.
  46752. */
  46753. virtual void setText (const String& newText);
  46754. /** Returns the text that should be shown in the text editor.
  46755. */
  46756. virtual const String getText() const;
  46757. /** @internal */
  46758. void refresh();
  46759. /** @internal */
  46760. void textWasEdited();
  46761. private:
  46762. ScopedPointer<Label> textEditor;
  46763. void createEditor (int maxNumChars, bool isMultiLine);
  46764. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextPropertyComponent);
  46765. };
  46766. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  46767. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  46768. #endif
  46769. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  46770. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  46771. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  46772. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  46773. #if JUCE_WINDOWS || DOXYGEN
  46774. /**
  46775. A Windows-specific class that can create and embed an ActiveX control inside
  46776. itself.
  46777. To use it, create one of these, put it in place and make sure it's visible in a
  46778. window, then use createControl() to instantiate an ActiveX control. The control
  46779. will then be moved and resized to follow the movements of this component.
  46780. Of course, since the control is a heavyweight window, it'll obliterate any
  46781. juce components that may overlap this component, but that's life.
  46782. */
  46783. class JUCE_API ActiveXControlComponent : public Component
  46784. {
  46785. public:
  46786. /** Create an initially-empty container. */
  46787. ActiveXControlComponent();
  46788. /** Destructor. */
  46789. ~ActiveXControlComponent();
  46790. /** Tries to create an ActiveX control and embed it in this peer.
  46791. The peer controlIID is a pointer to an IID structure - it's treated
  46792. as a void* because when including the Juce headers, you might not always
  46793. have included windows.h first, in which case IID wouldn't be defined.
  46794. e.g. @code
  46795. const IID myIID = __uuidof (QTControl);
  46796. myControlComp->createControl (&myIID);
  46797. @endcode
  46798. */
  46799. bool createControl (const void* controlIID);
  46800. /** Deletes the ActiveX control, if one has been created.
  46801. */
  46802. void deleteControl();
  46803. /** Returns true if a control is currently in use. */
  46804. bool isControlOpen() const throw() { return control != 0; }
  46805. /** Does a QueryInterface call on the embedded control object.
  46806. This allows you to cast the control to whatever type of COM object you need.
  46807. The iid parameter is a pointer to an IID structure - it's treated
  46808. as a void* because when including the Juce headers, you might not always
  46809. have included windows.h first, in which case IID wouldn't be defined, but
  46810. you should just pass a pointer to an IID.
  46811. e.g. @code
  46812. const IID iid = __uuidof (IOleWindow);
  46813. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  46814. if (oleWindow != 0)
  46815. {
  46816. HWND hwnd;
  46817. oleWindow->GetWindow (&hwnd);
  46818. ...
  46819. oleWindow->Release();
  46820. }
  46821. @endcode
  46822. */
  46823. void* queryInterface (const void* iid) const;
  46824. /** Set this to false to stop mouse events being allowed through to the control.
  46825. */
  46826. void setMouseEventsAllowed (bool eventsCanReachControl);
  46827. /** Returns true if mouse events are allowed to get through to the control.
  46828. */
  46829. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  46830. /** @internal */
  46831. void paint (Graphics& g);
  46832. /** @internal */
  46833. void* originalWndProc;
  46834. private:
  46835. class Pimpl;
  46836. friend class Pimpl;
  46837. friend class ScopedPointer <Pimpl>;
  46838. ScopedPointer <Pimpl> control;
  46839. bool mouseEventsAllowed;
  46840. void setControlBounds (const Rectangle<int>& bounds) const;
  46841. void setControlVisible (bool b) const;
  46842. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ActiveXControlComponent);
  46843. };
  46844. #endif
  46845. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  46846. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  46847. #endif
  46848. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  46849. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  46850. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  46851. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  46852. /**
  46853. A component containing controls to let the user change the audio settings of
  46854. an AudioDeviceManager object.
  46855. Very easy to use - just create one of these and show it to the user.
  46856. @see AudioDeviceManager
  46857. */
  46858. class JUCE_API AudioDeviceSelectorComponent : public Component,
  46859. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  46860. public ButtonListener,
  46861. public ChangeListener
  46862. {
  46863. public:
  46864. /** Creates the component.
  46865. If your app needs only output channels, you might ask for a maximum of 0 input
  46866. channels, and the component won't display any options for choosing the input
  46867. channels. And likewise if you're doing an input-only app.
  46868. @param deviceManager the device manager that this component should control
  46869. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  46870. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  46871. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  46872. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  46873. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  46874. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  46875. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  46876. treated as a set of separate mono channels.
  46877. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  46878. are shown, with an "advanced" button that shows the rest of them
  46879. */
  46880. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  46881. const int minAudioInputChannels,
  46882. const int maxAudioInputChannels,
  46883. const int minAudioOutputChannels,
  46884. const int maxAudioOutputChannels,
  46885. const bool showMidiInputOptions,
  46886. const bool showMidiOutputSelector,
  46887. const bool showChannelsAsStereoPairs,
  46888. const bool hideAdvancedOptionsWithButton);
  46889. /** Destructor */
  46890. ~AudioDeviceSelectorComponent();
  46891. /** @internal */
  46892. void resized();
  46893. /** @internal */
  46894. void comboBoxChanged (ComboBox*);
  46895. /** @internal */
  46896. void buttonClicked (Button*);
  46897. /** @internal */
  46898. void changeListenerCallback (ChangeBroadcaster*);
  46899. /** @internal */
  46900. void childBoundsChanged (Component*);
  46901. private:
  46902. AudioDeviceManager& deviceManager;
  46903. ScopedPointer<ComboBox> deviceTypeDropDown;
  46904. ScopedPointer<Label> deviceTypeDropDownLabel;
  46905. ScopedPointer<Component> audioDeviceSettingsComp;
  46906. String audioDeviceSettingsCompType;
  46907. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  46908. const bool showChannelsAsStereoPairs;
  46909. const bool hideAdvancedOptionsWithButton;
  46910. class MidiInputSelectorComponentListBox;
  46911. friend class ScopedPointer<MidiInputSelectorComponentListBox>;
  46912. ScopedPointer<MidiInputSelectorComponentListBox> midiInputsList;
  46913. ScopedPointer<ComboBox> midiOutputSelector;
  46914. ScopedPointer<Label> midiInputsLabel, midiOutputLabel;
  46915. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceSelectorComponent);
  46916. };
  46917. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  46918. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  46919. #endif
  46920. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  46921. /*** Start of inlined file: juce_BubbleComponent.h ***/
  46922. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  46923. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  46924. /**
  46925. A component for showing a message or other graphics inside a speech-bubble-shaped
  46926. outline, pointing at a location on the screen.
  46927. This is a base class that just draws and positions the bubble shape, but leaves
  46928. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  46929. that draws a text message.
  46930. To use it, create your subclass, then either add it to a parent component or
  46931. put it on the desktop with addToDesktop (0), use setPosition() to
  46932. resize and position it, then make it visible.
  46933. @see BubbleMessageComponent
  46934. */
  46935. class JUCE_API BubbleComponent : public Component
  46936. {
  46937. protected:
  46938. /** Creates a BubbleComponent.
  46939. Your subclass will need to implement the getContentSize() and paintContent()
  46940. methods to draw the bubble's contents.
  46941. */
  46942. BubbleComponent();
  46943. public:
  46944. /** Destructor. */
  46945. ~BubbleComponent();
  46946. /** A list of permitted placements for the bubble, relative to the co-ordinates
  46947. at which it should be pointing.
  46948. @see setAllowedPlacement
  46949. */
  46950. enum BubblePlacement
  46951. {
  46952. above = 1,
  46953. below = 2,
  46954. left = 4,
  46955. right = 8
  46956. };
  46957. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  46958. point at which it's pointing.
  46959. By default when setPosition() is called, the bubble will place itself either
  46960. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  46961. the values in BubblePlacement to restrict this choice.
  46962. E.g. if you only want your bubble to appear above or below the target area,
  46963. use setAllowedPlacement (above | below);
  46964. @see BubblePlacement
  46965. */
  46966. void setAllowedPlacement (int newPlacement);
  46967. /** Moves and resizes the bubble to point at a given component.
  46968. This will resize the bubble to fit its content, then find a position for it
  46969. so that it's next to, but doesn't overlap the given component.
  46970. It'll put itself either above, below, or to the side of the component depending
  46971. on where there's the most space, honouring any restrictions that were set
  46972. with setAllowedPlacement().
  46973. */
  46974. void setPosition (Component* componentToPointTo);
  46975. /** Moves and resizes the bubble to point at a given point.
  46976. This will resize the bubble to fit its content, then position it
  46977. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  46978. are relative to either the bubble component's parent component if it has one, or
  46979. they are screen co-ordinates if not.
  46980. It'll put itself either above, below, or to the side of this point, depending
  46981. on where there's the most space, honouring any restrictions that were set
  46982. with setAllowedPlacement().
  46983. */
  46984. void setPosition (int arrowTipX,
  46985. int arrowTipY);
  46986. /** Moves and resizes the bubble to point at a given rectangle.
  46987. This will resize the bubble to fit its content, then find a position for it
  46988. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  46989. co-ordinates are relative to either the bubble component's parent component
  46990. if it has one, or they are screen co-ordinates if not.
  46991. It'll put itself either above, below, or to the side of the component depending
  46992. on where there's the most space, honouring any restrictions that were set
  46993. with setAllowedPlacement().
  46994. */
  46995. void setPosition (const Rectangle<int>& rectangleToPointTo);
  46996. protected:
  46997. /** Subclasses should override this to return the size of the content they
  46998. want to draw inside the bubble.
  46999. */
  47000. virtual void getContentSize (int& width, int& height) = 0;
  47001. /** Subclasses should override this to draw their bubble's contents.
  47002. The graphics object's clip region and the dimensions passed in here are
  47003. set up to paint just the rectangle inside the bubble.
  47004. */
  47005. virtual void paintContent (Graphics& g, int width, int height) = 0;
  47006. public:
  47007. /** @internal */
  47008. void paint (Graphics& g);
  47009. private:
  47010. Rectangle<int> content;
  47011. int side, allowablePlacements;
  47012. float arrowTipX, arrowTipY;
  47013. DropShadowEffect shadow;
  47014. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleComponent);
  47015. };
  47016. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  47017. /*** End of inlined file: juce_BubbleComponent.h ***/
  47018. #endif
  47019. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47020. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  47021. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47022. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47023. /**
  47024. A speech-bubble component that displays a short message.
  47025. This can be used to show a message with the tail of the speech bubble
  47026. pointing to a particular component or location on the screen.
  47027. @see BubbleComponent
  47028. */
  47029. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  47030. private Timer
  47031. {
  47032. public:
  47033. /** Creates a bubble component.
  47034. After creating one a BubbleComponent, do the following:
  47035. - add it to an appropriate parent component, or put it on the
  47036. desktop with Component::addToDesktop (0).
  47037. - use the showAt() method to show a message.
  47038. - it will make itself invisible after it times-out (and can optionally
  47039. also delete itself), or you can reuse it somewhere else by calling
  47040. showAt() again.
  47041. */
  47042. BubbleMessageComponent (int fadeOutLengthMs = 150);
  47043. /** Destructor. */
  47044. ~BubbleMessageComponent();
  47045. /** Shows a message bubble at a particular position.
  47046. This shows the bubble with its stem pointing to the given location
  47047. (co-ordinates being relative to its parent component).
  47048. For details about exactly how it decides where to position itself, see
  47049. BubbleComponent::updatePosition().
  47050. @param x the x co-ordinate of end of the bubble's tail
  47051. @param y the y co-ordinate of end of the bubble's tail
  47052. @param message the text to display
  47053. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  47054. from its parent compnent. If this is 0 or less, it
  47055. will stay there until manually removed.
  47056. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  47057. mouse button is pressed (anywhere on the screen)
  47058. @param deleteSelfAfterUse if true, then the component will delete itself after
  47059. it becomes invisible
  47060. */
  47061. void showAt (int x, int y,
  47062. const String& message,
  47063. int numMillisecondsBeforeRemoving,
  47064. bool removeWhenMouseClicked = true,
  47065. bool deleteSelfAfterUse = false);
  47066. /** Shows a message bubble next to a particular component.
  47067. This shows the bubble with its stem pointing at the given component.
  47068. For details about exactly how it decides where to position itself, see
  47069. BubbleComponent::updatePosition().
  47070. @param component the component that you want to point at
  47071. @param message the text to display
  47072. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  47073. from its parent compnent. If this is 0 or less, it
  47074. will stay there until manually removed.
  47075. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  47076. mouse button is pressed (anywhere on the screen)
  47077. @param deleteSelfAfterUse if true, then the component will delete itself after
  47078. it becomes invisible
  47079. */
  47080. void showAt (Component* component,
  47081. const String& message,
  47082. int numMillisecondsBeforeRemoving,
  47083. bool removeWhenMouseClicked = true,
  47084. bool deleteSelfAfterUse = false);
  47085. /** @internal */
  47086. void getContentSize (int& w, int& h);
  47087. /** @internal */
  47088. void paintContent (Graphics& g, int w, int h);
  47089. /** @internal */
  47090. void timerCallback();
  47091. private:
  47092. int fadeOutLength, mouseClickCounter;
  47093. TextLayout textLayout;
  47094. int64 expiryTime;
  47095. bool deleteAfterUse;
  47096. void init (int numMillisecondsBeforeRemoving,
  47097. bool removeWhenMouseClicked,
  47098. bool deleteSelfAfterUse);
  47099. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleMessageComponent);
  47100. };
  47101. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  47102. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  47103. #endif
  47104. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  47105. /*** Start of inlined file: juce_ColourSelector.h ***/
  47106. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  47107. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  47108. /**
  47109. A component that lets the user choose a colour.
  47110. This shows RGB sliders and a colourspace that the user can pick colours from.
  47111. This class is also a ChangeBroadcaster, so listeners can register to be told
  47112. when the colour changes.
  47113. */
  47114. class JUCE_API ColourSelector : public Component,
  47115. public ChangeBroadcaster,
  47116. protected SliderListener
  47117. {
  47118. public:
  47119. /** Options for the type of selector to show. These are passed into the constructor. */
  47120. enum ColourSelectorOptions
  47121. {
  47122. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  47123. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  47124. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  47125. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  47126. };
  47127. /** Creates a ColourSelector object.
  47128. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  47129. which of the selector's features should be visible.
  47130. The edgeGap value specifies the amount of space to leave around the edge.
  47131. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  47132. colourspace and hue selector components.
  47133. */
  47134. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  47135. int edgeGap = 4,
  47136. int gapAroundColourSpaceComponent = 7);
  47137. /** Destructor. */
  47138. ~ColourSelector();
  47139. /** Returns the colour that the user has currently selected.
  47140. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  47141. register to be told when the colour changes.
  47142. @see setCurrentColour
  47143. */
  47144. const Colour getCurrentColour() const;
  47145. /** Changes the colour that is currently being shown.
  47146. */
  47147. void setCurrentColour (const Colour& newColour);
  47148. /** Tells the selector how many preset colour swatches you want to have on the component.
  47149. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  47150. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  47151. their values.
  47152. */
  47153. virtual int getNumSwatches() const;
  47154. /** Called by the selector to find out the colour of one of the swatches.
  47155. Your subclass should return the colour of the swatch with the given index.
  47156. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  47157. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  47158. their values.
  47159. */
  47160. virtual const Colour getSwatchColour (int index) const;
  47161. /** Called by the selector when the user puts a new colour into one of the swatches.
  47162. Your subclass should change the colour of the swatch with the given index.
  47163. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  47164. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  47165. their values.
  47166. */
  47167. virtual void setSwatchColour (int index, const Colour& newColour) const;
  47168. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  47169. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  47170. methods.
  47171. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  47172. */
  47173. enum ColourIds
  47174. {
  47175. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  47176. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  47177. };
  47178. private:
  47179. class ColourSpaceView;
  47180. class HueSelectorComp;
  47181. class SwatchComponent;
  47182. friend class ColourSpaceView;
  47183. friend class ScopedPointer<ColourSpaceView>;
  47184. friend class HueSelectorComp;
  47185. friend class ScopedPointer<HueSelectorComp>;
  47186. Colour colour;
  47187. float h, s, v;
  47188. ScopedPointer<Slider> sliders[4];
  47189. ScopedPointer<ColourSpaceView> colourSpace;
  47190. ScopedPointer<HueSelectorComp> hueSelector;
  47191. OwnedArray <SwatchComponent> swatchComponents;
  47192. const int flags;
  47193. int edgeGap;
  47194. Rectangle<int> previewArea;
  47195. void setHue (float newH);
  47196. void setSV (float newS, float newV);
  47197. void updateHSV();
  47198. void update();
  47199. void sliderValueChanged (Slider*);
  47200. void paint (Graphics& g);
  47201. void resized();
  47202. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ColourSelector);
  47203. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  47204. // This constructor is here temporarily to prevent old code compiling, because the parameters
  47205. // have changed - if you get an error here, update your code to use the new constructor instead..
  47206. ColourSelector (bool);
  47207. #endif
  47208. };
  47209. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  47210. /*** End of inlined file: juce_ColourSelector.h ***/
  47211. #endif
  47212. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  47213. #endif
  47214. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  47215. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  47216. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  47217. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  47218. /**
  47219. A component that displays a piano keyboard, whose notes can be clicked on.
  47220. This component will mimic a physical midi keyboard, showing the current state of
  47221. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  47222. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  47223. Another feature is that the computer keyboard can also be used to play notes. By
  47224. default it maps the top two rows of a standard querty keyboard to the notes, but
  47225. these can be remapped if needed. It will only respond to keypresses when it has
  47226. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  47227. The component is also a ChangeBroadcaster, so if you want to be informed when the
  47228. keyboard is scrolled, you can register a ChangeListener for callbacks.
  47229. @see MidiKeyboardState
  47230. */
  47231. class JUCE_API MidiKeyboardComponent : public Component,
  47232. public MidiKeyboardStateListener,
  47233. public ChangeBroadcaster,
  47234. private Timer,
  47235. private AsyncUpdater
  47236. {
  47237. public:
  47238. /** The direction of the keyboard.
  47239. @see setOrientation
  47240. */
  47241. enum Orientation
  47242. {
  47243. horizontalKeyboard,
  47244. verticalKeyboardFacingLeft,
  47245. verticalKeyboardFacingRight,
  47246. };
  47247. /** Creates a MidiKeyboardComponent.
  47248. @param state the midi keyboard model that this component will represent
  47249. @param orientation whether the keyboard is horizonal or vertical
  47250. */
  47251. MidiKeyboardComponent (MidiKeyboardState& state,
  47252. Orientation orientation);
  47253. /** Destructor. */
  47254. ~MidiKeyboardComponent();
  47255. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  47256. on the component.
  47257. Values are 0 to 1.0, where 1.0 is the heaviest.
  47258. @see setMidiChannel
  47259. */
  47260. void setVelocity (float velocity, bool useMousePositionForVelocity);
  47261. /** Changes the midi channel number that will be used for events triggered by clicking
  47262. on the component.
  47263. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  47264. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  47265. Although this is the channel used for outgoing events, the component can display
  47266. incoming events from more than one channel - see setMidiChannelsToDisplay()
  47267. @see setVelocity
  47268. */
  47269. void setMidiChannel (int midiChannelNumber);
  47270. /** Returns the midi channel that the keyboard is using for midi messages.
  47271. @see setMidiChannel
  47272. */
  47273. int getMidiChannel() const throw() { return midiChannel; }
  47274. /** Sets a mask to indicate which incoming midi channels should be represented by
  47275. key movements.
  47276. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  47277. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  47278. in this mask, the on-screen keys will also go down.
  47279. By default, this mask is set to 0xffff (all channels displayed).
  47280. @see setMidiChannel
  47281. */
  47282. void setMidiChannelsToDisplay (int midiChannelMask);
  47283. /** Returns the current set of midi channels represented by the component.
  47284. This is the value that was set with setMidiChannelsToDisplay().
  47285. */
  47286. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  47287. /** Changes the width used to draw the white keys. */
  47288. void setKeyWidth (float widthInPixels);
  47289. /** Returns the width that was set by setKeyWidth(). */
  47290. float getKeyWidth() const throw() { return keyWidth; }
  47291. /** Changes the keyboard's current direction. */
  47292. void setOrientation (Orientation newOrientation);
  47293. /** Returns the keyboard's current direction. */
  47294. const Orientation getOrientation() const throw() { return orientation; }
  47295. /** Sets the range of midi notes that the keyboard will be limited to.
  47296. By default the range is 0 to 127 (inclusive), but you can limit this if you
  47297. only want a restricted set of the keys to be shown.
  47298. Note that the values here are inclusive and must be between 0 and 127.
  47299. */
  47300. void setAvailableRange (int lowestNote,
  47301. int highestNote);
  47302. /** Returns the first note in the available range.
  47303. @see setAvailableRange
  47304. */
  47305. int getRangeStart() const throw() { return rangeStart; }
  47306. /** Returns the last note in the available range.
  47307. @see setAvailableRange
  47308. */
  47309. int getRangeEnd() const throw() { return rangeEnd; }
  47310. /** If the keyboard extends beyond the size of the component, this will scroll
  47311. it to show the given key at the start.
  47312. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  47313. base class to send a callback to any ChangeListeners that have been registered.
  47314. */
  47315. void setLowestVisibleKey (int noteNumber);
  47316. /** Returns the number of the first key shown in the component.
  47317. @see setLowestVisibleKey
  47318. */
  47319. int getLowestVisibleKey() const throw() { return firstKey; }
  47320. /** Returns the length of the black notes.
  47321. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  47322. */
  47323. int getBlackNoteLength() const throw() { return blackNoteLength; }
  47324. /** If set to true, then scroll buttons will appear at either end of the keyboard
  47325. if there are too many notes to fit them all in the component at once.
  47326. */
  47327. void setScrollButtonsVisible (bool canScroll);
  47328. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  47329. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  47330. methods.
  47331. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  47332. */
  47333. enum ColourIds
  47334. {
  47335. whiteNoteColourId = 0x1005000,
  47336. blackNoteColourId = 0x1005001,
  47337. keySeparatorLineColourId = 0x1005002,
  47338. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  47339. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  47340. textLabelColourId = 0x1005005,
  47341. upDownButtonBackgroundColourId = 0x1005006,
  47342. upDownButtonArrowColourId = 0x1005007
  47343. };
  47344. /** Returns the position within the component of the left-hand edge of a key.
  47345. Depending on the keyboard's orientation, this may be a horizontal or vertical
  47346. distance, in either direction.
  47347. */
  47348. int getKeyStartPosition (const int midiNoteNumber) const;
  47349. /** Deletes all key-mappings.
  47350. @see setKeyPressForNote
  47351. */
  47352. void clearKeyMappings();
  47353. /** Maps a key-press to a given note.
  47354. @param key the key that should trigger the note
  47355. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  47356. be. The actual midi note that gets played will be
  47357. this value + (12 * the current base octave). To change
  47358. the base octave, see setKeyPressBaseOctave()
  47359. */
  47360. void setKeyPressForNote (const KeyPress& key,
  47361. int midiNoteOffsetFromC);
  47362. /** Removes any key-mappings for a given note.
  47363. For a description of what the note number means, see setKeyPressForNote().
  47364. */
  47365. void removeKeyPressForNote (int midiNoteOffsetFromC);
  47366. /** Changes the base note above which key-press-triggered notes are played.
  47367. The set of key-mappings that trigger notes can be moved up and down to cover
  47368. the entire scale using this method.
  47369. The value passed in is an octave number between 0 and 10 (inclusive), and
  47370. indicates which C is the base note to which the key-mapped notes are
  47371. relative.
  47372. */
  47373. void setKeyPressBaseOctave (int newOctaveNumber);
  47374. /** This sets the octave number which is shown as the octave number for middle C.
  47375. This affects only the default implementation of getWhiteNoteText(), which
  47376. passes this octave number to MidiMessage::getMidiNoteName() in order to
  47377. get the note text. See MidiMessage::getMidiNoteName() for more info about
  47378. the parameter.
  47379. By default this value is set to 3.
  47380. @see getOctaveForMiddleC
  47381. */
  47382. void setOctaveForMiddleC (int octaveNumForMiddleC);
  47383. /** This returns the value set by setOctaveForMiddleC().
  47384. @see setOctaveForMiddleC
  47385. */
  47386. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  47387. /** @internal */
  47388. void paint (Graphics& g);
  47389. /** @internal */
  47390. void resized();
  47391. /** @internal */
  47392. void mouseMove (const MouseEvent& e);
  47393. /** @internal */
  47394. void mouseDrag (const MouseEvent& e);
  47395. /** @internal */
  47396. void mouseDown (const MouseEvent& e);
  47397. /** @internal */
  47398. void mouseUp (const MouseEvent& e);
  47399. /** @internal */
  47400. void mouseEnter (const MouseEvent& e);
  47401. /** @internal */
  47402. void mouseExit (const MouseEvent& e);
  47403. /** @internal */
  47404. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  47405. /** @internal */
  47406. void timerCallback();
  47407. /** @internal */
  47408. bool keyStateChanged (bool isKeyDown);
  47409. /** @internal */
  47410. void focusLost (FocusChangeType cause);
  47411. /** @internal */
  47412. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  47413. /** @internal */
  47414. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  47415. /** @internal */
  47416. void handleAsyncUpdate();
  47417. /** @internal */
  47418. void colourChanged();
  47419. protected:
  47420. /** Draws a white note in the given rectangle.
  47421. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  47422. currently pressed down.
  47423. When doing this, be sure to note the keyboard's orientation.
  47424. */
  47425. virtual void drawWhiteNote (int midiNoteNumber,
  47426. Graphics& g,
  47427. int x, int y, int w, int h,
  47428. bool isDown, bool isOver,
  47429. const Colour& lineColour,
  47430. const Colour& textColour);
  47431. /** Draws a black note in the given rectangle.
  47432. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  47433. currently pressed down.
  47434. When doing this, be sure to note the keyboard's orientation.
  47435. */
  47436. virtual void drawBlackNote (int midiNoteNumber,
  47437. Graphics& g,
  47438. int x, int y, int w, int h,
  47439. bool isDown, bool isOver,
  47440. const Colour& noteFillColour);
  47441. /** Allows text to be drawn on the white notes.
  47442. By default this is used to label the C in each octave, but could be used for other things.
  47443. @see setOctaveForMiddleC
  47444. */
  47445. virtual const String getWhiteNoteText (const int midiNoteNumber);
  47446. /** Draws the up and down buttons that change the base note. */
  47447. virtual void drawUpDownButton (Graphics& g, int w, int h,
  47448. const bool isMouseOver,
  47449. const bool isButtonPressed,
  47450. const bool movesOctavesUp);
  47451. /** Callback when the mouse is clicked on a key.
  47452. You could use this to do things like handle right-clicks on keys, etc.
  47453. Return true if you want the click to trigger the note, or false if you
  47454. want to handle it yourself and not have the note played.
  47455. @see mouseDraggedToKey
  47456. */
  47457. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  47458. /** Callback when the mouse is dragged from one key onto another.
  47459. @see mouseDownOnKey
  47460. */
  47461. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  47462. /** Calculates the positon of a given midi-note.
  47463. This can be overridden to create layouts with custom key-widths.
  47464. @param midiNoteNumber the note to find
  47465. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  47466. @param x the x position of the left-hand edge of the key (this method
  47467. always works in terms of a horizontal keyboard)
  47468. @param w the width of the key
  47469. */
  47470. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  47471. int& x, int& w) const;
  47472. private:
  47473. friend class MidiKeyboardUpDownButton;
  47474. MidiKeyboardState& state;
  47475. int xOffset, blackNoteLength;
  47476. float keyWidth;
  47477. Orientation orientation;
  47478. int midiChannel, midiInChannelMask;
  47479. float velocity;
  47480. int noteUnderMouse, mouseDownNote;
  47481. BigInteger keysPressed, keysCurrentlyDrawnDown;
  47482. int rangeStart, rangeEnd, firstKey;
  47483. bool canScroll, mouseDragging, useMousePositionForVelocity;
  47484. ScopedPointer<Button> scrollDown, scrollUp;
  47485. Array <KeyPress> keyPresses;
  47486. Array <int> keyPressNotes;
  47487. int keyMappingOctave;
  47488. int octaveNumForMiddleC;
  47489. static const uint8 whiteNotes[];
  47490. static const uint8 blackNotes[];
  47491. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  47492. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  47493. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  47494. void resetAnyKeysInUse();
  47495. void updateNoteUnderMouse (const Point<int>& pos);
  47496. void repaintNote (const int midiNoteNumber);
  47497. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardComponent);
  47498. };
  47499. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  47500. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  47501. #endif
  47502. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  47503. /*** Start of inlined file: juce_NSViewComponent.h ***/
  47504. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  47505. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  47506. #if ! DOXYGEN
  47507. class NSViewComponentInternal;
  47508. #endif
  47509. #if JUCE_MAC || DOXYGEN
  47510. /**
  47511. A Mac-specific class that can create and embed an NSView inside itself.
  47512. To use it, create one of these, put it in place and make sure it's visible in a
  47513. window, then use setView() to assign an NSView to it. The view will then be
  47514. moved and resized to follow the movements of this component.
  47515. Of course, since the view is a native object, it'll obliterate any
  47516. juce components that may overlap this component, but that's life.
  47517. */
  47518. class JUCE_API NSViewComponent : public Component
  47519. {
  47520. public:
  47521. /** Create an initially-empty container. */
  47522. NSViewComponent();
  47523. /** Destructor. */
  47524. ~NSViewComponent();
  47525. /** Assigns an NSView to this peer.
  47526. The view will be retained and released by this component for as long as
  47527. it is needed. To remove the current view, just call setView (0).
  47528. Note: a void* is used here to avoid including the cocoa headers as
  47529. part of the juce.h, but the method expects an NSView*.
  47530. */
  47531. void setView (void* nsView);
  47532. /** Returns the current NSView.
  47533. Note: a void* is returned here to avoid including the cocoa headers as
  47534. a requirement of juce.h, so you should just cast the object to an NSView*.
  47535. */
  47536. void* getView() const;
  47537. /** Resizes this component to fit the view that it contains. */
  47538. void resizeToFitView();
  47539. /** @internal */
  47540. void paint (Graphics& g);
  47541. private:
  47542. friend class NSViewComponentInternal;
  47543. ScopedPointer <NSViewComponentInternal> info;
  47544. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponent);
  47545. };
  47546. #endif
  47547. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  47548. /*** End of inlined file: juce_NSViewComponent.h ***/
  47549. #endif
  47550. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  47551. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  47552. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  47553. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  47554. // this is used to disable OpenGL, and is defined in juce_Config.h
  47555. #if JUCE_OPENGL || DOXYGEN
  47556. /**
  47557. Represents the various properties of an OpenGL bitmap format.
  47558. @see OpenGLComponent::setPixelFormat
  47559. */
  47560. class JUCE_API OpenGLPixelFormat
  47561. {
  47562. public:
  47563. /** Creates an OpenGLPixelFormat.
  47564. The default constructor just initialises the object as a simple 8-bit
  47565. RGBA format.
  47566. */
  47567. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  47568. int alphaBits = 8,
  47569. int depthBufferBits = 16,
  47570. int stencilBufferBits = 0);
  47571. OpenGLPixelFormat (const OpenGLPixelFormat&);
  47572. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  47573. bool operator== (const OpenGLPixelFormat&) const;
  47574. int redBits; /**< The number of bits per pixel to use for the red channel. */
  47575. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  47576. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  47577. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  47578. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  47579. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  47580. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  47581. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  47582. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  47583. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  47584. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  47585. /** Returns a list of all the pixel formats that can be used in this system.
  47586. A reference component is needed in case there are multiple screens with different
  47587. capabilities - in which case, the one that the component is on will be used.
  47588. */
  47589. static void getAvailablePixelFormats (Component* component,
  47590. OwnedArray <OpenGLPixelFormat>& results);
  47591. private:
  47592. JUCE_LEAK_DETECTOR (OpenGLPixelFormat);
  47593. };
  47594. /**
  47595. A base class for types of OpenGL context.
  47596. An OpenGLComponent will supply its own context for drawing in its window.
  47597. */
  47598. class JUCE_API OpenGLContext
  47599. {
  47600. public:
  47601. /** Destructor. */
  47602. virtual ~OpenGLContext();
  47603. /** Makes this context the currently active one. */
  47604. virtual bool makeActive() const throw() = 0;
  47605. /** If this context is currently active, it is disactivated. */
  47606. virtual bool makeInactive() const throw() = 0;
  47607. /** Returns true if this context is currently active. */
  47608. virtual bool isActive() const throw() = 0;
  47609. /** Swaps the buffers (if the context can do this). */
  47610. virtual void swapBuffers() = 0;
  47611. /** Sets whether the context checks the vertical sync before swapping.
  47612. The value is the number of frames to allow between buffer-swapping. This is
  47613. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  47614. and greater numbers indicate that it should swap less often.
  47615. Returns true if it sets the value successfully.
  47616. */
  47617. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  47618. /** Returns the current swap-sync interval.
  47619. See setSwapInterval() for info about the value returned.
  47620. */
  47621. virtual int getSwapInterval() const = 0;
  47622. /** Returns the pixel format being used by this context. */
  47623. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  47624. /** For windowed contexts, this moves the context within the bounds of
  47625. its parent window.
  47626. */
  47627. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  47628. /** For windowed contexts, this triggers a repaint of the window.
  47629. (Not relevent on all platforms).
  47630. */
  47631. virtual void repaint() = 0;
  47632. /** Returns an OS-dependent handle to the raw GL context.
  47633. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  47634. a GLXContext.
  47635. */
  47636. virtual void* getRawContext() const throw() = 0;
  47637. /** Deletes the context.
  47638. This must only be called on the message thread, or will deadlock.
  47639. On background threads, call getCurrentContext()->deleteContext(), but be careful not
  47640. to call any other OpenGL function afterwards.
  47641. This doesn't touch other resources, such as window handles, etc.
  47642. You'll probably never have to call this method directly.
  47643. */
  47644. virtual void deleteContext() = 0;
  47645. /** Returns the context that's currently in active use by the calling thread.
  47646. Returns 0 if there isn't an active context.
  47647. */
  47648. static OpenGLContext* getCurrentContext();
  47649. protected:
  47650. OpenGLContext() throw();
  47651. private:
  47652. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLContext);
  47653. };
  47654. /**
  47655. A component that contains an OpenGL canvas.
  47656. Override this, add it to whatever component you want to, and use the renderOpenGL()
  47657. method to draw its contents.
  47658. */
  47659. class JUCE_API OpenGLComponent : public Component
  47660. {
  47661. public:
  47662. /** Used to select the type of openGL API to use, if more than one choice is available
  47663. on a particular platform.
  47664. */
  47665. enum OpenGLType
  47666. {
  47667. openGLDefault = 0,
  47668. #if JUCE_IOS
  47669. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  47670. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  47671. #endif
  47672. };
  47673. /** Creates an OpenGLComponent. */
  47674. OpenGLComponent (OpenGLType type = openGLDefault);
  47675. /** Destructor. */
  47676. ~OpenGLComponent();
  47677. /** Changes the pixel format used by this component.
  47678. @see OpenGLPixelFormat::getAvailablePixelFormats()
  47679. */
  47680. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  47681. /** Returns the pixel format that this component is currently using. */
  47682. const OpenGLPixelFormat getPixelFormat() const;
  47683. /** Specifies an OpenGL context which should be shared with the one that this
  47684. component is using.
  47685. This is an OpenGL feature that lets two contexts share their texture data.
  47686. Note that this pointer is stored by the component, and when the component
  47687. needs to recreate its internal context for some reason, the same context
  47688. will be used again to share lists. So if you pass a context in here,
  47689. don't delete the context while this component is still using it! You can
  47690. call shareWith (0) to stop this component from sharing with it.
  47691. */
  47692. void shareWith (OpenGLContext* contextToShareListsWith);
  47693. /** Returns the context that this component is sharing with.
  47694. @see shareWith
  47695. */
  47696. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  47697. /** Flips the openGL buffers over. */
  47698. void swapBuffers();
  47699. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  47700. When this is called, makeCurrentContextActive() will already have been called
  47701. for you, so you just need to draw.
  47702. */
  47703. virtual void renderOpenGL() = 0;
  47704. /** This method is called when the component creates a new OpenGL context.
  47705. A new context may be created when the component is first used, or when it
  47706. is moved to a different window, or when the window is hidden and re-shown,
  47707. etc.
  47708. You can use this callback as an opportunity to set up things like textures
  47709. that your context needs.
  47710. New contexts are created on-demand by the makeCurrentContextActive() method - so
  47711. if the context is deleted, e.g. by changing the pixel format or window, no context
  47712. will be created until the next call to makeCurrentContextActive(), which will
  47713. synchronously create one and call this method. This means that if you're using
  47714. a non-GUI thread for rendering, you can make sure this method is be called by
  47715. your renderer thread.
  47716. When this callback happens, the context will already have been made current
  47717. using the makeCurrentContextActive() method, so there's no need to call it
  47718. again in your code.
  47719. */
  47720. virtual void newOpenGLContextCreated() = 0;
  47721. /** Returns the context that will draw into this component.
  47722. This may return 0 if the component is currently invisible or hasn't currently
  47723. got a context. The context object can be deleted and a new one created during
  47724. the lifetime of this component, and there may be times when it doesn't have one.
  47725. @see newOpenGLContextCreated()
  47726. */
  47727. OpenGLContext* getCurrentContext() const throw() { return context; }
  47728. /** Makes this component the current openGL context.
  47729. You might want to use this in things like your resize() method, before calling
  47730. GL commands.
  47731. If this returns false, then the context isn't active, so you should avoid
  47732. making any calls.
  47733. This call may actually create a context if one isn't currently initialised. If
  47734. it does this, it will also synchronously call the newOpenGLContextCreated()
  47735. method to let you initialise it as necessary.
  47736. @see OpenGLContext::makeActive
  47737. */
  47738. bool makeCurrentContextActive();
  47739. /** Stops the current component being the active OpenGL context.
  47740. This is the opposite of makeCurrentContextActive()
  47741. @see OpenGLContext::makeInactive
  47742. */
  47743. void makeCurrentContextInactive();
  47744. /** Returns true if this component is the active openGL context for the
  47745. current thread.
  47746. @see OpenGLContext::isActive
  47747. */
  47748. bool isActiveContext() const throw();
  47749. /** Calls the rendering callback, and swaps the buffers afterwards.
  47750. This is called automatically by paint() when the component needs to be rendered.
  47751. It can be overridden if you need to decouple the rendering from the paint callback
  47752. and render with a custom thread.
  47753. Returns true if the operation succeeded.
  47754. */
  47755. virtual bool renderAndSwapBuffers();
  47756. /** This returns a critical section that can be used to lock the current context.
  47757. Because the context that is used by this component can change, e.g. when the
  47758. component is shown or hidden, then if you're rendering to it on a background
  47759. thread, this allows you to lock the context for the duration of your rendering
  47760. routine.
  47761. */
  47762. CriticalSection& getContextLock() throw() { return contextLock; }
  47763. /** Returns the native handle of an embedded heavyweight window, if there is one.
  47764. E.g. On windows, this will return the HWND of the sub-window containing
  47765. the opengl context, on the mac it'll be the NSOpenGLView.
  47766. */
  47767. void* getNativeWindowHandle() const;
  47768. /** Delete the context.
  47769. This can be called back on the same thread that created the context. */
  47770. void deleteContext();
  47771. /** @internal */
  47772. void paint (Graphics& g);
  47773. private:
  47774. const OpenGLType type;
  47775. class OpenGLComponentWatcher;
  47776. friend class OpenGLComponentWatcher;
  47777. friend class ScopedPointer <OpenGLComponentWatcher>;
  47778. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  47779. ScopedPointer <OpenGLContext> context;
  47780. OpenGLContext* contextToShareListsWith;
  47781. CriticalSection contextLock;
  47782. OpenGLPixelFormat preferredPixelFormat;
  47783. bool needToUpdateViewport;
  47784. OpenGLContext* createContext();
  47785. void updateContextPosition();
  47786. void internalRepaint (int x, int y, int w, int h);
  47787. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponent);
  47788. };
  47789. #endif
  47790. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  47791. /*** End of inlined file: juce_OpenGLComponent.h ***/
  47792. #endif
  47793. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  47794. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  47795. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  47796. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  47797. /**
  47798. A component with a set of buttons at the top for changing between pages of
  47799. preferences.
  47800. This is just a handy way of writing a Mac-style preferences panel where you
  47801. have a row of buttons along the top for the different preference categories,
  47802. each button having an icon above its name. Clicking these will show an
  47803. appropriate prefs page below it.
  47804. You can either put one of these inside your own component, or just use the
  47805. showInDialogBox() method to show it in a window and run it modally.
  47806. To use it, just add a set of named pages with the addSettingsPage() method,
  47807. and implement the createComponentForPage() method to create suitable components
  47808. for each of these pages.
  47809. */
  47810. class JUCE_API PreferencesPanel : public Component,
  47811. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  47812. {
  47813. public:
  47814. /** Creates an empty panel.
  47815. Use addSettingsPage() to add some pages to it in your constructor.
  47816. */
  47817. PreferencesPanel();
  47818. /** Destructor. */
  47819. ~PreferencesPanel();
  47820. /** Creates a page using a set of drawables to define the page's icon.
  47821. Note that the other version of this method is much easier if you're using
  47822. an image instead of a custom drawable.
  47823. @param pageTitle the name of this preferences page - you'll need to
  47824. make sure your createComponentForPage() method creates
  47825. a suitable component when it is passed this name
  47826. @param normalIcon the drawable to display in the page's button normally
  47827. @param overIcon the drawable to display in the page's button when the mouse is over
  47828. @param downIcon the drawable to display in the page's button when the button is down
  47829. @see DrawableButton
  47830. */
  47831. void addSettingsPage (const String& pageTitle,
  47832. const Drawable* normalIcon,
  47833. const Drawable* overIcon,
  47834. const Drawable* downIcon);
  47835. /** Creates a page using a set of drawables to define the page's icon.
  47836. The other version of this method gives you more control over the icon, but this
  47837. one is much easier if you're just loading it from a file.
  47838. @param pageTitle the name of this preferences page - you'll need to
  47839. make sure your createComponentForPage() method creates
  47840. a suitable component when it is passed this name
  47841. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  47842. For this to look good, you'll probably want to use a nice
  47843. transparent png file.
  47844. @param imageDataSize the size of the image data, in bytes
  47845. */
  47846. void addSettingsPage (const String& pageTitle,
  47847. const void* imageData,
  47848. int imageDataSize);
  47849. /** Utility method to display this panel in a DialogWindow.
  47850. Calling this will create a DialogWindow containing this panel with the
  47851. given size and title, and will run it modally, returning when the user
  47852. closes the dialog box.
  47853. */
  47854. void showInDialogBox (const String& dialogTitle,
  47855. int dialogWidth,
  47856. int dialogHeight,
  47857. const Colour& backgroundColour = Colours::white);
  47858. /** Subclasses must override this to return a component for each preferences page.
  47859. The subclass should return a pointer to a new component representing the named
  47860. page, which the panel will then display.
  47861. The panel will delete the component later when the user goes to another page
  47862. or deletes the panel.
  47863. */
  47864. virtual Component* createComponentForPage (const String& pageName) = 0;
  47865. /** Changes the current page being displayed. */
  47866. void setCurrentPage (const String& pageName);
  47867. /** @internal */
  47868. void resized();
  47869. /** @internal */
  47870. void paint (Graphics& g);
  47871. /** @internal */
  47872. void buttonClicked (Button* button);
  47873. private:
  47874. String currentPageName;
  47875. ScopedPointer <Component> currentPage;
  47876. OwnedArray<DrawableButton> buttons;
  47877. int buttonSize;
  47878. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PreferencesPanel);
  47879. };
  47880. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  47881. /*** End of inlined file: juce_PreferencesPanel.h ***/
  47882. #endif
  47883. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  47884. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  47885. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  47886. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  47887. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  47888. // amalgamated build)
  47889. #ifndef DOXYGEN
  47890. #if JUCE_WINDOWS
  47891. typedef ActiveXControlComponent QTCompBaseClass;
  47892. #elif JUCE_MAC
  47893. typedef NSViewComponent QTCompBaseClass;
  47894. #endif
  47895. #endif
  47896. // this is used to disable QuickTime, and is defined in juce_Config.h
  47897. #if JUCE_QUICKTIME || DOXYGEN
  47898. /**
  47899. A window that can play back a QuickTime movie.
  47900. */
  47901. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  47902. {
  47903. public:
  47904. /** Creates a QuickTimeMovieComponent, initially blank.
  47905. Use the loadMovie() method to load a movie once you've added the
  47906. component to a window, (or put it on the desktop as a heavyweight window).
  47907. Loading a movie when the component isn't visible can cause problems, as
  47908. QuickTime needs a window handle to initialise properly.
  47909. */
  47910. QuickTimeMovieComponent();
  47911. /** Destructor. */
  47912. ~QuickTimeMovieComponent();
  47913. /** Returns true if QT is installed and working on this machine.
  47914. */
  47915. static bool isQuickTimeAvailable() throw();
  47916. /** Tries to load a QuickTime movie from a file into the player.
  47917. It's best to call this function once you've added the component to a window,
  47918. (or put it on the desktop as a heavyweight window). Loading a movie when the
  47919. component isn't visible can cause problems, because QuickTime needs a window
  47920. handle to do its stuff.
  47921. @param movieFile the .mov file to open
  47922. @param isControllerVisible whether to show a controller bar at the bottom
  47923. @returns true if the movie opens successfully
  47924. */
  47925. bool loadMovie (const File& movieFile,
  47926. bool isControllerVisible);
  47927. /** Tries to load a QuickTime movie from a URL into the player.
  47928. It's best to call this function once you've added the component to a window,
  47929. (or put it on the desktop as a heavyweight window). Loading a movie when the
  47930. component isn't visible can cause problems, because QuickTime needs a window
  47931. handle to do its stuff.
  47932. @param movieURL the .mov file to open
  47933. @param isControllerVisible whether to show a controller bar at the bottom
  47934. @returns true if the movie opens successfully
  47935. */
  47936. bool loadMovie (const URL& movieURL,
  47937. bool isControllerVisible);
  47938. /** Tries to load a QuickTime movie from a stream into the player.
  47939. It's best to call this function once you've added the component to a window,
  47940. (or put it on the desktop as a heavyweight window). Loading a movie when the
  47941. component isn't visible can cause problems, because QuickTime needs a window
  47942. handle to do its stuff.
  47943. @param movieStream a stream containing a .mov file. The component may try
  47944. to read the whole stream before playing, rather than
  47945. streaming from it.
  47946. @param isControllerVisible whether to show a controller bar at the bottom
  47947. @returns true if the movie opens successfully
  47948. */
  47949. bool loadMovie (InputStream* movieStream,
  47950. bool isControllerVisible);
  47951. /** Closes the movie, if one is open. */
  47952. void closeMovie();
  47953. /** Returns the movie file that is currently open.
  47954. If there isn't one, this returns File::nonexistent
  47955. */
  47956. const File getCurrentMovieFile() const;
  47957. /** Returns true if there's currently a movie open. */
  47958. bool isMovieOpen() const;
  47959. /** Returns the length of the movie, in seconds. */
  47960. double getMovieDuration() const;
  47961. /** Returns the movie's natural size, in pixels.
  47962. You can use this to resize the component to show the movie at its preferred
  47963. scale.
  47964. If no movie is loaded, the size returned will be 0 x 0.
  47965. */
  47966. void getMovieNormalSize (int& width, int& height) const;
  47967. /** This will position the component within a given area, keeping its aspect
  47968. ratio correct according to the movie's normal size.
  47969. The component will be made as large as it can go within the space, and will
  47970. be aligned according to the justification value if this means there are gaps at
  47971. the top or sides.
  47972. */
  47973. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  47974. const RectanglePlacement& placement);
  47975. /** Starts the movie playing. */
  47976. void play();
  47977. /** Stops the movie playing. */
  47978. void stop();
  47979. /** Returns true if the movie is currently playing. */
  47980. bool isPlaying() const;
  47981. /** Moves the movie's position back to the start. */
  47982. void goToStart();
  47983. /** Sets the movie's position to a given time. */
  47984. void setPosition (double seconds);
  47985. /** Returns the current play position of the movie. */
  47986. double getPosition() const;
  47987. /** Changes the movie playback rate.
  47988. A value of 1 is normal speed, greater values play it proportionately faster,
  47989. smaller values play it slower.
  47990. */
  47991. void setSpeed (float newSpeed);
  47992. /** Changes the movie's playback volume.
  47993. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  47994. */
  47995. void setMovieVolume (float newVolume);
  47996. /** Returns the movie's playback volume.
  47997. @returns the volume in the range 0 (silent) to 1.0 (full)
  47998. */
  47999. float getMovieVolume() const;
  48000. /** Tells the movie whether it should loop. */
  48001. void setLooping (bool shouldLoop);
  48002. /** Returns true if the movie is currently looping.
  48003. @see setLooping
  48004. */
  48005. bool isLooping() const;
  48006. /** True if the native QuickTime controller bar is shown in the window.
  48007. @see loadMovie
  48008. */
  48009. bool isControllerVisible() const;
  48010. /** @internal */
  48011. void paint (Graphics& g);
  48012. private:
  48013. File movieFile;
  48014. bool movieLoaded, controllerVisible, looping;
  48015. #if JUCE_WINDOWS
  48016. void parentHierarchyChanged();
  48017. void visibilityChanged();
  48018. void createControlIfNeeded();
  48019. bool isControlCreated() const;
  48020. class Pimpl;
  48021. friend class ScopedPointer <Pimpl>;
  48022. ScopedPointer <Pimpl> pimpl;
  48023. #else
  48024. void* movie;
  48025. #endif
  48026. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QuickTimeMovieComponent);
  48027. };
  48028. #endif
  48029. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  48030. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  48031. #endif
  48032. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48033. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  48034. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48035. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48036. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  48037. /**
  48038. On Windows only, this component sits in the taskbar tray as a small icon.
  48039. To use it, just create one of these components, but don't attempt to make it
  48040. visible, add it to a parent, or put it on the desktop.
  48041. You can then call setIconImage() to create an icon for it in the taskbar.
  48042. To change the icon's tooltip, you can use setIconTooltip().
  48043. To respond to mouse-events, you can override the normal mouseDown(),
  48044. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  48045. position will not be valid, you can use this to respond to clicks. Traditionally
  48046. you'd use a left-click to show your application's window, and a right-click
  48047. to show a pop-up menu.
  48048. */
  48049. class JUCE_API SystemTrayIconComponent : public Component
  48050. {
  48051. public:
  48052. SystemTrayIconComponent();
  48053. /** Destructor. */
  48054. ~SystemTrayIconComponent();
  48055. /** Changes the image shown in the taskbar.
  48056. */
  48057. void setIconImage (const Image& newImage);
  48058. /** Changes the tooltip that Windows shows above the icon. */
  48059. void setIconTooltip (const String& tooltip);
  48060. #if JUCE_LINUX
  48061. /** @internal */
  48062. void paint (Graphics& g);
  48063. #endif
  48064. private:
  48065. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SystemTrayIconComponent);
  48066. };
  48067. #endif
  48068. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  48069. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  48070. #endif
  48071. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48072. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  48073. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48074. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48075. #if JUCE_WEB_BROWSER || DOXYGEN
  48076. #if ! DOXYGEN
  48077. class WebBrowserComponentInternal;
  48078. #endif
  48079. /**
  48080. A component that displays an embedded web browser.
  48081. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  48082. Windows, probably IE.
  48083. */
  48084. class JUCE_API WebBrowserComponent : public Component
  48085. {
  48086. public:
  48087. /** Creates a WebBrowserComponent.
  48088. Once it's created and visible, send the browser to a URL using goToURL().
  48089. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  48090. component is taken offscreen, it'll clear the current page
  48091. and replace it with a blank page - this can be handy to stop
  48092. the browser using resources in the background when it's not
  48093. actually being used.
  48094. */
  48095. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  48096. /** Destructor. */
  48097. ~WebBrowserComponent();
  48098. /** Sends the browser to a particular URL.
  48099. @param url the URL to go to.
  48100. @param headers an optional set of parameters to put in the HTTP header. If
  48101. you supply this, it should be a set of string in the form
  48102. "HeaderKey: HeaderValue"
  48103. @param postData an optional block of data that will be attached to the HTTP
  48104. POST request
  48105. */
  48106. void goToURL (const String& url,
  48107. const StringArray* headers = 0,
  48108. const MemoryBlock* postData = 0);
  48109. /** Stops the current page loading.
  48110. */
  48111. void stop();
  48112. /** Sends the browser back one page.
  48113. */
  48114. void goBack();
  48115. /** Sends the browser forward one page.
  48116. */
  48117. void goForward();
  48118. /** Refreshes the browser.
  48119. */
  48120. void refresh();
  48121. /** This callback is called when the browser is about to navigate
  48122. to a new location.
  48123. You can override this method to perform some action when the user
  48124. tries to go to a particular URL. To allow the operation to carry on,
  48125. return true, or return false to stop the navigation happening.
  48126. */
  48127. virtual bool pageAboutToLoad (const String& newURL);
  48128. /** @internal */
  48129. void paint (Graphics& g);
  48130. /** @internal */
  48131. void resized();
  48132. /** @internal */
  48133. void parentHierarchyChanged();
  48134. /** @internal */
  48135. void visibilityChanged();
  48136. private:
  48137. WebBrowserComponentInternal* browser;
  48138. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  48139. String lastURL;
  48140. StringArray lastHeaders;
  48141. MemoryBlock lastPostData;
  48142. void reloadLastURL();
  48143. void checkWindowAssociation();
  48144. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponent);
  48145. };
  48146. #endif
  48147. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  48148. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  48149. #endif
  48150. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  48151. #endif
  48152. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  48153. /*** Start of inlined file: juce_CallOutBox.h ***/
  48154. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  48155. #define __JUCE_CALLOUTBOX_JUCEHEADER__
  48156. /**
  48157. A box with a small arrow that can be used as a temporary pop-up window to show
  48158. extra controls when a button or other component is clicked.
  48159. Using one of these is similar to having a popup menu attached to a button or
  48160. other component - but it looks fancier, and has an arrow that can indicate the
  48161. object that it applies to.
  48162. Normally, you'd create one of these on the stack and run it modally, e.g.
  48163. @code
  48164. void mouseUp (const MouseEvent& e)
  48165. {
  48166. MyContentComponent content;
  48167. content.setSize (300, 300);
  48168. CallOutBox callOut (content, *this, 0);
  48169. callOut.runModalLoop();
  48170. }
  48171. @endcode
  48172. The call-out will resize and position itself when the content changes size.
  48173. */
  48174. class JUCE_API CallOutBox : public Component
  48175. {
  48176. public:
  48177. /** Creates a CallOutBox.
  48178. @param contentComponent the component to display inside the call-out. This should
  48179. already have a size set (although the call-out will also
  48180. update itself when the component's size is changed later).
  48181. Obviously this component must not be deleted until the
  48182. call-out box has been deleted.
  48183. @param componentToPointTo the component that the call-out's arrow should point towards
  48184. @param parentComponent if non-zero, this is the component to add the call-out to. If
  48185. this is zero, the call-out will be added to the desktop.
  48186. */
  48187. CallOutBox (Component& contentComponent,
  48188. Component& componentToPointTo,
  48189. Component* parentComponent);
  48190. /** Destructor. */
  48191. ~CallOutBox();
  48192. /** Changes the length of the arrow. */
  48193. void setArrowSize (float newSize);
  48194. /** Updates the position and size of the box.
  48195. You shouldn't normally need to call this, unless you need more precise control over the
  48196. layout.
  48197. @param newAreaToPointTo the rectangle to make the box's arrow point to
  48198. @param newAreaToFitIn the area within which the box's position should be constrained
  48199. */
  48200. void updatePosition (const Rectangle<int>& newAreaToPointTo,
  48201. const Rectangle<int>& newAreaToFitIn);
  48202. /** @internal */
  48203. void paint (Graphics& g);
  48204. /** @internal */
  48205. void resized();
  48206. /** @internal */
  48207. void moved();
  48208. /** @internal */
  48209. void childBoundsChanged (Component*);
  48210. /** @internal */
  48211. bool hitTest (int x, int y);
  48212. /** @internal */
  48213. void inputAttemptWhenModal();
  48214. /** @internal */
  48215. bool keyPressed (const KeyPress& key);
  48216. /** @internal */
  48217. void handleCommandMessage (int commandId);
  48218. private:
  48219. int borderSpace;
  48220. float arrowSize;
  48221. Component& content;
  48222. Path outline;
  48223. Point<float> targetPoint;
  48224. Rectangle<int> availableArea, targetArea;
  48225. Image background;
  48226. void refreshPath();
  48227. void drawCallOutBoxBackground (Graphics& g, const Path& outline, int width, int height);
  48228. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallOutBox);
  48229. };
  48230. #endif // __JUCE_CALLOUTBOX_JUCEHEADER__
  48231. /*** End of inlined file: juce_CallOutBox.h ***/
  48232. #endif
  48233. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  48234. /*** Start of inlined file: juce_ComponentPeer.h ***/
  48235. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  48236. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  48237. class ComponentBoundsConstrainer;
  48238. /**
  48239. The Component class uses a ComponentPeer internally to create and manage a real
  48240. operating-system window.
  48241. This is an abstract base class - the platform specific code contains implementations of
  48242. it for the various platforms.
  48243. User-code should very rarely need to have any involvement with this class.
  48244. @see Component::createNewPeer
  48245. */
  48246. class JUCE_API ComponentPeer
  48247. {
  48248. public:
  48249. /** A combination of these flags is passed to the ComponentPeer constructor. */
  48250. enum StyleFlags
  48251. {
  48252. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  48253. entry on the taskbar (ignored on MacOSX) */
  48254. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  48255. tooltip, etc. */
  48256. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  48257. through it (may not be possible on some platforms). */
  48258. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  48259. title bar and frame\. if not specified, the window will be
  48260. borderless. */
  48261. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  48262. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  48263. minimise button on it. */
  48264. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  48265. maximise button on it. */
  48266. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  48267. close button on it. */
  48268. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  48269. not be possible on all platforms). */
  48270. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  48271. do its own repainting, but only to repaint when the
  48272. performAnyPendingRepaintsNow() method is called. */
  48273. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  48274. be used for things like plugin windows, to stop them interfering
  48275. with the host's shortcut keys */
  48276. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  48277. };
  48278. /** Creates a peer.
  48279. The component is the one that we intend to represent, and the style flags are
  48280. a combination of the values in the StyleFlags enum
  48281. */
  48282. ComponentPeer (Component* component, int styleFlags);
  48283. /** Destructor. */
  48284. virtual ~ComponentPeer();
  48285. /** Returns the component being represented by this peer. */
  48286. Component* getComponent() const throw() { return component; }
  48287. /** Returns the set of style flags that were set when the window was created.
  48288. @see Component::addToDesktop
  48289. */
  48290. int getStyleFlags() const throw() { return styleFlags; }
  48291. /** Returns the raw handle to whatever kind of window is being used.
  48292. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  48293. but rememeber there's no guarantees what you'll get back.
  48294. */
  48295. virtual void* getNativeHandle() const = 0;
  48296. /** Shows or hides the window. */
  48297. virtual void setVisible (bool shouldBeVisible) = 0;
  48298. /** Changes the title of the window. */
  48299. virtual void setTitle (const String& title) = 0;
  48300. /** Moves the window without changing its size.
  48301. If the native window is contained in another window, then the co-ordinates are
  48302. relative to the parent window's origin, not the screen origin.
  48303. This should result in a callback to handleMovedOrResized().
  48304. */
  48305. virtual void setPosition (int x, int y) = 0;
  48306. /** Resizes the window without changing its position.
  48307. This should result in a callback to handleMovedOrResized().
  48308. */
  48309. virtual void setSize (int w, int h) = 0;
  48310. /** Moves and resizes the window.
  48311. If the native window is contained in another window, then the co-ordinates are
  48312. relative to the parent window's origin, not the screen origin.
  48313. This should result in a callback to handleMovedOrResized().
  48314. */
  48315. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  48316. /** Returns the current position and size of the window.
  48317. If the native window is contained in another window, then the co-ordinates are
  48318. relative to the parent window's origin, not the screen origin.
  48319. */
  48320. virtual const Rectangle<int> getBounds() const = 0;
  48321. /** Returns the x-position of this window, relative to the screen's origin. */
  48322. virtual const Point<int> getScreenPosition() const = 0;
  48323. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  48324. virtual const Point<int> localToGlobal (const Point<int>& relativePosition) = 0;
  48325. /** Converts a rectangle relative to the top-left of this component to screen co-ordinates. */
  48326. virtual const Rectangle<int> localToGlobal (const Rectangle<int>& relativePosition);
  48327. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  48328. virtual const Point<int> globalToLocal (const Point<int>& screenPosition) = 0;
  48329. /** Converts a screen area to a position relative to the top-left of this component. */
  48330. virtual const Rectangle<int> globalToLocal (const Rectangle<int>& screenPosition);
  48331. /** Minimises the window. */
  48332. virtual void setMinimised (bool shouldBeMinimised) = 0;
  48333. /** True if the window is currently minimised. */
  48334. virtual bool isMinimised() const = 0;
  48335. /** Enable/disable fullscreen mode for the window. */
  48336. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  48337. /** True if the window is currently full-screen. */
  48338. virtual bool isFullScreen() const = 0;
  48339. /** Sets the size to restore to if fullscreen mode is turned off. */
  48340. void setNonFullScreenBounds (const Rectangle<int>& newBounds) throw();
  48341. /** Returns the size to restore to if fullscreen mode is turned off. */
  48342. const Rectangle<int>& getNonFullScreenBounds() const throw();
  48343. /** Attempts to change the icon associated with this window.
  48344. */
  48345. virtual void setIcon (const Image& newIcon) = 0;
  48346. /** Sets a constrainer to use if the peer can resize itself.
  48347. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  48348. */
  48349. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) throw();
  48350. /** Returns the current constrainer, if one has been set. */
  48351. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  48352. /** Checks if a point is in the window.
  48353. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  48354. is false, then this returns false if the point is actually inside a child of this
  48355. window.
  48356. */
  48357. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  48358. /** Returns the size of the window frame that's around this window.
  48359. Whether or not the window has a normal window frame depends on the flags
  48360. that were set when the window was created by Component::addToDesktop()
  48361. */
  48362. virtual const BorderSize<int> getFrameSize() const = 0;
  48363. /** This is called when the window's bounds change.
  48364. A peer implementation must call this when the window is moved and resized, so that
  48365. this method can pass the message on to the component.
  48366. */
  48367. void handleMovedOrResized();
  48368. /** This is called if the screen resolution changes.
  48369. A peer implementation must call this if the monitor arrangement changes or the available
  48370. screen size changes.
  48371. */
  48372. void handleScreenSizeChange();
  48373. /** This is called to repaint the component into the given context. */
  48374. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  48375. /** Sets this window to either be always-on-top or normal.
  48376. Some kinds of window might not be able to do this, so should return false.
  48377. */
  48378. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  48379. /** Brings the window to the top, optionally also giving it focus. */
  48380. virtual void toFront (bool makeActive) = 0;
  48381. /** Moves the window to be just behind another one. */
  48382. virtual void toBehind (ComponentPeer* other) = 0;
  48383. /** Called when the window is brought to the front, either by the OS or by a call
  48384. to toFront().
  48385. */
  48386. void handleBroughtToFront();
  48387. /** True if the window has the keyboard focus. */
  48388. virtual bool isFocused() const = 0;
  48389. /** Tries to give the window keyboard focus. */
  48390. virtual void grabFocus() = 0;
  48391. /** Tells the window that text input may be required at the given position.
  48392. This may cause things like a virtual on-screen keyboard to appear, depending
  48393. on the OS.
  48394. */
  48395. virtual void textInputRequired (const Point<int>& position) = 0;
  48396. /** Called when the window gains keyboard focus. */
  48397. void handleFocusGain();
  48398. /** Called when the window loses keyboard focus. */
  48399. void handleFocusLoss();
  48400. Component* getLastFocusedSubcomponent() const throw();
  48401. /** Called when a key is pressed.
  48402. For keycode info, see the KeyPress class.
  48403. Returns true if the keystroke was used.
  48404. */
  48405. bool handleKeyPress (int keyCode, juce_wchar textCharacter);
  48406. /** Called whenever a key is pressed or released.
  48407. Returns true if the keystroke was used.
  48408. */
  48409. bool handleKeyUpOrDown (bool isKeyDown);
  48410. /** Called whenever a modifier key is pressed or released. */
  48411. void handleModifierKeysChange();
  48412. /** Returns the currently focused TextInputTarget, or null if none is found. */
  48413. TextInputTarget* findCurrentTextInputTarget();
  48414. /** Invalidates a region of the window to be repainted asynchronously. */
  48415. virtual void repaint (const Rectangle<int>& area) = 0;
  48416. /** This can be called (from the message thread) to cause the immediate redrawing
  48417. of any areas of this window that need repainting.
  48418. You shouldn't ever really need to use this, it's mainly for special purposes
  48419. like supporting audio plugins where the host's event loop is out of our control.
  48420. */
  48421. virtual void performAnyPendingRepaintsNow() = 0;
  48422. /** Changes the window's transparency. */
  48423. virtual void setAlpha (float newAlpha) = 0;
  48424. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  48425. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  48426. void handleUserClosingWindow();
  48427. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  48428. void handleFileDragExit (const StringArray& files);
  48429. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  48430. /** Resets the masking region.
  48431. The subclass should call this every time it's about to call the handlePaint
  48432. method.
  48433. @see addMaskedRegion
  48434. */
  48435. void clearMaskedRegion();
  48436. /** Adds a rectangle to the set of areas not to paint over.
  48437. A component can call this on its peer during its paint() method, to signal
  48438. that the painting code should ignore a given region. The reason
  48439. for this is to stop embedded windows (such as OpenGL) getting painted over.
  48440. The masked region is cleared each time before a paint happens, so a component
  48441. will have to make sure it calls this every time it's painted.
  48442. */
  48443. void addMaskedRegion (int x, int y, int w, int h);
  48444. /** Returns the number of currently-active peers.
  48445. @see getPeer
  48446. */
  48447. static int getNumPeers() throw();
  48448. /** Returns one of the currently-active peers.
  48449. @see getNumPeers
  48450. */
  48451. static ComponentPeer* getPeer (int index) throw();
  48452. /** Checks if this peer object is valid.
  48453. @see getNumPeers
  48454. */
  48455. static bool isValidPeer (const ComponentPeer* peer) throw();
  48456. virtual const StringArray getAvailableRenderingEngines();
  48457. virtual int getCurrentRenderingEngine() throw();
  48458. virtual void setCurrentRenderingEngine (int index);
  48459. protected:
  48460. Component* const component;
  48461. const int styleFlags;
  48462. RectangleList maskedRegion;
  48463. Rectangle<int> lastNonFullscreenBounds;
  48464. uint32 lastPaintTime;
  48465. ComponentBoundsConstrainer* constrainer;
  48466. static void updateCurrentModifiers() throw();
  48467. private:
  48468. WeakReference<Component> lastFocusedComponent, dragAndDropTargetComponent;
  48469. Component* lastDragAndDropCompUnderMouse;
  48470. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  48471. friend class Component;
  48472. friend class Desktop;
  48473. static ComponentPeer* getPeerFor (const Component* component) throw();
  48474. void setLastDragDropTarget (Component* comp);
  48475. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentPeer);
  48476. };
  48477. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  48478. /*** End of inlined file: juce_ComponentPeer.h ***/
  48479. #endif
  48480. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  48481. /*** Start of inlined file: juce_DialogWindow.h ***/
  48482. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  48483. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  48484. /**
  48485. A dialog-box style window.
  48486. This class is a convenient way of creating a DocumentWindow with a close button
  48487. that can be triggered by pressing the escape key.
  48488. Any of the methods available to a DocumentWindow or ResizableWindow are also
  48489. available to this, so it can be made resizable, have a menu bar, etc.
  48490. To add items to the box, see the ResizableWindow::setContentOwned() or
  48491. ResizableWindow::setContentNonOwned() methods. Don't add components directly to this
  48492. class - always put them in a content component!
  48493. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  48494. the user clicking the close button - for more info, see the DocumentWindow
  48495. help.
  48496. @see DocumentWindow, ResizableWindow
  48497. */
  48498. class JUCE_API DialogWindow : public DocumentWindow
  48499. {
  48500. public:
  48501. /** Creates a DialogWindow.
  48502. @param name the name to give the component - this is also
  48503. the title shown at the top of the window. To change
  48504. this later, use setName()
  48505. @param backgroundColour the colour to use for filling the window's background.
  48506. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  48507. close button to be triggered
  48508. @param addToDesktop if true, the window will be automatically added to the
  48509. desktop; if false, you can use it as a child component
  48510. */
  48511. DialogWindow (const String& name,
  48512. const Colour& backgroundColour,
  48513. bool escapeKeyTriggersCloseButton,
  48514. bool addToDesktop = true);
  48515. /** Destructor.
  48516. If a content component has been set with setContentOwned(), it will be deleted.
  48517. */
  48518. ~DialogWindow();
  48519. /** Easy way of quickly showing a dialog box containing a given component.
  48520. This will open and display a DialogWindow containing a given component, making it
  48521. modal, but returning immediately to allow the dialog to finish in its own time. If
  48522. you want to block and run a modal loop until the dialog is dismissed, use showModalDialog()
  48523. instead.
  48524. To close the dialog programatically, you should call exitModalState (returnValue) on
  48525. the DialogWindow that is created. To find a pointer to this window from your
  48526. contentComponent, you can do something like this:
  48527. @code
  48528. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  48529. if (dw != 0)
  48530. dw->exitModalState (1234);
  48531. @endcode
  48532. @param dialogTitle the dialog box's title
  48533. @param contentComponent the content component for the dialog box. Make sure
  48534. that this has been set to the size you want it to
  48535. be before calling this method. The component won't
  48536. be deleted by this call, so you can re-use it or delete
  48537. it afterwards
  48538. @param componentToCentreAround if this is non-zero, it indicates a component that
  48539. you'd like to show this dialog box in front of. See the
  48540. DocumentWindow::centreAroundComponent() method for more
  48541. info on this parameter
  48542. @param backgroundColour a colour to use for the dialog box's background colour
  48543. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  48544. close button to be triggered
  48545. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  48546. a corner resizer
  48547. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  48548. to use a border or corner resizer component. See ResizableWindow::setResizable()
  48549. */
  48550. static void showDialog (const String& dialogTitle,
  48551. Component* contentComponent,
  48552. Component* componentToCentreAround,
  48553. const Colour& backgroundColour,
  48554. bool escapeKeyTriggersCloseButton,
  48555. bool shouldBeResizable = false,
  48556. bool useBottomRightCornerResizer = false);
  48557. /** Easy way of quickly showing a dialog box containing a given component.
  48558. This will open and display a DialogWindow containing a given component, returning
  48559. when the user clicks its close button.
  48560. It returns the value that was returned by the dialog box's runModalLoop() call.
  48561. To close the dialog programatically, you should call exitModalState (returnValue) on
  48562. the DialogWindow that is created. To find a pointer to this window from your
  48563. contentComponent, you can do something like this:
  48564. @code
  48565. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  48566. if (dw != 0)
  48567. dw->exitModalState (1234);
  48568. @endcode
  48569. @param dialogTitle the dialog box's title
  48570. @param contentComponent the content component for the dialog box. Make sure
  48571. that this has been set to the size you want it to
  48572. be before calling this method. The component won't
  48573. be deleted by this call, so you can re-use it or delete
  48574. it afterwards
  48575. @param componentToCentreAround if this is non-zero, it indicates a component that
  48576. you'd like to show this dialog box in front of. See the
  48577. DocumentWindow::centreAroundComponent() method for more
  48578. info on this parameter
  48579. @param backgroundColour a colour to use for the dialog box's background colour
  48580. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  48581. close button to be triggered
  48582. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  48583. a corner resizer
  48584. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  48585. to use a border or corner resizer component. See ResizableWindow::setResizable()
  48586. */
  48587. #if JUCE_MODAL_LOOPS_PERMITTED
  48588. static int showModalDialog (const String& dialogTitle,
  48589. Component* contentComponent,
  48590. Component* componentToCentreAround,
  48591. const Colour& backgroundColour,
  48592. bool escapeKeyTriggersCloseButton,
  48593. bool shouldBeResizable = false,
  48594. bool useBottomRightCornerResizer = false);
  48595. #endif
  48596. protected:
  48597. /** @internal */
  48598. void resized();
  48599. private:
  48600. bool escapeKeyTriggersCloseButton;
  48601. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DialogWindow);
  48602. };
  48603. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  48604. /*** End of inlined file: juce_DialogWindow.h ***/
  48605. #endif
  48606. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  48607. #endif
  48608. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  48609. #endif
  48610. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  48611. /*** Start of inlined file: juce_SplashScreen.h ***/
  48612. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  48613. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  48614. /** A component for showing a splash screen while your app starts up.
  48615. This will automatically position itself, and delete itself when the app has
  48616. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  48617. this).
  48618. To use it, just create one of these in your JUCEApplication::initialise() method,
  48619. call its show() method and let the object delete itself later.
  48620. E.g. @code
  48621. void MyApp::initialise (const String& commandLine)
  48622. {
  48623. SplashScreen* splash = new SplashScreen();
  48624. splash->show ("welcome to my app",
  48625. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  48626. 4000, false);
  48627. .. no need to delete the splash screen - it'll do that itself.
  48628. }
  48629. @endcode
  48630. */
  48631. class JUCE_API SplashScreen : public Component,
  48632. public Timer,
  48633. private DeletedAtShutdown
  48634. {
  48635. public:
  48636. /** Creates a SplashScreen object.
  48637. After creating one of these (or your subclass of it), call one of the show()
  48638. methods to display it.
  48639. */
  48640. SplashScreen();
  48641. /** Destructor. */
  48642. ~SplashScreen();
  48643. /** Creates a SplashScreen object that will display an image.
  48644. As soon as this is called, the SplashScreen will be displayed in the centre of the
  48645. screen. This method will also dispatch any pending messages to make sure that when
  48646. it returns, the splash screen has been completely drawn, and your initialisation
  48647. code can carry on.
  48648. @param title the name to give the component
  48649. @param backgroundImage an image to draw on the component. The component's size
  48650. will be set to the size of this image, and if the image is
  48651. semi-transparent, the component will be made semi-transparent
  48652. too. This image will be deleted (or released from the ImageCache
  48653. if that's how it was created) by the splash screen object when
  48654. it is itself deleted.
  48655. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  48656. should stay visible for. If the initialisation takes longer than
  48657. this time, the splash screen will wait for it to finish before
  48658. disappearing, but if initialisation is very quick, this lets
  48659. you make sure that people get a good look at your splash.
  48660. @param useDropShadow if true, the window will have a drop shadow
  48661. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  48662. the mouse (anywhere)
  48663. */
  48664. void show (const String& title,
  48665. const Image& backgroundImage,
  48666. int minimumTimeToDisplayFor,
  48667. bool useDropShadow,
  48668. bool removeOnMouseClick = true);
  48669. /** Creates a SplashScreen object with a specified size.
  48670. For a custom splash screen, you can use this method to display it at a certain size
  48671. and then override the paint() method yourself to do whatever's necessary.
  48672. As soon as this is called, the SplashScreen will be displayed in the centre of the
  48673. screen. This method will also dispatch any pending messages to make sure that when
  48674. it returns, the splash screen has been completely drawn, and your initialisation
  48675. code can carry on.
  48676. @param title the name to give the component
  48677. @param width the width to use
  48678. @param height the height to use
  48679. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  48680. should stay visible for. If the initialisation takes longer than
  48681. this time, the splash screen will wait for it to finish before
  48682. disappearing, but if initialisation is very quick, this lets
  48683. you make sure that people get a good look at your splash.
  48684. @param useDropShadow if true, the window will have a drop shadow
  48685. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  48686. the mouse (anywhere)
  48687. */
  48688. void show (const String& title,
  48689. int width,
  48690. int height,
  48691. int minimumTimeToDisplayFor,
  48692. bool useDropShadow,
  48693. bool removeOnMouseClick = true);
  48694. /** @internal */
  48695. void paint (Graphics& g);
  48696. /** @internal */
  48697. void timerCallback();
  48698. private:
  48699. Image backgroundImage;
  48700. Time earliestTimeToDelete;
  48701. int originalClickCounter;
  48702. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SplashScreen);
  48703. };
  48704. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  48705. /*** End of inlined file: juce_SplashScreen.h ***/
  48706. #endif
  48707. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  48708. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  48709. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  48710. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  48711. /**
  48712. A thread that automatically pops up a modal dialog box with a progress bar
  48713. and cancel button while it's busy running.
  48714. These are handy for performing some sort of task while giving the user feedback
  48715. about how long there is to go, etc.
  48716. E.g. @code
  48717. class MyTask : public ThreadWithProgressWindow
  48718. {
  48719. public:
  48720. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  48721. {
  48722. }
  48723. ~MyTask()
  48724. {
  48725. }
  48726. void run()
  48727. {
  48728. for (int i = 0; i < thingsToDo; ++i)
  48729. {
  48730. // must check this as often as possible, because this is
  48731. // how we know if the user's pressed 'cancel'
  48732. if (threadShouldExit())
  48733. break;
  48734. // this will update the progress bar on the dialog box
  48735. setProgress (i / (double) thingsToDo);
  48736. // ... do the business here...
  48737. }
  48738. }
  48739. };
  48740. void doTheTask()
  48741. {
  48742. MyTask m;
  48743. if (m.runThread())
  48744. {
  48745. // thread finished normally..
  48746. }
  48747. else
  48748. {
  48749. // user pressed the cancel button..
  48750. }
  48751. }
  48752. @endcode
  48753. @see Thread, AlertWindow
  48754. */
  48755. class JUCE_API ThreadWithProgressWindow : public Thread,
  48756. private Timer
  48757. {
  48758. public:
  48759. /** Creates the thread.
  48760. Initially, the dialog box won't be visible, it'll only appear when the
  48761. runThread() method is called.
  48762. @param windowTitle the title to go at the top of the dialog box
  48763. @param hasProgressBar whether the dialog box should have a progress bar (see
  48764. setProgress() )
  48765. @param hasCancelButton whether the dialog box should have a cancel button
  48766. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  48767. the thread to stop before killing it forcibly (see
  48768. Thread::stopThread() )
  48769. @param cancelButtonText the text that should be shown in the cancel button
  48770. (if it has one)
  48771. */
  48772. ThreadWithProgressWindow (const String& windowTitle,
  48773. bool hasProgressBar,
  48774. bool hasCancelButton,
  48775. int timeOutMsWhenCancelling = 10000,
  48776. const String& cancelButtonText = "Cancel");
  48777. /** Destructor. */
  48778. ~ThreadWithProgressWindow();
  48779. /** Starts the thread and waits for it to finish.
  48780. This will start the thread, make the dialog box appear, and wait until either
  48781. the thread finishes normally, or until the cancel button is pressed.
  48782. Before returning, the dialog box will be hidden.
  48783. @param threadPriority the priority to use when starting the thread - see
  48784. Thread::startThread() for values
  48785. @returns true if the thread finished normally; false if the user pressed cancel
  48786. */
  48787. bool runThread (int threadPriority = 5);
  48788. /** The thread should call this periodically to update the position of the progress bar.
  48789. @param newProgress the progress, from 0.0 to 1.0
  48790. @see setStatusMessage
  48791. */
  48792. void setProgress (double newProgress);
  48793. /** The thread can call this to change the message that's displayed in the dialog box.
  48794. */
  48795. void setStatusMessage (const String& newStatusMessage);
  48796. /** Returns the AlertWindow that is being used.
  48797. */
  48798. AlertWindow* getAlertWindow() const throw() { return alertWindow; }
  48799. private:
  48800. void timerCallback();
  48801. double progress;
  48802. ScopedPointer <AlertWindow> alertWindow;
  48803. String message;
  48804. CriticalSection messageLock;
  48805. const int timeOutMsWhenCancelling;
  48806. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadWithProgressWindow);
  48807. };
  48808. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  48809. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  48810. #endif
  48811. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  48812. #endif
  48813. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  48814. #endif
  48815. #ifndef __JUCE_COLOUR_JUCEHEADER__
  48816. #endif
  48817. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  48818. #endif
  48819. #ifndef __JUCE_COLOURS_JUCEHEADER__
  48820. #endif
  48821. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  48822. #endif
  48823. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  48824. /*** Start of inlined file: juce_EdgeTable.h ***/
  48825. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  48826. #define __JUCE_EDGETABLE_JUCEHEADER__
  48827. class Path;
  48828. class Image;
  48829. /**
  48830. A table of horizontal scan-line segments - used for rasterising Paths.
  48831. @see Path, Graphics
  48832. */
  48833. class JUCE_API EdgeTable
  48834. {
  48835. public:
  48836. /** Creates an edge table containing a path.
  48837. A table is created with a fixed vertical range, and only sections of the path
  48838. which lie within this range will be added to the table.
  48839. @param clipLimits only the region of the path that lies within this area will be added
  48840. @param pathToAdd the path to add to the table
  48841. @param transform a transform to apply to the path being added
  48842. */
  48843. EdgeTable (const Rectangle<int>& clipLimits,
  48844. const Path& pathToAdd,
  48845. const AffineTransform& transform);
  48846. /** Creates an edge table containing a rectangle. */
  48847. EdgeTable (const Rectangle<int>& rectangleToAdd);
  48848. /** Creates an edge table containing a rectangle list. */
  48849. EdgeTable (const RectangleList& rectanglesToAdd);
  48850. /** Creates an edge table containing a rectangle. */
  48851. EdgeTable (const Rectangle<float>& rectangleToAdd);
  48852. /** Creates a copy of another edge table. */
  48853. EdgeTable (const EdgeTable& other);
  48854. /** Copies from another edge table. */
  48855. EdgeTable& operator= (const EdgeTable& other);
  48856. /** Destructor. */
  48857. ~EdgeTable();
  48858. void clipToRectangle (const Rectangle<int>& r);
  48859. void excludeRectangle (const Rectangle<int>& r);
  48860. void clipToEdgeTable (const EdgeTable& other);
  48861. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels);
  48862. bool isEmpty() throw();
  48863. const Rectangle<int>& getMaximumBounds() const throw() { return bounds; }
  48864. void translate (float dx, int dy) throw();
  48865. /** Reduces the amount of space the table has allocated.
  48866. This will shrink the table down to use as little memory as possible - useful for
  48867. read-only tables that get stored and re-used for rendering.
  48868. */
  48869. void optimiseTable();
  48870. /** Iterates the lines in the table, for rendering.
  48871. This function will iterate each line in the table, and call a user-defined class
  48872. to render each pixel or continuous line of pixels that the table contains.
  48873. @param iterationCallback this templated class must contain the following methods:
  48874. @code
  48875. inline void setEdgeTableYPos (int y);
  48876. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  48877. inline void handleEdgeTablePixelFull (int x) const;
  48878. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  48879. inline void handleEdgeTableLineFull (int x, int width) const;
  48880. @endcode
  48881. (these don't necessarily have to be 'const', but it might help it go faster)
  48882. */
  48883. template <class EdgeTableIterationCallback>
  48884. void iterate (EdgeTableIterationCallback& iterationCallback) const throw()
  48885. {
  48886. const int* lineStart = table;
  48887. for (int y = 0; y < bounds.getHeight(); ++y)
  48888. {
  48889. const int* line = lineStart;
  48890. lineStart += lineStrideElements;
  48891. int numPoints = line[0];
  48892. if (--numPoints > 0)
  48893. {
  48894. int x = *++line;
  48895. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  48896. int levelAccumulator = 0;
  48897. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  48898. while (--numPoints >= 0)
  48899. {
  48900. const int level = *++line;
  48901. jassert (isPositiveAndBelow (level, (int) 256));
  48902. const int endX = *++line;
  48903. jassert (endX >= x);
  48904. const int endOfRun = (endX >> 8);
  48905. if (endOfRun == (x >> 8))
  48906. {
  48907. // small segment within the same pixel, so just save it for the next
  48908. // time round..
  48909. levelAccumulator += (endX - x) * level;
  48910. }
  48911. else
  48912. {
  48913. // plot the fist pixel of this segment, including any accumulated
  48914. // levels from smaller segments that haven't been drawn yet
  48915. levelAccumulator += (0x100 - (x & 0xff)) * level;
  48916. levelAccumulator >>= 8;
  48917. x >>= 8;
  48918. if (levelAccumulator > 0)
  48919. {
  48920. if (levelAccumulator >= 255)
  48921. iterationCallback.handleEdgeTablePixelFull (x);
  48922. else
  48923. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  48924. }
  48925. // if there's a run of similar pixels, do it all in one go..
  48926. if (level > 0)
  48927. {
  48928. jassert (endOfRun <= bounds.getRight());
  48929. const int numPix = endOfRun - ++x;
  48930. if (numPix > 0)
  48931. iterationCallback.handleEdgeTableLine (x, numPix, level);
  48932. }
  48933. // save the bit at the end to be drawn next time round the loop.
  48934. levelAccumulator = (endX & 0xff) * level;
  48935. }
  48936. x = endX;
  48937. }
  48938. levelAccumulator >>= 8;
  48939. if (levelAccumulator > 0)
  48940. {
  48941. x >>= 8;
  48942. jassert (x >= bounds.getX() && x < bounds.getRight());
  48943. if (levelAccumulator >= 255)
  48944. iterationCallback.handleEdgeTablePixelFull (x);
  48945. else
  48946. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  48947. }
  48948. }
  48949. }
  48950. }
  48951. private:
  48952. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  48953. HeapBlock<int> table;
  48954. Rectangle<int> bounds;
  48955. int maxEdgesPerLine, lineStrideElements;
  48956. bool needToCheckEmptinesss;
  48957. void addEdgePoint (int x, int y, int winding);
  48958. void remapTableForNumEdges (int newNumEdgesPerLine);
  48959. void intersectWithEdgeTableLine (int y, const int* otherLine);
  48960. void clipEdgeTableLineToRange (int* line, int x1, int x2) throw();
  48961. void sanitiseLevels (bool useNonZeroWinding) throw();
  48962. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) throw();
  48963. JUCE_LEAK_DETECTOR (EdgeTable);
  48964. };
  48965. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  48966. /*** End of inlined file: juce_EdgeTable.h ***/
  48967. #endif
  48968. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  48969. /*** Start of inlined file: juce_FillType.h ***/
  48970. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  48971. #define __JUCE_FILLTYPE_JUCEHEADER__
  48972. /**
  48973. Represents a colour or fill pattern to use for rendering paths.
  48974. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  48975. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  48976. @see Graphics::setFillType, DrawablePath::setFill
  48977. */
  48978. class JUCE_API FillType
  48979. {
  48980. public:
  48981. /** Creates a default fill type, of solid black. */
  48982. FillType() throw();
  48983. /** Creates a fill type of a solid colour.
  48984. @see setColour
  48985. */
  48986. FillType (const Colour& colour) throw();
  48987. /** Creates a gradient fill type.
  48988. @see setGradient
  48989. */
  48990. FillType (const ColourGradient& gradient);
  48991. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  48992. and rotation of the pattern.
  48993. @see setTiledImage
  48994. */
  48995. FillType (const Image& image, const AffineTransform& transform) throw();
  48996. /** Creates a copy of another FillType. */
  48997. FillType (const FillType& other);
  48998. /** Makes a copy of another FillType. */
  48999. FillType& operator= (const FillType& other);
  49000. /** Destructor. */
  49001. ~FillType() throw();
  49002. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  49003. bool isColour() const throw() { return gradient == 0 && image.isNull(); }
  49004. /** Returns true if this is a gradient fill. */
  49005. bool isGradient() const throw() { return gradient != 0; }
  49006. /** Returns true if this is a tiled image pattern fill. */
  49007. bool isTiledImage() const throw() { return image.isValid(); }
  49008. /** Turns this object into a solid colour fill.
  49009. If the object was an image or gradient, those fields will no longer be valid. */
  49010. void setColour (const Colour& newColour) throw();
  49011. /** Turns this object into a gradient fill. */
  49012. void setGradient (const ColourGradient& newGradient);
  49013. /** Turns this object into a tiled image fill type. The transform allows you to set
  49014. the scaling, offset and rotation of the pattern.
  49015. */
  49016. void setTiledImage (const Image& image, const AffineTransform& transform) throw();
  49017. /** Changes the opacity that should be used.
  49018. If the fill is a solid colour, this just changes the opacity of that colour. For
  49019. gradients and image tiles, it changes the opacity that will be used for them.
  49020. */
  49021. void setOpacity (float newOpacity) throw();
  49022. /** Returns the current opacity to be applied to the colour, gradient, or image.
  49023. @see setOpacity
  49024. */
  49025. float getOpacity() const throw() { return colour.getFloatAlpha(); }
  49026. /** Returns true if this fill type is completely transparent. */
  49027. bool isInvisible() const throw();
  49028. /** The solid colour being used.
  49029. If the fill type is not a solid colour, the alpha channel of this colour indicates
  49030. the opacity that should be used for the fill, and the RGB channels are ignored.
  49031. */
  49032. Colour colour;
  49033. /** Returns the gradient that should be used for filling.
  49034. This will be zero if the object is some other type of fill.
  49035. If a gradient is active, the overall opacity with which it should be applied
  49036. is indicated by the alpha channel of the colour variable.
  49037. */
  49038. ScopedPointer <ColourGradient> gradient;
  49039. /** The image that should be used for tiling.
  49040. If an image fill is active, the overall opacity with which it should be applied
  49041. is indicated by the alpha channel of the colour variable.
  49042. */
  49043. Image image;
  49044. /** The transform that should be applied to the image or gradient that's being drawn. */
  49045. AffineTransform transform;
  49046. bool operator== (const FillType& other) const;
  49047. bool operator!= (const FillType& other) const;
  49048. private:
  49049. JUCE_LEAK_DETECTOR (FillType);
  49050. };
  49051. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  49052. /*** End of inlined file: juce_FillType.h ***/
  49053. #endif
  49054. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  49055. #endif
  49056. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  49057. #endif
  49058. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49059. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  49060. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49061. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49062. /**
  49063. Interface class for graphics context objects, used internally by the Graphics class.
  49064. Users are not supposed to create instances of this class directly - do your drawing
  49065. via the Graphics object instead.
  49066. It's a base class for different types of graphics context, that may perform software-based
  49067. or OS-accelerated rendering.
  49068. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  49069. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  49070. context.
  49071. */
  49072. class JUCE_API LowLevelGraphicsContext
  49073. {
  49074. protected:
  49075. LowLevelGraphicsContext();
  49076. public:
  49077. virtual ~LowLevelGraphicsContext();
  49078. /** Returns true if this device is vector-based, e.g. a printer. */
  49079. virtual bool isVectorDevice() const = 0;
  49080. /** Moves the origin to a new position.
  49081. The co-ords are relative to the current origin, and indicate the new position
  49082. of (0, 0).
  49083. */
  49084. virtual void setOrigin (int x, int y) = 0;
  49085. virtual void addTransform (const AffineTransform& transform) = 0;
  49086. virtual float getScaleFactor() = 0;
  49087. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  49088. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  49089. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  49090. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  49091. virtual void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform) = 0;
  49092. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  49093. virtual const Rectangle<int> getClipBounds() const = 0;
  49094. virtual bool isClipEmpty() const = 0;
  49095. virtual void saveState() = 0;
  49096. virtual void restoreState() = 0;
  49097. virtual void beginTransparencyLayer (float opacity) = 0;
  49098. virtual void endTransparencyLayer() = 0;
  49099. virtual void setFill (const FillType& fillType) = 0;
  49100. virtual void setOpacity (float newOpacity) = 0;
  49101. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  49102. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  49103. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  49104. virtual void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  49105. virtual void drawLine (const Line <float>& line) = 0;
  49106. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  49107. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  49108. virtual void setFont (const Font& newFont) = 0;
  49109. virtual const Font getFont() = 0;
  49110. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  49111. };
  49112. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  49113. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  49114. #endif
  49115. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  49116. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  49117. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  49118. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  49119. /**
  49120. An implementation of LowLevelGraphicsContext that turns the drawing operations
  49121. into a PostScript document.
  49122. */
  49123. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  49124. {
  49125. public:
  49126. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  49127. const String& documentTitle,
  49128. int totalWidth,
  49129. int totalHeight);
  49130. ~LowLevelGraphicsPostScriptRenderer();
  49131. bool isVectorDevice() const;
  49132. void setOrigin (int x, int y);
  49133. void addTransform (const AffineTransform& transform);
  49134. float getScaleFactor();
  49135. bool clipToRectangle (const Rectangle<int>& r);
  49136. bool clipToRectangleList (const RectangleList& clipRegion);
  49137. void excludeClipRectangle (const Rectangle<int>& r);
  49138. void clipToPath (const Path& path, const AffineTransform& transform);
  49139. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  49140. void saveState();
  49141. void restoreState();
  49142. void beginTransparencyLayer (float opacity);
  49143. void endTransparencyLayer();
  49144. bool clipRegionIntersects (const Rectangle<int>& r);
  49145. const Rectangle<int> getClipBounds() const;
  49146. bool isClipEmpty() const;
  49147. void setFill (const FillType& fillType);
  49148. void setOpacity (float opacity);
  49149. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  49150. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  49151. void fillPath (const Path& path, const AffineTransform& transform);
  49152. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  49153. void drawLine (const Line <float>& line);
  49154. void drawVerticalLine (int x, float top, float bottom);
  49155. void drawHorizontalLine (int x, float top, float bottom);
  49156. const Font getFont();
  49157. void setFont (const Font& newFont);
  49158. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  49159. protected:
  49160. OutputStream& out;
  49161. int totalWidth, totalHeight;
  49162. bool needToClip;
  49163. Colour lastColour;
  49164. struct SavedState
  49165. {
  49166. SavedState();
  49167. ~SavedState();
  49168. RectangleList clip;
  49169. int xOffset, yOffset;
  49170. FillType fillType;
  49171. Font font;
  49172. private:
  49173. SavedState& operator= (const SavedState&);
  49174. };
  49175. OwnedArray <SavedState> stateStack;
  49176. void writeClip();
  49177. void writeColour (const Colour& colour);
  49178. void writePath (const Path& path) const;
  49179. void writeXY (float x, float y) const;
  49180. void writeTransform (const AffineTransform& trans) const;
  49181. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  49182. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsPostScriptRenderer);
  49183. };
  49184. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  49185. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  49186. #endif
  49187. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  49188. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  49189. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  49190. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  49191. /**
  49192. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  49193. its rendering in memory.
  49194. User code is not supposed to create instances of this class directly - do all your
  49195. rendering via the Graphics class instead.
  49196. */
  49197. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  49198. {
  49199. public:
  49200. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn);
  49201. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  49202. ~LowLevelGraphicsSoftwareRenderer();
  49203. bool isVectorDevice() const;
  49204. void setOrigin (int x, int y);
  49205. void addTransform (const AffineTransform& transform);
  49206. float getScaleFactor();
  49207. bool clipToRectangle (const Rectangle<int>& r);
  49208. bool clipToRectangleList (const RectangleList& clipRegion);
  49209. void excludeClipRectangle (const Rectangle<int>& r);
  49210. void clipToPath (const Path& path, const AffineTransform& transform);
  49211. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  49212. bool clipRegionIntersects (const Rectangle<int>& r);
  49213. const Rectangle<int> getClipBounds() const;
  49214. bool isClipEmpty() const;
  49215. void saveState();
  49216. void restoreState();
  49217. void beginTransparencyLayer (float opacity);
  49218. void endTransparencyLayer();
  49219. void setFill (const FillType& fillType);
  49220. void setOpacity (float opacity);
  49221. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  49222. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  49223. void fillPath (const Path& path, const AffineTransform& transform);
  49224. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  49225. void drawLine (const Line <float>& line);
  49226. void drawVerticalLine (int x, float top, float bottom);
  49227. void drawHorizontalLine (int x, float top, float bottom);
  49228. void setFont (const Font& newFont);
  49229. const Font getFont();
  49230. void drawGlyph (int glyphNumber, float x, float y);
  49231. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  49232. protected:
  49233. Image image;
  49234. class GlyphCache;
  49235. class CachedGlyph;
  49236. class SavedState;
  49237. friend class ScopedPointer <SavedState>;
  49238. friend class OwnedArray <SavedState>;
  49239. friend class OwnedArray <CachedGlyph>;
  49240. ScopedPointer <SavedState> currentState;
  49241. OwnedArray <SavedState> stateStack;
  49242. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsSoftwareRenderer);
  49243. };
  49244. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  49245. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  49246. #endif
  49247. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  49248. #endif
  49249. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  49250. #endif
  49251. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  49252. /*** Start of inlined file: juce_DrawableComposite.h ***/
  49253. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  49254. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  49255. /**
  49256. A drawable object which acts as a container for a set of other Drawables.
  49257. @see Drawable
  49258. */
  49259. class JUCE_API DrawableComposite : public Drawable
  49260. {
  49261. public:
  49262. /** Creates a composite Drawable. */
  49263. DrawableComposite();
  49264. /** Creates a copy of a DrawableComposite. */
  49265. DrawableComposite (const DrawableComposite& other);
  49266. /** Destructor. */
  49267. ~DrawableComposite();
  49268. /** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  49269. @see setContentArea
  49270. */
  49271. void setBoundingBox (const RelativeParallelogram& newBoundingBox);
  49272. /** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  49273. @see setBoundingBox
  49274. */
  49275. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  49276. /** Changes the bounding box transform to match the content area, so that any sub-items will
  49277. be drawn at their untransformed positions.
  49278. */
  49279. void resetBoundingBoxToContentArea();
  49280. /** Returns the main content rectangle.
  49281. The content area is actually defined by the markers named "left", "right", "top" and
  49282. "bottom", but this method is a shortcut that returns them all at once.
  49283. @see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  49284. */
  49285. const RelativeRectangle getContentArea() const;
  49286. /** Changes the main content area.
  49287. The content area is actually defined by the markers named "left", "right", "top" and
  49288. "bottom", but this method is a shortcut that sets them all at once.
  49289. @see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  49290. */
  49291. void setContentArea (const RelativeRectangle& newArea);
  49292. /** Resets the content area and the bounding transform to fit around the area occupied
  49293. by the child components (ignoring any markers).
  49294. */
  49295. void resetContentAreaAndBoundingBoxToFitChildren();
  49296. /** The name of the marker that defines the left edge of the content area. */
  49297. static const char* const contentLeftMarkerName;
  49298. /** The name of the marker that defines the right edge of the content area. */
  49299. static const char* const contentRightMarkerName;
  49300. /** The name of the marker that defines the top edge of the content area. */
  49301. static const char* const contentTopMarkerName;
  49302. /** The name of the marker that defines the bottom edge of the content area. */
  49303. static const char* const contentBottomMarkerName;
  49304. /** @internal */
  49305. Drawable* createCopy() const;
  49306. /** @internal */
  49307. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  49308. /** @internal */
  49309. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  49310. /** @internal */
  49311. static const Identifier valueTreeType;
  49312. /** @internal */
  49313. const Rectangle<float> getDrawableBounds() const;
  49314. /** @internal */
  49315. void childBoundsChanged (Component*);
  49316. /** @internal */
  49317. void childrenChanged();
  49318. /** @internal */
  49319. void parentHierarchyChanged();
  49320. /** @internal */
  49321. MarkerList* getMarkers (bool xAxis);
  49322. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  49323. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  49324. {
  49325. public:
  49326. ValueTreeWrapper (const ValueTree& state);
  49327. ValueTree getChildList() const;
  49328. ValueTree getChildListCreating (UndoManager* undoManager);
  49329. const RelativeParallelogram getBoundingBox() const;
  49330. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  49331. void resetBoundingBoxToContentArea (UndoManager* undoManager);
  49332. const RelativeRectangle getContentArea() const;
  49333. void setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager);
  49334. MarkerList::ValueTreeWrapper getMarkerList (bool xAxis) const;
  49335. MarkerList::ValueTreeWrapper getMarkerListCreating (bool xAxis, UndoManager* undoManager);
  49336. static const Identifier topLeft, topRight, bottomLeft;
  49337. private:
  49338. static const Identifier childGroupTag, markerGroupTagX, markerGroupTagY;
  49339. };
  49340. private:
  49341. RelativeParallelogram bounds;
  49342. MarkerList markersX, markersY;
  49343. bool updateBoundsReentrant;
  49344. friend class Drawable::Positioner<DrawableComposite>;
  49345. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  49346. void recalculateCoordinates (Expression::Scope*);
  49347. void updateBoundsToFitChildren();
  49348. DrawableComposite& operator= (const DrawableComposite&);
  49349. JUCE_LEAK_DETECTOR (DrawableComposite);
  49350. };
  49351. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  49352. /*** End of inlined file: juce_DrawableComposite.h ***/
  49353. #endif
  49354. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  49355. /*** Start of inlined file: juce_DrawableImage.h ***/
  49356. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  49357. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  49358. /**
  49359. A drawable object which is a bitmap image.
  49360. @see Drawable
  49361. */
  49362. class JUCE_API DrawableImage : public Drawable
  49363. {
  49364. public:
  49365. DrawableImage();
  49366. DrawableImage (const DrawableImage& other);
  49367. /** Destructor. */
  49368. ~DrawableImage();
  49369. /** Sets the image that this drawable will render. */
  49370. void setImage (const Image& imageToUse);
  49371. /** Returns the current image. */
  49372. const Image getImage() const { return image; }
  49373. /** Sets the opacity to use when drawing the image. */
  49374. void setOpacity (float newOpacity);
  49375. /** Returns the image's opacity. */
  49376. float getOpacity() const throw() { return opacity; }
  49377. /** Sets a colour to draw over the image's alpha channel.
  49378. By default this is transparent so isn't drawn, but if you set a non-transparent
  49379. colour here, then it will be overlaid on the image, using the image's alpha
  49380. channel as a mask.
  49381. This is handy for doing things like darkening or lightening an image by overlaying
  49382. it with semi-transparent black or white.
  49383. */
  49384. void setOverlayColour (const Colour& newOverlayColour);
  49385. /** Returns the overlay colour. */
  49386. const Colour& getOverlayColour() const throw() { return overlayColour; }
  49387. /** Sets the bounding box within which the image should be displayed. */
  49388. void setBoundingBox (const RelativeParallelogram& newBounds);
  49389. /** Returns the position to which the image's top-left corner should be remapped in the target
  49390. coordinate space when rendering this object.
  49391. @see setTransform
  49392. */
  49393. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  49394. /** @internal */
  49395. void paint (Graphics& g);
  49396. /** @internal */
  49397. bool hitTest (int x, int y);
  49398. /** @internal */
  49399. Drawable* createCopy() const;
  49400. /** @internal */
  49401. const Rectangle<float> getDrawableBounds() const;
  49402. /** @internal */
  49403. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  49404. /** @internal */
  49405. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  49406. /** @internal */
  49407. static const Identifier valueTreeType;
  49408. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  49409. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  49410. {
  49411. public:
  49412. ValueTreeWrapper (const ValueTree& state);
  49413. const var getImageIdentifier() const;
  49414. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  49415. Value getImageIdentifierValue (UndoManager* undoManager);
  49416. float getOpacity() const;
  49417. void setOpacity (float newOpacity, UndoManager* undoManager);
  49418. Value getOpacityValue (UndoManager* undoManager);
  49419. const Colour getOverlayColour() const;
  49420. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  49421. Value getOverlayColourValue (UndoManager* undoManager);
  49422. const RelativeParallelogram getBoundingBox() const;
  49423. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  49424. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  49425. };
  49426. private:
  49427. Image image;
  49428. float opacity;
  49429. Colour overlayColour;
  49430. RelativeParallelogram bounds;
  49431. friend class Drawable::Positioner<DrawableImage>;
  49432. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  49433. void recalculateCoordinates (Expression::Scope*);
  49434. DrawableImage& operator= (const DrawableImage&);
  49435. JUCE_LEAK_DETECTOR (DrawableImage);
  49436. };
  49437. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  49438. /*** End of inlined file: juce_DrawableImage.h ***/
  49439. #endif
  49440. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  49441. /*** Start of inlined file: juce_DrawablePath.h ***/
  49442. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  49443. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  49444. /*** Start of inlined file: juce_DrawableShape.h ***/
  49445. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  49446. #define __JUCE_DRAWABLESHAPE_JUCEHEADER__
  49447. /**
  49448. A base class implementing common functionality for Drawable classes which
  49449. consist of some kind of filled and stroked outline.
  49450. @see DrawablePath, DrawableRectangle
  49451. */
  49452. class JUCE_API DrawableShape : public Drawable
  49453. {
  49454. protected:
  49455. DrawableShape();
  49456. DrawableShape (const DrawableShape&);
  49457. public:
  49458. /** Destructor. */
  49459. ~DrawableShape();
  49460. /** A FillType wrapper that allows the gradient coordinates to be implemented using RelativePoint.
  49461. */
  49462. class RelativeFillType
  49463. {
  49464. public:
  49465. RelativeFillType();
  49466. RelativeFillType (const FillType& fill);
  49467. RelativeFillType (const RelativeFillType&);
  49468. RelativeFillType& operator= (const RelativeFillType&);
  49469. bool operator== (const RelativeFillType&) const;
  49470. bool operator!= (const RelativeFillType&) const;
  49471. bool isDynamic() const;
  49472. bool recalculateCoords (Expression::Scope* scope);
  49473. void writeTo (ValueTree& v, ComponentBuilder::ImageProvider*, UndoManager*) const;
  49474. bool readFrom (const ValueTree& v, ComponentBuilder::ImageProvider*);
  49475. FillType fill;
  49476. RelativePoint gradientPoint1, gradientPoint2, gradientPoint3;
  49477. };
  49478. /** Sets a fill type for the path.
  49479. This colour is used to fill the path - if you don't want the path to be
  49480. filled (e.g. if you're just drawing an outline), set this to a transparent
  49481. colour.
  49482. @see setPath, setStrokeFill
  49483. */
  49484. void setFill (const FillType& newFill);
  49485. /** Sets a fill type for the path.
  49486. This colour is used to fill the path - if you don't want the path to be
  49487. filled (e.g. if you're just drawing an outline), set this to a transparent
  49488. colour.
  49489. @see setPath, setStrokeFill
  49490. */
  49491. void setFill (const RelativeFillType& newFill);
  49492. /** Returns the current fill type.
  49493. @see setFill
  49494. */
  49495. const RelativeFillType& getFill() const throw() { return mainFill; }
  49496. /** Sets the fill type with which the outline will be drawn.
  49497. @see setFill
  49498. */
  49499. void setStrokeFill (const FillType& newStrokeFill);
  49500. /** Sets the fill type with which the outline will be drawn.
  49501. @see setFill
  49502. */
  49503. void setStrokeFill (const RelativeFillType& newStrokeFill);
  49504. /** Returns the current stroke fill.
  49505. @see setStrokeFill
  49506. */
  49507. const RelativeFillType& getStrokeFill() const throw() { return strokeFill; }
  49508. /** Changes the properties of the outline that will be drawn around the path.
  49509. If the stroke has 0 thickness, no stroke will be drawn.
  49510. @see setStrokeThickness, setStrokeColour
  49511. */
  49512. void setStrokeType (const PathStrokeType& newStrokeType);
  49513. /** Changes the stroke thickness.
  49514. This is a shortcut for calling setStrokeType.
  49515. */
  49516. void setStrokeThickness (float newThickness);
  49517. /** Returns the current outline style. */
  49518. const PathStrokeType& getStrokeType() const throw() { return strokeType; }
  49519. /** @internal */
  49520. class FillAndStrokeState : public Drawable::ValueTreeWrapperBase
  49521. {
  49522. public:
  49523. FillAndStrokeState (const ValueTree& state);
  49524. ValueTree getFillState (const Identifier& fillOrStrokeType);
  49525. const RelativeFillType getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider*) const;
  49526. void setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  49527. ComponentBuilder::ImageProvider*, UndoManager*);
  49528. const PathStrokeType getStrokeType() const;
  49529. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager*);
  49530. static const Identifier type, colour, colours, fill, stroke, path, jointStyle, capStyle, strokeWidth,
  49531. gradientPoint1, gradientPoint2, gradientPoint3, radial, imageId, imageOpacity;
  49532. };
  49533. /** @internal */
  49534. const Rectangle<float> getDrawableBounds() const;
  49535. /** @internal */
  49536. void paint (Graphics& g);
  49537. /** @internal */
  49538. bool hitTest (int x, int y);
  49539. protected:
  49540. /** Called when the cached path should be updated. */
  49541. void pathChanged();
  49542. /** Called when the cached stroke should be updated. */
  49543. void strokeChanged();
  49544. /** True if there's a stroke with a non-zero thickness and non-transparent colour. */
  49545. bool isStrokeVisible() const throw();
  49546. /** Updates the details from a FillAndStrokeState object, returning true if something changed. */
  49547. void refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider*);
  49548. /** Writes the stroke and fill details to a FillAndStrokeState object. */
  49549. void writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider*, UndoManager*) const;
  49550. PathStrokeType strokeType;
  49551. Path path, strokePath;
  49552. private:
  49553. class RelativePositioner;
  49554. RelativeFillType mainFill, strokeFill;
  49555. ScopedPointer<RelativeCoordinatePositionerBase> mainFillPositioner, strokeFillPositioner;
  49556. void setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  49557. ScopedPointer<RelativeCoordinatePositionerBase>& positioner);
  49558. DrawableShape& operator= (const DrawableShape&);
  49559. };
  49560. #endif // __JUCE_DRAWABLESHAPE_JUCEHEADER__
  49561. /*** End of inlined file: juce_DrawableShape.h ***/
  49562. /**
  49563. A drawable object which renders a filled or outlined shape.
  49564. For details on how to change the fill and stroke, see the DrawableShape class.
  49565. @see Drawable, DrawableShape
  49566. */
  49567. class JUCE_API DrawablePath : public DrawableShape
  49568. {
  49569. public:
  49570. /** Creates a DrawablePath. */
  49571. DrawablePath();
  49572. DrawablePath (const DrawablePath& other);
  49573. /** Destructor. */
  49574. ~DrawablePath();
  49575. /** Changes the path that will be drawn.
  49576. @see setFillColour, setStrokeType
  49577. */
  49578. void setPath (const Path& newPath);
  49579. /** Sets the path using a RelativePointPath.
  49580. Calling this will set up a Component::Positioner to automatically update the path
  49581. if any of the points in the source path are dynamic.
  49582. */
  49583. void setPath (const RelativePointPath& newPath);
  49584. /** Returns the current path. */
  49585. const Path& getPath() const;
  49586. /** Returns the current path for the outline. */
  49587. const Path& getStrokePath() const;
  49588. /** @internal */
  49589. Drawable* createCopy() const;
  49590. /** @internal */
  49591. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  49592. /** @internal */
  49593. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  49594. /** @internal */
  49595. static const Identifier valueTreeType;
  49596. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  49597. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  49598. {
  49599. public:
  49600. ValueTreeWrapper (const ValueTree& state);
  49601. bool usesNonZeroWinding() const;
  49602. void setUsesNonZeroWinding (bool b, UndoManager* undoManager);
  49603. class Element
  49604. {
  49605. public:
  49606. explicit Element (const ValueTree& state);
  49607. ~Element();
  49608. const Identifier getType() const throw() { return state.getType(); }
  49609. int getNumControlPoints() const throw();
  49610. const RelativePoint getControlPoint (int index) const;
  49611. Value getControlPointValue (int index, UndoManager*) const;
  49612. const RelativePoint getStartPoint() const;
  49613. const RelativePoint getEndPoint() const;
  49614. void setControlPoint (int index, const RelativePoint& point, UndoManager*);
  49615. float getLength (Expression::Scope*) const;
  49616. ValueTreeWrapper getParent() const;
  49617. Element getPreviousElement() const;
  49618. const String getModeOfEndPoint() const;
  49619. void setModeOfEndPoint (const String& newMode, UndoManager*);
  49620. void convertToLine (UndoManager*);
  49621. void convertToCubic (Expression::Scope*, UndoManager*);
  49622. void convertToPathBreak (UndoManager* undoManager);
  49623. ValueTree insertPoint (const Point<float>& targetPoint, Expression::Scope*, UndoManager*);
  49624. void removePoint (UndoManager* undoManager);
  49625. float findProportionAlongLine (const Point<float>& targetPoint, Expression::Scope*) const;
  49626. static const Identifier mode, startSubPathElement, closeSubPathElement,
  49627. lineToElement, quadraticToElement, cubicToElement;
  49628. static const char* cornerMode;
  49629. static const char* roundedMode;
  49630. static const char* symmetricMode;
  49631. ValueTree state;
  49632. };
  49633. ValueTree getPathState();
  49634. void readFrom (const RelativePointPath& path, UndoManager* undoManager);
  49635. void writeTo (RelativePointPath& path) const;
  49636. static const Identifier nonZeroWinding, point1, point2, point3;
  49637. };
  49638. private:
  49639. ScopedPointer<RelativePointPath> relativePath;
  49640. class RelativePositioner;
  49641. friend class RelativePositioner;
  49642. void applyRelativePath (const RelativePointPath&, Expression::Scope*);
  49643. DrawablePath& operator= (const DrawablePath&);
  49644. JUCE_LEAK_DETECTOR (DrawablePath);
  49645. };
  49646. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  49647. /*** End of inlined file: juce_DrawablePath.h ***/
  49648. #endif
  49649. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  49650. /*** Start of inlined file: juce_DrawableRectangle.h ***/
  49651. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  49652. #define __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  49653. /**
  49654. A Drawable object which draws a rectangle.
  49655. For details on how to change the fill and stroke, see the DrawableShape class.
  49656. @see Drawable, DrawableShape
  49657. */
  49658. class JUCE_API DrawableRectangle : public DrawableShape
  49659. {
  49660. public:
  49661. DrawableRectangle();
  49662. DrawableRectangle (const DrawableRectangle& other);
  49663. /** Destructor. */
  49664. ~DrawableRectangle();
  49665. /** Sets the rectangle's bounds. */
  49666. void setRectangle (const RelativeParallelogram& newBounds);
  49667. /** Returns the rectangle's bounds. */
  49668. const RelativeParallelogram& getRectangle() const throw() { return bounds; }
  49669. /** Returns the corner size to be used. */
  49670. const RelativePoint getCornerSize() const { return cornerSize; }
  49671. /** Sets a new corner size for the rectangle */
  49672. void setCornerSize (const RelativePoint& newSize);
  49673. /** @internal */
  49674. Drawable* createCopy() const;
  49675. /** @internal */
  49676. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  49677. /** @internal */
  49678. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  49679. /** @internal */
  49680. static const Identifier valueTreeType;
  49681. /** Internally-used class for wrapping a DrawableRectangle's state into a ValueTree. */
  49682. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  49683. {
  49684. public:
  49685. ValueTreeWrapper (const ValueTree& state);
  49686. const RelativeParallelogram getRectangle() const;
  49687. void setRectangle (const RelativeParallelogram& newBounds, UndoManager*);
  49688. void setCornerSize (const RelativePoint& cornerSize, UndoManager*);
  49689. const RelativePoint getCornerSize() const;
  49690. Value getCornerSizeValue (UndoManager*) const;
  49691. static const Identifier topLeft, topRight, bottomLeft, cornerSize;
  49692. };
  49693. private:
  49694. friend class Drawable::Positioner<DrawableRectangle>;
  49695. RelativeParallelogram bounds;
  49696. RelativePoint cornerSize;
  49697. void rebuildPath();
  49698. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  49699. void recalculateCoordinates (Expression::Scope*);
  49700. DrawableRectangle& operator= (const DrawableRectangle&);
  49701. JUCE_LEAK_DETECTOR (DrawableRectangle);
  49702. };
  49703. #endif // __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  49704. /*** End of inlined file: juce_DrawableRectangle.h ***/
  49705. #endif
  49706. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  49707. #endif
  49708. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  49709. /*** Start of inlined file: juce_DrawableText.h ***/
  49710. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  49711. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  49712. /**
  49713. A drawable object which renders a line of text.
  49714. @see Drawable
  49715. */
  49716. class JUCE_API DrawableText : public Drawable
  49717. {
  49718. public:
  49719. /** Creates a DrawableText object. */
  49720. DrawableText();
  49721. DrawableText (const DrawableText& other);
  49722. /** Destructor. */
  49723. ~DrawableText();
  49724. /** Sets the text to display.*/
  49725. void setText (const String& newText);
  49726. /** Sets the colour of the text. */
  49727. void setColour (const Colour& newColour);
  49728. /** Returns the current text colour. */
  49729. const Colour& getColour() const throw() { return colour; }
  49730. /** Sets the font to use.
  49731. Note that the font height and horizontal scale are actually based upon the position
  49732. of the fontSizeAndScaleAnchor parameter to setBounds(). If applySizeAndScale is true, then
  49733. the height and scale control point will be moved to match the dimensions of the font supplied;
  49734. if it is false, then the new font's height and scale are ignored.
  49735. */
  49736. void setFont (const Font& newFont, bool applySizeAndScale);
  49737. /** Changes the justification of the text within the bounding box. */
  49738. void setJustification (const Justification& newJustification);
  49739. /** Returns the parallelogram that defines the text bounding box. */
  49740. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  49741. /** Sets the bounding box that contains the text. */
  49742. void setBoundingBox (const RelativeParallelogram& newBounds);
  49743. /** Returns the point within the bounds that defines the font's size and scale. */
  49744. const RelativePoint& getFontSizeControlPoint() const throw() { return fontSizeControlPoint; }
  49745. /** Sets the control point that defines the font's height and horizontal scale.
  49746. This position is a point within the bounding box parallelogram, whose Y position (relative
  49747. to the parallelogram's origin and possibly distorted shape) specifies the font's height,
  49748. and its X defines the font's horizontal scale.
  49749. */
  49750. void setFontSizeControlPoint (const RelativePoint& newPoint);
  49751. /** @internal */
  49752. void paint (Graphics& g);
  49753. /** @internal */
  49754. Drawable* createCopy() const;
  49755. /** @internal */
  49756. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  49757. /** @internal */
  49758. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  49759. /** @internal */
  49760. static const Identifier valueTreeType;
  49761. /** @internal */
  49762. const Rectangle<float> getDrawableBounds() const;
  49763. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  49764. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  49765. {
  49766. public:
  49767. ValueTreeWrapper (const ValueTree& state);
  49768. const String getText() const;
  49769. void setText (const String& newText, UndoManager* undoManager);
  49770. Value getTextValue (UndoManager* undoManager);
  49771. const Colour getColour() const;
  49772. void setColour (const Colour& newColour, UndoManager* undoManager);
  49773. const Justification getJustification() const;
  49774. void setJustification (const Justification& newJustification, UndoManager* undoManager);
  49775. const Font getFont() const;
  49776. void setFont (const Font& newFont, UndoManager* undoManager);
  49777. Value getFontValue (UndoManager* undoManager);
  49778. const RelativeParallelogram getBoundingBox() const;
  49779. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  49780. const RelativePoint getFontSizeControlPoint() const;
  49781. void setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager);
  49782. static const Identifier text, colour, font, justification, topLeft, topRight, bottomLeft, fontSizeAnchor;
  49783. };
  49784. private:
  49785. RelativeParallelogram bounds;
  49786. RelativePoint fontSizeControlPoint;
  49787. Point<float> resolvedPoints[3];
  49788. Font font, scaledFont;
  49789. String text;
  49790. Colour colour;
  49791. Justification justification;
  49792. friend class Drawable::Positioner<DrawableText>;
  49793. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  49794. void recalculateCoordinates (Expression::Scope*);
  49795. void refreshBounds();
  49796. const AffineTransform getArrangementAndTransform (GlyphArrangement& glyphs) const;
  49797. DrawableText& operator= (const DrawableText&);
  49798. JUCE_LEAK_DETECTOR (DrawableText);
  49799. };
  49800. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  49801. /*** End of inlined file: juce_DrawableText.h ***/
  49802. #endif
  49803. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  49804. #endif
  49805. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  49806. /*** Start of inlined file: juce_GlowEffect.h ***/
  49807. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  49808. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  49809. /**
  49810. A component effect that adds a coloured blur around the component's contents.
  49811. (This will only work on non-opaque components).
  49812. @see Component::setComponentEffect, DropShadowEffect
  49813. */
  49814. class JUCE_API GlowEffect : public ImageEffectFilter
  49815. {
  49816. public:
  49817. /** Creates a default 'glow' effect.
  49818. To customise its appearance, use the setGlowProperties() method.
  49819. */
  49820. GlowEffect();
  49821. /** Destructor. */
  49822. ~GlowEffect();
  49823. /** Sets the glow's radius and colour.
  49824. The radius is how large the blur should be, and the colour is
  49825. used to render it (for a less intense glow, lower the colour's
  49826. opacity).
  49827. */
  49828. void setGlowProperties (float newRadius,
  49829. const Colour& newColour);
  49830. /** @internal */
  49831. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  49832. private:
  49833. float radius;
  49834. Colour colour;
  49835. JUCE_LEAK_DETECTOR (GlowEffect);
  49836. };
  49837. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  49838. /*** End of inlined file: juce_GlowEffect.h ***/
  49839. #endif
  49840. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  49841. #endif
  49842. #ifndef __JUCE_FONT_JUCEHEADER__
  49843. #endif
  49844. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  49845. #endif
  49846. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  49847. #endif
  49848. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  49849. #endif
  49850. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  49851. #endif
  49852. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  49853. #endif
  49854. #ifndef __JUCE_LINE_JUCEHEADER__
  49855. #endif
  49856. #ifndef __JUCE_PATH_JUCEHEADER__
  49857. #endif
  49858. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  49859. /*** Start of inlined file: juce_PathIterator.h ***/
  49860. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  49861. #define __JUCE_PATHITERATOR_JUCEHEADER__
  49862. /**
  49863. Flattens a Path object into a series of straight-line sections.
  49864. Use one of these to iterate through a Path object, and it will convert
  49865. all the curves into line sections so it's easy to render or perform
  49866. geometric operations on.
  49867. @see Path
  49868. */
  49869. class JUCE_API PathFlatteningIterator
  49870. {
  49871. public:
  49872. /** Creates a PathFlatteningIterator.
  49873. After creation, use the next() method to initialise the fields in the
  49874. object with the first line's position.
  49875. @param path the path to iterate along
  49876. @param transform a transform to apply to each point in the path being iterated
  49877. @param tolerance the amount by which the curves are allowed to deviate from the lines
  49878. into which they are being broken down - a higher tolerance contains
  49879. less lines, so can be generated faster, but will be less smooth.
  49880. */
  49881. PathFlatteningIterator (const Path& path,
  49882. const AffineTransform& transform = AffineTransform::identity,
  49883. float tolerance = defaultTolerance);
  49884. /** Destructor. */
  49885. ~PathFlatteningIterator();
  49886. /** Fetches the next line segment from the path.
  49887. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  49888. so that they describe the new line segment.
  49889. @returns false when there are no more lines to fetch.
  49890. */
  49891. bool next();
  49892. float x1; /**< The x position of the start of the current line segment. */
  49893. float y1; /**< The y position of the start of the current line segment. */
  49894. float x2; /**< The x position of the end of the current line segment. */
  49895. float y2; /**< The y position of the end of the current line segment. */
  49896. /** Indicates whether the current line segment is closing a sub-path.
  49897. If the current line is the one that connects the end of a sub-path
  49898. back to the start again, this will be true.
  49899. */
  49900. bool closesSubPath;
  49901. /** The index of the current line within the current sub-path.
  49902. E.g. you can use this to see whether the line is the first one in the
  49903. subpath by seeing if it's 0.
  49904. */
  49905. int subPathIndex;
  49906. /** Returns true if the current segment is the last in the current sub-path. */
  49907. bool isLastInSubpath() const throw();
  49908. /** This is the default value that should be used for the tolerance value (see the constructor parameters). */
  49909. static const float defaultTolerance;
  49910. private:
  49911. const Path& path;
  49912. const AffineTransform transform;
  49913. float* points;
  49914. const float toleranceSquared;
  49915. float subPathCloseX, subPathCloseY;
  49916. const bool isIdentityTransform;
  49917. HeapBlock <float> stackBase;
  49918. float* stackPos;
  49919. size_t index, stackSize;
  49920. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PathFlatteningIterator);
  49921. };
  49922. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  49923. /*** End of inlined file: juce_PathIterator.h ***/
  49924. #endif
  49925. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  49926. #endif
  49927. #ifndef __JUCE_POINT_JUCEHEADER__
  49928. #endif
  49929. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  49930. #endif
  49931. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  49932. #endif
  49933. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  49934. /*** Start of inlined file: juce_CameraDevice.h ***/
  49935. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  49936. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  49937. #if JUCE_USE_CAMERA || DOXYGEN
  49938. /**
  49939. Controls any video capture devices that might be available.
  49940. Use getAvailableDevices() to list the devices that are attached to the
  49941. system, then call openDevice to open one for use. Once you have a CameraDevice
  49942. object, you can get a viewer component from it, and use its methods to
  49943. stream to a file or capture still-frames.
  49944. */
  49945. class JUCE_API CameraDevice
  49946. {
  49947. public:
  49948. /** Destructor. */
  49949. virtual ~CameraDevice();
  49950. /** Returns a list of the available cameras on this machine.
  49951. You can open one of these devices by calling openDevice().
  49952. */
  49953. static const StringArray getAvailableDevices();
  49954. /** Opens a camera device.
  49955. The index parameter indicates which of the items returned by getAvailableDevices()
  49956. to open.
  49957. The size constraints allow the method to choose between different resolutions if
  49958. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  49959. then these will be ignored.
  49960. */
  49961. static CameraDevice* openDevice (int deviceIndex,
  49962. int minWidth = 128, int minHeight = 64,
  49963. int maxWidth = 1024, int maxHeight = 768);
  49964. /** Returns the name of this device */
  49965. const String getName() const { return name; }
  49966. /** Creates a component that can be used to display a preview of the
  49967. video from this camera.
  49968. */
  49969. Component* createViewerComponent();
  49970. /** Starts recording video to the specified file.
  49971. You should use getFileExtension() to find out the correct extension to
  49972. use for your filename.
  49973. If the file exists, it will be deleted before the recording starts.
  49974. This method may not start recording instantly, so if you need to know the
  49975. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  49976. after the recording has finished.
  49977. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  49978. or may not be used, depending on the driver.
  49979. */
  49980. void startRecordingToFile (const File& file, int quality = 2);
  49981. /** Stops recording, after a call to startRecordingToFile().
  49982. */
  49983. void stopRecording();
  49984. /** Returns the file extension that should be used for the files
  49985. that you pass to startRecordingToFile().
  49986. This may be platform-specific, e.g. ".mov" or ".avi".
  49987. */
  49988. static const String getFileExtension();
  49989. /** After calling stopRecording(), this method can be called to return the timestamp
  49990. of the first frame that was written to the file.
  49991. */
  49992. const Time getTimeOfFirstRecordedFrame() const;
  49993. /**
  49994. Receives callbacks with images from a CameraDevice.
  49995. @see CameraDevice::addListener
  49996. */
  49997. class JUCE_API Listener
  49998. {
  49999. public:
  50000. Listener() {}
  50001. virtual ~Listener() {}
  50002. /** This method is called when a new image arrives.
  50003. This may be called by any thread, so be careful about thread-safety,
  50004. and make sure that you process the data as quickly as possible to
  50005. avoid glitching!
  50006. */
  50007. virtual void imageReceived (const Image& image) = 0;
  50008. };
  50009. /** Adds a listener to receive images from the camera.
  50010. Be very careful not to delete the listener without first removing it by calling
  50011. removeListener().
  50012. */
  50013. void addListener (Listener* listenerToAdd);
  50014. /** Removes a listener that was previously added with addListener().
  50015. */
  50016. void removeListener (Listener* listenerToRemove);
  50017. protected:
  50018. /** @internal */
  50019. CameraDevice (const String& name, int index);
  50020. private:
  50021. void* internal;
  50022. bool isRecording;
  50023. String name;
  50024. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CameraDevice);
  50025. };
  50026. /** This typedef is just for compatibility with old code - newer code should use the CameraDevice::Listener class directly. */
  50027. typedef CameraDevice::Listener CameraImageListener;
  50028. #endif
  50029. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  50030. /*** End of inlined file: juce_CameraDevice.h ***/
  50031. #endif
  50032. #ifndef __JUCE_IMAGE_JUCEHEADER__
  50033. #endif
  50034. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  50035. /*** Start of inlined file: juce_ImageCache.h ***/
  50036. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  50037. #define __JUCE_IMAGECACHE_JUCEHEADER__
  50038. /**
  50039. A global cache of images that have been loaded from files or memory.
  50040. If you're loading an image and may need to use the image in more than one
  50041. place, this is used to allow the same image to be shared rather than loading
  50042. multiple copies into memory.
  50043. Another advantage is that after images are released, they will be kept in
  50044. memory for a few seconds before it is actually deleted, so if you're repeatedly
  50045. loading/deleting the same image, it'll reduce the chances of having to reload it
  50046. each time.
  50047. @see Image, ImageFileFormat
  50048. */
  50049. class JUCE_API ImageCache
  50050. {
  50051. public:
  50052. /** Loads an image from a file, (or just returns the image if it's already cached).
  50053. If the cache already contains an image that was loaded from this file,
  50054. that image will be returned. Otherwise, this method will try to load the
  50055. file, add it to the cache, and return it.
  50056. Remember that the image returned is shared, so drawing into it might
  50057. affect other things that are using it! If you want to draw on it, first
  50058. call Image::duplicateIfShared()
  50059. @param file the file to try to load
  50060. @returns the image, or null if it there was an error loading it
  50061. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  50062. */
  50063. static const Image getFromFile (const File& file);
  50064. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  50065. If the cache already contains an image that was loaded from this block of memory,
  50066. that image will be returned. Otherwise, this method will try to load the
  50067. file, add it to the cache, and return it.
  50068. Remember that the image returned is shared, so drawing into it might
  50069. affect other things that are using it! If you want to draw on it, first
  50070. call Image::duplicateIfShared()
  50071. @param imageData the block of memory containing the image data
  50072. @param dataSize the data size in bytes
  50073. @returns the image, or an invalid image if it there was an error loading it
  50074. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  50075. */
  50076. static const Image getFromMemory (const void* imageData, int dataSize);
  50077. /** Checks the cache for an image with a particular hashcode.
  50078. If there's an image in the cache with this hashcode, it will be returned,
  50079. otherwise it will return an invalid image.
  50080. @param hashCode the hash code that was associated with the image by addImageToCache()
  50081. @see addImageToCache
  50082. */
  50083. static const Image getFromHashCode (int64 hashCode);
  50084. /** Adds an image to the cache with a user-defined hash-code.
  50085. The image passed-in will be referenced (not copied) by the cache, so it's probably
  50086. a good idea not to draw into it after adding it, otherwise this will affect all
  50087. instances of it that may be in use.
  50088. @param image the image to add
  50089. @param hashCode the hash-code to associate with it
  50090. @see getFromHashCode
  50091. */
  50092. static void addImageToCache (const Image& image, int64 hashCode);
  50093. /** Changes the amount of time before an unused image will be removed from the cache.
  50094. By default this is about 5 seconds.
  50095. */
  50096. static void setCacheTimeout (int millisecs);
  50097. private:
  50098. class Pimpl;
  50099. friend class Pimpl;
  50100. ImageCache();
  50101. ~ImageCache();
  50102. JUCE_DECLARE_NON_COPYABLE (ImageCache);
  50103. };
  50104. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  50105. /*** End of inlined file: juce_ImageCache.h ***/
  50106. #endif
  50107. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50108. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  50109. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50110. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50111. /**
  50112. Represents a filter kernel to use in convoluting an image.
  50113. @see Image::applyConvolution
  50114. */
  50115. class JUCE_API ImageConvolutionKernel
  50116. {
  50117. public:
  50118. /** Creates an empty convulution kernel.
  50119. @param size the length of each dimension of the kernel, so e.g. if the size
  50120. is 5, it will create a 5x5 kernel
  50121. */
  50122. ImageConvolutionKernel (int size);
  50123. /** Destructor. */
  50124. ~ImageConvolutionKernel();
  50125. /** Resets all values in the kernel to zero. */
  50126. void clear();
  50127. /** Returns one of the kernel values. */
  50128. float getKernelValue (int x, int y) const throw();
  50129. /** Sets the value of a specific cell in the kernel.
  50130. The x and y parameters must be in the range 0 < x < getKernelSize().
  50131. @see setOverallSum
  50132. */
  50133. void setKernelValue (int x, int y, float value) throw();
  50134. /** Rescales all values in the kernel to make the total add up to a fixed value.
  50135. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  50136. */
  50137. void setOverallSum (float desiredTotalSum);
  50138. /** Multiplies all values in the kernel by a value. */
  50139. void rescaleAllValues (float multiplier);
  50140. /** Intialises the kernel for a gaussian blur.
  50141. @param blurRadius this may be larger or smaller than the kernel's actual
  50142. size but this will obviously be wasteful or clip at the
  50143. edges. Ideally the kernel should be just larger than
  50144. (blurRadius * 2).
  50145. */
  50146. void createGaussianBlur (float blurRadius);
  50147. /** Returns the size of the kernel.
  50148. E.g. if it's a 3x3 kernel, this returns 3.
  50149. */
  50150. int getKernelSize() const { return size; }
  50151. /** Applies the kernel to an image.
  50152. @param destImage the image that will receive the resultant convoluted pixels.
  50153. @param sourceImage the source image to read from - this can be the same image as
  50154. the destination, but if different, it must be exactly the same
  50155. size and format.
  50156. @param destinationArea the region of the image to apply the filter to
  50157. */
  50158. void applyToImage (Image& destImage,
  50159. const Image& sourceImage,
  50160. const Rectangle<int>& destinationArea) const;
  50161. private:
  50162. HeapBlock <float> values;
  50163. const int size;
  50164. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageConvolutionKernel);
  50165. };
  50166. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  50167. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  50168. #endif
  50169. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  50170. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  50171. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  50172. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  50173. /**
  50174. Base-class for codecs that can read and write image file formats such
  50175. as PNG, JPEG, etc.
  50176. This class also contains static methods to make it easy to load images
  50177. from files, streams or from memory.
  50178. @see Image, ImageCache
  50179. */
  50180. class JUCE_API ImageFileFormat
  50181. {
  50182. protected:
  50183. /** Creates an ImageFormat. */
  50184. ImageFileFormat() {}
  50185. public:
  50186. /** Destructor. */
  50187. virtual ~ImageFileFormat() {}
  50188. /** Returns a description of this file format.
  50189. E.g. "JPEG", "PNG"
  50190. */
  50191. virtual const String getFormatName() = 0;
  50192. /** Returns true if the given stream seems to contain data that this format
  50193. understands.
  50194. The format class should only read the first few bytes of the stream and sniff
  50195. for header bytes that it understands.
  50196. @see decodeImage
  50197. */
  50198. virtual bool canUnderstand (InputStream& input) = 0;
  50199. /** Tries to decode and return an image from the given stream.
  50200. This will be called for an image format after calling its canUnderStand() method
  50201. to see if it can handle the stream.
  50202. @param input the stream to read the data from. The stream will be positioned
  50203. at the start of the image data (but this may not necessarily
  50204. be position 0)
  50205. @returns the image that was decoded, or an invalid image if it fails.
  50206. @see loadFrom
  50207. */
  50208. virtual const Image decodeImage (InputStream& input) = 0;
  50209. /** Attempts to write an image to a stream.
  50210. To specify extra information like encoding quality, there will be appropriate parameters
  50211. in the subclasses of the specific file types.
  50212. @returns true if it nothing went wrong.
  50213. */
  50214. virtual bool writeImageToStream (const Image& sourceImage,
  50215. OutputStream& destStream) = 0;
  50216. /** Tries the built-in decoders to see if it can find one to read this stream.
  50217. There are currently built-in decoders for PNG, JPEG and GIF formats.
  50218. The object that is returned should not be deleted by the caller.
  50219. @see canUnderstand, decodeImage, loadFrom
  50220. */
  50221. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  50222. /** Tries to load an image from a stream.
  50223. This will use the findImageFormatForStream() method to locate a suitable
  50224. codec, and use that to load the image.
  50225. @returns the image that was decoded, or an invalid image if it fails.
  50226. */
  50227. static const Image loadFrom (InputStream& input);
  50228. /** Tries to load an image from a file.
  50229. This will use the findImageFormatForStream() method to locate a suitable
  50230. codec, and use that to load the image.
  50231. @returns the image that was decoded, or an invalid image if it fails.
  50232. */
  50233. static const Image loadFrom (const File& file);
  50234. /** Tries to load an image from a block of raw image data.
  50235. This will use the findImageFormatForStream() method to locate a suitable
  50236. codec, and use that to load the image.
  50237. @returns the image that was decoded, or an invalid image if it fails.
  50238. */
  50239. static const Image loadFrom (const void* rawData,
  50240. const int numBytesOfData);
  50241. };
  50242. /**
  50243. A subclass of ImageFileFormat for reading and writing PNG files.
  50244. @see ImageFileFormat, JPEGImageFormat
  50245. */
  50246. class JUCE_API PNGImageFormat : public ImageFileFormat
  50247. {
  50248. public:
  50249. PNGImageFormat();
  50250. ~PNGImageFormat();
  50251. const String getFormatName();
  50252. bool canUnderstand (InputStream& input);
  50253. const Image decodeImage (InputStream& input);
  50254. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  50255. };
  50256. /**
  50257. A subclass of ImageFileFormat for reading and writing JPEG files.
  50258. @see ImageFileFormat, PNGImageFormat
  50259. */
  50260. class JUCE_API JPEGImageFormat : public ImageFileFormat
  50261. {
  50262. public:
  50263. JPEGImageFormat();
  50264. ~JPEGImageFormat();
  50265. /** Specifies the quality to be used when writing a JPEG file.
  50266. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  50267. any negative value is "default" quality
  50268. */
  50269. void setQuality (float newQuality);
  50270. const String getFormatName();
  50271. bool canUnderstand (InputStream& input);
  50272. const Image decodeImage (InputStream& input);
  50273. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  50274. private:
  50275. float quality;
  50276. };
  50277. /**
  50278. A subclass of ImageFileFormat for reading GIF files.
  50279. @see ImageFileFormat, PNGImageFormat, JPEGImageFormat
  50280. */
  50281. class JUCE_API GIFImageFormat : public ImageFileFormat
  50282. {
  50283. public:
  50284. GIFImageFormat();
  50285. ~GIFImageFormat();
  50286. const String getFormatName();
  50287. bool canUnderstand (InputStream& input);
  50288. const Image decodeImage (InputStream& input);
  50289. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  50290. };
  50291. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  50292. /*** End of inlined file: juce_ImageFileFormat.h ***/
  50293. #endif
  50294. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  50295. #endif
  50296. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  50297. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  50298. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  50299. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  50300. /**
  50301. A class to take care of the logic involved with the loading/saving of some kind
  50302. of document.
  50303. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  50304. functions you need for documents that get saved to a file, so this class attempts
  50305. to abstract most of the boring stuff.
  50306. Your subclass should just implement all the pure virtual methods, and you can
  50307. then use the higher-level public methods to do the load/save dialogs, to warn the user
  50308. about overwriting files, etc.
  50309. The document object keeps track of whether it has changed since it was last saved or
  50310. loaded, so when you change something, call its changed() method. This will set a
  50311. flag so it knows it needs saving, and will also broadcast a change message using the
  50312. ChangeBroadcaster base class.
  50313. @see ChangeBroadcaster
  50314. */
  50315. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  50316. {
  50317. public:
  50318. /** Creates a FileBasedDocument.
  50319. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  50320. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  50321. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  50322. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  50323. */
  50324. FileBasedDocument (const String& fileExtension,
  50325. const String& fileWildCard,
  50326. const String& openFileDialogTitle,
  50327. const String& saveFileDialogTitle);
  50328. /** Destructor. */
  50329. virtual ~FileBasedDocument();
  50330. /** Returns true if the changed() method has been called since the file was
  50331. last saved or loaded.
  50332. @see resetChangedFlag, changed
  50333. */
  50334. bool hasChangedSinceSaved() const { return changedSinceSave; }
  50335. /** Called to indicate that the document has changed and needs saving.
  50336. This method will also trigger a change message to be sent out using the
  50337. ChangeBroadcaster base class.
  50338. After calling the method, the hasChangedSinceSaved() method will return true, until
  50339. it is reset either by saving to a file or using the resetChangedFlag() method.
  50340. @see hasChangedSinceSaved, resetChangedFlag
  50341. */
  50342. virtual void changed();
  50343. /** Sets the state of the 'changed' flag.
  50344. The 'changed' flag is set to true when the changed() method is called - use this method
  50345. to reset it or to set it without also broadcasting a change message.
  50346. @see changed, hasChangedSinceSaved
  50347. */
  50348. void setChangedFlag (bool hasChanged);
  50349. /** Tries to open a file.
  50350. If the file opens correctly, the document's file (see the getFile() method) is set
  50351. to this new one; if it fails, the document's file is left unchanged, and optionally
  50352. a message box is shown telling the user there was an error.
  50353. @returns true if the new file loaded successfully
  50354. @see loadDocument, loadFromUserSpecifiedFile
  50355. */
  50356. bool loadFrom (const File& fileToLoadFrom,
  50357. bool showMessageOnFailure);
  50358. /** Asks the user for a file and tries to load it.
  50359. This will pop up a dialog box using the title, file extension and
  50360. wildcard specified in the document's constructor, and asks the user
  50361. for a file. If they pick one, the loadFrom() method is used to
  50362. try to load it, optionally showing a message if it fails.
  50363. @returns true if a file was loaded; false if the user cancelled or if they
  50364. picked a file which failed to load correctly
  50365. @see loadFrom
  50366. */
  50367. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  50368. /** A set of possible outcomes of one of the save() methods
  50369. */
  50370. enum SaveResult
  50371. {
  50372. savedOk = 0, /**< indicates that a file was saved successfully. */
  50373. userCancelledSave, /**< indicates that the user aborted the save operation. */
  50374. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  50375. };
  50376. /** Tries to save the document to the last file it was saved or loaded from.
  50377. This will always try to write to the file, even if the document isn't flagged as
  50378. having changed.
  50379. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  50380. true, it will prompt the user to pick a file, as if
  50381. saveAsInteractive() was called.
  50382. @param showMessageOnFailure if true it will show a warning message when if the
  50383. save operation fails
  50384. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  50385. */
  50386. SaveResult save (bool askUserForFileIfNotSpecified,
  50387. bool showMessageOnFailure);
  50388. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  50389. it if they say yes.
  50390. If you've got a document open and want to close it (e.g. to quit the app), this is the
  50391. method to call.
  50392. If the document doesn't need saving it'll return the value savedOk so
  50393. you can go ahead and delete the document.
  50394. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  50395. return savedOk, so again, you can safely delete the document.
  50396. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  50397. close-document operation.
  50398. And if they click "save changes", it'll try to save and either return savedOk, or
  50399. failedToWriteToFile if there was a problem.
  50400. @see save, saveAs, saveAsInteractive
  50401. */
  50402. SaveResult saveIfNeededAndUserAgrees();
  50403. /** Tries to save the document to a specified file.
  50404. If this succeeds, it'll also change the document's internal file (as returned by
  50405. the getFile() method). If it fails, the file will be left unchanged.
  50406. @param newFile the file to try to write to
  50407. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  50408. the user first if they want to overwrite it
  50409. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  50410. use the saveAsInteractive() method to ask the user for a
  50411. filename
  50412. @param showMessageOnFailure if true and the write operation fails, it'll show
  50413. a message box to warn the user
  50414. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  50415. */
  50416. SaveResult saveAs (const File& newFile,
  50417. bool warnAboutOverwritingExistingFiles,
  50418. bool askUserForFileIfNotSpecified,
  50419. bool showMessageOnFailure);
  50420. /** Prompts the user for a filename and tries to save to it.
  50421. This will pop up a dialog box using the title, file extension and
  50422. wildcard specified in the document's constructor, and asks the user
  50423. for a file. If they pick one, the saveAs() method is used to try to save
  50424. to this file.
  50425. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  50426. the user first if they want to overwrite it
  50427. @see saveIfNeededAndUserAgrees, save, saveAs
  50428. */
  50429. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  50430. /** Returns the file that this document was last successfully saved or loaded from.
  50431. When the document object is created, this will be set to File::nonexistent.
  50432. It is changed when one of the load or save methods is used, or when setFile()
  50433. is used to explicitly set it.
  50434. */
  50435. const File getFile() const { return documentFile; }
  50436. /** Sets the file that this document thinks it was loaded from.
  50437. This won't actually load anything - it just changes the file stored internally.
  50438. @see getFile
  50439. */
  50440. void setFile (const File& newFile);
  50441. protected:
  50442. /** Overload this to return the title of the document.
  50443. This is used in message boxes, filenames and file choosers, so it should be
  50444. something sensible.
  50445. */
  50446. virtual const String getDocumentTitle() = 0;
  50447. /** This method should try to load your document from the given file.
  50448. If it fails, it should return an error message. If it succeeds, it should return
  50449. an empty string.
  50450. */
  50451. virtual const String loadDocument (const File& file) = 0;
  50452. /** This method should try to write your document to the given file.
  50453. If it fails, it should return an error message. If it succeeds, it should return
  50454. an empty string.
  50455. */
  50456. virtual const String saveDocument (const File& file) = 0;
  50457. /** This is used for dialog boxes to make them open at the last folder you
  50458. were using.
  50459. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  50460. the last document that was used - you might want to store this value
  50461. in a static variable, or even in your application's properties. It should
  50462. be a global setting rather than a property of this object.
  50463. This method works very well in conjunction with a RecentlyOpenedFilesList
  50464. object to manage your recent-files list.
  50465. As a default value, it's ok to return File::nonexistent, and the document
  50466. object will use a sensible one instead.
  50467. @see RecentlyOpenedFilesList
  50468. */
  50469. virtual const File getLastDocumentOpened() = 0;
  50470. /** This is used for dialog boxes to make them open at the last folder you
  50471. were using.
  50472. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  50473. the last document that was used - you might want to store this value
  50474. in a static variable, or even in your application's properties. It should
  50475. be a global setting rather than a property of this object.
  50476. This method works very well in conjunction with a RecentlyOpenedFilesList
  50477. object to manage your recent-files list.
  50478. @see RecentlyOpenedFilesList
  50479. */
  50480. virtual void setLastDocumentOpened (const File& file) = 0;
  50481. private:
  50482. File documentFile;
  50483. bool changedSinceSave;
  50484. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  50485. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBasedDocument);
  50486. };
  50487. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  50488. /*** End of inlined file: juce_FileBasedDocument.h ***/
  50489. #endif
  50490. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  50491. #endif
  50492. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  50493. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  50494. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  50495. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  50496. /**
  50497. Manages a set of files for use as a list of recently-opened documents.
  50498. This is a handy class for holding your list of recently-opened documents, with
  50499. helpful methods for things like purging any non-existent files, automatically
  50500. adding them to a menu, and making persistence easy.
  50501. @see File, FileBasedDocument
  50502. */
  50503. class JUCE_API RecentlyOpenedFilesList
  50504. {
  50505. public:
  50506. /** Creates an empty list.
  50507. */
  50508. RecentlyOpenedFilesList();
  50509. /** Destructor. */
  50510. ~RecentlyOpenedFilesList();
  50511. /** Sets a limit for the number of files that will be stored in the list.
  50512. When addFile() is called, then if there is no more space in the list, the
  50513. least-recently added file will be dropped.
  50514. @see getMaxNumberOfItems
  50515. */
  50516. void setMaxNumberOfItems (int newMaxNumber);
  50517. /** Returns the number of items that this list will store.
  50518. @see setMaxNumberOfItems
  50519. */
  50520. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  50521. /** Returns the number of files in the list.
  50522. The most recently added file is always at index 0.
  50523. */
  50524. int getNumFiles() const;
  50525. /** Returns one of the files in the list.
  50526. The most recently added file is always at index 0.
  50527. */
  50528. const File getFile (int index) const;
  50529. /** Returns an array of all the absolute pathnames in the list.
  50530. */
  50531. const StringArray& getAllFilenames() const throw() { return files; }
  50532. /** Clears all the files from the list. */
  50533. void clear();
  50534. /** Adds a file to the list.
  50535. The file will be added at index 0. If this file is already in the list, it will
  50536. be moved up to index 0, but a file can only appear once in the list.
  50537. If the list already contains the maximum number of items that is permitted, the
  50538. least-recently added file will be dropped from the end.
  50539. */
  50540. void addFile (const File& file);
  50541. /** Checks each of the files in the list, removing any that don't exist.
  50542. You might want to call this after reloading a list of files, or before putting them
  50543. on a menu.
  50544. */
  50545. void removeNonExistentFiles();
  50546. /** Adds entries to a menu, representing each of the files in the list.
  50547. This is handy for creating an "open recent file..." menu in your app. The
  50548. menu items are numbered consecutively starting with the baseItemId value,
  50549. and can either be added as complete pathnames, or just the last part of the
  50550. filename.
  50551. If dontAddNonExistentFiles is true, then each file will be checked and only those
  50552. that exist will be added.
  50553. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  50554. pointers to file objects. Any files that appear in this list will not be added to the
  50555. menu - the reason for this is that you might have a number of files already open, so
  50556. might not want these to be shown in the menu.
  50557. It returns the number of items that were added.
  50558. */
  50559. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  50560. int baseItemId,
  50561. bool showFullPaths,
  50562. bool dontAddNonExistentFiles,
  50563. const File** filesToAvoid = 0);
  50564. /** Returns a string that encapsulates all the files in the list.
  50565. The string that is returned can later be passed into restoreFromString() in
  50566. order to recreate the list. This is handy for persisting your list, e.g. in
  50567. a PropertiesFile object.
  50568. @see restoreFromString
  50569. */
  50570. const String toString() const;
  50571. /** Restores the list from a previously stringified version of the list.
  50572. Pass in a stringified version created with toString() in order to persist/restore
  50573. your list.
  50574. @see toString
  50575. */
  50576. void restoreFromString (const String& stringifiedVersion);
  50577. private:
  50578. StringArray files;
  50579. int maxNumberOfItems;
  50580. JUCE_LEAK_DETECTOR (RecentlyOpenedFilesList);
  50581. };
  50582. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  50583. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  50584. #endif
  50585. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  50586. #endif
  50587. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  50588. /*** Start of inlined file: juce_SystemClipboard.h ***/
  50589. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  50590. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  50591. /**
  50592. Handles reading/writing to the system's clipboard.
  50593. */
  50594. class JUCE_API SystemClipboard
  50595. {
  50596. public:
  50597. /** Copies a string of text onto the clipboard */
  50598. static void copyTextToClipboard (const String& text);
  50599. /** Gets the current clipboard's contents.
  50600. Obviously this might have come from another app, so could contain
  50601. anything..
  50602. */
  50603. static const String getTextFromClipboard();
  50604. };
  50605. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  50606. /*** End of inlined file: juce_SystemClipboard.h ***/
  50607. #endif
  50608. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  50609. #endif
  50610. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  50611. #endif
  50612. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  50613. /*** Start of inlined file: juce_UnitTest.h ***/
  50614. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  50615. #define __JUCE_UNITTEST_JUCEHEADER__
  50616. class UnitTestRunner;
  50617. /**
  50618. This is a base class for classes that perform a unit test.
  50619. To write a test using this class, your code should look something like this:
  50620. @code
  50621. class MyTest : public UnitTest
  50622. {
  50623. public:
  50624. MyTest() : UnitTest ("Foobar testing") {}
  50625. void runTest()
  50626. {
  50627. beginTest ("Part 1");
  50628. expect (myFoobar.doesSomething());
  50629. expect (myFoobar.doesSomethingElse());
  50630. beginTest ("Part 2");
  50631. expect (myOtherFoobar.doesSomething());
  50632. expect (myOtherFoobar.doesSomethingElse());
  50633. ...etc..
  50634. }
  50635. };
  50636. // Creating a static instance will automatically add the instance to the array
  50637. // returned by UnitTest::getAllTests(), so the test will be included when you call
  50638. // UnitTestRunner::runAllTests()
  50639. static MyTest test;
  50640. @endcode
  50641. To run a test, use the UnitTestRunner class.
  50642. @see UnitTestRunner
  50643. */
  50644. class JUCE_API UnitTest
  50645. {
  50646. public:
  50647. /** Creates a test with the given name. */
  50648. explicit UnitTest (const String& name);
  50649. /** Destructor. */
  50650. virtual ~UnitTest();
  50651. /** Returns the name of the test. */
  50652. const String getName() const throw() { return name; }
  50653. /** Runs the test, using the specified UnitTestRunner.
  50654. You shouldn't need to call this method directly - use
  50655. UnitTestRunner::runTests() instead.
  50656. */
  50657. void performTest (UnitTestRunner* runner);
  50658. /** Returns the set of all UnitTest objects that currently exist. */
  50659. static Array<UnitTest*>& getAllTests();
  50660. /** You can optionally implement this method to set up your test.
  50661. This method will be called before runTest().
  50662. */
  50663. virtual void initialise();
  50664. /** You can optionally implement this method to clear up after your test has been run.
  50665. This method will be called after runTest() has returned.
  50666. */
  50667. virtual void shutdown();
  50668. /** Implement this method in your subclass to actually run your tests.
  50669. The content of your implementation should call beginTest() and expect()
  50670. to perform the tests.
  50671. */
  50672. virtual void runTest() = 0;
  50673. /** Tells the system that a new subsection of tests is beginning.
  50674. This should be called from your runTest() method, and may be called
  50675. as many times as you like, to demarcate different sets of tests.
  50676. */
  50677. void beginTest (const String& testName);
  50678. /** Checks that the result of a test is true, and logs this result.
  50679. In your runTest() method, you should call this method for each condition that
  50680. you want to check, e.g.
  50681. @code
  50682. void runTest()
  50683. {
  50684. beginTest ("basic tests");
  50685. expect (x + y == 2);
  50686. expect (getThing() == someThing);
  50687. ...etc...
  50688. }
  50689. @endcode
  50690. If testResult is true, a pass is logged; if it's false, a failure is logged.
  50691. If the failure message is specified, it will be written to the log if the test fails.
  50692. */
  50693. void expect (bool testResult, const String& failureMessage = String::empty);
  50694. /** Compares two values, and if they don't match, prints out a message containing the
  50695. expected and actual result values.
  50696. */
  50697. template <class ValueType>
  50698. void expectEquals (ValueType actual, ValueType expected, String failureMessage = String::empty)
  50699. {
  50700. const bool result = (actual == expected);
  50701. if (! result)
  50702. {
  50703. if (failureMessage.isNotEmpty())
  50704. failureMessage << " -- ";
  50705. failureMessage << "Expected value: " << expected << ", Actual value: " << actual;
  50706. }
  50707. expect (result, failureMessage);
  50708. }
  50709. /** Writes a message to the test log.
  50710. This can only be called from within your runTest() method.
  50711. */
  50712. void logMessage (const String& message);
  50713. private:
  50714. const String name;
  50715. UnitTestRunner* runner;
  50716. JUCE_DECLARE_NON_COPYABLE (UnitTest);
  50717. };
  50718. /**
  50719. Runs a set of unit tests.
  50720. You can instantiate one of these objects and use it to invoke tests on a set of
  50721. UnitTest objects.
  50722. By using a subclass of UnitTestRunner, you can intercept logging messages and
  50723. perform custom behaviour when each test completes.
  50724. @see UnitTest
  50725. */
  50726. class JUCE_API UnitTestRunner
  50727. {
  50728. public:
  50729. /** */
  50730. UnitTestRunner();
  50731. /** Destructor. */
  50732. virtual ~UnitTestRunner();
  50733. /** Runs a set of tests.
  50734. The tests are performed in order, and the results are logged. To run all the
  50735. registered UnitTest objects that exist, use runAllTests().
  50736. */
  50737. void runTests (const Array<UnitTest*>& tests, bool assertOnFailure);
  50738. /** Runs all the UnitTest objects that currently exist.
  50739. This calls runTests() for all the objects listed in UnitTest::getAllTests().
  50740. */
  50741. void runAllTests (bool assertOnFailure);
  50742. /** Contains the results of a test.
  50743. One of these objects is instantiated each time UnitTest::beginTest() is called, and
  50744. it contains details of the number of subsequent UnitTest::expect() calls that are
  50745. made.
  50746. */
  50747. struct TestResult
  50748. {
  50749. /** The main name of this test (i.e. the name of the UnitTest object being run). */
  50750. String unitTestName;
  50751. /** The name of the current subcategory (i.e. the name that was set when UnitTest::beginTest() was called). */
  50752. String subcategoryName;
  50753. /** The number of UnitTest::expect() calls that succeeded. */
  50754. int passes;
  50755. /** The number of UnitTest::expect() calls that failed. */
  50756. int failures;
  50757. /** A list of messages describing the failed tests. */
  50758. StringArray messages;
  50759. };
  50760. /** Returns the number of TestResult objects that have been performed.
  50761. @see getResult
  50762. */
  50763. int getNumResults() const throw();
  50764. /** Returns one of the TestResult objects that describes a test that has been run.
  50765. @see getNumResults
  50766. */
  50767. const TestResult* getResult (int index) const throw();
  50768. protected:
  50769. /** Called when the list of results changes.
  50770. You can override this to perform some sort of behaviour when results are added.
  50771. */
  50772. virtual void resultsUpdated();
  50773. /** Logs a message about the current test progress.
  50774. By default this just writes the message to the Logger class, but you could override
  50775. this to do something else with the data.
  50776. */
  50777. virtual void logMessage (const String& message);
  50778. private:
  50779. friend class UnitTest;
  50780. UnitTest* currentTest;
  50781. String currentSubCategory;
  50782. OwnedArray <TestResult, CriticalSection> results;
  50783. bool assertOnFailure;
  50784. void beginNewTest (UnitTest* test, const String& subCategory);
  50785. void endTest();
  50786. void addPass();
  50787. void addFail (const String& failureMessage);
  50788. JUCE_DECLARE_NON_COPYABLE (UnitTestRunner);
  50789. };
  50790. #endif // __JUCE_UNITTEST_JUCEHEADER__
  50791. /*** End of inlined file: juce_UnitTest.h ***/
  50792. #endif
  50793. #endif
  50794. /*** End of inlined file: juce_app_includes.h ***/
  50795. #endif
  50796. #if JUCE_MSVC
  50797. #pragma warning (pop)
  50798. #pragma pack (pop)
  50799. #endif
  50800. END_JUCE_NAMESPACE
  50801. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  50802. #ifdef JUCE_NAMESPACE
  50803. // this will obviously save a lot of typing, but can be disabled by
  50804. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  50805. using namespace JUCE_NAMESPACE;
  50806. /* On the Mac, these symbols are defined in the Mac libraries, so
  50807. these macros make it easier to reference them without writing out
  50808. the namespace every time.
  50809. If you run into difficulties where these macros interfere with the contents
  50810. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  50811. the comments in that file for more information.
  50812. */
  50813. #if (JUCE_MAC || JUCE_IOS) && ! JUCE_DONT_DEFINE_MACROS
  50814. #define Component JUCE_NAMESPACE::Component
  50815. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  50816. #define Point JUCE_NAMESPACE::Point
  50817. #define Button JUCE_NAMESPACE::Button
  50818. #endif
  50819. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  50820. it easier to use the juce version explicitly.
  50821. If you run into difficulties where this macro interferes with other 3rd party header
  50822. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  50823. file for more information.
  50824. */
  50825. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  50826. #define Rectangle JUCE_NAMESPACE::Rectangle
  50827. #endif
  50828. #endif
  50829. #endif
  50830. /* Easy autolinking to the right JUCE libraries under win32.
  50831. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  50832. including this header file.
  50833. */
  50834. #if JUCE_MSVC
  50835. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  50836. /** If you want your application to link to Juce as a DLL instead of
  50837. a static library (on win32), just define the JUCE_DLL macro before
  50838. including juce.h
  50839. */
  50840. #ifdef JUCE_DLL
  50841. #if JUCE_DEBUG
  50842. #define AUTOLINKEDLIB "JUCE_debug.lib"
  50843. #else
  50844. #define AUTOLINKEDLIB "JUCE.lib"
  50845. #endif
  50846. #else
  50847. #if JUCE_DEBUG
  50848. #ifdef _WIN64
  50849. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  50850. #else
  50851. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  50852. #endif
  50853. #else
  50854. #ifdef _WIN64
  50855. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  50856. #else
  50857. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  50858. #endif
  50859. #endif
  50860. #endif
  50861. #pragma comment(lib, AUTOLINKEDLIB)
  50862. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  50863. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  50864. #endif
  50865. // Auto-link the other win32 libs that are needed by library calls..
  50866. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  50867. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  50868. // Auto-links to various win32 libs that are needed by library calls..
  50869. #pragma comment(lib, "kernel32.lib")
  50870. #pragma comment(lib, "user32.lib")
  50871. #pragma comment(lib, "shell32.lib")
  50872. #pragma comment(lib, "gdi32.lib")
  50873. #pragma comment(lib, "vfw32.lib")
  50874. #pragma comment(lib, "comdlg32.lib")
  50875. #pragma comment(lib, "winmm.lib")
  50876. #pragma comment(lib, "wininet.lib")
  50877. #pragma comment(lib, "ole32.lib")
  50878. #pragma comment(lib, "oleaut32.lib")
  50879. #pragma comment(lib, "advapi32.lib")
  50880. #pragma comment(lib, "ws2_32.lib")
  50881. #pragma comment(lib, "version.lib")
  50882. #pragma comment(lib, "shlwapi.lib")
  50883. #ifdef _NATIVE_WCHAR_T_DEFINED
  50884. #ifdef _DEBUG
  50885. #pragma comment(lib, "comsuppwd.lib")
  50886. #else
  50887. #pragma comment(lib, "comsuppw.lib")
  50888. #endif
  50889. #else
  50890. #ifdef _DEBUG
  50891. #pragma comment(lib, "comsuppd.lib")
  50892. #else
  50893. #pragma comment(lib, "comsupp.lib")
  50894. #endif
  50895. #endif
  50896. #if JUCE_OPENGL
  50897. #pragma comment(lib, "OpenGL32.Lib")
  50898. #pragma comment(lib, "GlU32.Lib")
  50899. #endif
  50900. #if JUCE_QUICKTIME
  50901. #pragma comment (lib, "QTMLClient.lib")
  50902. #endif
  50903. #if JUCE_USE_CAMERA
  50904. #pragma comment (lib, "Strmiids.lib")
  50905. #pragma comment (lib, "wmvcore.lib")
  50906. #endif
  50907. #if JUCE_DIRECT2D
  50908. #pragma comment (lib, "Dwrite.lib")
  50909. #pragma comment (lib, "D2d1.lib")
  50910. #endif
  50911. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  50912. #endif
  50913. #endif
  50914. #endif
  50915. #endif // __JUCE_JUCEHEADER__
  50916. /*** End of inlined file: juce.h ***/
  50917. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__