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.

66316 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 24
  53. /** Current Juce version number.
  54. Bits 16 to 32 = major version.
  55. Bits 8 to 16 = minor version.
  56. Bits 0 to 8 = point release (not currently used).
  57. See also SystemStats::getJUCEVersion() for a string version.
  58. */
  59. #define JUCE_VERSION ((JUCE_MAJOR_VERSION << 16) + (JUCE_MINOR_VERSION << 8) + JUCE_BUILDNUMBER)
  60. /*** Start of inlined file: juce_TargetPlatform.h ***/
  61. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  62. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  63. /* This file figures out which platform is being built, and defines some macros
  64. that the rest of the code can use for OS-specific compilation.
  65. Macros that will be set here are:
  66. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  67. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  68. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  69. - Either JUCE_INTEL or JUCE_PPC
  70. - Either JUCE_GCC or JUCE_MSVC
  71. */
  72. #if (defined (_WIN32) || defined (_WIN64))
  73. #define JUCE_WIN32 1
  74. #define JUCE_WINDOWS 1
  75. #elif defined (LINUX) || defined (__linux__)
  76. #define JUCE_LINUX 1
  77. #elif defined (__APPLE_CPP__) || defined(__APPLE_CC__)
  78. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  79. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  80. #define JUCE_IPHONE 1
  81. #define JUCE_IOS 1
  82. #else
  83. #define JUCE_MAC 1
  84. #endif
  85. #elif defined (JUCE_ANDROID)
  86. #undef JUCE_ANDROID
  87. #define JUCE_ANDROID 1
  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_DEBUG
  447. // If debugging is enabled..
  448. /** Writes a string to the standard error stream.
  449. This is only compiled in a debug build.
  450. @see Logger::outputDebugString
  451. */
  452. #define DBG(dbgtext) { JUCE_NAMESPACE::String tempDbgBuf; tempDbgBuf << dbgtext; JUCE_NAMESPACE::Logger::outputDebugString (tempDbgBuf); }
  453. // Assertions..
  454. #if JUCE_WINDOWS || DOXYGEN
  455. #if JUCE_USE_INTRINSICS
  456. #pragma intrinsic (__debugbreak)
  457. /** This will try to break the debugger if one is currently hosting this app.
  458. @see jassert()
  459. */
  460. #define juce_breakDebugger __debugbreak();
  461. #elif JUCE_GCC
  462. /** This will try to break the debugger if one is currently hosting this app.
  463. @see jassert()
  464. */
  465. #define juce_breakDebugger asm("int $3");
  466. #else
  467. /** This will try to break the debugger if one is currently hosting this app.
  468. @see jassert()
  469. */
  470. #define juce_breakDebugger { __asm int 3 }
  471. #endif
  472. #elif JUCE_MAC
  473. #define juce_breakDebugger Debugger();
  474. #elif JUCE_IOS || JUCE_LINUX || JUCE_ANDROID
  475. #define juce_breakDebugger kill (0, SIGTRAP);
  476. #endif
  477. /** This will always cause an assertion failure.
  478. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  479. in juce_Config.h).
  480. @see jassert()
  481. */
  482. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  483. /** Platform-independent assertion macro.
  484. This gets optimised out when not being built with debugging turned on.
  485. Be careful not to call any functions within its arguments that are vital to
  486. the behaviour of the program, because these won't get called in the release
  487. build.
  488. @see jassertfalse
  489. */
  490. #define jassert(expression) { if (! (expression)) jassertfalse; }
  491. #else
  492. // If debugging is disabled, these dummy debug and assertion macros are used..
  493. #define DBG(dbgtext)
  494. #define jassertfalse { juce_LogCurrentAssertion }
  495. #if JUCE_LOG_ASSERTIONS
  496. #define jassert(expression) { if (! (expression)) jassertfalse; }
  497. #else
  498. #define jassert(a) { }
  499. #endif
  500. #endif
  501. #ifndef DOXYGEN
  502. BEGIN_JUCE_NAMESPACE
  503. template <bool b> struct JuceStaticAssert;
  504. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  505. END_JUCE_NAMESPACE
  506. #endif
  507. /** A compile-time assertion macro.
  508. If the expression parameter is false, the macro will cause a compile error.
  509. */
  510. #define static_jassert(expression) JUCE_NAMESPACE::JuceStaticAssert<expression>::dummy();
  511. /** This is a shorthand macro for declaring stubs for a class's copy constructor and
  512. operator=.
  513. For example, instead of
  514. @code
  515. class MyClass
  516. {
  517. etc..
  518. private:
  519. MyClass (const MyClass&);
  520. MyClass& operator= (const MyClass&);
  521. };@endcode
  522. ..you can just write:
  523. @code
  524. class MyClass
  525. {
  526. etc..
  527. private:
  528. JUCE_DECLARE_NON_COPYABLE (MyClass);
  529. };@endcode
  530. */
  531. #define JUCE_DECLARE_NON_COPYABLE(className) \
  532. className (const className&);\
  533. className& operator= (const className&)
  534. /** This is a shorthand way of writing both a JUCE_DECLARE_NON_COPYABLE and
  535. JUCE_LEAK_DETECTOR macro for a class.
  536. */
  537. #define JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(className) \
  538. JUCE_DECLARE_NON_COPYABLE(className);\
  539. JUCE_LEAK_DETECTOR(className)
  540. #if ! DOXYGEN
  541. #define JUCE_JOIN_MACRO_HELPER(a, b) a ## b
  542. #endif
  543. /** Good old C macro concatenation helper.
  544. This combines two items (which may themselves be macros) into a single string,
  545. avoiding the pitfalls of the ## macro operator.
  546. */
  547. #define JUCE_JOIN_MACRO(a, b) JUCE_JOIN_MACRO_HELPER (a, b)
  548. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  549. #define JUCE_TRY try
  550. #define JUCE_CATCH_ALL catch (...) {}
  551. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse; }
  552. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  553. #define JUCE_CATCH_EXCEPTION JUCE_CATCH_ALL
  554. #else
  555. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  556. object so they can be logged by the application if it wants to.
  557. */
  558. #define JUCE_CATCH_EXCEPTION \
  559. catch (const std::exception& e) \
  560. { \
  561. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  562. } \
  563. catch (...) \
  564. { \
  565. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  566. }
  567. #endif
  568. #else
  569. #define JUCE_TRY
  570. #define JUCE_CATCH_EXCEPTION
  571. #define JUCE_CATCH_ALL
  572. #define JUCE_CATCH_ALL_ASSERT
  573. #endif
  574. // Macros for inlining.
  575. #if JUCE_MSVC
  576. /** A platform-independent way of forcing an inline function.
  577. Use the syntax: @code
  578. forcedinline void myfunction (int x)
  579. @endcode
  580. */
  581. #ifndef JUCE_DEBUG
  582. #define forcedinline __forceinline
  583. #else
  584. #define forcedinline inline
  585. #endif
  586. #define JUCE_ALIGN(bytes) __declspec (align (bytes))
  587. #else
  588. /** A platform-independent way of forcing an inline function.
  589. Use the syntax: @code
  590. forcedinline void myfunction (int x)
  591. @endcode
  592. */
  593. #ifndef JUCE_DEBUG
  594. #define forcedinline inline __attribute__((always_inline))
  595. #else
  596. #define forcedinline inline
  597. #endif
  598. #define JUCE_ALIGN(bytes) __attribute__ ((aligned (bytes)))
  599. #endif
  600. // Cross-compiler deprecation macros..
  601. #if JUCE_MSVC && ! JUCE_NO_DEPRECATION_WARNINGS
  602. #define JUCE_DEPRECATED(functionDef) __declspec(deprecated) functionDef
  603. #elif JUCE_GCC && ! JUCE_NO_DEPRECATION_WARNINGS
  604. #define JUCE_DEPRECATED(functionDef) functionDef __attribute__ ((deprecated))
  605. #else
  606. #define JUCE_DEPRECATED(functionDef) functionDef
  607. #endif
  608. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  609. /*** End of inlined file: juce_PlatformDefs.h ***/
  610. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  611. #if JUCE_MSVC
  612. #if JUCE_VC6
  613. #pragma warning (disable: 4284 4786) // (spurious VC6 warnings)
  614. namespace std // VC6 doesn't have sqrt/sin/cos/tan/abs in std, so declare them here:
  615. {
  616. template <typename Type> Type abs (Type a) { if (a < 0) return -a; return a; }
  617. template <typename Type> Type tan (Type a) { return static_cast<Type> (::tan (static_cast<double> (a))); }
  618. template <typename Type> Type sin (Type a) { return static_cast<Type> (::sin (static_cast<double> (a))); }
  619. template <typename Type> Type cos (Type a) { return static_cast<Type> (::cos (static_cast<double> (a))); }
  620. template <typename Type> Type sqrt (Type a) { return static_cast<Type> (::sqrt (static_cast<double> (a))); }
  621. template <typename Type> Type floor (Type a) { return static_cast<Type> (::floor (static_cast<double> (a))); }
  622. template <typename Type> Type ceil (Type a) { return static_cast<Type> (::ceil (static_cast<double> (a))); }
  623. template <typename Type> Type atan2 (Type a, Type b) { return static_cast<Type> (::atan2 (static_cast<double> (a), static_cast<double> (b))); }
  624. }
  625. #endif
  626. #pragma warning (push)
  627. #pragma warning (disable: 4514 4245 4100)
  628. #endif
  629. #include <cstdlib>
  630. #include <cstdarg>
  631. #include <climits>
  632. #include <limits>
  633. #include <cmath>
  634. #include <cwchar>
  635. #include <stdexcept>
  636. #include <typeinfo>
  637. #include <cstring>
  638. #include <cstdio>
  639. #include <iostream>
  640. #if JUCE_USE_INTRINSICS
  641. #include <intrin.h>
  642. #endif
  643. #if JUCE_MAC || JUCE_IOS
  644. #include <libkern/OSAtomic.h>
  645. #endif
  646. #if JUCE_LINUX
  647. #include <signal.h>
  648. #if __INTEL_COMPILER
  649. #if __ia64__
  650. #include <ia64intrin.h>
  651. #else
  652. #include <ia32intrin.h>
  653. #endif
  654. #endif
  655. #endif
  656. #if JUCE_MSVC && JUCE_DEBUG
  657. #include <crtdbg.h>
  658. #endif
  659. #if JUCE_MSVC
  660. #include <malloc.h>
  661. #pragma warning (pop)
  662. #if ! JUCE_PUBLIC_INCLUDES
  663. #pragma warning (4: 4511 4512 4100) // (enable some warnings that are turned off in VC8)
  664. #endif
  665. #endif
  666. #if JUCE_ANDROID
  667. #include <sys/atomics.h>
  668. #include <byteswap.h>
  669. #endif
  670. // DLL building settings on Win32
  671. #if JUCE_MSVC
  672. #ifdef JUCE_DLL_BUILD
  673. #define JUCE_API __declspec (dllexport)
  674. #pragma warning (disable: 4251)
  675. #elif defined (JUCE_DLL)
  676. #define JUCE_API __declspec (dllimport)
  677. #pragma warning (disable: 4251)
  678. #endif
  679. #ifdef __INTEL_COMPILER
  680. #pragma warning (disable: 1125) // (virtual override warning)
  681. #endif
  682. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  683. #ifdef JUCE_DLL_BUILD
  684. #define JUCE_API __attribute__ ((visibility("default")))
  685. #endif
  686. #endif
  687. #ifndef JUCE_API
  688. /** This macro is added to all juce public class declarations. */
  689. #define JUCE_API
  690. #endif
  691. /** This macro is added to all juce public function declarations. */
  692. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  693. /** This turns on some non-essential bits of code that should prevent old code from compiling
  694. in cases where method signatures have changed, etc.
  695. */
  696. #if (! defined (JUCE_CATCH_DEPRECATED_CODE_MISUSE)) && JUCE_DEBUG && ! DOXYGEN
  697. #define JUCE_CATCH_DEPRECATED_CODE_MISUSE 1
  698. #endif
  699. // Now include some basics that are needed by most of the Juce classes...
  700. BEGIN_JUCE_NAMESPACE
  701. extern JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger();
  702. #if JUCE_LOG_ASSERTIONS
  703. extern JUCE_API void juce_LogAssertion (const char* filename, int lineNum) throw();
  704. #endif
  705. /*** Start of inlined file: juce_Memory.h ***/
  706. #ifndef __JUCE_MEMORY_JUCEHEADER__
  707. #define __JUCE_MEMORY_JUCEHEADER__
  708. /*
  709. This file defines the various juce_malloc(), juce_free() macros that can be used in
  710. preference to the standard calls.
  711. None of this stuff is actually used in the library itself, and will probably be
  712. deprecated at some point in the future, to force everyone to use HeapBlock and other
  713. safer allocation methods.
  714. */
  715. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS && ! DOXYGEN
  716. #ifndef JUCE_DLL
  717. // Win32 debug non-DLL versions..
  718. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  719. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  720. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  721. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  722. #else
  723. // Win32 debug DLL versions..
  724. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  725. // way all juce calls in the DLL and in the host API will all use the same allocator.
  726. extern JUCE_API void* juce_DebugMalloc (int size, const char* file, int line);
  727. extern JUCE_API void* juce_DebugCalloc (int size, const char* file, int line);
  728. extern JUCE_API void* juce_DebugRealloc (void* block, int size, const char* file, int line);
  729. extern JUCE_API void juce_DebugFree (void* block);
  730. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  731. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  732. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  733. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  734. #define JUCE_LEAK_DETECTOR(OwnerClass) public:\
  735. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  736. static void* operator new (size_t, void* p) { return p; } \
  737. static void operator delete (void* p) { juce_free (p); } \
  738. static void operator delete (void*, void*) {}
  739. #endif
  740. #elif defined (JUCE_DLL) && ! DOXYGEN
  741. // Win32 DLL (release) versions..
  742. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  743. // way all juce calls in the DLL and in the host API will all use the same allocator.
  744. extern JUCE_API void* juce_Malloc (int size);
  745. extern JUCE_API void* juce_Calloc (int size);
  746. extern JUCE_API void* juce_Realloc (void* block, int size);
  747. extern JUCE_API void juce_Free (void* block);
  748. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  749. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  750. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  751. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  752. #define JUCE_LEAK_DETECTOR(OwnerClass) public:\
  753. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  754. static void* operator new (size_t, void* p) { return p; } \
  755. static void operator delete (void* p) { juce_free (p); } \
  756. static void operator delete (void*, void*) {}
  757. #else
  758. // Mac, Linux and Win32 (release) versions..
  759. /** This can be used instead of calling malloc directly.
  760. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  761. */
  762. #define juce_malloc(numBytes) malloc (numBytes)
  763. /** This can be used instead of calling calloc directly.
  764. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  765. */
  766. #define juce_calloc(numBytes) calloc (1, numBytes)
  767. /** This can be used instead of calling realloc directly.
  768. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  769. */
  770. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  771. /** This can be used instead of calling free directly.
  772. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  773. */
  774. #define juce_free(location) free (location)
  775. #endif
  776. /** (Deprecated) This was a win32-specific way of checking for object leaks - now please
  777. use the JUCE_LEAK_DETECTOR instead.
  778. */
  779. #ifndef juce_UseDebuggingNewOperator
  780. #define juce_UseDebuggingNewOperator
  781. #endif
  782. #if JUCE_MSVC || DOXYGEN
  783. /** This is a compiler-independent way of declaring a variable as being thread-local.
  784. E.g.
  785. @code
  786. juce_ThreadLocal int myVariable;
  787. @endcode
  788. */
  789. #define juce_ThreadLocal __declspec(thread)
  790. #else
  791. #define juce_ThreadLocal __thread
  792. #endif
  793. #if JUCE_MINGW
  794. /** This allocator is not defined in mingw gcc. */
  795. #define alloca __builtin_alloca
  796. #endif
  797. /** Fills a block of memory with zeros. */
  798. inline void zeromem (void* memory, size_t numBytes) throw() { memset (memory, 0, numBytes); }
  799. /** Overwrites a structure or object with zeros. */
  800. template <typename Type>
  801. inline void zerostruct (Type& structure) throw() { memset (&structure, 0, sizeof (structure)); }
  802. /** Delete an object pointer, and sets the pointer to null.
  803. Remember that it's not good c++ practice to use delete directly - always try to use a ScopedPointer
  804. or other automatic lieftime-management system rather than resorting to deleting raw pointers!
  805. */
  806. template <typename Type>
  807. inline void deleteAndZero (Type& pointer) { delete pointer; pointer = 0; }
  808. /** A handy function which adds a number of bytes to any type of pointer and returns the result.
  809. This can be useful to avoid casting pointers to a char* and back when you want to move them by
  810. a specific number of bytes,
  811. */
  812. template <typename Type>
  813. inline Type* addBytesToPointer (Type* pointer, int bytes) throw() { return (Type*) (((char*) pointer) + bytes); }
  814. #endif // __JUCE_MEMORY_JUCEHEADER__
  815. /*** End of inlined file: juce_Memory.h ***/
  816. /*** Start of inlined file: juce_MathsFunctions.h ***/
  817. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  818. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  819. /*
  820. This file sets up some handy mathematical typdefs and functions.
  821. */
  822. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  823. /** A platform-independent 8-bit signed integer type. */
  824. typedef signed char int8;
  825. /** A platform-independent 8-bit unsigned integer type. */
  826. typedef unsigned char uint8;
  827. /** A platform-independent 16-bit signed integer type. */
  828. typedef signed short int16;
  829. /** A platform-independent 16-bit unsigned integer type. */
  830. typedef unsigned short uint16;
  831. /** A platform-independent 32-bit signed integer type. */
  832. typedef signed int int32;
  833. /** A platform-independent 32-bit unsigned integer type. */
  834. typedef unsigned int uint32;
  835. #if JUCE_MSVC
  836. /** A platform-independent 64-bit integer type. */
  837. typedef __int64 int64;
  838. /** A platform-independent 64-bit unsigned integer type. */
  839. typedef unsigned __int64 uint64;
  840. /** A platform-independent macro for writing 64-bit literals, needed because
  841. different compilers have different syntaxes for this.
  842. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  843. GCC, or 0x1000000000 for MSVC.
  844. */
  845. #define literal64bit(longLiteral) ((__int64) longLiteral)
  846. #else
  847. /** A platform-independent 64-bit integer type. */
  848. typedef long long int64;
  849. /** A platform-independent 64-bit unsigned integer type. */
  850. typedef unsigned long long uint64;
  851. /** A platform-independent macro for writing 64-bit literals, needed because
  852. different compilers have different syntaxes for this.
  853. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  854. GCC, or 0x1000000000 for MSVC.
  855. */
  856. #define literal64bit(longLiteral) (longLiteral##LL)
  857. #endif
  858. #if JUCE_64BIT
  859. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  860. typedef int64 pointer_sized_int;
  861. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  862. typedef uint64 pointer_sized_uint;
  863. #elif JUCE_MSVC && ! JUCE_VC6
  864. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  865. typedef _W64 int pointer_sized_int;
  866. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  867. typedef _W64 unsigned int pointer_sized_uint;
  868. #else
  869. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  870. typedef int pointer_sized_int;
  871. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  872. typedef unsigned int pointer_sized_uint;
  873. #endif
  874. // Some indispensible min/max functions
  875. /** Returns the larger of two values. */
  876. template <typename Type>
  877. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  878. /** Returns the larger of three values. */
  879. template <typename Type>
  880. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  881. /** Returns the larger of four values. */
  882. template <typename Type>
  883. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  884. /** Returns the smaller of two values. */
  885. template <typename Type>
  886. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  887. /** Returns the smaller of three values. */
  888. template <typename Type>
  889. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  890. /** Returns the smaller of four values. */
  891. template <typename Type>
  892. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  893. /** Scans an array of values, returning the minimum value that it contains. */
  894. template <typename Type>
  895. const Type findMinimum (const Type* data, int numValues)
  896. {
  897. if (numValues <= 0)
  898. return Type();
  899. Type result (*data++);
  900. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  901. {
  902. const Type& v = *data++;
  903. if (v < result) result = v;
  904. }
  905. return result;
  906. }
  907. /** Scans an array of values, returning the minimum value that it contains. */
  908. template <typename Type>
  909. const Type findMaximum (const Type* values, int numValues)
  910. {
  911. if (numValues <= 0)
  912. return Type();
  913. Type result (*values++);
  914. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  915. {
  916. const Type& v = *values++;
  917. if (result > v) result = v;
  918. }
  919. return result;
  920. }
  921. /** Scans an array of values, returning the minimum and maximum values that it contains. */
  922. template <typename Type>
  923. void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
  924. {
  925. if (numValues <= 0)
  926. {
  927. lowest = Type();
  928. highest = Type();
  929. }
  930. else
  931. {
  932. Type mn (*values++);
  933. Type mx (mn);
  934. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  935. {
  936. const Type& v = *values++;
  937. if (mx < v) mx = v;
  938. if (v < mn) mn = v;
  939. }
  940. lowest = mn;
  941. highest = mx;
  942. }
  943. }
  944. /** Constrains a value to keep it within a given range.
  945. This will check that the specified value lies between the lower and upper bounds
  946. specified, and if not, will return the nearest value that would be in-range. Effectively,
  947. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  948. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  949. the results will be unpredictable.
  950. @param lowerLimit the minimum value to return
  951. @param upperLimit the maximum value to return
  952. @param valueToConstrain the value to try to return
  953. @returns the closest value to valueToConstrain which lies between lowerLimit
  954. and upperLimit (inclusive)
  955. @see jlimit0To, jmin, jmax
  956. */
  957. template <typename Type>
  958. inline Type jlimit (const Type lowerLimit,
  959. const Type upperLimit,
  960. const Type valueToConstrain) throw()
  961. {
  962. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  963. return (valueToConstrain < lowerLimit) ? lowerLimit
  964. : ((upperLimit < valueToConstrain) ? upperLimit
  965. : valueToConstrain);
  966. }
  967. /** Returns true if a value is at least zero, and also below a specified upper limit.
  968. This is basically a quicker way to write:
  969. @code valueToTest >= 0 && valueToTest < upperLimit
  970. @endcode
  971. */
  972. template <typename Type>
  973. inline bool isPositiveAndBelow (Type valueToTest, Type upperLimit) throw()
  974. {
  975. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  976. return Type() <= valueToTest && valueToTest < upperLimit;
  977. }
  978. #if ! JUCE_VC6
  979. template <>
  980. inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) throw()
  981. {
  982. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  983. return static_cast <unsigned int> (valueToTest) < static_cast <unsigned int> (upperLimit);
  984. }
  985. #endif
  986. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  987. This is basically a quicker way to write:
  988. @code valueToTest >= 0 && valueToTest <= upperLimit
  989. @endcode
  990. */
  991. template <typename Type>
  992. inline bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) throw()
  993. {
  994. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  995. return Type() <= valueToTest && valueToTest <= upperLimit;
  996. }
  997. #if ! JUCE_VC6
  998. template <>
  999. inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) throw()
  1000. {
  1001. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  1002. return static_cast <unsigned int> (valueToTest) <= static_cast <unsigned int> (upperLimit);
  1003. }
  1004. #endif
  1005. /** Handy function to swap two values over.
  1006. */
  1007. template <typename Type>
  1008. inline void swapVariables (Type& variable1, Type& variable2)
  1009. {
  1010. const Type tempVal = variable1;
  1011. variable1 = variable2;
  1012. variable2 = tempVal;
  1013. }
  1014. #if JUCE_VC6
  1015. #define numElementsInArray(X) (sizeof((X)) / sizeof(0[X]))
  1016. #else
  1017. /** Handy function for getting the number of elements in a simple const C array.
  1018. E.g.
  1019. @code
  1020. static int myArray[] = { 1, 2, 3 };
  1021. int numElements = numElementsInArray (myArray) // returns 3
  1022. @endcode
  1023. */
  1024. template <typename Type, int N>
  1025. inline int numElementsInArray (Type (&array)[N])
  1026. {
  1027. (void) array; // (required to avoid a spurious warning in MS compilers)
  1028. (void) sizeof (0[array]); // This line should cause an error if you pass an object with a user-defined subscript operator
  1029. return N;
  1030. }
  1031. #endif
  1032. // Some useful maths functions that aren't always present with all compilers and build settings.
  1033. /** Using juce_hypot is easier than dealing with the different types of hypot function
  1034. that are provided by the various platforms and compilers. */
  1035. template <typename Type>
  1036. inline Type juce_hypot (Type a, Type b) throw()
  1037. {
  1038. #if JUCE_WINDOWS
  1039. return static_cast <Type> (_hypot (a, b));
  1040. #else
  1041. return static_cast <Type> (hypot (a, b));
  1042. #endif
  1043. }
  1044. /** 64-bit abs function. */
  1045. inline int64 abs64 (const int64 n) throw()
  1046. {
  1047. return (n >= 0) ? n : -n;
  1048. }
  1049. /** This templated negate function will negate pointers as well as integers */
  1050. template <typename Type>
  1051. inline Type juce_negate (Type n) throw()
  1052. {
  1053. return sizeof (Type) == 1 ? (Type) -(char) n
  1054. : (sizeof (Type) == 2 ? (Type) -(short) n
  1055. : (sizeof (Type) == 4 ? (Type) -(int) n
  1056. : ((Type) -(int64) n)));
  1057. }
  1058. /** This templated negate function will negate pointers as well as integers */
  1059. template <typename Type>
  1060. inline Type* juce_negate (Type* n) throw()
  1061. {
  1062. return (Type*) -(pointer_sized_int) n;
  1063. }
  1064. /** A predefined value for Pi, at double-precision.
  1065. @see float_Pi
  1066. */
  1067. const double double_Pi = 3.1415926535897932384626433832795;
  1068. /** A predefined value for Pi, at sngle-precision.
  1069. @see double_Pi
  1070. */
  1071. const float float_Pi = 3.14159265358979323846f;
  1072. /** The isfinite() method seems to vary between platforms, so this is a
  1073. platform-independent function for it.
  1074. */
  1075. template <typename FloatingPointType>
  1076. inline bool juce_isfinite (FloatingPointType value)
  1077. {
  1078. #if JUCE_WINDOWS
  1079. return _finite (value);
  1080. #elif JUCE_ANDROID
  1081. return isfinite (value);
  1082. #else
  1083. return std::isfinite (value);
  1084. #endif
  1085. }
  1086. /** Fast floating-point-to-integer conversion.
  1087. This is faster than using the normal c++ cast to convert a float to an int, and
  1088. it will round the value to the nearest integer, rather than rounding it down
  1089. like the normal cast does.
  1090. Note that this routine gets its speed at the expense of some accuracy, and when
  1091. rounding values whose floating point component is exactly 0.5, odd numbers and
  1092. even numbers will be rounded up or down differently.
  1093. */
  1094. template <typename FloatType>
  1095. inline int roundToInt (const FloatType value) throw()
  1096. {
  1097. union { int asInt[2]; double asDouble; } n;
  1098. n.asDouble = ((double) value) + 6755399441055744.0;
  1099. #if JUCE_BIG_ENDIAN
  1100. return n.asInt [1];
  1101. #else
  1102. return n.asInt [0];
  1103. #endif
  1104. }
  1105. /** Fast floating-point-to-integer conversion.
  1106. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  1107. fine for values above zero, but negative numbers are rounded the wrong way.
  1108. */
  1109. inline int roundToIntAccurate (const double value) throw()
  1110. {
  1111. return roundToInt (value + 1.5e-8);
  1112. }
  1113. /** Fast floating-point-to-integer conversion.
  1114. This is faster than using the normal c++ cast to convert a double to an int, and
  1115. it will round the value to the nearest integer, rather than rounding it down
  1116. like the normal cast does.
  1117. Note that this routine gets its speed at the expense of some accuracy, and when
  1118. rounding values whose floating point component is exactly 0.5, odd numbers and
  1119. even numbers will be rounded up or down differently. For a more accurate conversion,
  1120. see roundDoubleToIntAccurate().
  1121. */
  1122. inline int roundDoubleToInt (const double value) throw()
  1123. {
  1124. return roundToInt (value);
  1125. }
  1126. /** Fast floating-point-to-integer conversion.
  1127. This is faster than using the normal c++ cast to convert a float to an int, and
  1128. it will round the value to the nearest integer, rather than rounding it down
  1129. like the normal cast does.
  1130. Note that this routine gets its speed at the expense of some accuracy, and when
  1131. rounding values whose floating point component is exactly 0.5, odd numbers and
  1132. even numbers will be rounded up or down differently.
  1133. */
  1134. inline int roundFloatToInt (const float value) throw()
  1135. {
  1136. return roundToInt (value);
  1137. }
  1138. /** This namespace contains a few template classes for helping work out class type variations.
  1139. */
  1140. namespace TypeHelpers
  1141. {
  1142. #if JUCE_VC8_OR_EARLIER
  1143. #define PARAMETER_TYPE(a) a
  1144. #else
  1145. /** The ParameterType struct is used to find the best type to use when passing some kind
  1146. of object as a parameter.
  1147. Of course, this is only likely to be useful in certain esoteric template situations.
  1148. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  1149. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  1150. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  1151. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  1152. pass-by-value, but passing objects as a const reference, to avoid copying.
  1153. */
  1154. template <typename Type> struct ParameterType { typedef const Type& type; };
  1155. #if ! DOXYGEN
  1156. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  1157. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  1158. template <> struct ParameterType <char> { typedef char type; };
  1159. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  1160. template <> struct ParameterType <short> { typedef short type; };
  1161. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  1162. template <> struct ParameterType <int> { typedef int type; };
  1163. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  1164. template <> struct ParameterType <long> { typedef long type; };
  1165. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  1166. template <> struct ParameterType <int64> { typedef int64 type; };
  1167. template <> struct ParameterType <uint64> { typedef uint64 type; };
  1168. template <> struct ParameterType <bool> { typedef bool type; };
  1169. template <> struct ParameterType <float> { typedef float type; };
  1170. template <> struct ParameterType <double> { typedef double type; };
  1171. #endif
  1172. /** A helpful macro to simplify the use of the ParameterType template.
  1173. @see ParameterType
  1174. */
  1175. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  1176. #endif
  1177. }
  1178. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  1179. /*** End of inlined file: juce_MathsFunctions.h ***/
  1180. /*** Start of inlined file: juce_ByteOrder.h ***/
  1181. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  1182. #define __JUCE_BYTEORDER_JUCEHEADER__
  1183. /** Contains static methods for converting the byte order between different
  1184. endiannesses.
  1185. */
  1186. class JUCE_API ByteOrder
  1187. {
  1188. public:
  1189. /** Swaps the upper and lower bytes of a 16-bit integer. */
  1190. static uint16 swap (uint16 value);
  1191. /** Reverses the order of the 4 bytes in a 32-bit integer. */
  1192. static uint32 swap (uint32 value);
  1193. /** Reverses the order of the 8 bytes in a 64-bit integer. */
  1194. static uint64 swap (uint64 value);
  1195. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  1196. static uint16 swapIfBigEndian (uint16 value);
  1197. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  1198. static uint32 swapIfBigEndian (uint32 value);
  1199. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  1200. static uint64 swapIfBigEndian (uint64 value);
  1201. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  1202. static uint16 swapIfLittleEndian (uint16 value);
  1203. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  1204. static uint32 swapIfLittleEndian (uint32 value);
  1205. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  1206. static uint64 swapIfLittleEndian (uint64 value);
  1207. /** Turns 4 bytes into a little-endian integer. */
  1208. static uint32 littleEndianInt (const void* bytes);
  1209. /** Turns 2 bytes into a little-endian integer. */
  1210. static uint16 littleEndianShort (const void* bytes);
  1211. /** Turns 4 bytes into a big-endian integer. */
  1212. static uint32 bigEndianInt (const void* bytes);
  1213. /** Turns 2 bytes into a big-endian integer. */
  1214. static uint16 bigEndianShort (const void* bytes);
  1215. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1216. static int littleEndian24Bit (const char* bytes);
  1217. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1218. static int bigEndian24Bit (const char* bytes);
  1219. /** Copies a 24-bit number to 3 little-endian bytes. */
  1220. static void littleEndian24BitToChars (int value, char* destBytes);
  1221. /** Copies a 24-bit number to 3 big-endian bytes. */
  1222. static void bigEndian24BitToChars (int value, char* destBytes);
  1223. /** Returns true if the current CPU is big-endian. */
  1224. static bool isBigEndian();
  1225. private:
  1226. ByteOrder();
  1227. JUCE_DECLARE_NON_COPYABLE (ByteOrder);
  1228. };
  1229. #if JUCE_USE_INTRINSICS
  1230. #pragma intrinsic (_byteswap_ulong)
  1231. #endif
  1232. inline uint16 ByteOrder::swap (uint16 n)
  1233. {
  1234. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  1235. return static_cast <uint16> (_byteswap_ushort (n));
  1236. #else
  1237. return static_cast <uint16> ((n << 8) | (n >> 8));
  1238. #endif
  1239. }
  1240. inline uint32 ByteOrder::swap (uint32 n)
  1241. {
  1242. #if JUCE_MAC || JUCE_IOS
  1243. return OSSwapInt32 (n);
  1244. #elif JUCE_GCC && JUCE_INTEL
  1245. asm("bswap %%eax" : "=a"(n) : "a"(n));
  1246. return n;
  1247. #elif JUCE_USE_INTRINSICS
  1248. return _byteswap_ulong (n);
  1249. #elif JUCE_MSVC
  1250. __asm {
  1251. mov eax, n
  1252. bswap eax
  1253. mov n, eax
  1254. }
  1255. return n;
  1256. #elif JUCE_ANDROID
  1257. return bswap_32 (n);
  1258. #else
  1259. return (n << 24) | (n >> 24) | ((n & 0xff00) << 8) | ((n & 0xff0000) >> 8);
  1260. #endif
  1261. }
  1262. inline uint64 ByteOrder::swap (uint64 value)
  1263. {
  1264. #if JUCE_MAC || JUCE_IOS
  1265. return OSSwapInt64 (value);
  1266. #elif JUCE_USE_INTRINSICS
  1267. return _byteswap_uint64 (value);
  1268. #else
  1269. return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
  1270. #endif
  1271. }
  1272. #if JUCE_LITTLE_ENDIAN
  1273. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
  1274. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
  1275. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
  1276. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
  1277. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
  1278. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
  1279. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1280. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1281. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1282. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1283. inline bool ByteOrder::isBigEndian() { return false; }
  1284. #else
  1285. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
  1286. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
  1287. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
  1288. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
  1289. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
  1290. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
  1291. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1292. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1293. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1294. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1295. inline bool ByteOrder::isBigEndian() { return true; }
  1296. #endif
  1297. inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1298. inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1299. 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); }
  1300. 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); }
  1301. #endif // __JUCE_BYTEORDER_JUCEHEADER__
  1302. /*** End of inlined file: juce_ByteOrder.h ***/
  1303. /*** Start of inlined file: juce_Logger.h ***/
  1304. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1305. #define __JUCE_LOGGER_JUCEHEADER__
  1306. /*** Start of inlined file: juce_String.h ***/
  1307. #ifndef __JUCE_STRING_JUCEHEADER__
  1308. #define __JUCE_STRING_JUCEHEADER__
  1309. /*** Start of inlined file: juce_CharacterFunctions.h ***/
  1310. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1311. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1312. #if JUCE_ANDROID && ! DOXYGEN
  1313. typedef uint32 juce_wchar;
  1314. #define JUCE_T(stringLiteral) CharPointer_UTF8 (stringLiteral)
  1315. #define JUCE_NATIVE_WCHAR_IS_NOT_UTF32 1
  1316. #elif JUCE_WINDOWS && ! DOXYGEN
  1317. typedef uint32 juce_wchar;
  1318. #define JUCE_T(stringLiteral) L##stringLiteral
  1319. #define JUCE_NATIVE_WCHAR_IS_NOT_UTF32 1
  1320. #else
  1321. /** A platform-independent unicode character type. */
  1322. typedef wchar_t juce_wchar;
  1323. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1324. #endif
  1325. #if ! JUCE_DONT_DEFINE_MACROS
  1326. /** The 'T' macro allows a literal string to be compiled as unicode.
  1327. If you write your string literals in the form T("xyz"), it will be compiled as L"xyz"
  1328. or "xyz", depending on which representation is best for the String class to work with.
  1329. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1330. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1331. the juce/src directory) to avoid defining this macro. See the comments in
  1332. juce_withoutMacros.h for more info.
  1333. */
  1334. #define T(stringLiteral) JUCE_T(stringLiteral)
  1335. #endif
  1336. #undef max
  1337. #undef min
  1338. /**
  1339. A set of methods for manipulating characters and character strings.
  1340. These are defined as wrappers around the basic C string handlers, to provide
  1341. a clean, cross-platform layer, (because various platforms differ in the
  1342. range of C library calls that they provide).
  1343. @see String
  1344. */
  1345. class JUCE_API CharacterFunctions
  1346. {
  1347. public:
  1348. static juce_wchar toUpperCase (juce_wchar character) throw();
  1349. static juce_wchar toLowerCase (juce_wchar character) throw();
  1350. static bool isUpperCase (juce_wchar character) throw();
  1351. static bool isLowerCase (juce_wchar character) throw();
  1352. static bool isWhitespace (char character) throw();
  1353. static bool isWhitespace (juce_wchar character) throw();
  1354. static bool isDigit (char character) throw();
  1355. static bool isDigit (juce_wchar character) throw();
  1356. static bool isLetter (char character) throw();
  1357. static bool isLetter (juce_wchar character) throw();
  1358. static bool isLetterOrDigit (char character) throw();
  1359. static bool isLetterOrDigit (juce_wchar character) throw();
  1360. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legal hex digit. */
  1361. static int getHexDigitValue (juce_wchar digit) throw();
  1362. template <typename CharPointerType>
  1363. static double readDoubleValue (CharPointerType& text) throw()
  1364. {
  1365. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  1366. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  1367. int exponent = 0, decPointIndex = 0, digit = 0;
  1368. int lastDigit = 0, numSignificantDigits = 0;
  1369. bool isNegative = false, digitsFound = false;
  1370. const int maxSignificantDigits = 15 + 2;
  1371. text = text.findEndOfWhitespace();
  1372. juce_wchar c = *text;
  1373. switch (c)
  1374. {
  1375. case '-': isNegative = true; // fall-through..
  1376. case '+': c = *++text;
  1377. }
  1378. switch (c)
  1379. {
  1380. case 'n':
  1381. case 'N':
  1382. if ((text[1] == 'a' || text[1] == 'A') && (text[2] == 'n' || text[2] == 'N'))
  1383. return std::numeric_limits<double>::quiet_NaN();
  1384. break;
  1385. case 'i':
  1386. case 'I':
  1387. if ((text[1] == 'n' || text[1] == 'N') && (text[2] == 'f' || text[2] == 'F'))
  1388. return std::numeric_limits<double>::infinity();
  1389. break;
  1390. }
  1391. for (;;)
  1392. {
  1393. if (text.isDigit())
  1394. {
  1395. lastDigit = digit;
  1396. digit = text.getAndAdvance() - '0';
  1397. digitsFound = true;
  1398. if (decPointIndex != 0)
  1399. exponentAdjustment[1]++;
  1400. if (numSignificantDigits == 0 && digit == 0)
  1401. continue;
  1402. if (++numSignificantDigits > maxSignificantDigits)
  1403. {
  1404. if (digit > 5)
  1405. ++accumulator [decPointIndex];
  1406. else if (digit == 5 && (lastDigit & 1) != 0)
  1407. ++accumulator [decPointIndex];
  1408. if (decPointIndex > 0)
  1409. exponentAdjustment[1]--;
  1410. else
  1411. exponentAdjustment[0]++;
  1412. while (text.isDigit())
  1413. {
  1414. ++text;
  1415. if (decPointIndex == 0)
  1416. exponentAdjustment[0]++;
  1417. }
  1418. }
  1419. else
  1420. {
  1421. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  1422. if (accumulator [decPointIndex] > maxAccumulatorValue)
  1423. {
  1424. result [decPointIndex] = mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  1425. + accumulator [decPointIndex];
  1426. accumulator [decPointIndex] = 0;
  1427. exponentAccumulator [decPointIndex] = 0;
  1428. }
  1429. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  1430. exponentAccumulator [decPointIndex]++;
  1431. }
  1432. }
  1433. else if (decPointIndex == 0 && *text == '.')
  1434. {
  1435. ++text;
  1436. decPointIndex = 1;
  1437. if (numSignificantDigits > maxSignificantDigits)
  1438. {
  1439. while (text.isDigit())
  1440. ++text;
  1441. break;
  1442. }
  1443. }
  1444. else
  1445. {
  1446. break;
  1447. }
  1448. }
  1449. result[0] = mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  1450. if (decPointIndex != 0)
  1451. result[1] = mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  1452. c = *text;
  1453. if ((c == 'e' || c == 'E') && digitsFound)
  1454. {
  1455. bool negativeExponent = false;
  1456. switch (*++text)
  1457. {
  1458. case '-': negativeExponent = true; // fall-through..
  1459. case '+': ++text;
  1460. }
  1461. while (text.isDigit())
  1462. exponent = (exponent * 10) + (text.getAndAdvance() - '0');
  1463. if (negativeExponent)
  1464. exponent = -exponent;
  1465. }
  1466. double r = mulexp10 (result[0], exponent + exponentAdjustment[0]);
  1467. if (decPointIndex != 0)
  1468. r += mulexp10 (result[1], exponent - exponentAdjustment[1]);
  1469. return isNegative ? -r : r;
  1470. }
  1471. template <typename CharPointerType>
  1472. static double getDoubleValue (const CharPointerType& text) throw()
  1473. {
  1474. CharPointerType t (text);
  1475. return readDoubleValue (t);
  1476. }
  1477. template <typename IntType, typename CharPointerType>
  1478. static IntType getIntValue (const CharPointerType& text) throw()
  1479. {
  1480. IntType v = 0;
  1481. CharPointerType s (text.findEndOfWhitespace());
  1482. const bool isNeg = *s == '-';
  1483. if (isNeg)
  1484. ++s;
  1485. for (;;)
  1486. {
  1487. const juce_wchar c = s.getAndAdvance();
  1488. if (c >= '0' && c <= '9')
  1489. v = v * 10 + (IntType) (c - '0');
  1490. else
  1491. break;
  1492. }
  1493. return isNeg ? -v : v;
  1494. }
  1495. static int ftime (char* dest, int maxChars, const char* format, const struct tm* tm) throw();
  1496. static int ftime (juce_wchar* dest, int maxChars, const juce_wchar* format, const struct tm* tm) throw();
  1497. template <typename CharPointerType>
  1498. static size_t lengthUpTo (const CharPointerType& text, const size_t maxCharsToCount) throw()
  1499. {
  1500. size_t len = 0;
  1501. CharPointerType t (text);
  1502. while (len < maxCharsToCount && t.getAndAdvance() != 0)
  1503. ++len;
  1504. return len;
  1505. }
  1506. template <typename DestCharPointerType, typename SrcCharPointerType>
  1507. static void copyAll (DestCharPointerType& dest, SrcCharPointerType src) throw()
  1508. {
  1509. for (;;)
  1510. {
  1511. const juce_wchar c = src.getAndAdvance();
  1512. if (c == 0)
  1513. break;
  1514. dest.write (c);
  1515. }
  1516. dest.writeNull();
  1517. }
  1518. template <typename DestCharPointerType, typename SrcCharPointerType>
  1519. static int copyWithDestByteLimit (DestCharPointerType& dest, SrcCharPointerType src, int maxBytes) throw()
  1520. {
  1521. int numBytesDone = 0;
  1522. maxBytes -= sizeof (typename DestCharPointerType::CharType); // (allow for a terminating null)
  1523. for (;;)
  1524. {
  1525. const juce_wchar c = src.getAndAdvance();
  1526. const int bytesNeeded = (int) DestCharPointerType::getBytesRequiredFor (c);
  1527. maxBytes -= bytesNeeded;
  1528. if (c == 0 || maxBytes < 0)
  1529. break;
  1530. numBytesDone += bytesNeeded;
  1531. dest.write (c);
  1532. }
  1533. dest.writeNull();
  1534. return numBytesDone;
  1535. }
  1536. template <typename DestCharPointerType, typename SrcCharPointerType>
  1537. static void copyWithCharLimit (DestCharPointerType& dest, SrcCharPointerType src, int maxChars) throw()
  1538. {
  1539. while (--maxChars > 0)
  1540. {
  1541. const juce_wchar c = src.getAndAdvance();
  1542. if (c == 0)
  1543. break;
  1544. dest.write (c);
  1545. }
  1546. dest.writeNull();
  1547. }
  1548. template <typename CharPointerType1, typename CharPointerType2>
  1549. static int compare (CharPointerType1 s1, CharPointerType2 s2) throw()
  1550. {
  1551. for (;;)
  1552. {
  1553. const int c1 = (int) s1.getAndAdvance();
  1554. const int c2 = (int) s2.getAndAdvance();
  1555. const int diff = c1 - c2;
  1556. if (diff != 0)
  1557. return diff < 0 ? -1 : 1;
  1558. else if (c1 == 0)
  1559. break;
  1560. }
  1561. return 0;
  1562. }
  1563. template <typename CharPointerType1, typename CharPointerType2>
  1564. static int compareUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) throw()
  1565. {
  1566. while (--maxChars >= 0)
  1567. {
  1568. const int c1 = (int) s1.getAndAdvance();
  1569. const int c2 = (int) s2.getAndAdvance();
  1570. const int diff = c1 - c2;
  1571. if (diff != 0)
  1572. return diff < 0 ? -1 : 1;
  1573. else if (c1 == 0)
  1574. break;
  1575. }
  1576. return 0;
  1577. }
  1578. template <typename CharPointerType1, typename CharPointerType2>
  1579. static int compareIgnoreCase (CharPointerType1 s1, CharPointerType2 s2) throw()
  1580. {
  1581. for (;;)
  1582. {
  1583. int c1 = s1.toUpperCase();
  1584. int c2 = s2.toUpperCase();
  1585. ++s1;
  1586. ++s2;
  1587. const int diff = c1 - c2;
  1588. if (diff != 0)
  1589. return diff < 0 ? -1 : 1;
  1590. else if (c1 == 0)
  1591. break;
  1592. }
  1593. return 0;
  1594. }
  1595. template <typename CharPointerType1, typename CharPointerType2>
  1596. static int compareIgnoreCaseUpTo (CharPointerType1 s1, CharPointerType2 s2, int maxChars) throw()
  1597. {
  1598. while (--maxChars >= 0)
  1599. {
  1600. int c1 = s1.toUpperCase();
  1601. int c2 = s2.toUpperCase();
  1602. ++s1;
  1603. ++s2;
  1604. const int diff = c1 - c2;
  1605. if (diff != 0)
  1606. return diff < 0 ? -1 : 1;
  1607. else if (c1 == 0)
  1608. break;
  1609. }
  1610. return 0;
  1611. }
  1612. template <typename CharPointerType1, typename CharPointerType2>
  1613. static int indexOf (CharPointerType1 haystack, const CharPointerType2& needle) throw()
  1614. {
  1615. int index = 0;
  1616. const int needleLength = (int) needle.length();
  1617. for (;;)
  1618. {
  1619. if (haystack.compareUpTo (needle, needleLength) == 0)
  1620. return index;
  1621. if (haystack.getAndAdvance() == 0)
  1622. return -1;
  1623. ++index;
  1624. }
  1625. }
  1626. template <typename Type>
  1627. static int indexOfChar (Type text, const juce_wchar charToFind) throw()
  1628. {
  1629. int i = 0;
  1630. while (! text.isEmpty())
  1631. {
  1632. if (text.getAndAdvance() == charToFind)
  1633. return i;
  1634. ++i;
  1635. }
  1636. return -1;
  1637. }
  1638. template <typename Type>
  1639. static int indexOfCharIgnoreCase (Type text, juce_wchar charToFind) throw()
  1640. {
  1641. charToFind = CharacterFunctions::toLowerCase (charToFind);
  1642. int i = 0;
  1643. while (! text.isEmpty())
  1644. {
  1645. if (text.toLowerCase() == charToFind)
  1646. return i;
  1647. ++text;
  1648. ++i;
  1649. }
  1650. return -1;
  1651. }
  1652. template <typename Type>
  1653. static Type findEndOfWhitespace (const Type& text) throw()
  1654. {
  1655. Type p (text);
  1656. while (p.isWhitespace())
  1657. ++p;
  1658. return p;
  1659. }
  1660. private:
  1661. static double mulexp10 (const double value, int exponent) throw();
  1662. };
  1663. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1664. /*** End of inlined file: juce_CharacterFunctions.h ***/
  1665. #if JUCE_MSVC
  1666. #pragma warning (push)
  1667. #pragma warning (disable: 4514 4996)
  1668. #endif
  1669. /*** Start of inlined file: juce_Atomic.h ***/
  1670. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1671. #define __JUCE_ATOMIC_JUCEHEADER__
  1672. /**
  1673. Simple class to hold a primitive value and perform atomic operations on it.
  1674. The type used must be a 32 or 64 bit primitive, like an int, pointer, etc.
  1675. There are methods to perform most of the basic atomic operations.
  1676. */
  1677. template <typename Type>
  1678. class Atomic
  1679. {
  1680. public:
  1681. /** Creates a new value, initialised to zero. */
  1682. inline Atomic() throw()
  1683. : value (0)
  1684. {
  1685. }
  1686. /** Creates a new value, with a given initial value. */
  1687. inline Atomic (const Type initialValue) throw()
  1688. : value (initialValue)
  1689. {
  1690. }
  1691. /** Copies another value (atomically). */
  1692. inline Atomic (const Atomic& other) throw()
  1693. : value (other.get())
  1694. {
  1695. }
  1696. /** Destructor. */
  1697. inline ~Atomic() throw()
  1698. {
  1699. // This class can only be used for types which are 32 or 64 bits in size.
  1700. static_jassert (sizeof (Type) == 4 || sizeof (Type) == 8);
  1701. }
  1702. /** Atomically reads and returns the current value. */
  1703. Type get() const throw();
  1704. /** Copies another value onto this one (atomically). */
  1705. inline Atomic& operator= (const Atomic& other) throw() { exchange (other.get()); return *this; }
  1706. /** Copies another value onto this one (atomically). */
  1707. inline Atomic& operator= (const Type newValue) throw() { exchange (newValue); return *this; }
  1708. /** Atomically sets the current value. */
  1709. void set (Type newValue) throw() { exchange (newValue); }
  1710. /** Atomically sets the current value, returning the value that was replaced. */
  1711. Type exchange (Type value) throw();
  1712. /** Atomically adds a number to this value, returning the new value. */
  1713. Type operator+= (Type amountToAdd) throw();
  1714. /** Atomically subtracts a number from this value, returning the new value. */
  1715. Type operator-= (Type amountToSubtract) throw();
  1716. /** Atomically increments this value, returning the new value. */
  1717. Type operator++() throw();
  1718. /** Atomically decrements this value, returning the new value. */
  1719. Type operator--() throw();
  1720. /** Atomically compares this value with a target value, and if it is equal, sets
  1721. this to be equal to a new value.
  1722. This operation is the atomic equivalent of doing this:
  1723. @code
  1724. bool compareAndSetBool (Type newValue, Type valueToCompare)
  1725. {
  1726. if (get() == valueToCompare)
  1727. {
  1728. set (newValue);
  1729. return true;
  1730. }
  1731. return false;
  1732. }
  1733. @endcode
  1734. @returns true if the comparison was true and the value was replaced; false if
  1735. the comparison failed and the value was left unchanged.
  1736. @see compareAndSetValue
  1737. */
  1738. bool compareAndSetBool (Type newValue, Type valueToCompare) throw();
  1739. /** Atomically compares this value with a target value, and if it is equal, sets
  1740. this to be equal to a new value.
  1741. This operation is the atomic equivalent of doing this:
  1742. @code
  1743. Type compareAndSetValue (Type newValue, Type valueToCompare)
  1744. {
  1745. Type oldValue = get();
  1746. if (oldValue == valueToCompare)
  1747. set (newValue);
  1748. return oldValue;
  1749. }
  1750. @endcode
  1751. @returns the old value before it was changed.
  1752. @see compareAndSetBool
  1753. */
  1754. Type compareAndSetValue (Type newValue, Type valueToCompare) throw();
  1755. /** Implements a memory read/write barrier. */
  1756. static void memoryBarrier() throw();
  1757. JUCE_ALIGN(8)
  1758. /** The raw value that this class operates on.
  1759. This is exposed publically in case you need to manipulate it directly
  1760. for performance reasons.
  1761. */
  1762. volatile Type value;
  1763. private:
  1764. static inline Type castFrom32Bit (int32 value) throw() { return *(Type*) &value; }
  1765. static inline Type castFrom64Bit (int64 value) throw() { return *(Type*) &value; }
  1766. static inline int32 castTo32Bit (Type value) throw() { return *(int32*) &value; }
  1767. static inline int64 castTo64Bit (Type value) throw() { return *(int64*) &value; }
  1768. Type operator++ (int); // better to just use pre-increment with atomics..
  1769. Type operator-- (int);
  1770. };
  1771. /*
  1772. The following code is in the header so that the atomics can be inlined where possible...
  1773. */
  1774. #if (JUCE_IOS && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  1775. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  1776. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  1777. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1778. #define JUCE_MAC_ATOMICS_VOLATILE
  1779. #else
  1780. #define JUCE_MAC_ATOMICS_VOLATILE volatile
  1781. #endif
  1782. #if JUCE_PPC || JUCE_IOS
  1783. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  1784. template <typename Type> static Type OSAtomicAdd64Barrier (Type b, JUCE_MAC_ATOMICS_VOLATILE Type* a) throw() { jassertfalse; return *a += b; }
  1785. template <typename Type> static Type OSAtomicIncrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) throw() { jassertfalse; return ++*a; }
  1786. template <typename Type> static Type OSAtomicDecrement64Barrier (JUCE_MAC_ATOMICS_VOLATILE Type* a) throw() { jassertfalse; return --*a; }
  1787. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, JUCE_MAC_ATOMICS_VOLATILE Type* value) throw()
  1788. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  1789. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1790. #endif
  1791. #elif JUCE_GCC
  1792. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  1793. #if JUCE_IOS
  1794. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1 // (on the iphone, the 64-bit ops will compile but not link)
  1795. #endif
  1796. #else
  1797. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  1798. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  1799. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  1800. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  1801. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  1802. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  1803. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  1804. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  1805. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  1806. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  1807. #define juce_MemoryBarrier _ReadWriteBarrier
  1808. #else
  1809. // (these are defined in juce_win32_Threads.cpp)
  1810. long juce_InterlockedExchange (volatile long* a, long b) throw();
  1811. long juce_InterlockedIncrement (volatile long* a) throw();
  1812. long juce_InterlockedDecrement (volatile long* a) throw();
  1813. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw();
  1814. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw();
  1815. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) throw();
  1816. inline void juce_MemoryBarrier() throw() { long x = 0; juce_InterlockedIncrement (&x); }
  1817. #endif
  1818. #if JUCE_64BIT
  1819. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  1820. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  1821. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  1822. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  1823. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  1824. #else
  1825. // None of these atomics are available in a 32-bit Windows build!!
  1826. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a += b; return old; }
  1827. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a = b; return old; }
  1828. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) throw() { jassertfalse; return ++*a; }
  1829. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) throw() { jassertfalse; return --*a; }
  1830. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  1831. #endif
  1832. #endif
  1833. #if JUCE_MSVC
  1834. #pragma warning (push)
  1835. #pragma warning (disable: 4311) // (truncation warning)
  1836. #endif
  1837. template <typename Type>
  1838. inline Type Atomic<Type>::get() const throw()
  1839. {
  1840. #if JUCE_ATOMICS_MAC
  1841. return sizeof (Type) == 4 ? castFrom32Bit ((int32) OSAtomicAdd32Barrier ((int32_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value))
  1842. : castFrom64Bit ((int64) OSAtomicAdd64Barrier ((int64_t) 0, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value));
  1843. #elif JUCE_ATOMICS_WINDOWS
  1844. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchangeAdd ((volatile long*) &value, (long) 0))
  1845. : castFrom64Bit ((int64) juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0));
  1846. #elif JUCE_ANDROID
  1847. return castFrom32Bit (__atomic_cmpxchg (castTo32Bit (value), castTo32Bit (value), (volatile int*) &value));
  1848. #elif JUCE_ATOMICS_GCC
  1849. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_add_and_fetch ((volatile int32*) &value, 0))
  1850. : castFrom64Bit ((int64) __sync_add_and_fetch ((volatile int64*) &value, 0));
  1851. #endif
  1852. }
  1853. template <typename Type>
  1854. inline Type Atomic<Type>::exchange (const Type newValue) throw()
  1855. {
  1856. #if JUCE_ANDROID
  1857. return castFrom32Bit (__atomic_swap (castTo32Bit (newValue), (volatile int*) &value));
  1858. #elif JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  1859. Type currentVal = value;
  1860. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  1861. return currentVal;
  1862. #elif JUCE_ATOMICS_WINDOWS
  1863. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue)))
  1864. : castFrom64Bit ((int64) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue)));
  1865. #endif
  1866. }
  1867. template <typename Type>
  1868. inline Type Atomic<Type>::operator+= (const Type amountToAdd) throw()
  1869. {
  1870. #if JUCE_ATOMICS_MAC
  1871. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32Barrier ((int32_t) castTo32Bit (amountToAdd), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1872. : (Type) OSAtomicAdd64Barrier ((int64_t) amountToAdd, (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1873. #elif JUCE_ATOMICS_WINDOWS
  1874. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  1875. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  1876. #elif JUCE_ANDROID
  1877. for (;;)
  1878. {
  1879. const Type oldValue (value);
  1880. const Type newValue (oldValue + amountToAdd);
  1881. if (compareAndSetBool (newValue, oldValue))
  1882. return newValue;
  1883. }
  1884. #elif JUCE_ATOMICS_GCC
  1885. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  1886. #endif
  1887. }
  1888. template <typename Type>
  1889. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) throw()
  1890. {
  1891. return operator+= (juce_negate (amountToSubtract));
  1892. }
  1893. template <typename Type>
  1894. inline Type Atomic<Type>::operator++() throw()
  1895. {
  1896. #if JUCE_ATOMICS_MAC
  1897. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1898. : (Type) OSAtomicIncrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1899. #elif JUCE_ATOMICS_WINDOWS
  1900. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  1901. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  1902. #elif JUCE_ANDROID
  1903. return (Type) __atomic_inc (&value);
  1904. #elif JUCE_ATOMICS_GCC
  1905. return (Type) __sync_add_and_fetch (&value, 1);
  1906. #endif
  1907. }
  1908. template <typename Type>
  1909. inline Type Atomic<Type>::operator--() throw()
  1910. {
  1911. #if JUCE_ATOMICS_MAC
  1912. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32Barrier ((JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1913. : (Type) OSAtomicDecrement64Barrier ((JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1914. #elif JUCE_ATOMICS_WINDOWS
  1915. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  1916. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  1917. #elif JUCE_ANDROID
  1918. return (Type) __atomic_dec (&value);
  1919. #elif JUCE_ATOMICS_GCC
  1920. return (Type) __sync_add_and_fetch (&value, -1);
  1921. #endif
  1922. }
  1923. template <typename Type>
  1924. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) throw()
  1925. {
  1926. #if JUCE_ATOMICS_MAC
  1927. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) castTo32Bit (valueToCompare), (int32_t) castTo32Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int32_t*) &value)
  1928. : OSAtomicCompareAndSwap64Barrier ((int64_t) castTo64Bit (valueToCompare), (int64_t) castTo64Bit (newValue), (JUCE_MAC_ATOMICS_VOLATILE int64_t*) &value);
  1929. #elif JUCE_ATOMICS_WINDOWS || JUCE_ANDROID
  1930. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  1931. #elif JUCE_ATOMICS_GCC
  1932. return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))
  1933. : __sync_bool_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue));
  1934. #endif
  1935. }
  1936. template <typename Type>
  1937. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) throw()
  1938. {
  1939. #if JUCE_ATOMICS_MAC
  1940. for (;;) // Annoying workaround for OSX only having a bool CAS operation..
  1941. {
  1942. if (compareAndSetBool (newValue, valueToCompare))
  1943. return valueToCompare;
  1944. const Type result = value;
  1945. if (result != valueToCompare)
  1946. return result;
  1947. }
  1948. #elif JUCE_ATOMICS_WINDOWS
  1949. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare)))
  1950. : castFrom64Bit ((int64) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare)));
  1951. #elif JUCE_ANDROID
  1952. return castFrom32Bit (__atomic_cmpxchg (castTo32Bit (valueToCompare), castTo32Bit (newValue), (volatile int*) &value));
  1953. #elif JUCE_ATOMICS_GCC
  1954. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_val_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)))
  1955. : castFrom64Bit ((int64) __sync_val_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)));
  1956. #endif
  1957. }
  1958. template <typename Type>
  1959. inline void Atomic<Type>::memoryBarrier() throw()
  1960. {
  1961. #if JUCE_ATOMICS_MAC
  1962. OSMemoryBarrier();
  1963. #elif JUCE_ATOMICS_GCC
  1964. __sync_synchronize();
  1965. #elif JUCE_ATOMICS_WINDOWS
  1966. juce_MemoryBarrier();
  1967. #endif
  1968. }
  1969. #if JUCE_MSVC
  1970. #pragma warning (pop)
  1971. #endif
  1972. #endif // __JUCE_ATOMIC_JUCEHEADER__
  1973. /*** End of inlined file: juce_Atomic.h ***/
  1974. /*** Start of inlined file: juce_CharPointer_UTF8.h ***/
  1975. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  1976. #define __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  1977. /**
  1978. Wraps a pointer to a null-terminated UTF-8 character string, and provides
  1979. various methods to operate on the data.
  1980. @see CharPointer_UTF16, CharPointer_UTF32
  1981. */
  1982. class CharPointer_UTF8
  1983. {
  1984. public:
  1985. typedef char CharType;
  1986. inline explicit CharPointer_UTF8 (const CharType* const rawPointer) throw()
  1987. : data (const_cast <CharType*> (rawPointer))
  1988. {
  1989. }
  1990. inline CharPointer_UTF8 (const CharPointer_UTF8& other) throw()
  1991. : data (other.data)
  1992. {
  1993. }
  1994. inline CharPointer_UTF8& operator= (const CharPointer_UTF8& other) throw()
  1995. {
  1996. data = other.data;
  1997. return *this;
  1998. }
  1999. inline CharPointer_UTF8& operator= (const CharType* text) throw()
  2000. {
  2001. data = const_cast <CharType*> (text);
  2002. return *this;
  2003. }
  2004. /** This is a pointer comparison, it doesn't compare the actual text. */
  2005. inline bool operator== (const CharPointer_UTF8& other) const throw()
  2006. {
  2007. return data == other.data;
  2008. }
  2009. /** This is a pointer comparison, it doesn't compare the actual text. */
  2010. inline bool operator!= (const CharPointer_UTF8& other) const throw()
  2011. {
  2012. return data == other.data;
  2013. }
  2014. /** Returns the address that this pointer is pointing to. */
  2015. inline CharType* getAddress() const throw() { return data; }
  2016. /** Returns the address that this pointer is pointing to. */
  2017. inline operator const CharType*() const throw() { return data; }
  2018. /** Returns true if this pointer is pointing to a null character. */
  2019. inline bool isEmpty() const throw() { return *data == 0; }
  2020. /** Returns the unicode character that this pointer is pointing to. */
  2021. juce_wchar operator*() const throw()
  2022. {
  2023. const char byte = *data;
  2024. if (byte >= 0)
  2025. return byte;
  2026. uint32 n = (uint32) (uint8) byte;
  2027. uint32 mask = 0x7f;
  2028. uint32 bit = 0x40;
  2029. size_t numExtraValues = 0;
  2030. while ((n & bit) != 0 && bit > 0x10)
  2031. {
  2032. mask >>= 1;
  2033. ++numExtraValues;
  2034. bit >>= 1;
  2035. }
  2036. n &= mask;
  2037. for (size_t i = 1; i <= numExtraValues; ++i)
  2038. {
  2039. const juce_wchar nextByte = data [i];
  2040. if ((nextByte & 0xc0) != 0x80)
  2041. break;
  2042. n <<= 6;
  2043. n |= (nextByte & 0x3f);
  2044. }
  2045. return (juce_wchar) n;
  2046. }
  2047. /** Moves this pointer along to the next character in the string. */
  2048. CharPointer_UTF8& operator++() throw()
  2049. {
  2050. const char n = *data++;
  2051. if (n < 0)
  2052. {
  2053. juce_wchar bit = 0x40;
  2054. while ((n & bit) != 0 && bit > 0x8)
  2055. {
  2056. ++data;
  2057. bit >>= 1;
  2058. }
  2059. }
  2060. return *this;
  2061. }
  2062. /** Returns the character that this pointer is currently pointing to, and then
  2063. advances the pointer to point to the next character. */
  2064. juce_wchar getAndAdvance() throw()
  2065. {
  2066. const char byte = *data++;
  2067. if (byte >= 0)
  2068. return byte;
  2069. uint32 n = (uint32) (uint8) byte;
  2070. uint32 mask = 0x7f;
  2071. uint32 bit = 0x40;
  2072. int numExtraValues = 0;
  2073. while ((n & bit) != 0 && bit > 0x8)
  2074. {
  2075. mask >>= 1;
  2076. ++numExtraValues;
  2077. bit >>= 1;
  2078. }
  2079. n &= mask;
  2080. while (--numExtraValues >= 0)
  2081. {
  2082. const uint32 nextByte = (uint32) (uint8) *data++;
  2083. if ((nextByte & 0xc0) != 0x80)
  2084. break;
  2085. n <<= 6;
  2086. n |= (nextByte & 0x3f);
  2087. }
  2088. return (juce_wchar) n;
  2089. }
  2090. /** Moves this pointer along to the next character in the string. */
  2091. CharPointer_UTF8 operator++ (int) throw()
  2092. {
  2093. CharPointer_UTF8 temp (*this);
  2094. ++*this;
  2095. return temp;
  2096. }
  2097. /** Moves this pointer forwards by the specified number of characters. */
  2098. void operator+= (int numToSkip) throw()
  2099. {
  2100. jassert (numToSkip >= 0);
  2101. while (--numToSkip >= 0)
  2102. ++*this;
  2103. }
  2104. /** Returns the character at a given character index from the start of the string. */
  2105. juce_wchar operator[] (int characterIndex) const throw()
  2106. {
  2107. CharPointer_UTF8 p (*this);
  2108. p += characterIndex;
  2109. return *p;
  2110. }
  2111. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2112. CharPointer_UTF8 operator+ (int numToSkip) const throw()
  2113. {
  2114. CharPointer_UTF8 p (*this);
  2115. p += numToSkip;
  2116. return p;
  2117. }
  2118. /** Returns the number of characters in this string. */
  2119. size_t length() const throw()
  2120. {
  2121. const CharType* d = data;
  2122. size_t count = 0;
  2123. for (;;)
  2124. {
  2125. const int n = *d++;
  2126. if ((n & 0x80) != 0)
  2127. {
  2128. int bit = 0x40;
  2129. while ((n & bit) != 0)
  2130. {
  2131. ++d;
  2132. bit >>= 1;
  2133. if (bit == 0)
  2134. break; // illegal utf-8 sequence
  2135. }
  2136. }
  2137. else if (n == 0)
  2138. break;
  2139. ++count;
  2140. }
  2141. return count;
  2142. }
  2143. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2144. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  2145. {
  2146. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2147. }
  2148. /** Returns the number of bytes that are used to represent this string.
  2149. This includes the terminating null character.
  2150. */
  2151. size_t sizeInBytes() const throw()
  2152. {
  2153. return strlen (data) + 1;
  2154. }
  2155. /** Returns the number of bytes that would be needed to represent the given
  2156. unicode character in this encoding format.
  2157. */
  2158. static size_t getBytesRequiredFor (const juce_wchar charToWrite) throw()
  2159. {
  2160. size_t num = 1;
  2161. const uint32 c = (uint32) charToWrite;
  2162. if (c >= 0x80)
  2163. {
  2164. ++num;
  2165. if (c >= 0x800)
  2166. {
  2167. ++num;
  2168. if (c >= 0x10000)
  2169. ++num;
  2170. }
  2171. }
  2172. return num;
  2173. }
  2174. /** Returns the number of bytes that would be needed to represent the given
  2175. string in this encoding format.
  2176. The value returned does NOT include the terminating null character.
  2177. */
  2178. template <class CharPointer>
  2179. static size_t getBytesRequiredFor (CharPointer text) throw()
  2180. {
  2181. size_t count = 0;
  2182. juce_wchar n;
  2183. while ((n = text.getAndAdvance()) != 0)
  2184. count += getBytesRequiredFor (n);
  2185. return count;
  2186. }
  2187. /** Returns a pointer to the null character that terminates this string. */
  2188. CharPointer_UTF8 findTerminatingNull() const throw()
  2189. {
  2190. return CharPointer_UTF8 (data + strlen (data));
  2191. }
  2192. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2193. void write (const juce_wchar charToWrite) throw()
  2194. {
  2195. const uint32 c = (uint32) charToWrite;
  2196. if (c >= 0x80)
  2197. {
  2198. int numExtraBytes = 1;
  2199. if (c >= 0x800)
  2200. {
  2201. ++numExtraBytes;
  2202. if (c >= 0x10000)
  2203. ++numExtraBytes;
  2204. }
  2205. *data++ = (CharType) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  2206. while (--numExtraBytes >= 0)
  2207. *data++ = (CharType) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  2208. }
  2209. else
  2210. {
  2211. *data++ = (CharType) c;
  2212. }
  2213. }
  2214. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2215. inline void writeNull() const throw()
  2216. {
  2217. *data = 0;
  2218. }
  2219. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2220. template <typename CharPointer>
  2221. void writeAll (const CharPointer& src) throw()
  2222. {
  2223. CharacterFunctions::copyAll (*this, src);
  2224. }
  2225. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2226. void writeAll (const CharPointer_UTF8& src) throw()
  2227. {
  2228. const CharType* s = src.data;
  2229. while ((*data = *s) != 0)
  2230. {
  2231. ++data;
  2232. ++s;
  2233. }
  2234. }
  2235. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2236. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2237. to the destination buffer before stopping.
  2238. */
  2239. template <typename CharPointer>
  2240. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  2241. {
  2242. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2243. }
  2244. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2245. The maxChars parameter specifies the maximum number of characters that can be
  2246. written to the destination buffer before stopping (including the terminating null).
  2247. */
  2248. template <typename CharPointer>
  2249. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  2250. {
  2251. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2252. }
  2253. /** Compares this string with another one. */
  2254. template <typename CharPointer>
  2255. int compare (const CharPointer& other) const throw()
  2256. {
  2257. return CharacterFunctions::compare (*this, other);
  2258. }
  2259. /** Compares this string with another one, up to a specified number of characters. */
  2260. template <typename CharPointer>
  2261. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  2262. {
  2263. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2264. }
  2265. /** Compares this string with another one. */
  2266. template <typename CharPointer>
  2267. int compareIgnoreCase (const CharPointer& other) const throw()
  2268. {
  2269. return CharacterFunctions::compareIgnoreCase (*this, other);
  2270. }
  2271. /** Compares this string with another one. */
  2272. int compareIgnoreCase (const CharPointer_UTF8& other) const throw()
  2273. {
  2274. #if JUCE_WINDOWS
  2275. return stricmp (data, other.data);
  2276. #else
  2277. return strcasecmp (data, other.data);
  2278. #endif
  2279. }
  2280. /** Compares this string with another one, up to a specified number of characters. */
  2281. template <typename CharPointer>
  2282. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  2283. {
  2284. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2285. }
  2286. /** Compares this string with another one, up to a specified number of characters. */
  2287. int compareIgnoreCaseUpTo (const CharPointer_UTF8& other, const int maxChars) const throw()
  2288. {
  2289. #if JUCE_WINDOWS
  2290. return strnicmp (data, other.data, maxChars);
  2291. #else
  2292. return strncasecmp (data, other.data, maxChars);
  2293. #endif
  2294. }
  2295. /** Returns the character index of a substring, or -1 if it isn't found. */
  2296. template <typename CharPointer>
  2297. int indexOf (const CharPointer& stringToFind) const throw()
  2298. {
  2299. return CharacterFunctions::indexOf (*this, stringToFind);
  2300. }
  2301. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2302. int indexOf (const juce_wchar charToFind) const throw()
  2303. {
  2304. return CharacterFunctions::indexOfChar (*this, charToFind);
  2305. }
  2306. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2307. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  2308. {
  2309. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2310. : CharacterFunctions::indexOfChar (*this, charToFind);
  2311. }
  2312. /** Returns true if the first character of this string is whitespace. */
  2313. bool isWhitespace() const throw() { return *data == ' ' || (*data <= 13 && *data >= 9); }
  2314. /** Returns true if the first character of this string is a digit. */
  2315. bool isDigit() const throw() { return *data >= '0' && *data <= '9'; }
  2316. /** Returns true if the first character of this string is a letter. */
  2317. bool isLetter() const throw() { return CharacterFunctions::isLetter (operator*()) != 0; }
  2318. /** Returns true if the first character of this string is a letter or digit. */
  2319. bool isLetterOrDigit() const throw() { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2320. /** Returns true if the first character of this string is upper-case. */
  2321. bool isUpperCase() const throw() { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2322. /** Returns true if the first character of this string is lower-case. */
  2323. bool isLowerCase() const throw() { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2324. /** Returns an upper-case version of the first character of this string. */
  2325. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (operator*()); }
  2326. /** Returns a lower-case version of the first character of this string. */
  2327. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (operator*()); }
  2328. /** Parses this string as a 32-bit integer. */
  2329. int getIntValue32() const throw() { return atoi (data); }
  2330. /** Parses this string as a 64-bit integer. */
  2331. int64 getIntValue64() const throw()
  2332. {
  2333. #if JUCE_LINUX || JUCE_ANDROID
  2334. return atoll (data);
  2335. #elif JUCE_WINDOWS
  2336. return _atoi64 (data);
  2337. #else
  2338. return CharacterFunctions::getIntValue <int64, CharPointer_UTF8> (*this);
  2339. #endif
  2340. }
  2341. /** Parses this string as a floating point double. */
  2342. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  2343. /** Returns the first non-whitespace character in the string. */
  2344. CharPointer_UTF8 findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  2345. /** Returns true if the given unicode character can be represented in this encoding. */
  2346. static bool canRepresent (juce_wchar character) throw()
  2347. {
  2348. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  2349. }
  2350. /** Returns true if this data contains a valid string in this encoding. */
  2351. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2352. {
  2353. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2354. {
  2355. const char byte = *dataToTest;
  2356. if (byte < 0)
  2357. {
  2358. uint32 n = (uint32) (uint8) byte;
  2359. uint32 mask = 0x7f;
  2360. uint32 bit = 0x40;
  2361. int numExtraValues = 0;
  2362. while ((n & bit) != 0)
  2363. {
  2364. if (bit <= 0x10)
  2365. return false;
  2366. mask >>= 1;
  2367. ++numExtraValues;
  2368. bit >>= 1;
  2369. }
  2370. n &= mask;
  2371. while (--numExtraValues >= 0)
  2372. {
  2373. const uint32 nextByte = (uint32) (uint8) *dataToTest++;
  2374. if ((nextByte & 0xc0) != 0x80)
  2375. return false;
  2376. }
  2377. }
  2378. }
  2379. return true;
  2380. }
  2381. /** These values are the byte-order-mark (BOM) values for a UTF-8 stream. */
  2382. enum
  2383. {
  2384. byteOrderMark1 = 0xef,
  2385. byteOrderMark2 = 0xbb,
  2386. byteOrderMark3 = 0xbf
  2387. };
  2388. private:
  2389. CharType* data;
  2390. };
  2391. #endif // __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  2392. /*** End of inlined file: juce_CharPointer_UTF8.h ***/
  2393. /*** Start of inlined file: juce_CharPointer_UTF16.h ***/
  2394. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2395. #define __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2396. /**
  2397. Wraps a pointer to a null-terminated UTF-16 character string, and provides
  2398. various methods to operate on the data.
  2399. @see CharPointer_UTF8, CharPointer_UTF32
  2400. */
  2401. class CharPointer_UTF16
  2402. {
  2403. public:
  2404. #if JUCE_WINDOWS && ! DOXYGEN
  2405. typedef wchar_t CharType;
  2406. #else
  2407. typedef int16 CharType;
  2408. #endif
  2409. inline explicit CharPointer_UTF16 (const CharType* const rawPointer) throw()
  2410. : data (const_cast <CharType*> (rawPointer))
  2411. {
  2412. }
  2413. inline CharPointer_UTF16 (const CharPointer_UTF16& other) throw()
  2414. : data (other.data)
  2415. {
  2416. }
  2417. inline CharPointer_UTF16& operator= (const CharPointer_UTF16& other) throw()
  2418. {
  2419. data = other.data;
  2420. return *this;
  2421. }
  2422. inline CharPointer_UTF16& operator= (const CharType* text) throw()
  2423. {
  2424. data = const_cast <CharType*> (text);
  2425. return *this;
  2426. }
  2427. /** This is a pointer comparison, it doesn't compare the actual text. */
  2428. inline bool operator== (const CharPointer_UTF16& other) const throw()
  2429. {
  2430. return data == other.data;
  2431. }
  2432. /** This is a pointer comparison, it doesn't compare the actual text. */
  2433. inline bool operator!= (const CharPointer_UTF16& other) const throw()
  2434. {
  2435. return data == other.data;
  2436. }
  2437. /** Returns the address that this pointer is pointing to. */
  2438. inline CharType* getAddress() const throw() { return data; }
  2439. /** Returns the address that this pointer is pointing to. */
  2440. inline operator const CharType*() const throw() { return data; }
  2441. /** Returns true if this pointer is pointing to a null character. */
  2442. inline bool isEmpty() const throw() { return *data == 0; }
  2443. /** Returns the unicode character that this pointer is pointing to. */
  2444. juce_wchar operator*() const throw()
  2445. {
  2446. uint32 n = (uint32) (uint16) *data;
  2447. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) data[1]) >= 0xdc00)
  2448. n = 0x10000 + (((n - 0xd800) << 10) | (((uint32) (uint16) data[1]) - 0xdc00));
  2449. return (juce_wchar) n;
  2450. }
  2451. /** Moves this pointer along to the next character in the string. */
  2452. CharPointer_UTF16& operator++() throw()
  2453. {
  2454. const juce_wchar n = *data++;
  2455. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2456. ++data;
  2457. return *this;
  2458. }
  2459. /** Returns the character that this pointer is currently pointing to, and then
  2460. advances the pointer to point to the next character. */
  2461. juce_wchar getAndAdvance() throw()
  2462. {
  2463. uint32 n = (uint32) (uint16) *data++;
  2464. if (n >= 0xd800 && n <= 0xdfff && ((uint32) (uint16) *data) >= 0xdc00)
  2465. n = 0x10000 + ((((n - 0xd800) << 10) | (((uint32) (uint16) *data++) - 0xdc00)));
  2466. return (juce_wchar) n;
  2467. }
  2468. /** Moves this pointer along to the next character in the string. */
  2469. CharPointer_UTF16 operator++ (int) throw()
  2470. {
  2471. CharPointer_UTF16 temp (*this);
  2472. ++*this;
  2473. return temp;
  2474. }
  2475. /** Moves this pointer forwards by the specified number of characters. */
  2476. void operator+= (int numToSkip) throw()
  2477. {
  2478. jassert (numToSkip >= 0);
  2479. while (--numToSkip >= 0)
  2480. ++*this;
  2481. }
  2482. /** Returns the character at a given character index from the start of the string. */
  2483. juce_wchar operator[] (const int characterIndex) const throw()
  2484. {
  2485. CharPointer_UTF16 p (*this);
  2486. p += characterIndex;
  2487. return *p;
  2488. }
  2489. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2490. CharPointer_UTF16 operator+ (const int numToSkip) const throw()
  2491. {
  2492. CharPointer_UTF16 p (*this);
  2493. p += numToSkip;
  2494. return p;
  2495. }
  2496. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2497. void write (juce_wchar charToWrite) throw()
  2498. {
  2499. if (charToWrite >= 0x10000)
  2500. {
  2501. charToWrite -= 0x10000;
  2502. *data++ = (CharType) (0xd800 + (charToWrite >> 10));
  2503. *data++ = (CharType) (0xdc00 + (charToWrite & 0x3ff));
  2504. }
  2505. else
  2506. {
  2507. *data++ = (CharType) charToWrite;
  2508. }
  2509. }
  2510. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2511. inline void writeNull() const throw()
  2512. {
  2513. *data = 0;
  2514. }
  2515. /** Returns the number of characters in this string. */
  2516. size_t length() const throw()
  2517. {
  2518. const CharType* d = data;
  2519. size_t count = 0;
  2520. for (;;)
  2521. {
  2522. const int n = *d++;
  2523. if (n >= 0xd800 && n <= 0xdfff)
  2524. {
  2525. if (*d++ == 0)
  2526. break;
  2527. }
  2528. else if (n == 0)
  2529. break;
  2530. ++count;
  2531. }
  2532. return count;
  2533. }
  2534. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2535. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  2536. {
  2537. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2538. }
  2539. /** Returns the number of bytes that are used to represent this string.
  2540. This includes the terminating null character.
  2541. */
  2542. size_t sizeInBytes() const throw()
  2543. {
  2544. return sizeof (CharType) * (findNullIndex (data) + 1);
  2545. }
  2546. /** Returns the number of bytes that would be needed to represent the given
  2547. unicode character in this encoding format.
  2548. */
  2549. static size_t getBytesRequiredFor (const juce_wchar charToWrite) throw()
  2550. {
  2551. return (charToWrite >= 0x10000) ? (sizeof (CharType) * 2) : sizeof (CharType);
  2552. }
  2553. /** Returns the number of bytes that would be needed to represent the given
  2554. string in this encoding format.
  2555. The value returned does NOT include the terminating null character.
  2556. */
  2557. template <class CharPointer>
  2558. static size_t getBytesRequiredFor (CharPointer text) throw()
  2559. {
  2560. size_t count = 0;
  2561. juce_wchar n;
  2562. while ((n = text.getAndAdvance()) != 0)
  2563. count += getBytesRequiredFor (n);
  2564. return count;
  2565. }
  2566. /** Returns a pointer to the null character that terminates this string. */
  2567. CharPointer_UTF16 findTerminatingNull() const throw()
  2568. {
  2569. const CharType* t = data;
  2570. while (*t != 0)
  2571. ++t;
  2572. return CharPointer_UTF16 (t);
  2573. }
  2574. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2575. template <typename CharPointer>
  2576. void writeAll (const CharPointer& src) throw()
  2577. {
  2578. CharacterFunctions::copyAll (*this, src);
  2579. }
  2580. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2581. void writeAll (const CharPointer_UTF16& src) throw()
  2582. {
  2583. const CharType* s = src.data;
  2584. while ((*data = *s) != 0)
  2585. {
  2586. ++data;
  2587. ++s;
  2588. }
  2589. }
  2590. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2591. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2592. to the destination buffer before stopping.
  2593. */
  2594. template <typename CharPointer>
  2595. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  2596. {
  2597. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2598. }
  2599. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2600. The maxChars parameter specifies the maximum number of characters that can be
  2601. written to the destination buffer before stopping (including the terminating null).
  2602. */
  2603. template <typename CharPointer>
  2604. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  2605. {
  2606. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2607. }
  2608. /** Compares this string with another one. */
  2609. template <typename CharPointer>
  2610. int compare (const CharPointer& other) const throw()
  2611. {
  2612. return CharacterFunctions::compare (*this, other);
  2613. }
  2614. /** Compares this string with another one, up to a specified number of characters. */
  2615. template <typename CharPointer>
  2616. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  2617. {
  2618. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2619. }
  2620. /** Compares this string with another one. */
  2621. template <typename CharPointer>
  2622. int compareIgnoreCase (const CharPointer& other) const throw()
  2623. {
  2624. return CharacterFunctions::compareIgnoreCase (*this, other);
  2625. }
  2626. /** Compares this string with another one, up to a specified number of characters. */
  2627. template <typename CharPointer>
  2628. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  2629. {
  2630. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2631. }
  2632. #if JUCE_WINDOWS && ! DOXYGEN
  2633. int compareIgnoreCase (const CharPointer_UTF16& other) const throw()
  2634. {
  2635. return _wcsicmp (data, other.data);
  2636. }
  2637. int compareIgnoreCaseUpTo (const CharPointer_UTF16& other, int maxChars) const throw()
  2638. {
  2639. return _wcsnicmp (data, other.data, maxChars);
  2640. }
  2641. int indexOf (const CharPointer_UTF16& stringToFind) const throw()
  2642. {
  2643. const CharType* const t = wcsstr (data, stringToFind.getAddress());
  2644. return t == 0 ? -1 : (int) (t - data);
  2645. }
  2646. #endif
  2647. /** Returns the character index of a substring, or -1 if it isn't found. */
  2648. template <typename CharPointer>
  2649. int indexOf (const CharPointer& stringToFind) const throw()
  2650. {
  2651. return CharacterFunctions::indexOf (*this, stringToFind);
  2652. }
  2653. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2654. int indexOf (const juce_wchar charToFind) const throw()
  2655. {
  2656. return CharacterFunctions::indexOfChar (*this, charToFind);
  2657. }
  2658. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2659. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  2660. {
  2661. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2662. : CharacterFunctions::indexOfChar (*this, charToFind);
  2663. }
  2664. /** Returns true if the first character of this string is whitespace. */
  2665. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (operator*()) != 0; }
  2666. /** Returns true if the first character of this string is a digit. */
  2667. bool isDigit() const throw() { return CharacterFunctions::isDigit (operator*()) != 0; }
  2668. /** Returns true if the first character of this string is a letter. */
  2669. bool isLetter() const throw() { return CharacterFunctions::isLetter (operator*()) != 0; }
  2670. /** Returns true if the first character of this string is a letter or digit. */
  2671. bool isLetterOrDigit() const throw() { return CharacterFunctions::isLetterOrDigit (operator*()) != 0; }
  2672. /** Returns true if the first character of this string is upper-case. */
  2673. bool isUpperCase() const throw() { return CharacterFunctions::isUpperCase (operator*()) != 0; }
  2674. /** Returns true if the first character of this string is lower-case. */
  2675. bool isLowerCase() const throw() { return CharacterFunctions::isLowerCase (operator*()) != 0; }
  2676. /** Returns an upper-case version of the first character of this string. */
  2677. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (operator*()); }
  2678. /** Returns a lower-case version of the first character of this string. */
  2679. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (operator*()); }
  2680. /** Parses this string as a 32-bit integer. */
  2681. int getIntValue32() const throw()
  2682. {
  2683. #if JUCE_WINDOWS
  2684. return _wtoi (data);
  2685. #else
  2686. return CharacterFunctions::getIntValue <int, CharPointer_UTF16> (*this);
  2687. #endif
  2688. }
  2689. /** Parses this string as a 64-bit integer. */
  2690. int64 getIntValue64() const throw()
  2691. {
  2692. #if JUCE_WINDOWS
  2693. return _wtoi64 (data);
  2694. #else
  2695. return CharacterFunctions::getIntValue <int64, CharPointer_UTF16> (*this);
  2696. #endif
  2697. }
  2698. /** Parses this string as a floating point double. */
  2699. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  2700. /** Returns the first non-whitespace character in the string. */
  2701. CharPointer_UTF16 findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  2702. /** Returns true if the given unicode character can be represented in this encoding. */
  2703. static bool canRepresent (juce_wchar character) throw()
  2704. {
  2705. return ((unsigned int) character) < (unsigned int) 0x10ffff
  2706. && (((unsigned int) character) < 0xd800 || ((unsigned int) character) > 0xdfff);
  2707. }
  2708. /** Returns true if this data contains a valid string in this encoding. */
  2709. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  2710. {
  2711. maxBytesToRead /= sizeof (CharType);
  2712. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  2713. {
  2714. const uint32 n = (uint32) (uint16) *dataToTest++;
  2715. if (n >= 0xd800)
  2716. {
  2717. if (n > 0x10ffff)
  2718. return false;
  2719. if (n <= 0xdfff)
  2720. {
  2721. if (n > 0xdc00)
  2722. return false;
  2723. const uint32 nextChar = (uint32) (uint16) *dataToTest++;
  2724. if (nextChar < 0xdc00 || nextChar > 0xdfff)
  2725. return false;
  2726. }
  2727. }
  2728. }
  2729. return true;
  2730. }
  2731. /** These values are the byte-order-mark (BOM) values for a UTF-16 stream. */
  2732. enum
  2733. {
  2734. byteOrderMarkBE1 = 0xfe,
  2735. byteOrderMarkBE2 = 0xff,
  2736. byteOrderMarkLE1 = 0xff,
  2737. byteOrderMarkLE2 = 0xfe
  2738. };
  2739. private:
  2740. CharType* data;
  2741. static int findNullIndex (const CharType* const t) throw()
  2742. {
  2743. int n = 0;
  2744. while (t[n] != 0)
  2745. ++n;
  2746. return n;
  2747. }
  2748. };
  2749. #endif // __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  2750. /*** End of inlined file: juce_CharPointer_UTF16.h ***/
  2751. /*** Start of inlined file: juce_CharPointer_UTF32.h ***/
  2752. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2753. #define __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  2754. /**
  2755. Wraps a pointer to a null-terminated UTF-32 character string, and provides
  2756. various methods to operate on the data.
  2757. @see CharPointer_UTF8, CharPointer_UTF16
  2758. */
  2759. class CharPointer_UTF32
  2760. {
  2761. public:
  2762. typedef juce_wchar CharType;
  2763. inline explicit CharPointer_UTF32 (const CharType* const rawPointer) throw()
  2764. : data (const_cast <CharType*> (rawPointer))
  2765. {
  2766. }
  2767. inline CharPointer_UTF32 (const CharPointer_UTF32& other) throw()
  2768. : data (other.data)
  2769. {
  2770. }
  2771. inline CharPointer_UTF32& operator= (const CharPointer_UTF32& other) throw()
  2772. {
  2773. data = other.data;
  2774. return *this;
  2775. }
  2776. inline CharPointer_UTF32& operator= (const CharType* text) throw()
  2777. {
  2778. data = const_cast <CharType*> (text);
  2779. return *this;
  2780. }
  2781. /** This is a pointer comparison, it doesn't compare the actual text. */
  2782. inline bool operator== (const CharPointer_UTF32& other) const throw()
  2783. {
  2784. return data == other.data;
  2785. }
  2786. /** This is a pointer comparison, it doesn't compare the actual text. */
  2787. inline bool operator!= (const CharPointer_UTF32& other) const throw()
  2788. {
  2789. return data == other.data;
  2790. }
  2791. /** Returns the address that this pointer is pointing to. */
  2792. inline CharType* getAddress() const throw() { return data; }
  2793. /** Returns the address that this pointer is pointing to. */
  2794. inline operator const CharType*() const throw() { return data; }
  2795. /** Returns true if this pointer is pointing to a null character. */
  2796. inline bool isEmpty() const throw() { return *data == 0; }
  2797. /** Returns the unicode character that this pointer is pointing to. */
  2798. inline juce_wchar operator*() const throw() { return *data; }
  2799. /** Moves this pointer along to the next character in the string. */
  2800. inline CharPointer_UTF32& operator++() throw()
  2801. {
  2802. ++data;
  2803. return *this;
  2804. }
  2805. /** Moves this pointer to the previous character in the string. */
  2806. inline CharPointer_UTF32& operator--() throw()
  2807. {
  2808. --data;
  2809. return *this;
  2810. }
  2811. /** Returns the character that this pointer is currently pointing to, and then
  2812. advances the pointer to point to the next character. */
  2813. inline juce_wchar getAndAdvance() throw() { return *data++; }
  2814. /** Moves this pointer along to the next character in the string. */
  2815. CharPointer_UTF32 operator++ (int) throw()
  2816. {
  2817. CharPointer_UTF32 temp (*this);
  2818. ++data;
  2819. return temp;
  2820. }
  2821. /** Moves this pointer forwards by the specified number of characters. */
  2822. inline void operator+= (const int numToSkip) throw()
  2823. {
  2824. data += numToSkip;
  2825. }
  2826. inline void operator-= (const int numToSkip) throw()
  2827. {
  2828. data -= numToSkip;
  2829. }
  2830. /** Returns the character at a given character index from the start of the string. */
  2831. inline juce_wchar& operator[] (const int characterIndex) const throw()
  2832. {
  2833. return data [characterIndex];
  2834. }
  2835. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  2836. CharPointer_UTF32 operator+ (const int numToSkip) const throw()
  2837. {
  2838. return CharPointer_UTF32 (data + numToSkip);
  2839. }
  2840. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  2841. CharPointer_UTF32 operator- (const int numToSkip) const throw()
  2842. {
  2843. return CharPointer_UTF32 (data - numToSkip);
  2844. }
  2845. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  2846. inline void write (const juce_wchar charToWrite) throw()
  2847. {
  2848. *data++ = charToWrite;
  2849. }
  2850. inline void replaceChar (const juce_wchar newChar) throw()
  2851. {
  2852. *data = newChar;
  2853. }
  2854. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  2855. inline void writeNull() const throw()
  2856. {
  2857. *data = 0;
  2858. }
  2859. /** Returns the number of characters in this string. */
  2860. size_t length() const throw()
  2861. {
  2862. #if JUCE_NATIVE_WCHAR_IS_NOT_UTF32
  2863. size_t n = 0;
  2864. while (data[n] != 0)
  2865. ++n;
  2866. return n;
  2867. #else
  2868. return wcslen (data);
  2869. #endif
  2870. }
  2871. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  2872. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  2873. {
  2874. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  2875. }
  2876. /** Returns the number of bytes that are used to represent this string.
  2877. This includes the terminating null character.
  2878. */
  2879. size_t sizeInBytes() const throw()
  2880. {
  2881. return sizeof (CharType) * (length() + 1);
  2882. }
  2883. /** Returns the number of bytes that would be needed to represent the given
  2884. unicode character in this encoding format.
  2885. */
  2886. static inline size_t getBytesRequiredFor (const juce_wchar) throw()
  2887. {
  2888. return sizeof (CharType);
  2889. }
  2890. /** Returns the number of bytes that would be needed to represent the given
  2891. string in this encoding format.
  2892. The value returned does NOT include the terminating null character.
  2893. */
  2894. template <class CharPointer>
  2895. static size_t getBytesRequiredFor (const CharPointer& text) throw()
  2896. {
  2897. return sizeof (CharType) * text.length();
  2898. }
  2899. /** Returns a pointer to the null character that terminates this string. */
  2900. CharPointer_UTF32 findTerminatingNull() const throw()
  2901. {
  2902. return CharPointer_UTF32 (data + length());
  2903. }
  2904. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2905. template <typename CharPointer>
  2906. void writeAll (const CharPointer& src) throw()
  2907. {
  2908. CharacterFunctions::copyAll (*this, src);
  2909. }
  2910. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  2911. void writeAll (const CharPointer_UTF32& src) throw()
  2912. {
  2913. const CharType* s = src.data;
  2914. while ((*data = *s) != 0)
  2915. {
  2916. ++data;
  2917. ++s;
  2918. }
  2919. }
  2920. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2921. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  2922. to the destination buffer before stopping.
  2923. */
  2924. template <typename CharPointer>
  2925. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  2926. {
  2927. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  2928. }
  2929. /** Copies a source string to this pointer, advancing this pointer as it goes.
  2930. The maxChars parameter specifies the maximum number of characters that can be
  2931. written to the destination buffer before stopping (including the terminating null).
  2932. */
  2933. template <typename CharPointer>
  2934. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  2935. {
  2936. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  2937. }
  2938. /** Compares this string with another one. */
  2939. template <typename CharPointer>
  2940. int compare (const CharPointer& other) const throw()
  2941. {
  2942. return CharacterFunctions::compare (*this, other);
  2943. }
  2944. #if ! JUCE_NATIVE_WCHAR_IS_NOT_UTF32
  2945. /** Compares this string with another one. */
  2946. int compare (const CharPointer_UTF32& other) const throw()
  2947. {
  2948. return wcscmp (data, other.data);
  2949. }
  2950. #endif
  2951. /** Compares this string with another one, up to a specified number of characters. */
  2952. template <typename CharPointer>
  2953. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  2954. {
  2955. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  2956. }
  2957. /** Compares this string with another one. */
  2958. template <typename CharPointer>
  2959. int compareIgnoreCase (const CharPointer& other) const
  2960. {
  2961. return CharacterFunctions::compareIgnoreCase (*this, other);
  2962. }
  2963. /** Compares this string with another one, up to a specified number of characters. */
  2964. template <typename CharPointer>
  2965. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  2966. {
  2967. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  2968. }
  2969. /** Returns the character index of a substring, or -1 if it isn't found. */
  2970. template <typename CharPointer>
  2971. int indexOf (const CharPointer& stringToFind) const throw()
  2972. {
  2973. return CharacterFunctions::indexOf (*this, stringToFind);
  2974. }
  2975. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2976. int indexOf (const juce_wchar charToFind) const throw()
  2977. {
  2978. int i = 0;
  2979. while (data[i] != 0)
  2980. {
  2981. if (data[i] == charToFind)
  2982. return i;
  2983. ++i;
  2984. }
  2985. return -1;
  2986. }
  2987. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  2988. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  2989. {
  2990. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  2991. : CharacterFunctions::indexOfChar (*this, charToFind);
  2992. }
  2993. /** Returns true if the first character of this string is whitespace. */
  2994. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  2995. /** Returns true if the first character of this string is a digit. */
  2996. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  2997. /** Returns true if the first character of this string is a letter. */
  2998. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  2999. /** Returns true if the first character of this string is a letter or digit. */
  3000. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3001. /** Returns true if the first character of this string is upper-case. */
  3002. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3003. /** Returns true if the first character of this string is lower-case. */
  3004. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3005. /** Returns an upper-case version of the first character of this string. */
  3006. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (*data); }
  3007. /** Returns a lower-case version of the first character of this string. */
  3008. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (*data); }
  3009. /** Parses this string as a 32-bit integer. */
  3010. int getIntValue32() const throw() { return CharacterFunctions::getIntValue <int, CharPointer_UTF32> (*this); }
  3011. /** Parses this string as a 64-bit integer. */
  3012. int64 getIntValue64() const throw() { return CharacterFunctions::getIntValue <int64, CharPointer_UTF32> (*this); }
  3013. /** Parses this string as a floating point double. */
  3014. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  3015. /** Returns the first non-whitespace character in the string. */
  3016. CharPointer_UTF32 findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  3017. /** Returns true if the given unicode character can be represented in this encoding. */
  3018. static bool canRepresent (juce_wchar character) throw()
  3019. {
  3020. return ((unsigned int) character) < (unsigned int) 0x10ffff;
  3021. }
  3022. /** Returns true if this data contains a valid string in this encoding. */
  3023. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3024. {
  3025. maxBytesToRead /= sizeof (CharType);
  3026. while (--maxBytesToRead >= 0 && *dataToTest != 0)
  3027. if (! canRepresent (*dataToTest++))
  3028. return false;
  3029. return true;
  3030. }
  3031. /** Atomically swaps this pointer for a new value, returning the previous value. */
  3032. CharPointer_UTF32 atomicSwap (const CharPointer_UTF32& newValue)
  3033. {
  3034. return CharPointer_UTF32 (reinterpret_cast <Atomic<CharType*>&> (data).exchange (newValue.data));
  3035. }
  3036. private:
  3037. CharType* data;
  3038. };
  3039. #endif // __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  3040. /*** End of inlined file: juce_CharPointer_UTF32.h ***/
  3041. /*** Start of inlined file: juce_CharPointer_ASCII.h ***/
  3042. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3043. #define __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3044. /**
  3045. Wraps a pointer to a null-terminated ASCII character string, and provides
  3046. various methods to operate on the data.
  3047. A valid ASCII string is assumed to not contain any characters above 127.
  3048. @see CharPointer_UTF8, CharPointer_UTF16, CharPointer_UTF32
  3049. */
  3050. class CharPointer_ASCII
  3051. {
  3052. public:
  3053. typedef char CharType;
  3054. inline explicit CharPointer_ASCII (const CharType* const rawPointer) throw()
  3055. : data (const_cast <CharType*> (rawPointer))
  3056. {
  3057. }
  3058. inline CharPointer_ASCII (const CharPointer_ASCII& other) throw()
  3059. : data (other.data)
  3060. {
  3061. }
  3062. inline CharPointer_ASCII& operator= (const CharPointer_ASCII& other) throw()
  3063. {
  3064. data = other.data;
  3065. return *this;
  3066. }
  3067. inline CharPointer_ASCII& operator= (const CharType* text) throw()
  3068. {
  3069. data = const_cast <CharType*> (text);
  3070. return *this;
  3071. }
  3072. /** This is a pointer comparison, it doesn't compare the actual text. */
  3073. inline bool operator== (const CharPointer_ASCII& other) const throw()
  3074. {
  3075. return data == other.data;
  3076. }
  3077. /** This is a pointer comparison, it doesn't compare the actual text. */
  3078. inline bool operator!= (const CharPointer_ASCII& other) const throw()
  3079. {
  3080. return data == other.data;
  3081. }
  3082. /** Returns the address that this pointer is pointing to. */
  3083. inline CharType* getAddress() const throw() { return data; }
  3084. /** Returns the address that this pointer is pointing to. */
  3085. inline operator const CharType*() const throw() { return data; }
  3086. /** Returns true if this pointer is pointing to a null character. */
  3087. inline bool isEmpty() const throw() { return *data == 0; }
  3088. /** Returns the unicode character that this pointer is pointing to. */
  3089. inline juce_wchar operator*() const throw() { return *data; }
  3090. /** Moves this pointer along to the next character in the string. */
  3091. inline CharPointer_ASCII& operator++() throw()
  3092. {
  3093. ++data;
  3094. return *this;
  3095. }
  3096. /** Moves this pointer to the previous character in the string. */
  3097. inline CharPointer_ASCII& operator--() throw()
  3098. {
  3099. --data;
  3100. return *this;
  3101. }
  3102. /** Returns the character that this pointer is currently pointing to, and then
  3103. advances the pointer to point to the next character. */
  3104. inline juce_wchar getAndAdvance() throw() { return *data++; }
  3105. /** Moves this pointer along to the next character in the string. */
  3106. CharPointer_ASCII operator++ (int) throw()
  3107. {
  3108. CharPointer_ASCII temp (*this);
  3109. ++data;
  3110. return temp;
  3111. }
  3112. /** Moves this pointer forwards by the specified number of characters. */
  3113. inline void operator+= (const int numToSkip) throw()
  3114. {
  3115. data += numToSkip;
  3116. }
  3117. inline void operator-= (const int numToSkip) throw()
  3118. {
  3119. data -= numToSkip;
  3120. }
  3121. /** Returns the character at a given character index from the start of the string. */
  3122. inline juce_wchar operator[] (const int characterIndex) const throw()
  3123. {
  3124. return (juce_wchar) (unsigned char) data [characterIndex];
  3125. }
  3126. /** Returns a pointer which is moved forwards from this one by the specified number of characters. */
  3127. CharPointer_ASCII operator+ (const int numToSkip) const throw()
  3128. {
  3129. return CharPointer_ASCII (data + numToSkip);
  3130. }
  3131. /** Returns a pointer which is moved backwards from this one by the specified number of characters. */
  3132. CharPointer_ASCII operator- (const int numToSkip) const throw()
  3133. {
  3134. return CharPointer_ASCII (data - numToSkip);
  3135. }
  3136. /** Writes a unicode character to this string, and advances this pointer to point to the next position. */
  3137. inline void write (const juce_wchar charToWrite) throw()
  3138. {
  3139. *data++ = (char) charToWrite;
  3140. }
  3141. inline void replaceChar (const juce_wchar newChar) throw()
  3142. {
  3143. *data = (char) newChar;
  3144. }
  3145. /** Writes a null character to this string (leaving the pointer's position unchanged). */
  3146. inline void writeNull() const throw()
  3147. {
  3148. *data = 0;
  3149. }
  3150. /** Returns the number of characters in this string. */
  3151. size_t length() const throw()
  3152. {
  3153. return (size_t) strlen (data);
  3154. }
  3155. /** Returns the number of characters in this string, or the given value, whichever is lower. */
  3156. size_t lengthUpTo (const size_t maxCharsToCount) const throw()
  3157. {
  3158. return CharacterFunctions::lengthUpTo (*this, maxCharsToCount);
  3159. }
  3160. /** Returns the number of bytes that are used to represent this string.
  3161. This includes the terminating null character.
  3162. */
  3163. size_t sizeInBytes() const throw()
  3164. {
  3165. return length() + 1;
  3166. }
  3167. /** Returns the number of bytes that would be needed to represent the given
  3168. unicode character in this encoding format.
  3169. */
  3170. static inline size_t getBytesRequiredFor (const juce_wchar) throw()
  3171. {
  3172. return 1;
  3173. }
  3174. /** Returns the number of bytes that would be needed to represent the given
  3175. string in this encoding format.
  3176. The value returned does NOT include the terminating null character.
  3177. */
  3178. template <class CharPointer>
  3179. static size_t getBytesRequiredFor (const CharPointer& text) throw()
  3180. {
  3181. return text.length();
  3182. }
  3183. /** Returns a pointer to the null character that terminates this string. */
  3184. CharPointer_ASCII findTerminatingNull() const throw()
  3185. {
  3186. return CharPointer_ASCII (data + length());
  3187. }
  3188. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3189. template <typename CharPointer>
  3190. void writeAll (const CharPointer& src) throw()
  3191. {
  3192. CharacterFunctions::copyAll (*this, src);
  3193. }
  3194. /** Copies a source string to this pointer, advancing this pointer as it goes. */
  3195. void writeAll (const CharPointer_ASCII& src) throw()
  3196. {
  3197. strcpy (data, src.data);
  3198. }
  3199. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3200. The maxDestBytes parameter specifies the maximum number of bytes that can be written
  3201. to the destination buffer before stopping.
  3202. */
  3203. template <typename CharPointer>
  3204. int writeWithDestByteLimit (const CharPointer& src, const int maxDestBytes) throw()
  3205. {
  3206. return CharacterFunctions::copyWithDestByteLimit (*this, src, maxDestBytes);
  3207. }
  3208. /** Copies a source string to this pointer, advancing this pointer as it goes.
  3209. The maxChars parameter specifies the maximum number of characters that can be
  3210. written to the destination buffer before stopping (including the terminating null).
  3211. */
  3212. template <typename CharPointer>
  3213. void writeWithCharLimit (const CharPointer& src, const int maxChars) throw()
  3214. {
  3215. CharacterFunctions::copyWithCharLimit (*this, src, maxChars);
  3216. }
  3217. /** Compares this string with another one. */
  3218. template <typename CharPointer>
  3219. int compare (const CharPointer& other) const throw()
  3220. {
  3221. return CharacterFunctions::compare (*this, other);
  3222. }
  3223. /** Compares this string with another one. */
  3224. int compare (const CharPointer_ASCII& other) const throw()
  3225. {
  3226. return strcmp (data, other.data);
  3227. }
  3228. /** Compares this string with another one, up to a specified number of characters. */
  3229. template <typename CharPointer>
  3230. int compareUpTo (const CharPointer& other, const int maxChars) const throw()
  3231. {
  3232. return CharacterFunctions::compareUpTo (*this, other, maxChars);
  3233. }
  3234. /** Compares this string with another one, up to a specified number of characters. */
  3235. int compareUpTo (const CharPointer_ASCII& other, const int maxChars) const throw()
  3236. {
  3237. return strncmp (data, other.data, (size_t) maxChars);
  3238. }
  3239. /** Compares this string with another one. */
  3240. template <typename CharPointer>
  3241. int compareIgnoreCase (const CharPointer& other) const
  3242. {
  3243. return CharacterFunctions::compareIgnoreCase (*this, other);
  3244. }
  3245. int compareIgnoreCase (const CharPointer_ASCII& other) const
  3246. {
  3247. #if JUCE_WINDOWS
  3248. return stricmp (data, other.data);
  3249. #else
  3250. return strcasecmp (data, other.data);
  3251. #endif
  3252. }
  3253. /** Compares this string with another one, up to a specified number of characters. */
  3254. template <typename CharPointer>
  3255. int compareIgnoreCaseUpTo (const CharPointer& other, const int maxChars) const throw()
  3256. {
  3257. return CharacterFunctions::compareIgnoreCaseUpTo (*this, other, maxChars);
  3258. }
  3259. /** Returns the character index of a substring, or -1 if it isn't found. */
  3260. template <typename CharPointer>
  3261. int indexOf (const CharPointer& stringToFind) const throw()
  3262. {
  3263. return CharacterFunctions::indexOf (*this, stringToFind);
  3264. }
  3265. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3266. int indexOf (const juce_wchar charToFind) const throw()
  3267. {
  3268. int i = 0;
  3269. while (data[i] != 0)
  3270. {
  3271. if (data[i] == (char) charToFind)
  3272. return i;
  3273. ++i;
  3274. }
  3275. return -1;
  3276. }
  3277. /** Returns the character index of a unicode character, or -1 if it isn't found. */
  3278. int indexOf (const juce_wchar charToFind, const bool ignoreCase) const throw()
  3279. {
  3280. return ignoreCase ? CharacterFunctions::indexOfCharIgnoreCase (*this, charToFind)
  3281. : CharacterFunctions::indexOfChar (*this, charToFind);
  3282. }
  3283. /** Returns true if the first character of this string is whitespace. */
  3284. bool isWhitespace() const { return CharacterFunctions::isWhitespace (*data) != 0; }
  3285. /** Returns true if the first character of this string is a digit. */
  3286. bool isDigit() const { return CharacterFunctions::isDigit (*data) != 0; }
  3287. /** Returns true if the first character of this string is a letter. */
  3288. bool isLetter() const { return CharacterFunctions::isLetter (*data) != 0; }
  3289. /** Returns true if the first character of this string is a letter or digit. */
  3290. bool isLetterOrDigit() const { return CharacterFunctions::isLetterOrDigit (*data) != 0; }
  3291. /** Returns true if the first character of this string is upper-case. */
  3292. bool isUpperCase() const { return CharacterFunctions::isUpperCase (*data) != 0; }
  3293. /** Returns true if the first character of this string is lower-case. */
  3294. bool isLowerCase() const { return CharacterFunctions::isLowerCase (*data) != 0; }
  3295. /** Returns an upper-case version of the first character of this string. */
  3296. juce_wchar toUpperCase() const throw() { return CharacterFunctions::toUpperCase (*data); }
  3297. /** Returns a lower-case version of the first character of this string. */
  3298. juce_wchar toLowerCase() const throw() { return CharacterFunctions::toLowerCase (*data); }
  3299. /** Parses this string as a 32-bit integer. */
  3300. int getIntValue32() const throw() { return atoi (data); }
  3301. /** Parses this string as a 64-bit integer. */
  3302. int64 getIntValue64() const throw()
  3303. {
  3304. #if JUCE_LINUX || JUCE_ANDROID
  3305. return atoll (data);
  3306. #elif JUCE_WINDOWS
  3307. return _atoi64 (data);
  3308. #else
  3309. return CharacterFunctions::getIntValue <int64, CharPointer_ASCII> (*this);
  3310. #endif
  3311. }
  3312. /** Parses this string as a floating point double. */
  3313. double getDoubleValue() const throw() { return CharacterFunctions::getDoubleValue (*this); }
  3314. /** Returns the first non-whitespace character in the string. */
  3315. CharPointer_ASCII findEndOfWhitespace() const throw() { return CharacterFunctions::findEndOfWhitespace (*this); }
  3316. /** Returns true if the given unicode character can be represented in this encoding. */
  3317. static bool canRepresent (juce_wchar character) throw()
  3318. {
  3319. return ((unsigned int) character) < (unsigned int) 128;
  3320. }
  3321. /** Returns true if this data contains a valid string in this encoding. */
  3322. static bool isValidString (const CharType* dataToTest, int maxBytesToRead)
  3323. {
  3324. while (--maxBytesToRead >= 0)
  3325. {
  3326. if (*dataToTest <= 0)
  3327. return *dataToTest == 0;
  3328. ++dataToTest;
  3329. }
  3330. return true;
  3331. }
  3332. private:
  3333. CharType* data;
  3334. };
  3335. #endif // __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  3336. /*** End of inlined file: juce_CharPointer_ASCII.h ***/
  3337. #if JUCE_MSVC
  3338. #pragma warning (pop)
  3339. #endif
  3340. class OutputStream;
  3341. /**
  3342. The JUCE String class!
  3343. Using a reference-counted internal representation, these strings are fast
  3344. and efficient, and there are methods to do just about any operation you'll ever
  3345. dream of.
  3346. @see StringArray, StringPairArray
  3347. */
  3348. class JUCE_API String
  3349. {
  3350. public:
  3351. /** Creates an empty string.
  3352. @see empty
  3353. */
  3354. String() throw();
  3355. /** Creates a copy of another string. */
  3356. String (const String& other) throw();
  3357. /** Creates a string from a zero-terminated ascii text string.
  3358. The string passed-in must not contain any characters with a value above 127, because
  3359. these can't be converted to unicode without knowing the original encoding that was
  3360. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3361. assertion.
  3362. To create strings with extended characters from UTF-8, you should explicitly call
  3363. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3364. use UTF-8 with escape characters in your source code to represent extended characters,
  3365. because there's no other way to represent unicode strings in a way that isn't dependent
  3366. on the compiler, source code editor and platform.
  3367. */
  3368. String (const char* text);
  3369. /** Creates a string from a string of 8-bit ascii characters.
  3370. The string passed-in must not contain any characters with a value above 127, because
  3371. these can't be converted to unicode without knowing the original encoding that was
  3372. used to create the string. If you attempt to pass-in values above 127, you'll get an
  3373. assertion.
  3374. To create strings with extended characters from UTF-8, you should explicitly call
  3375. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  3376. use UTF-8 with escape characters in your source code to represent extended characters,
  3377. because there's no other way to represent unicode strings in a way that isn't dependent
  3378. on the compiler, source code editor and platform.
  3379. This will use up the the first maxChars characters of the string (or less if the string
  3380. is actually shorter).
  3381. */
  3382. String (const char* text, size_t maxChars);
  3383. /** Creates a string from a zero-terminated unicode text string. */
  3384. String (const juce_wchar* unicodeText);
  3385. /** Creates a string from a unicode text string.
  3386. This will use up the the first maxChars characters of the string (or
  3387. less if the string is actually shorter)
  3388. */
  3389. String (const juce_wchar* unicodeText, size_t maxChars);
  3390. /** Creates a string from a UTF-8 character string */
  3391. String (const CharPointer_UTF8& text);
  3392. /** Creates a string from a UTF-16 character string */
  3393. String (const CharPointer_UTF16& text);
  3394. /** Creates a string from a UTF-32 character string */
  3395. String (const CharPointer_UTF32& text);
  3396. /** Creates a string from a UTF-32 character string */
  3397. String (const CharPointer_UTF32& text, size_t maxChars);
  3398. /** Creates a string from an ASCII character string */
  3399. String (const CharPointer_ASCII& text);
  3400. #if JUCE_WINDOWS
  3401. /** Creates a string from a UTF-16 character string */
  3402. String (const wchar_t* text);
  3403. /** Creates a string from a UTF-16 character string */
  3404. String (const wchar_t* text, size_t maxChars);
  3405. #endif
  3406. /** Creates a string from a single character. */
  3407. static const String charToString (juce_wchar character);
  3408. /** Destructor. */
  3409. ~String() throw();
  3410. /** This is an empty string that can be used whenever one is needed.
  3411. It's better to use this than String() because it explains what's going on
  3412. and is more efficient.
  3413. */
  3414. static const String empty;
  3415. /** This is the character encoding type used internally to store the string. */
  3416. typedef CharPointer_UTF32 CharPointerType;
  3417. /** Generates a probably-unique 32-bit hashcode from this string. */
  3418. int hashCode() const throw();
  3419. /** Generates a probably-unique 64-bit hashcode from this string. */
  3420. int64 hashCode64() const throw();
  3421. /** Returns the number of characters in the string. */
  3422. int length() const throw();
  3423. // Assignment and concatenation operators..
  3424. /** Replaces this string's contents with another string. */
  3425. String& operator= (const String& other) throw();
  3426. /** Appends another string at the end of this one. */
  3427. String& operator+= (const juce_wchar* textToAppend);
  3428. /** Appends another string at the end of this one. */
  3429. String& operator+= (const String& stringToAppend);
  3430. /** Appends a character at the end of this string. */
  3431. String& operator+= (char characterToAppend);
  3432. /** Appends a character at the end of this string. */
  3433. String& operator+= (juce_wchar characterToAppend);
  3434. #if JUCE_WINDOWS
  3435. /** Appends a character at the end of this string. */
  3436. String& operator+= (wchar_t characterToAppend);
  3437. /** Appends another string at the end of this one. */
  3438. String& operator+= (const wchar_t* textToAppend);
  3439. #endif
  3440. /** Appends a decimal number at the end of this string. */
  3441. String& operator+= (int numberToAppend);
  3442. /** Appends a string to the end of this one.
  3443. @param textToAppend the string to add
  3444. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3445. */
  3446. void append (const String& textToAppend, size_t maxCharsToTake);
  3447. /** Appends a string to the end of this one.
  3448. @param textToAppend the string to add
  3449. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3450. */
  3451. template <class CharPointer>
  3452. void appendCharPointer (const CharPointer& textToAppend, size_t maxCharsToTake)
  3453. {
  3454. if (textToAppend.getAddress() != 0)
  3455. {
  3456. const size_t numExtraChars = textToAppend.lengthUpTo (maxCharsToTake);
  3457. if (numExtraChars > 0)
  3458. {
  3459. const int oldLen = length();
  3460. preallocateStorage (oldLen + numExtraChars);
  3461. CharPointerType (text + oldLen).writeWithCharLimit (textToAppend, (int) (numExtraChars + 1));
  3462. }
  3463. }
  3464. }
  3465. /** Appends a string to the end of this one.
  3466. @param textToAppend the string to add
  3467. @param maxCharsToTake the maximum number of characters to take from the string passed in
  3468. */
  3469. template <class CharPointer>
  3470. void appendCharPointer (const CharPointer& textToAppend)
  3471. {
  3472. if (textToAppend.getAddress() != 0)
  3473. {
  3474. const size_t numExtraChars = textToAppend.length();
  3475. if (numExtraChars > 0)
  3476. {
  3477. const int oldLen = length();
  3478. preallocateStorage (oldLen + numExtraChars);
  3479. CharPointerType (text + oldLen).writeAll (textToAppend);
  3480. }
  3481. }
  3482. }
  3483. // Comparison methods..
  3484. /** Returns true if the string contains no characters.
  3485. Note that there's also an isNotEmpty() method to help write readable code.
  3486. @see containsNonWhitespaceChars()
  3487. */
  3488. inline bool isEmpty() const throw() { return text[0] == 0; }
  3489. /** Returns true if the string contains at least one character.
  3490. Note that there's also an isEmpty() method to help write readable code.
  3491. @see containsNonWhitespaceChars()
  3492. */
  3493. inline bool isNotEmpty() const throw() { return text[0] != 0; }
  3494. /** Case-insensitive comparison with another string. */
  3495. bool equalsIgnoreCase (const String& other) const throw();
  3496. /** Case-insensitive comparison with another string. */
  3497. bool equalsIgnoreCase (const juce_wchar* other) const throw();
  3498. /** Case-insensitive comparison with another string. */
  3499. bool equalsIgnoreCase (const char* other) const throw();
  3500. /** Case-sensitive comparison with another string.
  3501. @returns 0 if the two strings are identical; negative if this string
  3502. comes before the other one alphabetically, or positive if it
  3503. comes after it.
  3504. */
  3505. int compare (const String& other) const throw();
  3506. /** Case-sensitive comparison with another string.
  3507. @returns 0 if the two strings are identical; negative if this string
  3508. comes before the other one alphabetically, or positive if it
  3509. comes after it.
  3510. */
  3511. int compare (const char* other) const throw();
  3512. /** Case-sensitive comparison with another string.
  3513. @returns 0 if the two strings are identical; negative if this string
  3514. comes before the other one alphabetically, or positive if it
  3515. comes after it.
  3516. */
  3517. int compare (const juce_wchar* other) const throw();
  3518. /** Case-insensitive comparison with another string.
  3519. @returns 0 if the two strings are identical; negative if this string
  3520. comes before the other one alphabetically, or positive if it
  3521. comes after it.
  3522. */
  3523. int compareIgnoreCase (const String& other) const throw();
  3524. /** Lexicographic comparison with another string.
  3525. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  3526. characters, making it good for sorting human-readable strings.
  3527. @returns 0 if the two strings are identical; negative if this string
  3528. comes before the other one alphabetically, or positive if it
  3529. comes after it.
  3530. */
  3531. int compareLexicographically (const String& other) const throw();
  3532. /** Tests whether the string begins with another string.
  3533. If the parameter is an empty string, this will always return true.
  3534. Uses a case-sensitive comparison.
  3535. */
  3536. bool startsWith (const String& text) const throw();
  3537. /** Tests whether the string begins with a particular character.
  3538. If the character is 0, this will always return false.
  3539. Uses a case-sensitive comparison.
  3540. */
  3541. bool startsWithChar (juce_wchar character) const throw();
  3542. /** Tests whether the string begins with another string.
  3543. If the parameter is an empty string, this will always return true.
  3544. Uses a case-insensitive comparison.
  3545. */
  3546. bool startsWithIgnoreCase (const String& text) const throw();
  3547. /** Tests whether the string ends with another string.
  3548. If the parameter is an empty string, this will always return true.
  3549. Uses a case-sensitive comparison.
  3550. */
  3551. bool endsWith (const String& text) const throw();
  3552. /** Tests whether the string ends with a particular character.
  3553. If the character is 0, this will always return false.
  3554. Uses a case-sensitive comparison.
  3555. */
  3556. bool endsWithChar (juce_wchar character) const throw();
  3557. /** Tests whether the string ends with another string.
  3558. If the parameter is an empty string, this will always return true.
  3559. Uses a case-insensitive comparison.
  3560. */
  3561. bool endsWithIgnoreCase (const String& text) const throw();
  3562. /** Tests whether the string contains another substring.
  3563. If the parameter is an empty string, this will always return true.
  3564. Uses a case-sensitive comparison.
  3565. */
  3566. bool contains (const String& text) const throw();
  3567. /** Tests whether the string contains a particular character.
  3568. Uses a case-sensitive comparison.
  3569. */
  3570. bool containsChar (juce_wchar character) const throw();
  3571. /** Tests whether the string contains another substring.
  3572. Uses a case-insensitive comparison.
  3573. */
  3574. bool containsIgnoreCase (const String& text) const throw();
  3575. /** Tests whether the string contains another substring as a distict word.
  3576. @returns true if the string contains this word, surrounded by
  3577. non-alphanumeric characters
  3578. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3579. */
  3580. bool containsWholeWord (const String& wordToLookFor) const throw();
  3581. /** Tests whether the string contains another substring as a distict word.
  3582. @returns true if the string contains this word, surrounded by
  3583. non-alphanumeric characters
  3584. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3585. */
  3586. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  3587. /** Finds an instance of another substring if it exists as a distict word.
  3588. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3589. then this will return the index of the start of the substring. If it isn't
  3590. found, then it will return -1
  3591. @see indexOfWholeWordIgnoreCase, containsWholeWord
  3592. */
  3593. int indexOfWholeWord (const String& wordToLookFor) const throw();
  3594. /** Finds an instance of another substring if it exists as a distict word.
  3595. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  3596. then this will return the index of the start of the substring. If it isn't
  3597. found, then it will return -1
  3598. @see indexOfWholeWord, containsWholeWordIgnoreCase
  3599. */
  3600. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  3601. /** Looks for any of a set of characters in the string.
  3602. Uses a case-sensitive comparison.
  3603. @returns true if the string contains any of the characters from
  3604. the string that is passed in.
  3605. */
  3606. bool containsAnyOf (const String& charactersItMightContain) const throw();
  3607. /** Looks for a set of characters in the string.
  3608. Uses a case-sensitive comparison.
  3609. @returns Returns false if any of the characters in this string do not occur in
  3610. the parameter string. If this string is empty, the return value will
  3611. always be true.
  3612. */
  3613. bool containsOnly (const String& charactersItMightContain) const throw();
  3614. /** Returns true if this string contains any non-whitespace characters.
  3615. This will return false if the string contains only whitespace characters, or
  3616. if it's empty.
  3617. It is equivalent to calling "myString.trim().isNotEmpty()".
  3618. */
  3619. bool containsNonWhitespaceChars() const throw();
  3620. /** Returns true if the string matches this simple wildcard expression.
  3621. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  3622. This isn't a full-blown regex though! The only wildcard characters supported
  3623. are "*" and "?". It's mainly intended for filename pattern matching.
  3624. */
  3625. bool matchesWildcard (const String& wildcard, bool ignoreCase) const throw();
  3626. // Substring location methods..
  3627. /** Searches for a character inside this string.
  3628. Uses a case-sensitive comparison.
  3629. @returns the index of the first occurrence of the character in this
  3630. string, or -1 if it's not found.
  3631. */
  3632. int indexOfChar (juce_wchar characterToLookFor) const throw();
  3633. /** Searches for a character inside this string.
  3634. Uses a case-sensitive comparison.
  3635. @param startIndex the index from which the search should proceed
  3636. @param characterToLookFor the character to look for
  3637. @returns the index of the first occurrence of the character in this
  3638. string, or -1 if it's not found.
  3639. */
  3640. int indexOfChar (int startIndex, juce_wchar characterToLookFor) const throw();
  3641. /** Returns the index of the first character that matches one of the characters
  3642. passed-in to this method.
  3643. This scans the string, beginning from the startIndex supplied, and if it finds
  3644. a character that appears in the string charactersToLookFor, it returns its index.
  3645. If none of these characters are found, it returns -1.
  3646. If ignoreCase is true, the comparison will be case-insensitive.
  3647. @see indexOfChar, lastIndexOfAnyOf
  3648. */
  3649. int indexOfAnyOf (const String& charactersToLookFor,
  3650. int startIndex = 0,
  3651. bool ignoreCase = false) const throw();
  3652. /** Searches for a substring within this string.
  3653. Uses a case-sensitive comparison.
  3654. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3655. */
  3656. int indexOf (const String& text) const throw();
  3657. /** Searches for a substring within this string.
  3658. Uses a case-sensitive comparison.
  3659. @param startIndex the index from which the search should proceed
  3660. @param textToLookFor the string to search for
  3661. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3662. */
  3663. int indexOf (int startIndex,
  3664. const String& textToLookFor) const throw();
  3665. /** Searches for a substring within this string.
  3666. Uses a case-insensitive comparison.
  3667. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3668. */
  3669. int indexOfIgnoreCase (const String& textToLookFor) const throw();
  3670. /** Searches for a substring within this string.
  3671. Uses a case-insensitive comparison.
  3672. @param startIndex the index from which the search should proceed
  3673. @param textToLookFor the string to search for
  3674. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  3675. */
  3676. int indexOfIgnoreCase (int startIndex,
  3677. const String& textToLookFor) const throw();
  3678. /** Searches for a character inside this string (working backwards from the end of the string).
  3679. Uses a case-sensitive comparison.
  3680. @returns the index of the last occurrence of the character in this
  3681. string, or -1 if it's not found.
  3682. */
  3683. int lastIndexOfChar (juce_wchar character) const throw();
  3684. /** Searches for a substring inside this string (working backwards from the end of the string).
  3685. Uses a case-sensitive comparison.
  3686. @returns the index of the start of the last occurrence of the
  3687. substring within this string, or -1 if it's not found.
  3688. */
  3689. int lastIndexOf (const String& textToLookFor) const throw();
  3690. /** Searches for a substring inside this string (working backwards from the end of the string).
  3691. Uses a case-insensitive comparison.
  3692. @returns the index of the start of the last occurrence of the
  3693. substring within this string, or -1 if it's not found.
  3694. */
  3695. int lastIndexOfIgnoreCase (const String& textToLookFor) const throw();
  3696. /** Returns the index of the last character in this string that matches one of the
  3697. characters passed-in to this method.
  3698. This scans the string backwards, starting from its end, and if it finds
  3699. a character that appears in the string charactersToLookFor, it returns its index.
  3700. If none of these characters are found, it returns -1.
  3701. If ignoreCase is true, the comparison will be case-insensitive.
  3702. @see lastIndexOf, indexOfAnyOf
  3703. */
  3704. int lastIndexOfAnyOf (const String& charactersToLookFor,
  3705. bool ignoreCase = false) const throw();
  3706. // Substring extraction and manipulation methods..
  3707. /** Returns the character at this index in the string.
  3708. No checks are made to see if the index is within a valid range, so be careful!
  3709. */
  3710. const juce_wchar operator[] (int index) const throw();
  3711. /** Returns the final character of the string.
  3712. If the string is empty this will return 0.
  3713. */
  3714. juce_wchar getLastCharacter() const throw();
  3715. /** Returns a subsection of the string.
  3716. If the range specified is beyond the limits of the string, as much as
  3717. possible is returned.
  3718. @param startIndex the index of the start of the substring needed
  3719. @param endIndex all characters from startIndex up to (but not including)
  3720. this index are returned
  3721. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  3722. */
  3723. const String substring (int startIndex, int endIndex) const;
  3724. /** Returns a section of the string, starting from a given position.
  3725. @param startIndex the first character to include. If this is beyond the end
  3726. of the string, an empty string is returned. If it is zero or
  3727. less, the whole string is returned.
  3728. @returns the substring from startIndex up to the end of the string
  3729. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  3730. */
  3731. const String substring (int startIndex) const;
  3732. /** Returns a version of this string with a number of characters removed
  3733. from the end.
  3734. @param numberToDrop the number of characters to drop from the end of the
  3735. string. If this is greater than the length of the string,
  3736. an empty string will be returned. If zero or less, the
  3737. original string will be returned.
  3738. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  3739. */
  3740. const String dropLastCharacters (int numberToDrop) const;
  3741. /** Returns a number of characters from the end of the string.
  3742. This returns the last numCharacters characters from the end of the string. If the
  3743. string is shorter than numCharacters, the whole string is returned.
  3744. @see substring, dropLastCharacters, getLastCharacter
  3745. */
  3746. const String getLastCharacters (int numCharacters) const;
  3747. /** Returns a section of the string starting from a given substring.
  3748. This will search for the first occurrence of the given substring, and
  3749. return the section of the string starting from the point where this is
  3750. found (optionally not including the substring itself).
  3751. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  3752. fromFirstOccurrenceOf ("34", false) would return "56".
  3753. If the substring isn't found, the method will return an empty string.
  3754. If ignoreCase is true, the comparison will be case-insensitive.
  3755. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  3756. */
  3757. const String fromFirstOccurrenceOf (const String& substringToStartFrom,
  3758. bool includeSubStringInResult,
  3759. bool ignoreCase) const;
  3760. /** Returns a section of the string starting from the last occurrence of a given substring.
  3761. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  3762. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  3763. return the whole of the original string.
  3764. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  3765. */
  3766. const String fromLastOccurrenceOf (const String& substringToFind,
  3767. bool includeSubStringInResult,
  3768. bool ignoreCase) const;
  3769. /** Returns the start of this string, up to the first occurrence of a substring.
  3770. This will search for the first occurrence of a given substring, and then
  3771. return a copy of the string, up to the position of this substring,
  3772. optionally including or excluding the substring itself in the result.
  3773. e.g. for the string "123456", upTo ("34", false) would return "12", and
  3774. upTo ("34", true) would return "1234".
  3775. If the substring isn't found, this will return the whole of the original string.
  3776. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  3777. */
  3778. const String upToFirstOccurrenceOf (const String& substringToEndWith,
  3779. bool includeSubStringInResult,
  3780. bool ignoreCase) const;
  3781. /** Returns the start of this string, up to the last occurrence of a substring.
  3782. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  3783. If the substring isn't found, this will return the whole of the original string.
  3784. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  3785. */
  3786. const String upToLastOccurrenceOf (const String& substringToFind,
  3787. bool includeSubStringInResult,
  3788. bool ignoreCase) const;
  3789. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  3790. const String trim() const;
  3791. /** Returns a copy of this string with any whitespace characters removed from the start. */
  3792. const String trimStart() const;
  3793. /** Returns a copy of this string with any whitespace characters removed from the end. */
  3794. const String trimEnd() const;
  3795. /** Returns a copy of this string, having removed a specified set of characters from its start.
  3796. Characters are removed from the start of the string until it finds one that is not in the
  3797. specified set, and then it stops.
  3798. @param charactersToTrim the set of characters to remove.
  3799. @see trim, trimStart, trimCharactersAtEnd
  3800. */
  3801. const String trimCharactersAtStart (const String& charactersToTrim) const;
  3802. /** Returns a copy of this string, having removed a specified set of characters from its end.
  3803. Characters are removed from the end of the string until it finds one that is not in the
  3804. specified set, and then it stops.
  3805. @param charactersToTrim the set of characters to remove.
  3806. @see trim, trimEnd, trimCharactersAtStart
  3807. */
  3808. const String trimCharactersAtEnd (const String& charactersToTrim) const;
  3809. /** Returns an upper-case version of this string. */
  3810. const String toUpperCase() const;
  3811. /** Returns an lower-case version of this string. */
  3812. const String toLowerCase() const;
  3813. /** Replaces a sub-section of the string with another string.
  3814. This will return a copy of this string, with a set of characters
  3815. from startIndex to startIndex + numCharsToReplace removed, and with
  3816. a new string inserted in their place.
  3817. Note that this is a const method, and won't alter the string itself.
  3818. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  3819. it will be constrained to a valid range.
  3820. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  3821. characters will be taken out.
  3822. @param stringToInsert the new string to insert at startIndex after the characters have been
  3823. removed.
  3824. */
  3825. const String replaceSection (int startIndex,
  3826. int numCharactersToReplace,
  3827. const String& stringToInsert) const;
  3828. /** Replaces all occurrences of a substring with another string.
  3829. Returns a copy of this string, with any occurrences of stringToReplace
  3830. swapped for stringToInsertInstead.
  3831. Note that this is a const method, and won't alter the string itself.
  3832. */
  3833. const String replace (const String& stringToReplace,
  3834. const String& stringToInsertInstead,
  3835. bool ignoreCase = false) const;
  3836. /** Returns a string with all occurrences of a character replaced with a different one. */
  3837. const String replaceCharacter (juce_wchar characterToReplace,
  3838. juce_wchar characterToInsertInstead) const;
  3839. /** Replaces a set of characters with another set.
  3840. Returns a string in which each character from charactersToReplace has been replaced
  3841. by the character at the equivalent position in newCharacters (so the two strings
  3842. passed in must be the same length).
  3843. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  3844. Note that this is a const method, and won't affect the string itself.
  3845. */
  3846. const String replaceCharacters (const String& charactersToReplace,
  3847. const String& charactersToInsertInstead) const;
  3848. /** Returns a version of this string that only retains a fixed set of characters.
  3849. This will return a copy of this string, omitting any characters which are not
  3850. found in the string passed-in.
  3851. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  3852. Note that this is a const method, and won't alter the string itself.
  3853. */
  3854. const String retainCharacters (const String& charactersToRetain) const;
  3855. /** Returns a version of this string with a set of characters removed.
  3856. This will return a copy of this string, omitting any characters which are
  3857. found in the string passed-in.
  3858. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  3859. Note that this is a const method, and won't alter the string itself.
  3860. */
  3861. const String removeCharacters (const String& charactersToRemove) const;
  3862. /** Returns a section from the start of the string that only contains a certain set of characters.
  3863. This returns the leftmost section of the string, up to (and not including) the
  3864. first character that doesn't appear in the string passed in.
  3865. */
  3866. const String initialSectionContainingOnly (const String& permittedCharacters) const;
  3867. /** Returns a section from the start of the string that only contains a certain set of characters.
  3868. This returns the leftmost section of the string, up to (and not including) the
  3869. first character that occurs in the string passed in.
  3870. */
  3871. const String initialSectionNotContaining (const String& charactersToStopAt) const;
  3872. /** Checks whether the string might be in quotation marks.
  3873. @returns true if the string begins with a quote character (either a double or single quote).
  3874. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  3875. @see unquoted, quoted
  3876. */
  3877. bool isQuotedString() const;
  3878. /** Removes quotation marks from around the string, (if there are any).
  3879. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  3880. at the ends of the string are not affected. If there aren't any quotes, the original string
  3881. is returned.
  3882. Note that this is a const method, and won't alter the string itself.
  3883. @see isQuotedString, quoted
  3884. */
  3885. const String unquoted() const;
  3886. /** Adds quotation marks around a string.
  3887. This will return a copy of the string with a quote at the start and end, (but won't
  3888. add the quote if there's already one there, so it's safe to call this on strings that
  3889. may already have quotes around them).
  3890. Note that this is a const method, and won't alter the string itself.
  3891. @param quoteCharacter the character to add at the start and end
  3892. @see isQuotedString, unquoted
  3893. */
  3894. const String quoted (juce_wchar quoteCharacter = '"') const;
  3895. /** Creates a string which is a version of a string repeated and joined together.
  3896. @param stringToRepeat the string to repeat
  3897. @param numberOfTimesToRepeat how many times to repeat it
  3898. */
  3899. static const String repeatedString (const String& stringToRepeat,
  3900. int numberOfTimesToRepeat);
  3901. /** Returns a copy of this string with the specified character repeatedly added to its
  3902. beginning until the total length is at least the minimum length specified.
  3903. */
  3904. const String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  3905. /** Returns a copy of this string with the specified character repeatedly added to its
  3906. end until the total length is at least the minimum length specified.
  3907. */
  3908. const String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  3909. /** Creates a string from data in an unknown format.
  3910. This looks at some binary data and tries to guess whether it's Unicode
  3911. or 8-bit characters, then returns a string that represents it correctly.
  3912. Should be able to handle Unicode endianness correctly, by looking at
  3913. the first two bytes.
  3914. */
  3915. static const String createStringFromData (const void* data, int size);
  3916. /** Creates a String from a printf-style parameter list.
  3917. I don't like this method. I don't use it myself, and I recommend avoiding it and
  3918. using the operator<< methods or pretty much anything else instead. It's only provided
  3919. here because of the popular unrest that was stirred-up when I tried to remove it...
  3920. If you're really determined to use it, at least make sure that you never, ever,
  3921. pass any String objects to it as parameters.
  3922. */
  3923. static const String formatted (const juce_wchar* formatString, ... );
  3924. // Numeric conversions..
  3925. /** Creates a string containing this signed 32-bit integer as a decimal number.
  3926. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  3927. */
  3928. explicit String (int decimalInteger);
  3929. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  3930. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  3931. */
  3932. explicit String (unsigned int decimalInteger);
  3933. /** Creates a string containing this signed 16-bit integer as a decimal number.
  3934. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  3935. */
  3936. explicit String (short decimalInteger);
  3937. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  3938. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  3939. */
  3940. explicit String (unsigned short decimalInteger);
  3941. /** Creates a string containing this signed 64-bit integer as a decimal number.
  3942. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  3943. */
  3944. explicit String (int64 largeIntegerValue);
  3945. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  3946. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  3947. */
  3948. explicit String (uint64 largeIntegerValue);
  3949. /** Creates a string representing this floating-point number.
  3950. @param floatValue the value to convert to a string
  3951. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  3952. decimal places, and will not use exponent notation. If 0 or
  3953. less, it will use exponent notation if necessary.
  3954. @see getDoubleValue, getIntValue
  3955. */
  3956. explicit String (float floatValue,
  3957. int numberOfDecimalPlaces = 0);
  3958. /** Creates a string representing this floating-point number.
  3959. @param doubleValue the value to convert to a string
  3960. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  3961. decimal places, and will not use exponent notation. If 0 or
  3962. less, it will use exponent notation if necessary.
  3963. @see getFloatValue, getIntValue
  3964. */
  3965. explicit String (double doubleValue,
  3966. int numberOfDecimalPlaces = 0);
  3967. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  3968. @returns the value of the string as a 32 bit signed base-10 integer.
  3969. @see getTrailingIntValue, getHexValue32, getHexValue64
  3970. */
  3971. int getIntValue() const throw();
  3972. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  3973. @returns the value of the string as a 64 bit signed base-10 integer.
  3974. */
  3975. int64 getLargeIntValue() const throw();
  3976. /** Parses a decimal number from the end of the string.
  3977. This will look for a value at the end of the string.
  3978. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  3979. Negative numbers are not handled, so "xyz-5" returns 5.
  3980. @see getIntValue
  3981. */
  3982. int getTrailingIntValue() const throw();
  3983. /** Parses this string as a floating point number.
  3984. @returns the value of the string as a 32-bit floating point value.
  3985. @see getDoubleValue
  3986. */
  3987. float getFloatValue() const throw();
  3988. /** Parses this string as a floating point number.
  3989. @returns the value of the string as a 64-bit floating point value.
  3990. @see getFloatValue
  3991. */
  3992. double getDoubleValue() const throw();
  3993. /** Parses the string as a hexadecimal number.
  3994. Non-hexadecimal characters in the string are ignored.
  3995. If the string contains too many characters, then the lowest significant
  3996. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  3997. @returns a 32-bit number which is the value of the string in hex.
  3998. */
  3999. int getHexValue32() const throw();
  4000. /** Parses the string as a hexadecimal number.
  4001. Non-hexadecimal characters in the string are ignored.
  4002. If the string contains too many characters, then the lowest significant
  4003. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  4004. @returns a 64-bit number which is the value of the string in hex.
  4005. */
  4006. int64 getHexValue64() const throw();
  4007. /** Creates a string representing this 32-bit value in hexadecimal. */
  4008. static const String toHexString (int number);
  4009. /** Creates a string representing this 64-bit value in hexadecimal. */
  4010. static const String toHexString (int64 number);
  4011. /** Creates a string representing this 16-bit value in hexadecimal. */
  4012. static const String toHexString (short number);
  4013. /** Creates a string containing a hex dump of a block of binary data.
  4014. @param data the binary data to use as input
  4015. @param size how many bytes of data to use
  4016. @param groupSize how many bytes are grouped together before inserting a
  4017. space into the output. e.g. group size 0 has no spaces,
  4018. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  4019. like "bea1 c2ff".
  4020. */
  4021. static const String toHexString (const unsigned char* data,
  4022. int size,
  4023. int groupSize = 1);
  4024. /** Returns a unicode version of this string.
  4025. Because it returns a reference to the string's internal data, the pointer
  4026. that is returned must not be stored anywhere, as it can become invalid whenever
  4027. any string methods (even some const ones!) are called.
  4028. */
  4029. inline operator const juce_wchar*() const throw() { return toUTF32().getAddress(); }
  4030. /** Returns the character pointer currently being used to store this string.
  4031. Because it returns a reference to the string's internal data, the pointer
  4032. that is returned must not be stored anywhere, as it can be deleted whenever the
  4033. string changes.
  4034. */
  4035. inline const CharPointerType& getCharPointer() const throw() { return text; }
  4036. /** Returns a pointer to a UTF-8 version of this string.
  4037. Because it returns a reference to the string's internal data, the pointer
  4038. that is returned must not be stored anywhere, as it can be deleted whenever the
  4039. string changes.
  4040. To find out how many bytes you need to store this string as UTF-8, you can call
  4041. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4042. @see getCharPointer, toUTF16, toUTF32
  4043. */
  4044. const CharPointer_UTF8 toUTF8() const;
  4045. /** Returns a pointer to a UTF-32 version of this string.
  4046. Because it returns a reference to the string's internal data, the pointer
  4047. that is returned must not be stored anywhere, as it can be deleted whenever the
  4048. string changes.
  4049. To find out how many bytes you need to store this string as UTF-16, you can call
  4050. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4051. @see getCharPointer, toUTF8, toUTF32
  4052. */
  4053. CharPointer_UTF16 toUTF16() const;
  4054. /** Returns a pointer to a UTF-32 version of this string.
  4055. Because it returns a reference to the string's internal data, the pointer
  4056. that is returned must not be stored anywhere, as it can be deleted whenever the
  4057. string changes.
  4058. @see getCharPointer, toUTF8, toUTF16
  4059. */
  4060. inline CharPointer_UTF32 toUTF32() const throw() { return text; }
  4061. /** Creates a String from a UTF-8 encoded buffer.
  4062. If the size is < 0, it'll keep reading until it hits a zero.
  4063. */
  4064. static const String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  4065. /** Returns the number of bytes required to represent this string as UTF8.
  4066. The number returned does NOT include the trailing zero.
  4067. @see toUTF8, copyToUTF8
  4068. */
  4069. int getNumBytesAsUTF8() const throw();
  4070. /** Copies the string to a buffer as UTF-8 characters.
  4071. Returns the number of bytes copied to the buffer, including the terminating null
  4072. character.
  4073. To find out how many bytes you need to store this string as UTF-8, you can call
  4074. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4075. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4076. returns the number of bytes required (including the terminating null character).
  4077. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4078. put in as many as it can while still allowing for a terminating null char at the
  4079. end, and will return the number of bytes that were actually used.
  4080. @see CharPointer_UTF8::writeWithDestByteLimit
  4081. */
  4082. int copyToUTF8 (CharPointer_UTF8::CharType* destBuffer, int maxBufferSizeBytes) const throw();
  4083. /** Copies the string to a buffer as UTF-16 characters.
  4084. Returns the number of bytes copied to the buffer, including the terminating null
  4085. character.
  4086. To find out how many bytes you need to store this string as UTF-16, you can call
  4087. CharPointer_UTF16::getBytesRequiredFor (myString.getCharPointer())
  4088. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  4089. returns the number of bytes required (including the terminating null character).
  4090. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  4091. put in as many as it can while still allowing for a terminating null char at the
  4092. end, and will return the number of bytes that were actually used.
  4093. @see CharPointer_UTF16::writeWithDestByteLimit
  4094. */
  4095. int copyToUTF16 (CharPointer_UTF16::CharType* destBuffer, int maxBufferSizeBytes) const throw();
  4096. /** Returns a version of this string using the default 8-bit multi-byte system encoding.
  4097. Because it returns a reference to the string's internal data, the pointer
  4098. that is returned must not be stored anywhere, as it can be deleted whenever the
  4099. string changes.
  4100. @see getNumBytesAsCString, copyToCString, toUTF8
  4101. */
  4102. const char* toCString() const;
  4103. /** Returns the number of bytes required to represent this string as C-string.
  4104. The number returned does NOT include the trailing zero.
  4105. Note that you can also get this value by using CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  4106. */
  4107. int getNumBytesAsCString() const throw();
  4108. /** Copies the string to a buffer.
  4109. @param destBuffer the place to copy it to; if this is a null pointer,
  4110. the method just returns the number of bytes required
  4111. (including the terminating null character).
  4112. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  4113. string won't fit, it'll put in as many as it can while
  4114. still allowing for a terminating null char at the end, and
  4115. will return the number of bytes that were actually used.
  4116. */
  4117. int copyToCString (char* destBuffer, int maxBufferSizeBytes) const throw();
  4118. /** Increases the string's internally allocated storage.
  4119. Although the string's contents won't be affected by this call, it will
  4120. increase the amount of memory allocated internally for the string to grow into.
  4121. If you're about to make a large number of calls to methods such
  4122. as += or <<, it's more efficient to preallocate enough extra space
  4123. beforehand, so that these methods won't have to keep resizing the string
  4124. to append the extra characters.
  4125. @param numCharsNeeded the number of characters to allocate storage for. If this
  4126. value is less than the currently allocated size, it will
  4127. have no effect.
  4128. */
  4129. void preallocateStorage (size_t numCharsNeeded);
  4130. /** Swaps the contents of this string with another one.
  4131. This is a very fast operation, as no allocation or copying needs to be done.
  4132. */
  4133. void swapWith (String& other) throw();
  4134. /** A helper class to improve performance when concatenating many large strings
  4135. together.
  4136. Because appending one string to another involves measuring the length of
  4137. both strings, repeatedly doing this for many long strings will become
  4138. an exponentially slow operation. This class uses some internal state to
  4139. avoid that, so that each append operation only needs to measure the length
  4140. of the appended string.
  4141. */
  4142. class JUCE_API Concatenator
  4143. {
  4144. public:
  4145. Concatenator (String& stringToAppendTo);
  4146. ~Concatenator();
  4147. void append (const String& s);
  4148. private:
  4149. String& result;
  4150. int nextIndex;
  4151. JUCE_DECLARE_NON_COPYABLE (Concatenator);
  4152. };
  4153. private:
  4154. CharPointerType text;
  4155. struct Preallocation
  4156. {
  4157. explicit Preallocation (size_t);
  4158. size_t numChars;
  4159. };
  4160. // This constructor preallocates a certain amount of memory
  4161. explicit String (const Preallocation&);
  4162. String (const String& stringToCopy, size_t charsToAllocate);
  4163. void appendFixedLength (const juce_wchar* text, int numExtraChars);
  4164. void enlarge (size_t newTotalNumChars);
  4165. void* createSpaceAtEndOfBuffer (size_t numExtraBytes) const;
  4166. // This private cast operator should prevent strings being accidentally cast
  4167. // to bools (this is possible because the compiler can add an implicit cast
  4168. // via a const char*)
  4169. operator bool() const throw() { return false; }
  4170. };
  4171. /** Concatenates two strings. */
  4172. JUCE_API const String JUCE_CALLTYPE operator+ (const char* string1, const String& string2);
  4173. /** Concatenates two strings. */
  4174. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* string1, const String& string2);
  4175. /** Concatenates two strings. */
  4176. JUCE_API const String JUCE_CALLTYPE operator+ (char string1, const String& string2);
  4177. /** Concatenates two strings. */
  4178. JUCE_API const String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2);
  4179. /** Concatenates two strings. */
  4180. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2);
  4181. /** Concatenates two strings. */
  4182. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* string2);
  4183. /** Concatenates two strings. */
  4184. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* string2);
  4185. /** Concatenates two strings. */
  4186. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, char characterToAppend);
  4187. /** Concatenates two strings. */
  4188. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend);
  4189. #if JUCE_WINDOWS
  4190. /** Concatenates two strings. */
  4191. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, wchar_t characterToAppend);
  4192. /** Concatenates two strings. */
  4193. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2);
  4194. /** Concatenates two strings. */
  4195. JUCE_API const String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2);
  4196. #endif
  4197. /** Appends a character at the end of a string. */
  4198. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend);
  4199. /** Appends a character at the end of a string. */
  4200. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend);
  4201. /** Appends a string to the end of the first one. */
  4202. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* string2);
  4203. /** Appends a string to the end of the first one. */
  4204. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* string2);
  4205. /** Appends a string to the end of the first one. */
  4206. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2);
  4207. /** Appends a decimal number at the end of a string. */
  4208. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, short number);
  4209. /** Appends a decimal number at the end of a string. */
  4210. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, int number);
  4211. /** Appends a decimal number at the end of a string. */
  4212. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, long number);
  4213. /** Appends a decimal number at the end of a string. */
  4214. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, float number);
  4215. /** Appends a decimal number at the end of a string. */
  4216. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, double number);
  4217. /** Case-sensitive comparison of two strings. */
  4218. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw();
  4219. /** Case-sensitive comparison of two strings. */
  4220. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw();
  4221. /** Case-sensitive comparison of two strings. */
  4222. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw();
  4223. /** Case-sensitive comparison of two strings. */
  4224. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF8& string2) throw();
  4225. /** Case-sensitive comparison of two strings. */
  4226. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF16& string2) throw();
  4227. /** Case-sensitive comparison of two strings. */
  4228. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF32& string2) throw();
  4229. /** Case-sensitive comparison of two strings. */
  4230. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw();
  4231. /** Case-sensitive comparison of two strings. */
  4232. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw();
  4233. /** Case-sensitive comparison of two strings. */
  4234. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw();
  4235. /** Case-sensitive comparison of two strings. */
  4236. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8& string2) throw();
  4237. /** Case-sensitive comparison of two strings. */
  4238. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16& string2) throw();
  4239. /** Case-sensitive comparison of two strings. */
  4240. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32& string2) throw();
  4241. /** Case-sensitive comparison of two strings. */
  4242. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw();
  4243. /** Case-sensitive comparison of two strings. */
  4244. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw();
  4245. /** Case-sensitive comparison of two strings. */
  4246. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw();
  4247. /** Case-sensitive comparison of two strings. */
  4248. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw();
  4249. /** This streaming override allows you to pass a juce String directly into std output streams.
  4250. This is very handy for writing strings to std::cout, std::cerr, etc.
  4251. */
  4252. template <class charT, class traits>
  4253. JUCE_API std::basic_ostream <charT, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <charT, traits>& stream, const String& stringToWrite)
  4254. {
  4255. return stream << stringToWrite.toUTF8().getAddress();
  4256. }
  4257. /** Writes a string to an OutputStream as UTF8. */
  4258. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text);
  4259. #endif // __JUCE_STRING_JUCEHEADER__
  4260. /*** End of inlined file: juce_String.h ***/
  4261. /**
  4262. Acts as an application-wide logging class.
  4263. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  4264. method and this will then be used by all calls to writeToLog.
  4265. The logger class also contains methods for writing messages to the debugger's
  4266. output stream.
  4267. @see FileLogger
  4268. */
  4269. class JUCE_API Logger
  4270. {
  4271. public:
  4272. /** Destructor. */
  4273. virtual ~Logger();
  4274. /** Sets the current logging class to use.
  4275. Note that the object passed in won't be deleted when no longer needed.
  4276. A null pointer can be passed-in to disable any logging.
  4277. If deleteOldLogger is set to true, the existing logger will be
  4278. deleted (if there is one).
  4279. */
  4280. static void JUCE_CALLTYPE setCurrentLogger (Logger* newLogger,
  4281. bool deleteOldLogger = false);
  4282. /** Writes a string to the current logger.
  4283. This will pass the string to the logger's logMessage() method if a logger
  4284. has been set.
  4285. @see logMessage
  4286. */
  4287. static void JUCE_CALLTYPE writeToLog (const String& message);
  4288. /** Writes a message to the standard error stream.
  4289. This can be called directly, or by using the DBG() macro in
  4290. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  4291. */
  4292. static void JUCE_CALLTYPE outputDebugString (const String& text);
  4293. protected:
  4294. Logger();
  4295. /** This is overloaded by subclasses to implement custom logging behaviour.
  4296. @see setCurrentLogger
  4297. */
  4298. virtual void logMessage (const String& message) = 0;
  4299. private:
  4300. static Logger* currentLogger;
  4301. };
  4302. #endif // __JUCE_LOGGER_JUCEHEADER__
  4303. /*** End of inlined file: juce_Logger.h ***/
  4304. /*** Start of inlined file: juce_LeakedObjectDetector.h ***/
  4305. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4306. #define __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4307. /**
  4308. Embedding an instance of this class inside another class can be used as a low-overhead
  4309. way of detecting leaked instances.
  4310. This class keeps an internal static count of the number of instances that are
  4311. active, so that when the app is shutdown and the static destructors are called,
  4312. it can check whether there are any left-over instances that may have been leaked.
  4313. To use it, use the JUCE_LEAK_DETECTOR macro as a simple way to put one in your
  4314. class declaration. Have a look through the juce codebase for examples, it's used
  4315. in most of the classes.
  4316. */
  4317. template <class OwnerClass>
  4318. class LeakedObjectDetector
  4319. {
  4320. public:
  4321. LeakedObjectDetector() throw() { ++(getCounter().numObjects); }
  4322. LeakedObjectDetector (const LeakedObjectDetector&) throw() { ++(getCounter().numObjects); }
  4323. ~LeakedObjectDetector()
  4324. {
  4325. if (--(getCounter().numObjects) < 0)
  4326. {
  4327. DBG ("*** Dangling pointer deletion! Class: " << String (typeid (OwnerClass).name()));
  4328. /** If you hit this, then you've managed to delete more instances of this class than you've
  4329. created.. That indicates that you're deleting some dangling pointers.
  4330. Note that although this assertion will have been triggered during a destructor, it might
  4331. not be this particular deletion that's at fault - the incorrect one may have happened
  4332. at an earlier point in the program, and simply not been detected until now.
  4333. Most errors like this are caused by using old-fashioned, non-RAII techniques for
  4334. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4335. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4336. */
  4337. jassertfalse;
  4338. }
  4339. }
  4340. private:
  4341. class LeakCounter
  4342. {
  4343. public:
  4344. LeakCounter() {}
  4345. ~LeakCounter()
  4346. {
  4347. if (numObjects.value > 0)
  4348. {
  4349. DBG ("*** Leaked objects detected: " << numObjects.value << " instance(s) of class " << String (typeid (OwnerClass).name()));
  4350. /** If you hit this, then you've leaked one or more objects of the type specified by
  4351. the 'OwnerClass' template parameter - the name should have been printed by the line above.
  4352. If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for
  4353. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  4354. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  4355. */
  4356. jassertfalse;
  4357. }
  4358. }
  4359. Atomic<int> numObjects;
  4360. };
  4361. static LeakCounter& getCounter() throw()
  4362. {
  4363. static LeakCounter counter;
  4364. return counter;
  4365. }
  4366. };
  4367. #if DOXYGEN || ! defined (JUCE_LEAK_DETECTOR)
  4368. #if (DOXYGEN || JUCE_CHECK_MEMORY_LEAKS)
  4369. /** This macro lets you embed a leak-detecting object inside a class.
  4370. To use it, simply declare a JUCE_LEAK_DETECTOR(YourClassName) inside a private section
  4371. of the class declaration. E.g.
  4372. @code
  4373. class MyClass
  4374. {
  4375. public:
  4376. MyClass();
  4377. void blahBlah();
  4378. private:
  4379. JUCE_LEAK_DETECTOR (MyClass);
  4380. };@endcode
  4381. @see JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR, LeakedObjectDetector
  4382. */
  4383. #define JUCE_LEAK_DETECTOR(OwnerClass) JUCE_NAMESPACE::LeakedObjectDetector<OwnerClass> JUCE_JOIN_MACRO (leakDetector, __LINE__);
  4384. #else
  4385. #define JUCE_LEAK_DETECTOR(OwnerClass)
  4386. #endif
  4387. #endif
  4388. #endif // __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  4389. /*** End of inlined file: juce_LeakedObjectDetector.h ***/
  4390. END_JUCE_NAMESPACE
  4391. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  4392. /*** End of inlined file: juce_StandardHeader.h ***/
  4393. BEGIN_JUCE_NAMESPACE
  4394. #if JUCE_MSVC
  4395. // this is set explicitly in case the app is using a different packing size.
  4396. #pragma pack (push, 8)
  4397. #pragma warning (push)
  4398. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  4399. #ifdef __INTEL_COMPILER
  4400. #pragma warning (disable: 1125)
  4401. #endif
  4402. #endif
  4403. // this is where all the class header files get brought in..
  4404. /*** Start of inlined file: juce_core_includes.h ***/
  4405. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4406. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  4407. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4408. /*** Start of inlined file: juce_AbstractFifo.h ***/
  4409. #ifndef __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4410. #define __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4411. /**
  4412. Encapsulates the logic required to implement a lock-free FIFO.
  4413. This class handles the logic needed when building a single-reader, single-writer FIFO.
  4414. It doesn't actually hold any data itself, but your FIFO class can use one of these to manage
  4415. its position and status when reading or writing to it.
  4416. To use it, you can call prepareToWrite() to determine the position within your own buffer that
  4417. an incoming block of data should be stored, and prepareToRead() to find out when the next
  4418. outgoing block should be read from.
  4419. e.g.
  4420. @code
  4421. class MyFifo
  4422. {
  4423. public:
  4424. MyFifo() : abstractFifo (1024)
  4425. {
  4426. }
  4427. void addToFifo (const int* someData, int numItems)
  4428. {
  4429. int start1, size1, start2, size2;
  4430. prepareToWrite (numItems, start1, size1, start2, size2);
  4431. if (size1 > 0)
  4432. copySomeData (myBuffer + start1, someData, size1);
  4433. if (size2 > 0)
  4434. copySomeData (myBuffer + start2, someData + size1, size2);
  4435. finishedWrite (size1 + size2);
  4436. }
  4437. void readFromFifo (int* someData, int numItems)
  4438. {
  4439. int start1, size1, start2, size2;
  4440. prepareToRead (numSamples, start1, size1, start2, size2);
  4441. if (size1 > 0)
  4442. copySomeData (someData, myBuffer + start1, size1);
  4443. if (size2 > 0)
  4444. copySomeData (someData + size1, myBuffer + start2, size2);
  4445. finishedRead (size1 + size2);
  4446. }
  4447. private:
  4448. AbstractFifo abstractFifo;
  4449. int myBuffer [1024];
  4450. };
  4451. @endcode
  4452. */
  4453. class JUCE_API AbstractFifo
  4454. {
  4455. public:
  4456. /** Creates a FIFO to manage a buffer with the specified capacity. */
  4457. AbstractFifo (int capacity) throw();
  4458. /** Destructor */
  4459. ~AbstractFifo();
  4460. /** Returns the total size of the buffer being managed. */
  4461. int getTotalSize() const throw();
  4462. /** Returns the number of items that can currently be added to the buffer without it overflowing. */
  4463. int getFreeSpace() const throw();
  4464. /** Returns the number of items that can currently be read from the buffer. */
  4465. int getNumReady() const throw();
  4466. /** Clears the buffer positions, so that it appears empty. */
  4467. void reset() throw();
  4468. /** Changes the buffer's total size.
  4469. Note that this isn't thread-safe, so don't call it if there's any danger that it
  4470. might overlap with a call to any other method in this class!
  4471. */
  4472. void setTotalSize (int newSize) throw();
  4473. /** Returns the location within the buffer at which an incoming block of data should be written.
  4474. Because the section of data that you want to add to the buffer may overlap the end
  4475. and wrap around to the start, two blocks within your buffer are returned, and you
  4476. should copy your data into the first one, with any remaining data spilling over into
  4477. the second.
  4478. If the number of items you ask for is too large to fit within the buffer's free space, then
  4479. blockSize1 + blockSize2 may add up to a lower value than numToWrite. If this happens, you
  4480. may decide to keep waiting and re-trying the method until there's enough space available.
  4481. After calling this method, if you choose to write your data into the blocks returned, you
  4482. must call finishedWrite() to tell the FIFO how much data you actually added.
  4483. e.g.
  4484. @code
  4485. void addToFifo (const int* someData, int numItems)
  4486. {
  4487. int start1, size1, start2, size2;
  4488. prepareToWrite (numItems, start1, size1, start2, size2);
  4489. if (size1 > 0)
  4490. copySomeData (myBuffer + start1, someData, size1);
  4491. if (size2 > 0)
  4492. copySomeData (myBuffer + start2, someData + size1, size2);
  4493. finishedWrite (size1 + size2);
  4494. }
  4495. @endcode
  4496. @param numToWrite indicates how many items you'd like to add to the buffer
  4497. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4498. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4499. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4500. the first block should be written
  4501. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4502. @see finishedWrite
  4503. */
  4504. void prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw();
  4505. /** Called after reading from the FIFO, to indicate that this many items have been added.
  4506. @see prepareToWrite
  4507. */
  4508. void finishedWrite (int numWritten) throw();
  4509. /** Returns the location within the buffer from which the next block of data should be read.
  4510. Because the section of data that you want to read from the buffer may overlap the end
  4511. and wrap around to the start, two blocks within your buffer are returned, and you
  4512. should read from both of them.
  4513. If the number of items you ask for is greater than the amount of data available, then
  4514. blockSize1 + blockSize2 may add up to a lower value than numWanted. If this happens, you
  4515. may decide to keep waiting and re-trying the method until there's enough data available.
  4516. After calling this method, if you choose to read the data, you must call finishedRead() to
  4517. tell the FIFO how much data you have consumed.
  4518. e.g.
  4519. @code
  4520. void readFromFifo (int* someData, int numItems)
  4521. {
  4522. int start1, size1, start2, size2;
  4523. prepareToRead (numSamples, start1, size1, start2, size2);
  4524. if (size1 > 0)
  4525. copySomeData (someData, myBuffer + start1, size1);
  4526. if (size2 > 0)
  4527. copySomeData (someData + size1, myBuffer + start2, size2);
  4528. finishedRead (size1 + size2);
  4529. }
  4530. @endcode
  4531. @param numWanted indicates how many items you'd like to add to the buffer
  4532. @param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
  4533. @param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
  4534. @param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
  4535. the first block should be written
  4536. @param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
  4537. @see finishedRead
  4538. */
  4539. void prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw();
  4540. /** Called after reading from the FIFO, to indicate that this many items have now been consumed.
  4541. @see prepareToRead
  4542. */
  4543. void finishedRead (int numRead) throw();
  4544. private:
  4545. int bufferSize;
  4546. Atomic <int> validStart, validEnd;
  4547. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AbstractFifo);
  4548. };
  4549. #endif // __JUCE_ABSTRACTFIFO_JUCEHEADER__
  4550. /*** End of inlined file: juce_AbstractFifo.h ***/
  4551. #endif
  4552. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4553. /*** Start of inlined file: juce_Array.h ***/
  4554. #ifndef __JUCE_ARRAY_JUCEHEADER__
  4555. #define __JUCE_ARRAY_JUCEHEADER__
  4556. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  4557. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4558. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4559. /*** Start of inlined file: juce_HeapBlock.h ***/
  4560. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  4561. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  4562. /**
  4563. Very simple container class to hold a pointer to some data on the heap.
  4564. When you need to allocate some heap storage for something, always try to use
  4565. this class instead of allocating the memory directly using malloc/free.
  4566. A HeapBlock<char> object can be treated in pretty much exactly the same way
  4567. as an char*, but as long as you allocate it on the stack or as a class member,
  4568. it's almost impossible for it to leak memory.
  4569. It also makes your code much more concise and readable than doing the same thing
  4570. using direct allocations,
  4571. E.g. instead of this:
  4572. @code
  4573. int* temp = (int*) malloc (1024 * sizeof (int));
  4574. memcpy (temp, xyz, 1024 * sizeof (int));
  4575. free (temp);
  4576. temp = (int*) calloc (2048 * sizeof (int));
  4577. temp[0] = 1234;
  4578. memcpy (foobar, temp, 2048 * sizeof (int));
  4579. free (temp);
  4580. @endcode
  4581. ..you could just write this:
  4582. @code
  4583. HeapBlock <int> temp (1024);
  4584. memcpy (temp, xyz, 1024 * sizeof (int));
  4585. temp.calloc (2048);
  4586. temp[0] = 1234;
  4587. memcpy (foobar, temp, 2048 * sizeof (int));
  4588. @endcode
  4589. The class is extremely lightweight, containing only a pointer to the
  4590. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  4591. as their less object-oriented counterparts. Despite adding safety, you probably
  4592. won't sacrifice any performance by using this in place of normal pointers.
  4593. @see Array, OwnedArray, MemoryBlock
  4594. */
  4595. template <class ElementType>
  4596. class HeapBlock
  4597. {
  4598. public:
  4599. /** Creates a HeapBlock which is initially just a null pointer.
  4600. After creation, you can resize the array using the malloc(), calloc(),
  4601. or realloc() methods.
  4602. */
  4603. HeapBlock() throw() : data (0)
  4604. {
  4605. }
  4606. /** Creates a HeapBlock containing a number of elements.
  4607. The contents of the block are undefined, as it will have been created by a
  4608. malloc call.
  4609. If you want an array of zero values, you can use the calloc() method instead.
  4610. */
  4611. explicit HeapBlock (const size_t numElements)
  4612. : data (static_cast <ElementType*> (::malloc (numElements * sizeof (ElementType))))
  4613. {
  4614. }
  4615. /** Destructor.
  4616. This will free the data, if any has been allocated.
  4617. */
  4618. ~HeapBlock()
  4619. {
  4620. ::free (data);
  4621. }
  4622. /** Returns a raw pointer to the allocated data.
  4623. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4624. freed by calling the free() method.
  4625. */
  4626. inline operator ElementType*() const throw() { return data; }
  4627. /** Returns a raw pointer to the allocated data.
  4628. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4629. freed by calling the free() method.
  4630. */
  4631. inline ElementType* getData() const throw() { return data; }
  4632. /** Returns a void pointer to the allocated data.
  4633. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4634. freed by calling the free() method.
  4635. */
  4636. inline operator void*() const throw() { return static_cast <void*> (data); }
  4637. /** Returns a void pointer to the allocated data.
  4638. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  4639. freed by calling the free() method.
  4640. */
  4641. inline operator const void*() const throw() { return static_cast <const void*> (data); }
  4642. /** Lets you use indirect calls to the first element in the array.
  4643. Obviously this will cause problems if the array hasn't been initialised, because it'll
  4644. be referencing a null pointer.
  4645. */
  4646. inline ElementType* operator->() const throw() { return data; }
  4647. /** Returns a reference to one of the data elements.
  4648. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  4649. has no idea of the size it currently has allocated.
  4650. */
  4651. template <typename IndexType>
  4652. inline ElementType& operator[] (IndexType index) const throw() { return data [index]; }
  4653. /** Returns a pointer to a data element at an offset from the start of the array.
  4654. This is the same as doing pointer arithmetic on the raw pointer itself.
  4655. */
  4656. template <typename IndexType>
  4657. inline ElementType* operator+ (IndexType index) const throw() { return data + index; }
  4658. /** Compares the pointer with another pointer.
  4659. This can be handy for checking whether this is a null pointer.
  4660. */
  4661. inline bool operator== (const ElementType* const otherPointer) const throw() { return otherPointer == data; }
  4662. /** Compares the pointer with another pointer.
  4663. This can be handy for checking whether this is a null pointer.
  4664. */
  4665. inline bool operator!= (const ElementType* const otherPointer) const throw() { return otherPointer != data; }
  4666. /** Allocates a specified amount of memory.
  4667. This uses the normal malloc to allocate an amount of memory for this object.
  4668. Any previously allocated memory will be freed by this method.
  4669. The number of bytes allocated will be (newNumElements * elementSize). Normally
  4670. you wouldn't need to specify the second parameter, but it can be handy if you need
  4671. to allocate a size in bytes rather than in terms of the number of elements.
  4672. The data that is allocated will be freed when this object is deleted, or when you
  4673. call free() or any of the allocation methods.
  4674. */
  4675. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4676. {
  4677. ::free (data);
  4678. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4679. }
  4680. /** Allocates a specified amount of memory and clears it.
  4681. This does the same job as the malloc() method, but clears the memory that it allocates.
  4682. */
  4683. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4684. {
  4685. ::free (data);
  4686. data = static_cast <ElementType*> (::calloc (newNumElements, elementSize));
  4687. }
  4688. /** Allocates a specified amount of memory and optionally clears it.
  4689. This does the same job as either malloc() or calloc(), depending on the
  4690. initialiseToZero parameter.
  4691. */
  4692. void allocate (const size_t newNumElements, const bool initialiseToZero)
  4693. {
  4694. ::free (data);
  4695. if (initialiseToZero)
  4696. data = static_cast <ElementType*> (::calloc (newNumElements, sizeof (ElementType)));
  4697. else
  4698. data = static_cast <ElementType*> (::malloc (newNumElements * sizeof (ElementType)));
  4699. }
  4700. /** Re-allocates a specified amount of memory.
  4701. The semantics of this method are the same as malloc() and calloc(), but it
  4702. uses realloc() to keep as much of the existing data as possible.
  4703. */
  4704. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  4705. {
  4706. if (data == 0)
  4707. data = static_cast <ElementType*> (::malloc (newNumElements * elementSize));
  4708. else
  4709. data = static_cast <ElementType*> (::realloc (data, newNumElements * elementSize));
  4710. }
  4711. /** Frees any currently-allocated data.
  4712. This will free the data and reset this object to be a null pointer.
  4713. */
  4714. void free()
  4715. {
  4716. ::free (data);
  4717. data = 0;
  4718. }
  4719. /** Swaps this object's data with the data of another HeapBlock.
  4720. The two objects simply exchange their data pointers.
  4721. */
  4722. void swapWith (HeapBlock <ElementType>& other) throw()
  4723. {
  4724. swapVariables (data, other.data);
  4725. }
  4726. private:
  4727. ElementType* data;
  4728. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HeapBlock);
  4729. };
  4730. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  4731. /*** End of inlined file: juce_HeapBlock.h ***/
  4732. /**
  4733. Implements some basic array storage allocation functions.
  4734. This class isn't really for public use - it's used by the other
  4735. array classes, but might come in handy for some purposes.
  4736. It inherits from a critical section class to allow the arrays to use
  4737. the "empty base class optimisation" pattern to reduce their footprint.
  4738. @see Array, OwnedArray, ReferenceCountedArray
  4739. */
  4740. template <class ElementType, class TypeOfCriticalSectionToUse>
  4741. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  4742. {
  4743. public:
  4744. /** Creates an empty array. */
  4745. ArrayAllocationBase() throw()
  4746. : numAllocated (0)
  4747. {
  4748. }
  4749. /** Destructor. */
  4750. ~ArrayAllocationBase()
  4751. {
  4752. }
  4753. /** Changes the amount of storage allocated.
  4754. This will retain any data currently held in the array, and either add or
  4755. remove extra space at the end.
  4756. @param numElements the number of elements that are needed
  4757. */
  4758. void setAllocatedSize (const int numElements)
  4759. {
  4760. if (numAllocated != numElements)
  4761. {
  4762. if (numElements > 0)
  4763. elements.realloc (numElements);
  4764. else
  4765. elements.free();
  4766. numAllocated = numElements;
  4767. }
  4768. }
  4769. /** Increases the amount of storage allocated if it is less than a given amount.
  4770. This will retain any data currently held in the array, but will add
  4771. extra space at the end to make sure there it's at least as big as the size
  4772. passed in. If it's already bigger, no action is taken.
  4773. @param minNumElements the minimum number of elements that are needed
  4774. */
  4775. void ensureAllocatedSize (const int minNumElements)
  4776. {
  4777. if (minNumElements > numAllocated)
  4778. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  4779. }
  4780. /** Minimises the amount of storage allocated so that it's no more than
  4781. the given number of elements.
  4782. */
  4783. void shrinkToNoMoreThan (const int maxNumElements)
  4784. {
  4785. if (maxNumElements < numAllocated)
  4786. setAllocatedSize (maxNumElements);
  4787. }
  4788. /** Swap the contents of two objects. */
  4789. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  4790. {
  4791. elements.swapWith (other.elements);
  4792. swapVariables (numAllocated, other.numAllocated);
  4793. }
  4794. HeapBlock <ElementType> elements;
  4795. int numAllocated;
  4796. private:
  4797. JUCE_DECLARE_NON_COPYABLE (ArrayAllocationBase);
  4798. };
  4799. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  4800. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  4801. /*** Start of inlined file: juce_ElementComparator.h ***/
  4802. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4803. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4804. /**
  4805. Sorts a range of elements in an array.
  4806. The comparator object that is passed-in must define a public method with the following
  4807. signature:
  4808. @code
  4809. int compareElements (ElementType first, ElementType second);
  4810. @endcode
  4811. ..and this method must return:
  4812. - a value of < 0 if the first comes before the second
  4813. - a value of 0 if the two objects are equivalent
  4814. - a value of > 0 if the second comes before the first
  4815. To improve performance, the compareElements() method can be declared as static or const.
  4816. @param comparator an object which defines a compareElements() method
  4817. @param array the array to sort
  4818. @param firstElement the index of the first element of the range to be sorted
  4819. @param lastElement the index of the last element in the range that needs
  4820. sorting (this is inclusive)
  4821. @param retainOrderOfEquivalentItems if true, the order of items that the
  4822. comparator deems the same will be maintained - this will be
  4823. a slower algorithm than if they are allowed to be moved around.
  4824. @see sortArrayRetainingOrder
  4825. */
  4826. template <class ElementType, class ElementComparator>
  4827. static void sortArray (ElementComparator& comparator,
  4828. ElementType* const array,
  4829. int firstElement,
  4830. int lastElement,
  4831. const bool retainOrderOfEquivalentItems)
  4832. {
  4833. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4834. // avoids getting warning messages about the parameter being unused
  4835. if (lastElement > firstElement)
  4836. {
  4837. if (retainOrderOfEquivalentItems)
  4838. {
  4839. for (int i = firstElement; i < lastElement; ++i)
  4840. {
  4841. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  4842. {
  4843. swapVariables (array[i], array[i + 1]);
  4844. if (i > firstElement)
  4845. i -= 2;
  4846. }
  4847. }
  4848. }
  4849. else
  4850. {
  4851. int fromStack[30], toStack[30];
  4852. int stackIndex = 0;
  4853. for (;;)
  4854. {
  4855. const int size = (lastElement - firstElement) + 1;
  4856. if (size <= 8)
  4857. {
  4858. int j = lastElement;
  4859. int maxIndex;
  4860. while (j > firstElement)
  4861. {
  4862. maxIndex = firstElement;
  4863. for (int k = firstElement + 1; k <= j; ++k)
  4864. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  4865. maxIndex = k;
  4866. swapVariables (array[j], array[maxIndex]);
  4867. --j;
  4868. }
  4869. }
  4870. else
  4871. {
  4872. const int mid = firstElement + (size >> 1);
  4873. swapVariables (array[mid], array[firstElement]);
  4874. int i = firstElement;
  4875. int j = lastElement + 1;
  4876. for (;;)
  4877. {
  4878. while (++i <= lastElement
  4879. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  4880. {}
  4881. while (--j > firstElement
  4882. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  4883. {}
  4884. if (j < i)
  4885. break;
  4886. swapVariables (array[i], array[j]);
  4887. }
  4888. swapVariables (array[j], array[firstElement]);
  4889. if (j - 1 - firstElement >= lastElement - i)
  4890. {
  4891. if (firstElement + 1 < j)
  4892. {
  4893. fromStack [stackIndex] = firstElement;
  4894. toStack [stackIndex] = j - 1;
  4895. ++stackIndex;
  4896. }
  4897. if (i < lastElement)
  4898. {
  4899. firstElement = i;
  4900. continue;
  4901. }
  4902. }
  4903. else
  4904. {
  4905. if (i < lastElement)
  4906. {
  4907. fromStack [stackIndex] = i;
  4908. toStack [stackIndex] = lastElement;
  4909. ++stackIndex;
  4910. }
  4911. if (firstElement + 1 < j)
  4912. {
  4913. lastElement = j - 1;
  4914. continue;
  4915. }
  4916. }
  4917. }
  4918. if (--stackIndex < 0)
  4919. break;
  4920. jassert (stackIndex < numElementsInArray (fromStack));
  4921. firstElement = fromStack [stackIndex];
  4922. lastElement = toStack [stackIndex];
  4923. }
  4924. }
  4925. }
  4926. }
  4927. /**
  4928. Searches a sorted array of elements, looking for the index at which a specified value
  4929. should be inserted for it to be in the correct order.
  4930. The comparator object that is passed-in must define a public method with the following
  4931. signature:
  4932. @code
  4933. int compareElements (ElementType first, ElementType second);
  4934. @endcode
  4935. ..and this method must return:
  4936. - a value of < 0 if the first comes before the second
  4937. - a value of 0 if the two objects are equivalent
  4938. - a value of > 0 if the second comes before the first
  4939. To improve performance, the compareElements() method can be declared as static or const.
  4940. @param comparator an object which defines a compareElements() method
  4941. @param array the array to search
  4942. @param newElement the value that is going to be inserted
  4943. @param firstElement the index of the first element to search
  4944. @param lastElement the index of the last element in the range (this is non-inclusive)
  4945. */
  4946. template <class ElementType, class ElementComparator>
  4947. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  4948. ElementType* const array,
  4949. const ElementType newElement,
  4950. int firstElement,
  4951. int lastElement)
  4952. {
  4953. jassert (firstElement <= lastElement);
  4954. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4955. // avoids getting warning messages about the parameter being unused
  4956. while (firstElement < lastElement)
  4957. {
  4958. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  4959. {
  4960. ++firstElement;
  4961. break;
  4962. }
  4963. else
  4964. {
  4965. const int halfway = (firstElement + lastElement) >> 1;
  4966. if (halfway == firstElement)
  4967. {
  4968. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  4969. ++firstElement;
  4970. break;
  4971. }
  4972. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  4973. {
  4974. firstElement = halfway;
  4975. }
  4976. else
  4977. {
  4978. lastElement = halfway;
  4979. }
  4980. }
  4981. }
  4982. return firstElement;
  4983. }
  4984. /**
  4985. A simple ElementComparator class that can be used to sort an array of
  4986. objects that support the '<' operator.
  4987. This will work for primitive types and objects that implement operator<().
  4988. Example: @code
  4989. Array <int> myArray;
  4990. DefaultElementComparator<int> sorter;
  4991. myArray.sort (sorter);
  4992. @endcode
  4993. @see ElementComparator
  4994. */
  4995. template <class ElementType>
  4996. class DefaultElementComparator
  4997. {
  4998. private:
  4999. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5000. public:
  5001. static int compareElements (ParameterType first, ParameterType second)
  5002. {
  5003. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  5004. }
  5005. };
  5006. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  5007. /*** End of inlined file: juce_ElementComparator.h ***/
  5008. /*** Start of inlined file: juce_CriticalSection.h ***/
  5009. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  5010. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  5011. #ifndef DOXYGEN
  5012. class JUCE_API ScopedLock;
  5013. class JUCE_API ScopedUnlock;
  5014. #endif
  5015. /**
  5016. Prevents multiple threads from accessing shared objects at the same time.
  5017. @see ScopedLock, Thread, InterProcessLock
  5018. */
  5019. class JUCE_API CriticalSection
  5020. {
  5021. public:
  5022. /**
  5023. Creates a CriticalSection object
  5024. */
  5025. CriticalSection() throw();
  5026. /** Destroys a CriticalSection object.
  5027. If the critical section is deleted whilst locked, its subsequent behaviour
  5028. is unpredictable.
  5029. */
  5030. ~CriticalSection() throw();
  5031. /** Locks this critical section.
  5032. If the lock is currently held by another thread, this will wait until it
  5033. becomes free.
  5034. If the lock is already held by the caller thread, the method returns immediately.
  5035. @see exit, ScopedLock
  5036. */
  5037. void enter() const throw();
  5038. /** Attempts to lock this critical section without blocking.
  5039. This method behaves identically to CriticalSection::enter, except that the caller thread
  5040. does not wait if the lock is currently held by another thread but returns false immediately.
  5041. @returns false if the lock is currently held by another thread, true otherwise.
  5042. @see enter
  5043. */
  5044. bool tryEnter() const throw();
  5045. /** Releases the lock.
  5046. If the caller thread hasn't got the lock, this can have unpredictable results.
  5047. If the enter() method has been called multiple times by the thread, each
  5048. call must be matched by a call to exit() before other threads will be allowed
  5049. to take over the lock.
  5050. @see enter, ScopedLock
  5051. */
  5052. void exit() const throw();
  5053. /** Provides the type of scoped lock to use with this type of critical section object. */
  5054. typedef ScopedLock ScopedLockType;
  5055. /** Provides the type of scoped unlocker to use with this type of critical section object. */
  5056. typedef ScopedUnlock ScopedUnlockType;
  5057. private:
  5058. #if JUCE_WINDOWS
  5059. #if JUCE_64BIT
  5060. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  5061. // block of memory here that's big enough to be used internally as a windows critical
  5062. // section object.
  5063. uint8 internal [44];
  5064. #else
  5065. uint8 internal [24];
  5066. #endif
  5067. #else
  5068. mutable pthread_mutex_t internal;
  5069. #endif
  5070. JUCE_DECLARE_NON_COPYABLE (CriticalSection);
  5071. };
  5072. /**
  5073. A class that can be used in place of a real CriticalSection object.
  5074. This is currently used by some templated classes, and should get
  5075. optimised out by the compiler.
  5076. @see Array, OwnedArray, ReferenceCountedArray
  5077. */
  5078. class JUCE_API DummyCriticalSection
  5079. {
  5080. public:
  5081. inline DummyCriticalSection() throw() {}
  5082. inline ~DummyCriticalSection() throw() {}
  5083. inline void enter() const throw() {}
  5084. inline void exit() const throw() {}
  5085. /** A dummy scoped-lock type to use with a dummy critical section. */
  5086. struct ScopedLockType
  5087. {
  5088. ScopedLockType (const DummyCriticalSection&) throw() {}
  5089. };
  5090. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  5091. typedef ScopedLockType ScopedUnlockType;
  5092. private:
  5093. JUCE_DECLARE_NON_COPYABLE (DummyCriticalSection);
  5094. };
  5095. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  5096. /*** End of inlined file: juce_CriticalSection.h ***/
  5097. /**
  5098. Holds a resizable array of primitive or copy-by-value objects.
  5099. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  5100. The Array class can be used to hold simple, non-polymorphic objects as well as primitive types - to
  5101. do so, the class must fulfil these requirements:
  5102. - it must have a copy constructor and assignment operator
  5103. - it must be able to be relocated in memory by a memcpy without this causing any problems - so
  5104. objects whose functionality relies on external pointers or references to themselves can be used.
  5105. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  5106. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  5107. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  5108. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  5109. specialised class StringArray, which provides more useful functions.
  5110. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  5111. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  5112. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  5113. */
  5114. template <typename ElementType,
  5115. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  5116. class Array
  5117. {
  5118. private:
  5119. #if JUCE_VC8_OR_EARLIER
  5120. typedef const ElementType& ParameterType;
  5121. #else
  5122. typedef PARAMETER_TYPE (ElementType) ParameterType;
  5123. #endif
  5124. public:
  5125. /** Creates an empty array. */
  5126. Array() throw()
  5127. : numUsed (0)
  5128. {
  5129. }
  5130. /** Creates a copy of another array.
  5131. @param other the array to copy
  5132. */
  5133. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  5134. {
  5135. const ScopedLockType lock (other.getLock());
  5136. numUsed = other.numUsed;
  5137. data.setAllocatedSize (other.numUsed);
  5138. for (int i = 0; i < numUsed; ++i)
  5139. new (data.elements + i) ElementType (other.data.elements[i]);
  5140. }
  5141. /** Initalises from a null-terminated C array of values.
  5142. @param values the array to copy from
  5143. */
  5144. template <typename TypeToCreateFrom>
  5145. explicit Array (const TypeToCreateFrom* values)
  5146. : numUsed (0)
  5147. {
  5148. while (*values != TypeToCreateFrom())
  5149. add (*values++);
  5150. }
  5151. /** Initalises from a C array of values.
  5152. @param values the array to copy from
  5153. @param numValues the number of values in the array
  5154. */
  5155. template <typename TypeToCreateFrom>
  5156. Array (const TypeToCreateFrom* values, int numValues)
  5157. : numUsed (numValues)
  5158. {
  5159. data.setAllocatedSize (numValues);
  5160. for (int i = 0; i < numValues; ++i)
  5161. new (data.elements + i) ElementType (values[i]);
  5162. }
  5163. /** Destructor. */
  5164. ~Array()
  5165. {
  5166. for (int i = 0; i < numUsed; ++i)
  5167. data.elements[i].~ElementType();
  5168. }
  5169. /** Copies another array.
  5170. @param other the array to copy
  5171. */
  5172. Array& operator= (const Array& other)
  5173. {
  5174. if (this != &other)
  5175. {
  5176. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  5177. swapWithArray (otherCopy);
  5178. }
  5179. return *this;
  5180. }
  5181. /** Compares this array to another one.
  5182. Two arrays are considered equal if they both contain the same set of
  5183. elements, in the same order.
  5184. @param other the other array to compare with
  5185. */
  5186. template <class OtherArrayType>
  5187. bool operator== (const OtherArrayType& other) const
  5188. {
  5189. const ScopedLockType lock (getLock());
  5190. if (numUsed != other.numUsed)
  5191. return false;
  5192. for (int i = numUsed; --i >= 0;)
  5193. if (! (data.elements [i] == other.data.elements [i]))
  5194. return false;
  5195. return true;
  5196. }
  5197. /** Compares this array to another one.
  5198. Two arrays are considered equal if they both contain the same set of
  5199. elements, in the same order.
  5200. @param other the other array to compare with
  5201. */
  5202. template <class OtherArrayType>
  5203. bool operator!= (const OtherArrayType& other) const
  5204. {
  5205. return ! operator== (other);
  5206. }
  5207. /** Removes all elements from the array.
  5208. This will remove all the elements, and free any storage that the array is
  5209. using. To clear the array without freeing the storage, use the clearQuick()
  5210. method instead.
  5211. @see clearQuick
  5212. */
  5213. void clear()
  5214. {
  5215. const ScopedLockType lock (getLock());
  5216. for (int i = 0; i < numUsed; ++i)
  5217. data.elements[i].~ElementType();
  5218. data.setAllocatedSize (0);
  5219. numUsed = 0;
  5220. }
  5221. /** Removes all elements from the array without freeing the array's allocated storage.
  5222. @see clear
  5223. */
  5224. void clearQuick()
  5225. {
  5226. const ScopedLockType lock (getLock());
  5227. for (int i = 0; i < numUsed; ++i)
  5228. data.elements[i].~ElementType();
  5229. numUsed = 0;
  5230. }
  5231. /** Returns the current number of elements in the array.
  5232. */
  5233. inline int size() const throw()
  5234. {
  5235. return numUsed;
  5236. }
  5237. /** Returns one of the elements in the array.
  5238. If the index passed in is beyond the range of valid elements, this
  5239. will return zero.
  5240. If you're certain that the index will always be a valid element, you
  5241. can call getUnchecked() instead, which is faster.
  5242. @param index the index of the element being requested (0 is the first element in the array)
  5243. @see getUnchecked, getFirst, getLast
  5244. */
  5245. inline ElementType operator[] (const int index) const
  5246. {
  5247. const ScopedLockType lock (getLock());
  5248. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  5249. : ElementType();
  5250. }
  5251. /** Returns one of the elements in the array, without checking the index passed in.
  5252. Unlike the operator[] method, this will try to return an element without
  5253. checking that the index is within the bounds of the array, so should only
  5254. be used when you're confident that it will always be a valid index.
  5255. @param index the index of the element being requested (0 is the first element in the array)
  5256. @see operator[], getFirst, getLast
  5257. */
  5258. inline const ElementType getUnchecked (const int index) const
  5259. {
  5260. const ScopedLockType lock (getLock());
  5261. jassert (isPositiveAndBelow (index, numUsed));
  5262. return data.elements [index];
  5263. }
  5264. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  5265. This is like getUnchecked, but returns a direct reference to the element, so that
  5266. you can alter it directly. Obviously this can be dangerous, so only use it when
  5267. absolutely necessary.
  5268. @param index the index of the element being requested (0 is the first element in the array)
  5269. @see operator[], getFirst, getLast
  5270. */
  5271. inline ElementType& getReference (const int index) const throw()
  5272. {
  5273. const ScopedLockType lock (getLock());
  5274. jassert (isPositiveAndBelow (index, numUsed));
  5275. return data.elements [index];
  5276. }
  5277. /** Returns the first element in the array, or 0 if the array is empty.
  5278. @see operator[], getUnchecked, getLast
  5279. */
  5280. inline ElementType getFirst() const
  5281. {
  5282. const ScopedLockType lock (getLock());
  5283. return (numUsed > 0) ? data.elements [0]
  5284. : ElementType();
  5285. }
  5286. /** Returns the last element in the array, or 0 if the array is empty.
  5287. @see operator[], getUnchecked, getFirst
  5288. */
  5289. inline ElementType getLast() const
  5290. {
  5291. const ScopedLockType lock (getLock());
  5292. return (numUsed > 0) ? data.elements [numUsed - 1]
  5293. : ElementType();
  5294. }
  5295. /** Returns a pointer to the actual array data.
  5296. This pointer will only be valid until the next time a non-const method
  5297. is called on the array.
  5298. */
  5299. inline ElementType* getRawDataPointer() throw()
  5300. {
  5301. return data.elements;
  5302. }
  5303. /** Finds the index of the first element which matches the value passed in.
  5304. This will search the array for the given object, and return the index
  5305. of its first occurrence. If the object isn't found, the method will return -1.
  5306. @param elementToLookFor the value or object to look for
  5307. @returns the index of the object, or -1 if it's not found
  5308. */
  5309. int indexOf (ParameterType elementToLookFor) const
  5310. {
  5311. const ScopedLockType lock (getLock());
  5312. const ElementType* e = data.elements.getData();
  5313. const ElementType* const end = e + numUsed;
  5314. while (e != end)
  5315. {
  5316. if (elementToLookFor == *e)
  5317. return static_cast <int> (e - data.elements.getData());
  5318. ++e;
  5319. }
  5320. return -1;
  5321. }
  5322. /** Returns true if the array contains at least one occurrence of an object.
  5323. @param elementToLookFor the value or object to look for
  5324. @returns true if the item is found
  5325. */
  5326. bool contains (ParameterType elementToLookFor) const
  5327. {
  5328. const ScopedLockType lock (getLock());
  5329. const ElementType* e = data.elements.getData();
  5330. const ElementType* const end = e + numUsed;
  5331. while (e != end)
  5332. {
  5333. if (elementToLookFor == *e)
  5334. return true;
  5335. ++e;
  5336. }
  5337. return false;
  5338. }
  5339. /** Appends a new element at the end of the array.
  5340. @param newElement the new object to add to the array
  5341. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  5342. */
  5343. void add (ParameterType newElement)
  5344. {
  5345. const ScopedLockType lock (getLock());
  5346. data.ensureAllocatedSize (numUsed + 1);
  5347. new (data.elements + numUsed++) ElementType (newElement);
  5348. }
  5349. /** Inserts a new element into the array at a given position.
  5350. If the index is less than 0 or greater than the size of the array, the
  5351. element will be added to the end of the array.
  5352. Otherwise, it will be inserted into the array, moving all the later elements
  5353. along to make room.
  5354. @param indexToInsertAt the index at which the new element should be
  5355. inserted (pass in -1 to add it to the end)
  5356. @param newElement the new object to add to the array
  5357. @see add, addSorted, addUsingDefaultSort, set
  5358. */
  5359. void insert (int indexToInsertAt, ParameterType newElement)
  5360. {
  5361. const ScopedLockType lock (getLock());
  5362. data.ensureAllocatedSize (numUsed + 1);
  5363. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5364. {
  5365. ElementType* const insertPos = data.elements + indexToInsertAt;
  5366. const int numberToMove = numUsed - indexToInsertAt;
  5367. if (numberToMove > 0)
  5368. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  5369. new (insertPos) ElementType (newElement);
  5370. ++numUsed;
  5371. }
  5372. else
  5373. {
  5374. new (data.elements + numUsed++) ElementType (newElement);
  5375. }
  5376. }
  5377. /** Inserts multiple copies of an element into the array at a given position.
  5378. If the index is less than 0 or greater than the size of the array, the
  5379. element will be added to the end of the array.
  5380. Otherwise, it will be inserted into the array, moving all the later elements
  5381. along to make room.
  5382. @param indexToInsertAt the index at which the new element should be inserted
  5383. @param newElement the new object to add to the array
  5384. @param numberOfTimesToInsertIt how many copies of the value to insert
  5385. @see insert, add, addSorted, set
  5386. */
  5387. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  5388. int numberOfTimesToInsertIt)
  5389. {
  5390. if (numberOfTimesToInsertIt > 0)
  5391. {
  5392. const ScopedLockType lock (getLock());
  5393. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  5394. ElementType* insertPos;
  5395. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5396. {
  5397. insertPos = data.elements + indexToInsertAt;
  5398. const int numberToMove = numUsed - indexToInsertAt;
  5399. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  5400. }
  5401. else
  5402. {
  5403. insertPos = data.elements + numUsed;
  5404. }
  5405. numUsed += numberOfTimesToInsertIt;
  5406. while (--numberOfTimesToInsertIt >= 0)
  5407. new (insertPos++) ElementType (newElement);
  5408. }
  5409. }
  5410. /** Inserts an array of values into this array at a given position.
  5411. If the index is less than 0 or greater than the size of the array, the
  5412. new elements will be added to the end of the array.
  5413. Otherwise, they will be inserted into the array, moving all the later elements
  5414. along to make room.
  5415. @param indexToInsertAt the index at which the first new element should be inserted
  5416. @param newElements the new values to add to the array
  5417. @param numberOfElements how many items are in the array
  5418. @see insert, add, addSorted, set
  5419. */
  5420. void insertArray (int indexToInsertAt,
  5421. const ElementType* newElements,
  5422. int numberOfElements)
  5423. {
  5424. if (numberOfElements > 0)
  5425. {
  5426. const ScopedLockType lock (getLock());
  5427. data.ensureAllocatedSize (numUsed + numberOfElements);
  5428. ElementType* insertPos;
  5429. if (isPositiveAndBelow (indexToInsertAt, numUsed))
  5430. {
  5431. insertPos = data.elements + indexToInsertAt;
  5432. const int numberToMove = numUsed - indexToInsertAt;
  5433. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  5434. }
  5435. else
  5436. {
  5437. insertPos = data.elements + numUsed;
  5438. }
  5439. numUsed += numberOfElements;
  5440. while (--numberOfElements >= 0)
  5441. new (insertPos++) ElementType (*newElements++);
  5442. }
  5443. }
  5444. /** Appends a new element at the end of the array as long as the array doesn't
  5445. already contain it.
  5446. If the array already contains an element that matches the one passed in, nothing
  5447. will be done.
  5448. @param newElement the new object to add to the array
  5449. */
  5450. void addIfNotAlreadyThere (ParameterType newElement)
  5451. {
  5452. const ScopedLockType lock (getLock());
  5453. if (! contains (newElement))
  5454. add (newElement);
  5455. }
  5456. /** Replaces an element with a new value.
  5457. If the index is less than zero, this method does nothing.
  5458. If the index is beyond the end of the array, the item is added to the end of the array.
  5459. @param indexToChange the index whose value you want to change
  5460. @param newValue the new value to set for this index.
  5461. @see add, insert
  5462. */
  5463. void set (const int indexToChange, ParameterType newValue)
  5464. {
  5465. jassert (indexToChange >= 0);
  5466. const ScopedLockType lock (getLock());
  5467. if (isPositiveAndBelow (indexToChange, numUsed))
  5468. {
  5469. data.elements [indexToChange] = newValue;
  5470. }
  5471. else if (indexToChange >= 0)
  5472. {
  5473. data.ensureAllocatedSize (numUsed + 1);
  5474. new (data.elements + numUsed++) ElementType (newValue);
  5475. }
  5476. }
  5477. /** Replaces an element with a new value without doing any bounds-checking.
  5478. This just sets a value directly in the array's internal storage, so you'd
  5479. better make sure it's in range!
  5480. @param indexToChange the index whose value you want to change
  5481. @param newValue the new value to set for this index.
  5482. @see set, getUnchecked
  5483. */
  5484. void setUnchecked (const int indexToChange, ParameterType newValue)
  5485. {
  5486. const ScopedLockType lock (getLock());
  5487. jassert (isPositiveAndBelow (indexToChange, numUsed));
  5488. data.elements [indexToChange] = newValue;
  5489. }
  5490. /** Adds elements from an array to the end of this array.
  5491. @param elementsToAdd the array of elements to add
  5492. @param numElementsToAdd how many elements are in this other array
  5493. @see add
  5494. */
  5495. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  5496. {
  5497. const ScopedLockType lock (getLock());
  5498. if (numElementsToAdd > 0)
  5499. {
  5500. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5501. while (--numElementsToAdd >= 0)
  5502. {
  5503. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  5504. ++numUsed;
  5505. }
  5506. }
  5507. }
  5508. /** This swaps the contents of this array with those of another array.
  5509. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5510. because it just swaps their internal pointers.
  5511. */
  5512. void swapWithArray (Array& otherArray) throw()
  5513. {
  5514. const ScopedLockType lock1 (getLock());
  5515. const ScopedLockType lock2 (otherArray.getLock());
  5516. data.swapWith (otherArray.data);
  5517. swapVariables (numUsed, otherArray.numUsed);
  5518. }
  5519. /** Adds elements from another array to the end of this array.
  5520. @param arrayToAddFrom the array from which to copy the elements
  5521. @param startIndex the first element of the other array to start copying from
  5522. @param numElementsToAdd how many elements to add from the other array. If this
  5523. value is negative or greater than the number of available elements,
  5524. all available elements will be copied.
  5525. @see add
  5526. */
  5527. template <class OtherArrayType>
  5528. void addArray (const OtherArrayType& arrayToAddFrom,
  5529. int startIndex = 0,
  5530. int numElementsToAdd = -1)
  5531. {
  5532. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5533. {
  5534. const ScopedLockType lock2 (getLock());
  5535. if (startIndex < 0)
  5536. {
  5537. jassertfalse;
  5538. startIndex = 0;
  5539. }
  5540. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5541. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5542. while (--numElementsToAdd >= 0)
  5543. add (arrayToAddFrom.getUnchecked (startIndex++));
  5544. }
  5545. }
  5546. /** Inserts a new element into the array, assuming that the array is sorted.
  5547. This will use a comparator to find the position at which the new element
  5548. should go. If the array isn't sorted, the behaviour of this
  5549. method will be unpredictable.
  5550. @param comparator the comparator to use to compare the elements - see the sort()
  5551. method for details about the form this object should take
  5552. @param newElement the new element to insert to the array
  5553. @see addUsingDefaultSort, add, sort
  5554. */
  5555. template <class ElementComparator>
  5556. void addSorted (ElementComparator& comparator, ParameterType newElement)
  5557. {
  5558. const ScopedLockType lock (getLock());
  5559. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed), newElement);
  5560. }
  5561. /** Inserts a new element into the array, assuming that the array is sorted.
  5562. This will use the DefaultElementComparator class for sorting, so your ElementType
  5563. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  5564. method will be unpredictable.
  5565. @param newElement the new element to insert to the array
  5566. @see addSorted, sort
  5567. */
  5568. void addUsingDefaultSort (ParameterType newElement)
  5569. {
  5570. DefaultElementComparator <ElementType> comparator;
  5571. addSorted (comparator, newElement);
  5572. }
  5573. /** Finds the index of an element in the array, assuming that the array is sorted.
  5574. This will use a comparator to do a binary-chop to find the index of the given
  5575. element, if it exists. If the array isn't sorted, the behaviour of this
  5576. method will be unpredictable.
  5577. @param comparator the comparator to use to compare the elements - see the sort()
  5578. method for details about the form this object should take
  5579. @param elementToLookFor the element to search for
  5580. @returns the index of the element, or -1 if it's not found
  5581. @see addSorted, sort
  5582. */
  5583. template <class ElementComparator>
  5584. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  5585. {
  5586. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5587. // avoids getting warning messages about the parameter being unused
  5588. const ScopedLockType lock (getLock());
  5589. int start = 0;
  5590. int end = numUsed;
  5591. for (;;)
  5592. {
  5593. if (start >= end)
  5594. {
  5595. return -1;
  5596. }
  5597. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  5598. {
  5599. return start;
  5600. }
  5601. else
  5602. {
  5603. const int halfway = (start + end) >> 1;
  5604. if (halfway == start)
  5605. return -1;
  5606. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  5607. start = halfway;
  5608. else
  5609. end = halfway;
  5610. }
  5611. }
  5612. }
  5613. /** Removes an element from the array.
  5614. This will remove the element at a given index, and move back
  5615. all the subsequent elements to close the gap.
  5616. If the index passed in is out-of-range, nothing will happen.
  5617. @param indexToRemove the index of the element to remove
  5618. @returns the element that has been removed
  5619. @see removeValue, removeRange
  5620. */
  5621. ElementType remove (const int indexToRemove)
  5622. {
  5623. const ScopedLockType lock (getLock());
  5624. if (isPositiveAndBelow (indexToRemove, numUsed))
  5625. {
  5626. --numUsed;
  5627. ElementType* const e = data.elements + indexToRemove;
  5628. ElementType removed (*e);
  5629. e->~ElementType();
  5630. const int numberToShift = numUsed - indexToRemove;
  5631. if (numberToShift > 0)
  5632. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  5633. if ((numUsed << 1) < data.numAllocated)
  5634. minimiseStorageOverheads();
  5635. return removed;
  5636. }
  5637. else
  5638. {
  5639. return ElementType();
  5640. }
  5641. }
  5642. /** Removes an item from the array.
  5643. This will remove the first occurrence of the given element from the array.
  5644. If the item isn't found, no action is taken.
  5645. @param valueToRemove the object to try to remove
  5646. @see remove, removeRange
  5647. */
  5648. void removeValue (ParameterType valueToRemove)
  5649. {
  5650. const ScopedLockType lock (getLock());
  5651. ElementType* e = data.elements;
  5652. for (int i = numUsed; --i >= 0;)
  5653. {
  5654. if (valueToRemove == *e)
  5655. {
  5656. remove (static_cast <int> (e - data.elements.getData()));
  5657. break;
  5658. }
  5659. ++e;
  5660. }
  5661. }
  5662. /** Removes a range of elements from the array.
  5663. This will remove a set of elements, starting from the given index,
  5664. and move subsequent elements down to close the gap.
  5665. If the range extends beyond the bounds of the array, it will
  5666. be safely clipped to the size of the array.
  5667. @param startIndex the index of the first element to remove
  5668. @param numberToRemove how many elements should be removed
  5669. @see remove, removeValue
  5670. */
  5671. void removeRange (int startIndex, int numberToRemove)
  5672. {
  5673. const ScopedLockType lock (getLock());
  5674. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  5675. startIndex = jlimit (0, numUsed, startIndex);
  5676. if (endIndex > startIndex)
  5677. {
  5678. ElementType* const e = data.elements + startIndex;
  5679. numberToRemove = endIndex - startIndex;
  5680. for (int i = 0; i < numberToRemove; ++i)
  5681. e[i].~ElementType();
  5682. const int numToShift = numUsed - endIndex;
  5683. if (numToShift > 0)
  5684. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  5685. numUsed -= numberToRemove;
  5686. if ((numUsed << 1) < data.numAllocated)
  5687. minimiseStorageOverheads();
  5688. }
  5689. }
  5690. /** Removes the last n elements from the array.
  5691. @param howManyToRemove how many elements to remove from the end of the array
  5692. @see remove, removeValue, removeRange
  5693. */
  5694. void removeLast (int howManyToRemove = 1)
  5695. {
  5696. const ScopedLockType lock (getLock());
  5697. if (howManyToRemove > numUsed)
  5698. howManyToRemove = numUsed;
  5699. for (int i = 1; i <= howManyToRemove; ++i)
  5700. data.elements [numUsed - i].~ElementType();
  5701. numUsed -= howManyToRemove;
  5702. if ((numUsed << 1) < data.numAllocated)
  5703. minimiseStorageOverheads();
  5704. }
  5705. /** Removes any elements which are also in another array.
  5706. @param otherArray the other array in which to look for elements to remove
  5707. @see removeValuesNotIn, remove, removeValue, removeRange
  5708. */
  5709. template <class OtherArrayType>
  5710. void removeValuesIn (const OtherArrayType& otherArray)
  5711. {
  5712. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  5713. const ScopedLockType lock2 (getLock());
  5714. if (this == &otherArray)
  5715. {
  5716. clear();
  5717. }
  5718. else
  5719. {
  5720. if (otherArray.size() > 0)
  5721. {
  5722. for (int i = numUsed; --i >= 0;)
  5723. if (otherArray.contains (data.elements [i]))
  5724. remove (i);
  5725. }
  5726. }
  5727. }
  5728. /** Removes any elements which are not found in another array.
  5729. Only elements which occur in this other array will be retained.
  5730. @param otherArray the array in which to look for elements NOT to remove
  5731. @see removeValuesIn, remove, removeValue, removeRange
  5732. */
  5733. template <class OtherArrayType>
  5734. void removeValuesNotIn (const OtherArrayType& otherArray)
  5735. {
  5736. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  5737. const ScopedLockType lock2 (getLock());
  5738. if (this != &otherArray)
  5739. {
  5740. if (otherArray.size() <= 0)
  5741. {
  5742. clear();
  5743. }
  5744. else
  5745. {
  5746. for (int i = numUsed; --i >= 0;)
  5747. if (! otherArray.contains (data.elements [i]))
  5748. remove (i);
  5749. }
  5750. }
  5751. }
  5752. /** Swaps over two elements in the array.
  5753. This swaps over the elements found at the two indexes passed in.
  5754. If either index is out-of-range, this method will do nothing.
  5755. @param index1 index of one of the elements to swap
  5756. @param index2 index of the other element to swap
  5757. */
  5758. void swap (const int index1,
  5759. const int index2)
  5760. {
  5761. const ScopedLockType lock (getLock());
  5762. if (isPositiveAndBelow (index1, numUsed)
  5763. && isPositiveAndBelow (index2, numUsed))
  5764. {
  5765. swapVariables (data.elements [index1],
  5766. data.elements [index2]);
  5767. }
  5768. }
  5769. /** Moves one of the values to a different position.
  5770. This will move the value to a specified index, shuffling along
  5771. any intervening elements as required.
  5772. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5773. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5774. @param currentIndex the index of the value to be moved. If this isn't a
  5775. valid index, then nothing will be done
  5776. @param newIndex the index at which you'd like this value to end up. If this
  5777. is less than zero, the value will be moved to the end
  5778. of the array
  5779. */
  5780. void move (const int currentIndex, int newIndex) throw()
  5781. {
  5782. if (currentIndex != newIndex)
  5783. {
  5784. const ScopedLockType lock (getLock());
  5785. if (isPositiveAndBelow (currentIndex, numUsed))
  5786. {
  5787. if (! isPositiveAndBelow (newIndex, numUsed))
  5788. newIndex = numUsed - 1;
  5789. char tempCopy [sizeof (ElementType)];
  5790. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  5791. if (newIndex > currentIndex)
  5792. {
  5793. memmove (data.elements + currentIndex,
  5794. data.elements + currentIndex + 1,
  5795. (newIndex - currentIndex) * sizeof (ElementType));
  5796. }
  5797. else
  5798. {
  5799. memmove (data.elements + newIndex + 1,
  5800. data.elements + newIndex,
  5801. (currentIndex - newIndex) * sizeof (ElementType));
  5802. }
  5803. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  5804. }
  5805. }
  5806. }
  5807. /** Reduces the amount of storage being used by the array.
  5808. Arrays typically allocate slightly more storage than they need, and after
  5809. removing elements, they may have quite a lot of unused space allocated.
  5810. This method will reduce the amount of allocated storage to a minimum.
  5811. */
  5812. void minimiseStorageOverheads()
  5813. {
  5814. const ScopedLockType lock (getLock());
  5815. data.shrinkToNoMoreThan (numUsed);
  5816. }
  5817. /** Increases the array's internal storage to hold a minimum number of elements.
  5818. Calling this before adding a large known number of elements means that
  5819. the array won't have to keep dynamically resizing itself as the elements
  5820. are added, and it'll therefore be more efficient.
  5821. */
  5822. void ensureStorageAllocated (const int minNumElements)
  5823. {
  5824. const ScopedLockType lock (getLock());
  5825. data.ensureAllocatedSize (minNumElements);
  5826. }
  5827. /** Sorts the elements in the array.
  5828. This will use a comparator object to sort the elements into order. The object
  5829. passed must have a method of the form:
  5830. @code
  5831. int compareElements (ElementType first, ElementType second);
  5832. @endcode
  5833. ..and this method must return:
  5834. - a value of < 0 if the first comes before the second
  5835. - a value of 0 if the two objects are equivalent
  5836. - a value of > 0 if the second comes before the first
  5837. To improve performance, the compareElements() method can be declared as static or const.
  5838. @param comparator the comparator to use for comparing elements.
  5839. @param retainOrderOfEquivalentItems if this is true, then items
  5840. which the comparator says are equivalent will be
  5841. kept in the order in which they currently appear
  5842. in the array. This is slower to perform, but may
  5843. be important in some cases. If it's false, a faster
  5844. algorithm is used, but equivalent elements may be
  5845. rearranged.
  5846. @see addSorted, indexOfSorted, sortArray
  5847. */
  5848. template <class ElementComparator>
  5849. void sort (ElementComparator& comparator,
  5850. const bool retainOrderOfEquivalentItems = false) const
  5851. {
  5852. const ScopedLockType lock (getLock());
  5853. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5854. // avoids getting warning messages about the parameter being unused
  5855. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  5856. }
  5857. /** Returns the CriticalSection that locks this array.
  5858. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  5859. an object of ScopedLockType as an RAII lock for it.
  5860. */
  5861. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  5862. /** Returns the type of scoped lock to use for locking this array */
  5863. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  5864. private:
  5865. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  5866. int numUsed;
  5867. };
  5868. #endif // __JUCE_ARRAY_JUCEHEADER__
  5869. /*** End of inlined file: juce_Array.h ***/
  5870. #endif
  5871. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  5872. #endif
  5873. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  5874. /*** Start of inlined file: juce_DynamicObject.h ***/
  5875. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  5876. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  5877. /*** Start of inlined file: juce_NamedValueSet.h ***/
  5878. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  5879. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  5880. /*** Start of inlined file: juce_Variant.h ***/
  5881. #ifndef __JUCE_VARIANT_JUCEHEADER__
  5882. #define __JUCE_VARIANT_JUCEHEADER__
  5883. /*** Start of inlined file: juce_Identifier.h ***/
  5884. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  5885. #define __JUCE_IDENTIFIER_JUCEHEADER__
  5886. /*** Start of inlined file: juce_StringPool.h ***/
  5887. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  5888. #define __JUCE_STRINGPOOL_JUCEHEADER__
  5889. /**
  5890. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  5891. comparison speed when dealing with many duplicate strings.
  5892. When you add a string to a pool using getPooledString, it'll return a character
  5893. array containing the same string. This array is owned by the pool, and the same array
  5894. is returned every time a matching string is asked for. This means that it's trivial to
  5895. compare two pooled strings for equality, as you can simply compare their pointers. It
  5896. also cuts down on storage if you're using many copies of the same string.
  5897. */
  5898. class JUCE_API StringPool
  5899. {
  5900. public:
  5901. /** Creates an empty pool. */
  5902. StringPool() throw();
  5903. /** Destructor */
  5904. ~StringPool();
  5905. /** Returns a pointer to a copy of the string that is passed in.
  5906. The pool will always return the same pointer when asked for a string that matches it.
  5907. The pool will own all the pointers that it returns, deleting them when the pool itself
  5908. is deleted.
  5909. */
  5910. const String::CharPointerType getPooledString (const String& original);
  5911. /** Returns a pointer to a copy of the string that is passed in.
  5912. The pool will always return the same pointer when asked for a string that matches it.
  5913. The pool will own all the pointers that it returns, deleting them when the pool itself
  5914. is deleted.
  5915. */
  5916. const String::CharPointerType getPooledString (const char* original);
  5917. /** Returns a pointer to a copy of the string that is passed in.
  5918. The pool will always return the same pointer when asked for a string that matches it.
  5919. The pool will own all the pointers that it returns, deleting them when the pool itself
  5920. is deleted.
  5921. */
  5922. const String::CharPointerType getPooledString (const juce_wchar* original);
  5923. /** Returns the number of strings in the pool. */
  5924. int size() const throw();
  5925. /** Returns one of the strings in the pool, by index. */
  5926. const juce_wchar* operator[] (int index) const throw();
  5927. private:
  5928. Array <String> strings;
  5929. };
  5930. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  5931. /*** End of inlined file: juce_StringPool.h ***/
  5932. /**
  5933. Represents a string identifier, designed for accessing properties by name.
  5934. Identifier objects are very light and fast to copy, but slower to initialise
  5935. from a string, so it's much faster to keep a static identifier object to refer
  5936. to frequently-used names, rather than constructing them each time you need it.
  5937. @see NamedPropertySet, ValueTree
  5938. */
  5939. class JUCE_API Identifier
  5940. {
  5941. public:
  5942. /** Creates a null identifier. */
  5943. Identifier() throw();
  5944. /** Creates an identifier with a specified name.
  5945. Because this name may need to be used in contexts such as script variables or XML
  5946. tags, it must only contain ascii letters and digits, or the underscore character.
  5947. */
  5948. Identifier (const char* name);
  5949. /** Creates an identifier with a specified name.
  5950. Because this name may need to be used in contexts such as script variables or XML
  5951. tags, it must only contain ascii letters and digits, or the underscore character.
  5952. */
  5953. Identifier (const String& name);
  5954. /** Creates a copy of another identifier. */
  5955. Identifier (const Identifier& other) throw();
  5956. /** Creates a copy of another identifier. */
  5957. Identifier& operator= (const Identifier& other) throw();
  5958. /** Destructor */
  5959. ~Identifier();
  5960. /** Compares two identifiers. This is a very fast operation. */
  5961. inline bool operator== (const Identifier& other) const throw() { return name == other.name; }
  5962. /** Compares two identifiers. This is a very fast operation. */
  5963. inline bool operator!= (const Identifier& other) const throw() { return name != other.name; }
  5964. /** Returns this identifier as a string. */
  5965. const String toString() const { return name; }
  5966. /** Returns this identifier's raw string pointer. */
  5967. operator const juce_wchar*() const throw() { return name; }
  5968. private:
  5969. const juce_wchar* name;
  5970. static StringPool& getPool();
  5971. };
  5972. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  5973. /*** End of inlined file: juce_Identifier.h ***/
  5974. /*** Start of inlined file: juce_OutputStream.h ***/
  5975. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  5976. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  5977. /*** Start of inlined file: juce_NewLine.h ***/
  5978. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  5979. #define __JUCE_NEWLINE_JUCEHEADER__
  5980. /** This class is used for represent a new-line character sequence.
  5981. To write a new-line to a stream, you can use the predefined 'newLine' variable, e.g.
  5982. @code
  5983. myOutputStream << "Hello World" << newLine << newLine;
  5984. @endcode
  5985. The exact character sequence that will be used for the new-line can be set and
  5986. retrieved with OutputStream::setNewLineString() and OutputStream::getNewLineString().
  5987. */
  5988. class JUCE_API NewLine
  5989. {
  5990. public:
  5991. /** Returns the default new-line sequence that the library uses.
  5992. @see OutputStream::setNewLineString()
  5993. */
  5994. static const char* getDefault() throw() { return "\r\n"; }
  5995. /** Returns the default new-line sequence that the library uses.
  5996. @see getDefault()
  5997. */
  5998. operator const String() const { return getDefault(); }
  5999. };
  6000. /** An predefined object representing a new-line, which can be written to a string or stream.
  6001. To write a new-line to a stream, you can use the predefined 'newLine' variable like this:
  6002. @code
  6003. myOutputStream << "Hello World" << newLine << newLine;
  6004. @endcode
  6005. */
  6006. extern NewLine newLine;
  6007. /** Writes a new-line sequence to a string.
  6008. You can use the predefined object 'newLine' to invoke this, e.g.
  6009. @code
  6010. myString << "Hello World" << newLine << newLine;
  6011. @endcode
  6012. */
  6013. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&);
  6014. #endif // __JUCE_NEWLINE_JUCEHEADER__
  6015. /*** End of inlined file: juce_NewLine.h ***/
  6016. /*** Start of inlined file: juce_InputStream.h ***/
  6017. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6018. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6019. /*** Start of inlined file: juce_MemoryBlock.h ***/
  6020. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  6021. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  6022. /**
  6023. A class to hold a resizable block of raw data.
  6024. */
  6025. class JUCE_API MemoryBlock
  6026. {
  6027. public:
  6028. /** Create an uninitialised block with 0 size. */
  6029. MemoryBlock() throw();
  6030. /** Creates a memory block with a given initial size.
  6031. @param initialSize the size of block to create
  6032. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  6033. */
  6034. MemoryBlock (const size_t initialSize,
  6035. bool initialiseToZero = false);
  6036. /** Creates a copy of another memory block. */
  6037. MemoryBlock (const MemoryBlock& other);
  6038. /** Creates a memory block using a copy of a block of data.
  6039. @param dataToInitialiseFrom some data to copy into this block
  6040. @param sizeInBytes how much space to use
  6041. */
  6042. MemoryBlock (const void* dataToInitialiseFrom, size_t sizeInBytes);
  6043. /** Destructor. */
  6044. ~MemoryBlock() throw();
  6045. /** Copies another memory block onto this one.
  6046. This block will be resized and copied to exactly match the other one.
  6047. */
  6048. MemoryBlock& operator= (const MemoryBlock& other);
  6049. /** Compares two memory blocks.
  6050. @returns true only if the two blocks are the same size and have identical contents.
  6051. */
  6052. bool operator== (const MemoryBlock& other) const throw();
  6053. /** Compares two memory blocks.
  6054. @returns true if the two blocks are different sizes or have different contents.
  6055. */
  6056. bool operator!= (const MemoryBlock& other) const throw();
  6057. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  6058. */
  6059. bool matches (const void* data, size_t dataSize) const throw();
  6060. /** Returns a void pointer to the data.
  6061. Note that the pointer returned will probably become invalid when the
  6062. block is resized.
  6063. */
  6064. void* getData() const throw() { return data; }
  6065. /** Returns a byte from the memory block.
  6066. This returns a reference, so you can also use it to set a byte.
  6067. */
  6068. template <typename Type>
  6069. char& operator[] (const Type offset) const throw() { return data [offset]; }
  6070. /** Returns the block's current allocated size, in bytes. */
  6071. size_t getSize() const throw() { return size; }
  6072. /** Resizes the memory block.
  6073. This will try to keep as much of the block's current content as it can,
  6074. and can optionally be made to clear any new space that gets allocated at
  6075. the end of the block.
  6076. @param newSize the new desired size for the block
  6077. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  6078. whether to clear the new section or just leave it
  6079. uninitialised
  6080. @see ensureSize
  6081. */
  6082. void setSize (const size_t newSize,
  6083. bool initialiseNewSpaceToZero = false);
  6084. /** Increases the block's size only if it's smaller than a given size.
  6085. @param minimumSize if the block is already bigger than this size, no action
  6086. will be taken; otherwise it will be increased to this size
  6087. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  6088. whether to clear the new section or just leave it
  6089. uninitialised
  6090. @see setSize
  6091. */
  6092. void ensureSize (const size_t minimumSize,
  6093. bool initialiseNewSpaceToZero = false);
  6094. /** Fills the entire memory block with a repeated byte value.
  6095. This is handy for clearing a block of memory to zero.
  6096. */
  6097. void fillWith (uint8 valueToUse) throw();
  6098. /** Adds another block of data to the end of this one.
  6099. This block's size will be increased accordingly.
  6100. */
  6101. void append (const void* data, size_t numBytes);
  6102. /** Exchanges the contents of this and another memory block.
  6103. No actual copying is required for this, so it's very fast.
  6104. */
  6105. void swapWith (MemoryBlock& other) throw();
  6106. /** Copies data into this MemoryBlock from a memory address.
  6107. @param srcData the memory location of the data to copy into this block
  6108. @param destinationOffset the offset in this block at which the data being copied should begin
  6109. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  6110. it will be clipped so not to do anything nasty)
  6111. */
  6112. void copyFrom (const void* srcData,
  6113. int destinationOffset,
  6114. size_t numBytes) throw();
  6115. /** Copies data from this MemoryBlock to a memory address.
  6116. @param destData the memory location to write to
  6117. @param sourceOffset the offset within this block from which the copied data will be read
  6118. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  6119. zeros will be used for that portion of the data)
  6120. */
  6121. void copyTo (void* destData,
  6122. int sourceOffset,
  6123. size_t numBytes) const throw();
  6124. /** Chops out a section of the block.
  6125. This will remove a section of the memory block and close the gap around it,
  6126. shifting any subsequent data downwards and reducing the size of the block.
  6127. If the range specified goes beyond the size of the block, it will be clipped.
  6128. */
  6129. void removeSection (size_t startByte, size_t numBytesToRemove);
  6130. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  6131. characters in the system's default encoding. */
  6132. const String toString() const;
  6133. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  6134. The block will be resized to the number of valid bytes read from the string.
  6135. Non-hex characters in the string will be ignored.
  6136. @see String::toHexString()
  6137. */
  6138. void loadFromHexString (const String& sourceHexString);
  6139. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  6140. void setBitRange (size_t bitRangeStart,
  6141. size_t numBits,
  6142. int binaryNumberToApply) throw();
  6143. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  6144. int getBitRange (size_t bitRangeStart,
  6145. size_t numBitsToRead) const throw();
  6146. /** Returns a string of characters that represent the binary contents of this block.
  6147. Uses a 64-bit encoding system to allow binary data to be turned into a string
  6148. of simple non-extended characters, e.g. for storage in XML.
  6149. @see fromBase64Encoding
  6150. */
  6151. const String toBase64Encoding() const;
  6152. /** Takes a string of encoded characters and turns it into binary data.
  6153. The string passed in must have been created by to64BitEncoding(), and this
  6154. block will be resized to recreate the original data block.
  6155. @see toBase64Encoding
  6156. */
  6157. bool fromBase64Encoding (const String& encodedString);
  6158. private:
  6159. HeapBlock <char> data;
  6160. size_t size;
  6161. static const char* const encodingTable;
  6162. JUCE_LEAK_DETECTOR (MemoryBlock);
  6163. };
  6164. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  6165. /*** End of inlined file: juce_MemoryBlock.h ***/
  6166. /** The base class for streams that read data.
  6167. Input and output streams are used throughout the library - subclasses can override
  6168. some or all of the virtual functions to implement their behaviour.
  6169. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6170. */
  6171. class JUCE_API InputStream
  6172. {
  6173. public:
  6174. /** Destructor. */
  6175. virtual ~InputStream() {}
  6176. /** Returns the total number of bytes available for reading in this stream.
  6177. Note that this is the number of bytes available from the start of the
  6178. stream, not from the current position.
  6179. If the size of the stream isn't actually known, this may return -1.
  6180. */
  6181. virtual int64 getTotalLength() = 0;
  6182. /** Returns true if the stream has no more data to read. */
  6183. virtual bool isExhausted() = 0;
  6184. /** Reads a set of bytes from the stream into a memory buffer.
  6185. This is the only read method that subclasses actually need to implement, as the
  6186. InputStream base class implements the other read methods in terms of this one (although
  6187. it's often more efficient for subclasses to implement them directly).
  6188. @param destBuffer the destination buffer for the data
  6189. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6190. memory block passed in is big enough to contain this
  6191. many bytes.
  6192. @returns the actual number of bytes that were read, which may be less than
  6193. maxBytesToRead if the stream is exhausted before it gets that far
  6194. */
  6195. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  6196. /** Reads a byte from the stream.
  6197. If the stream is exhausted, this will return zero.
  6198. @see OutputStream::writeByte
  6199. */
  6200. virtual char readByte();
  6201. /** Reads a boolean from the stream.
  6202. The bool is encoded as a single byte - 1 for true, 0 for false.
  6203. If the stream is exhausted, this will return false.
  6204. @see OutputStream::writeBool
  6205. */
  6206. virtual bool readBool();
  6207. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6208. If the next two bytes read are byte1 and byte2, this returns
  6209. (byte1 | (byte2 << 8)).
  6210. If the stream is exhausted partway through reading the bytes, this will return zero.
  6211. @see OutputStream::writeShort, readShortBigEndian
  6212. */
  6213. virtual short readShort();
  6214. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6215. If the next two bytes read are byte1 and byte2, this returns
  6216. (byte2 | (byte1 << 8)).
  6217. If the stream is exhausted partway through reading the bytes, this will return zero.
  6218. @see OutputStream::writeShortBigEndian, readShort
  6219. */
  6220. virtual short readShortBigEndian();
  6221. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6222. If the next four bytes are byte1 to byte4, this returns
  6223. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6224. If the stream is exhausted partway through reading the bytes, this will return zero.
  6225. @see OutputStream::writeInt, readIntBigEndian
  6226. */
  6227. virtual int readInt();
  6228. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6229. If the next four bytes are byte1 to byte4, this returns
  6230. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6231. If the stream is exhausted partway through reading the bytes, this will return zero.
  6232. @see OutputStream::writeIntBigEndian, readInt
  6233. */
  6234. virtual int readIntBigEndian();
  6235. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6236. If the next eight bytes are byte1 to byte8, this returns
  6237. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6238. If the stream is exhausted partway through reading the bytes, this will return zero.
  6239. @see OutputStream::writeInt64, readInt64BigEndian
  6240. */
  6241. virtual int64 readInt64();
  6242. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6243. If the next eight bytes are byte1 to byte8, this returns
  6244. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6245. If the stream is exhausted partway through reading the bytes, this will return zero.
  6246. @see OutputStream::writeInt64BigEndian, readInt64
  6247. */
  6248. virtual int64 readInt64BigEndian();
  6249. /** Reads four bytes as a 32-bit floating point value.
  6250. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6251. If the stream is exhausted partway through reading the bytes, this will return zero.
  6252. @see OutputStream::writeFloat, readDouble
  6253. */
  6254. virtual float readFloat();
  6255. /** Reads four bytes as a 32-bit floating point value.
  6256. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6257. If the stream is exhausted partway through reading the bytes, this will return zero.
  6258. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6259. */
  6260. virtual float readFloatBigEndian();
  6261. /** Reads eight bytes as a 64-bit floating point value.
  6262. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6263. If the stream is exhausted partway through reading the bytes, this will return zero.
  6264. @see OutputStream::writeDouble, readFloat
  6265. */
  6266. virtual double readDouble();
  6267. /** Reads eight bytes as a 64-bit floating point value.
  6268. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6269. If the stream is exhausted partway through reading the bytes, this will return zero.
  6270. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6271. */
  6272. virtual double readDoubleBigEndian();
  6273. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6274. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6275. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6276. @see OutputStream::writeCompressedInt()
  6277. */
  6278. virtual int readCompressedInt();
  6279. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  6280. This will read up to the next "\n" or "\r\n" or end-of-stream.
  6281. After this call, the stream's position will be left pointing to the next character
  6282. following the line-feed, but the linefeeds aren't included in the string that
  6283. is returned.
  6284. */
  6285. virtual const String readNextLine();
  6286. /** Reads a zero-terminated UTF8 string from the stream.
  6287. This will read characters from the stream until it hits a zero character or
  6288. end-of-stream.
  6289. @see OutputStream::writeString, readEntireStreamAsString
  6290. */
  6291. virtual const String readString();
  6292. /** Tries to read the whole stream and turn it into a string.
  6293. This will read from the stream's current position until the end-of-stream, and
  6294. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6295. */
  6296. virtual const String readEntireStreamAsString();
  6297. /** Reads from the stream and appends the data to a MemoryBlock.
  6298. @param destBlock the block to append the data onto
  6299. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6300. of bytes that will be read - if it's negative, data
  6301. will be read until the stream is exhausted.
  6302. @returns the number of bytes that were added to the memory block
  6303. */
  6304. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6305. int maxNumBytesToRead = -1);
  6306. /** Returns the offset of the next byte that will be read from the stream.
  6307. @see setPosition
  6308. */
  6309. virtual int64 getPosition() = 0;
  6310. /** Tries to move the current read position of the stream.
  6311. The position is an absolute number of bytes from the stream's start.
  6312. Some streams might not be able to do this, in which case they should do
  6313. nothing and return false. Others might be able to manage it by resetting
  6314. themselves and skipping to the correct position, although this is
  6315. obviously a bit slow.
  6316. @returns true if the stream manages to reposition itself correctly
  6317. @see getPosition
  6318. */
  6319. virtual bool setPosition (int64 newPosition) = 0;
  6320. /** Reads and discards a number of bytes from the stream.
  6321. Some input streams might implement this efficiently, but the base
  6322. class will just keep reading data until the requisite number of bytes
  6323. have been done.
  6324. */
  6325. virtual void skipNextBytes (int64 numBytesToSkip);
  6326. protected:
  6327. InputStream() throw() {}
  6328. private:
  6329. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InputStream);
  6330. };
  6331. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6332. /*** End of inlined file: juce_InputStream.h ***/
  6333. class File;
  6334. /**
  6335. The base class for streams that write data to some kind of destination.
  6336. Input and output streams are used throughout the library - subclasses can override
  6337. some or all of the virtual functions to implement their behaviour.
  6338. @see InputStream, MemoryOutputStream, FileOutputStream
  6339. */
  6340. class JUCE_API OutputStream
  6341. {
  6342. protected:
  6343. OutputStream();
  6344. public:
  6345. /** Destructor.
  6346. Some subclasses might want to do things like call flush() during their
  6347. destructors.
  6348. */
  6349. virtual ~OutputStream();
  6350. /** If the stream is using a buffer, this will ensure it gets written
  6351. out to the destination. */
  6352. virtual void flush() = 0;
  6353. /** Tries to move the stream's output position.
  6354. Not all streams will be able to seek to a new position - this will return
  6355. false if it fails to work.
  6356. @see getPosition
  6357. */
  6358. virtual bool setPosition (int64 newPosition) = 0;
  6359. /** Returns the stream's current position.
  6360. @see setPosition
  6361. */
  6362. virtual int64 getPosition() = 0;
  6363. /** Writes a block of data to the stream.
  6364. When creating a subclass of OutputStream, this is the only write method
  6365. that needs to be overloaded - the base class has methods for writing other
  6366. types of data which use this to do the work.
  6367. @returns false if the write operation fails for some reason
  6368. */
  6369. virtual bool write (const void* dataToWrite,
  6370. int howManyBytes) = 0;
  6371. /** Writes a single byte to the stream.
  6372. @see InputStream::readByte
  6373. */
  6374. virtual void writeByte (char byte);
  6375. /** Writes a boolean to the stream as a single byte.
  6376. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  6377. @see InputStream::readBool
  6378. */
  6379. virtual void writeBool (bool boolValue);
  6380. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6381. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6382. @see InputStream::readShort
  6383. */
  6384. virtual void writeShort (short value);
  6385. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6386. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6387. @see InputStream::readShortBigEndian
  6388. */
  6389. virtual void writeShortBigEndian (short value);
  6390. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6391. @see InputStream::readInt
  6392. */
  6393. virtual void writeInt (int value);
  6394. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6395. @see InputStream::readIntBigEndian
  6396. */
  6397. virtual void writeIntBigEndian (int value);
  6398. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6399. @see InputStream::readInt64
  6400. */
  6401. virtual void writeInt64 (int64 value);
  6402. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6403. @see InputStream::readInt64BigEndian
  6404. */
  6405. virtual void writeInt64BigEndian (int64 value);
  6406. /** Writes a 32-bit floating point value to the stream in a binary format.
  6407. The binary 32-bit encoding of the float is written as a little-endian int.
  6408. @see InputStream::readFloat
  6409. */
  6410. virtual void writeFloat (float value);
  6411. /** Writes a 32-bit floating point value to the stream in a binary format.
  6412. The binary 32-bit encoding of the float is written as a big-endian int.
  6413. @see InputStream::readFloatBigEndian
  6414. */
  6415. virtual void writeFloatBigEndian (float value);
  6416. /** Writes a 64-bit floating point value to the stream in a binary format.
  6417. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6418. @see InputStream::readDouble
  6419. */
  6420. virtual void writeDouble (double value);
  6421. /** Writes a 64-bit floating point value to the stream in a binary format.
  6422. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6423. @see InputStream::readDoubleBigEndian
  6424. */
  6425. virtual void writeDoubleBigEndian (double value);
  6426. /** Writes a byte to the output stream a given number of times. */
  6427. virtual void writeRepeatedByte (uint8 byte, int numTimesToRepeat);
  6428. /** Writes a condensed binary encoding of a 32-bit integer.
  6429. If you're storing a lot of integers which are unlikely to have very large values,
  6430. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6431. under 0xffff only 3 bytes, etc.
  6432. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6433. @see InputStream::readCompressedInt
  6434. */
  6435. virtual void writeCompressedInt (int value);
  6436. /** Stores a string in the stream in a binary format.
  6437. This isn't the method to use if you're trying to append text to the end of a
  6438. text-file! It's intended for storing a string so that it can be retrieved later
  6439. by InputStream::readString().
  6440. It writes the string to the stream as UTF8, including the null termination character.
  6441. For appending text to a file, instead use writeText, or operator<<
  6442. @see InputStream::readString, writeText, operator<<
  6443. */
  6444. virtual void writeString (const String& text);
  6445. /** Writes a string of text to the stream.
  6446. It can either write the text as UTF-8 or UTF-16, and can also add the UTF-16 byte-order-mark
  6447. bytes (0xff, 0xfe) to indicate the endianness (these should only be used at the start
  6448. of a file).
  6449. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6450. */
  6451. virtual void writeText (const String& text,
  6452. bool asUTF16,
  6453. bool writeUTF16ByteOrderMark);
  6454. /** Reads data from an input stream and writes it to this stream.
  6455. @param source the stream to read from
  6456. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6457. less than zero, it will keep reading until the input
  6458. is exhausted)
  6459. */
  6460. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  6461. /** Sets the string that will be written to the stream when the writeNewLine()
  6462. method is called.
  6463. By default this will be set the the value of NewLine::getDefault().
  6464. */
  6465. void setNewLineString (const String& newLineString);
  6466. /** Returns the current new-line string that was set by setNewLineString(). */
  6467. const String& getNewLineString() const throw() { return newLineString; }
  6468. private:
  6469. String newLineString;
  6470. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OutputStream);
  6471. };
  6472. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6473. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  6474. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  6475. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  6476. /** Writes a character to a stream. */
  6477. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  6478. /** Writes a null-terminated text string to a stream. */
  6479. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  6480. /** Writes a block of data from a MemoryBlock to a stream. */
  6481. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  6482. /** Writes the contents of a file to a stream. */
  6483. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  6484. /** Writes a new-line to a stream.
  6485. You can use the predefined symbol 'newLine' to invoke this, e.g.
  6486. @code
  6487. myOutputStream << "Hello World" << newLine << newLine;
  6488. @endcode
  6489. @see OutputStream::setNewLineString
  6490. */
  6491. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&);
  6492. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6493. /*** End of inlined file: juce_OutputStream.h ***/
  6494. #ifndef DOXYGEN
  6495. class JUCE_API DynamicObject;
  6496. #endif
  6497. /**
  6498. A variant class, that can be used to hold a range of primitive values.
  6499. A var object can hold a range of simple primitive values, strings, or
  6500. a reference-counted pointer to a DynamicObject. The var class is intended
  6501. to act like the values used in dynamic scripting languages.
  6502. @see DynamicObject
  6503. */
  6504. class JUCE_API var
  6505. {
  6506. public:
  6507. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  6508. typedef Identifier identifier;
  6509. /** Creates a void variant. */
  6510. var() throw();
  6511. /** Destructor. */
  6512. ~var() throw();
  6513. /** A static var object that can be used where you need an empty variant object. */
  6514. static const var null;
  6515. var (const var& valueToCopy);
  6516. var (int value) throw();
  6517. var (bool value) throw();
  6518. var (double value) throw();
  6519. var (const char* value);
  6520. var (const juce_wchar* value);
  6521. var (const String& value);
  6522. var (DynamicObject* object);
  6523. var (MethodFunction method) throw();
  6524. var& operator= (const var& valueToCopy);
  6525. var& operator= (int value);
  6526. var& operator= (bool value);
  6527. var& operator= (double value);
  6528. var& operator= (const char* value);
  6529. var& operator= (const juce_wchar* value);
  6530. var& operator= (const String& value);
  6531. var& operator= (DynamicObject* object);
  6532. var& operator= (MethodFunction method);
  6533. void swapWith (var& other) throw();
  6534. operator int() const;
  6535. operator bool() const;
  6536. operator float() const;
  6537. operator double() const;
  6538. operator const String() const;
  6539. const String toString() const;
  6540. DynamicObject* getObject() const;
  6541. bool isVoid() const throw();
  6542. bool isInt() const throw();
  6543. bool isBool() const throw();
  6544. bool isDouble() const throw();
  6545. bool isString() const throw();
  6546. bool isObject() const throw();
  6547. bool isMethod() const throw();
  6548. /** Writes a binary representation of this value to a stream.
  6549. The data can be read back later using readFromStream().
  6550. */
  6551. void writeToStream (OutputStream& output) const;
  6552. /** Reads back a stored binary representation of a value.
  6553. The data in the stream must have been written using writeToStream(), or this
  6554. will have unpredictable results.
  6555. */
  6556. static const var readFromStream (InputStream& input);
  6557. /** If this variant is an object, this returns one of its properties. */
  6558. const var operator[] (const Identifier& propertyName) const;
  6559. /** If this variant is an object, this invokes one of its methods with no arguments. */
  6560. const var call (const Identifier& method) const;
  6561. /** If this variant is an object, this invokes one of its methods with one argument. */
  6562. const var call (const Identifier& method, const var& arg1) const;
  6563. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  6564. const var call (const Identifier& method, const var& arg1, const var& arg2) const;
  6565. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  6566. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  6567. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  6568. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  6569. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  6570. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  6571. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  6572. const var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  6573. /** If this variant is a method pointer, this invokes it on a target object. */
  6574. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  6575. /** Returns true if this var has the same value as the one supplied. */
  6576. bool equals (const var& other) const throw();
  6577. /** Returns true if this var has the same value and type as the one supplied.
  6578. This differs from equals() because e.g. "0" and 0 will be considered different.
  6579. */
  6580. bool equalsWithSameType (const var& other) const throw();
  6581. private:
  6582. class VariantType;
  6583. friend class VariantType;
  6584. class VariantType_Void;
  6585. friend class VariantType_Void;
  6586. class VariantType_Int;
  6587. friend class VariantType_Int;
  6588. class VariantType_Double;
  6589. friend class VariantType_Double;
  6590. class VariantType_Float;
  6591. friend class VariantType_Float;
  6592. class VariantType_Bool;
  6593. friend class VariantType_Bool;
  6594. class VariantType_String;
  6595. friend class VariantType_String;
  6596. class VariantType_Object;
  6597. friend class VariantType_Object;
  6598. class VariantType_Method;
  6599. friend class VariantType_Method;
  6600. union ValueUnion
  6601. {
  6602. int intValue;
  6603. bool boolValue;
  6604. double doubleValue;
  6605. String* stringValue;
  6606. DynamicObject* objectValue;
  6607. MethodFunction methodValue;
  6608. };
  6609. const VariantType* type;
  6610. ValueUnion value;
  6611. };
  6612. bool operator== (const var& v1, const var& v2) throw();
  6613. bool operator!= (const var& v1, const var& v2) throw();
  6614. bool operator== (const var& v1, const String& v2) throw();
  6615. bool operator!= (const var& v1, const String& v2) throw();
  6616. #endif // __JUCE_VARIANT_JUCEHEADER__
  6617. /*** End of inlined file: juce_Variant.h ***/
  6618. /*** Start of inlined file: juce_LinkedListPointer.h ***/
  6619. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  6620. #define __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  6621. /**
  6622. Helps to manipulate singly-linked lists of objects.
  6623. For objects that are designed to contain a pointer to the subsequent item in the
  6624. list, this class contains methods to deal with the list. To use it, the ObjectType
  6625. class that it points to must contain a LinkedListPointer called nextListItem, e.g.
  6626. @code
  6627. struct MyObject
  6628. {
  6629. int x, y, z;
  6630. // A linkable object must contain a member with this name and type, which must be
  6631. // accessible by the LinkedListPointer class. (This doesn't mean it has to be public -
  6632. // you could make your class a friend of a LinkedListPointer<MyObject> instead).
  6633. LinkedListPointer<MyObject> nextListItem;
  6634. };
  6635. LinkedListPointer<MyObject> myList;
  6636. myList.append (new MyObject());
  6637. myList.append (new MyObject());
  6638. int numItems = myList.size(); // returns 2
  6639. MyObject* lastInList = myList.getLast();
  6640. @endcode
  6641. */
  6642. template <class ObjectType>
  6643. class LinkedListPointer
  6644. {
  6645. public:
  6646. /** Creates a null pointer to an empty list. */
  6647. LinkedListPointer() throw()
  6648. : item (0)
  6649. {
  6650. }
  6651. /** Creates a pointer to a list whose head is the item provided. */
  6652. explicit LinkedListPointer (ObjectType* const headItem) throw()
  6653. : item (headItem)
  6654. {
  6655. }
  6656. /** Sets this pointer to point to a new list. */
  6657. LinkedListPointer& operator= (ObjectType* const newItem) throw()
  6658. {
  6659. item = newItem;
  6660. return *this;
  6661. }
  6662. /** Returns the item which this pointer points to. */
  6663. inline operator ObjectType*() const throw()
  6664. {
  6665. return item;
  6666. }
  6667. /** Returns the item which this pointer points to. */
  6668. inline ObjectType* get() const throw()
  6669. {
  6670. return item;
  6671. }
  6672. /** Returns the last item in the list which this pointer points to.
  6673. This will iterate the list and return the last item found. Obviously the speed
  6674. of this operation will be proportional to the size of the list. If the list is
  6675. empty the return value will be this object.
  6676. If you're planning on appending a number of items to your list, it's much more
  6677. efficient to use the Appender class than to repeatedly call getLast() to find the end.
  6678. */
  6679. LinkedListPointer& getLast() throw()
  6680. {
  6681. LinkedListPointer* l = this;
  6682. while (l->item != 0)
  6683. l = &(l->item->nextListItem);
  6684. return *l;
  6685. }
  6686. /** Returns the number of items in the list.
  6687. Obviously with a simple linked list, getting the size involves iterating the list, so
  6688. this can be a lengthy operation - be careful when using this method in your code.
  6689. */
  6690. int size() const throw()
  6691. {
  6692. int total = 0;
  6693. for (ObjectType* i = item; i != 0; i = i->nextListItem)
  6694. ++total;
  6695. return total;
  6696. }
  6697. /** Returns the item at a given index in the list.
  6698. Since the only way to find an item is to iterate the list, this operation can obviously
  6699. be slow, depending on its size, so you should be careful when using this in algorithms.
  6700. */
  6701. LinkedListPointer& operator[] (int index) throw()
  6702. {
  6703. LinkedListPointer* l = this;
  6704. while (--index >= 0 && l->item != 0)
  6705. l = &(l->item->nextListItem);
  6706. return *l;
  6707. }
  6708. /** Returns the item at a given index in the list.
  6709. Since the only way to find an item is to iterate the list, this operation can obviously
  6710. be slow, depending on its size, so you should be careful when using this in algorithms.
  6711. */
  6712. const LinkedListPointer& operator[] (int index) const throw()
  6713. {
  6714. const LinkedListPointer* l = this;
  6715. while (--index >= 0 && l->item != 0)
  6716. l = &(l->item->nextListItem);
  6717. return *l;
  6718. }
  6719. /** Returns true if the list contains the given item. */
  6720. bool contains (const ObjectType* const itemToLookFor) const throw()
  6721. {
  6722. for (ObjectType* i = item; i != 0; i = i->nextListItem)
  6723. if (itemToLookFor == i)
  6724. return true;
  6725. return false;
  6726. }
  6727. /** Inserts an item into the list, placing it before the item that this pointer
  6728. currently points to.
  6729. */
  6730. void insertNext (ObjectType* const newItem)
  6731. {
  6732. jassert (newItem != 0);
  6733. jassert (newItem->nextListItem == 0);
  6734. newItem->nextListItem = item;
  6735. item = newItem;
  6736. }
  6737. /** Inserts an item at a numeric index in the list.
  6738. Obviously this will involve iterating the list to find the item at the given index,
  6739. so be careful about the impact this may have on execution time.
  6740. */
  6741. void insertAtIndex (int index, ObjectType* newItem)
  6742. {
  6743. jassert (newItem != 0);
  6744. LinkedListPointer* l = this;
  6745. while (index != 0 && l->item != 0)
  6746. {
  6747. l = &(l->item->nextListItem);
  6748. --index;
  6749. }
  6750. l->insertNext (newItem);
  6751. }
  6752. /** Replaces the object that this pointer points to, appending the rest of the list to
  6753. the new object, and returning the old one.
  6754. */
  6755. ObjectType* replaceNext (ObjectType* const newItem) throw()
  6756. {
  6757. jassert (newItem != 0);
  6758. jassert (newItem->nextListItem == 0);
  6759. ObjectType* const oldItem = item;
  6760. item = newItem;
  6761. item->nextListItem = oldItem->nextListItem.item;
  6762. oldItem->nextListItem = (ObjectType*) 0;
  6763. return oldItem;
  6764. }
  6765. /** Adds an item to the end of the list.
  6766. This operation involves iterating the whole list, so can be slow - if you need to
  6767. append a number of items to your list, it's much more efficient to use the Appender
  6768. class than to repeatedly call append().
  6769. */
  6770. void append (ObjectType* const newItem)
  6771. {
  6772. getLast().item = newItem;
  6773. }
  6774. /** Creates copies of all the items in another list and adds them to this one.
  6775. This will use the ObjectType's copy constructor to try to create copies of each
  6776. item in the other list, and appends them to this list.
  6777. */
  6778. void addCopyOfList (const LinkedListPointer& other)
  6779. {
  6780. LinkedListPointer* insertPoint = this;
  6781. for (ObjectType* i = other.item; i != 0; i = i->nextListItem)
  6782. {
  6783. insertPoint->insertNext (new ObjectType (*i));
  6784. insertPoint = &(insertPoint->item->nextListItem);
  6785. }
  6786. }
  6787. /** Removes the head item from the list.
  6788. This won't delete the object that is removed, but returns it, so the caller can
  6789. delete it if necessary.
  6790. */
  6791. ObjectType* removeNext() throw()
  6792. {
  6793. ObjectType* const oldItem = item;
  6794. if (oldItem != 0)
  6795. {
  6796. item = oldItem->nextListItem;
  6797. oldItem->nextListItem = (ObjectType*) 0;
  6798. }
  6799. return oldItem;
  6800. }
  6801. /** Removes a specific item from the list.
  6802. Note that this will not delete the item, it simply unlinks it from the list.
  6803. */
  6804. void remove (ObjectType* const itemToRemove)
  6805. {
  6806. LinkedListPointer* const l = findPointerTo (itemToRemove);
  6807. if (l != 0)
  6808. l->removeNext();
  6809. }
  6810. /** Iterates the list, calling the delete operator on all of its elements and
  6811. leaving this pointer empty.
  6812. */
  6813. void deleteAll()
  6814. {
  6815. while (item != 0)
  6816. {
  6817. ObjectType* const oldItem = item;
  6818. item = oldItem->nextListItem;
  6819. delete oldItem;
  6820. }
  6821. }
  6822. /** Finds a pointer to a given item.
  6823. If the item is found in the list, this returns the pointer that points to it. If
  6824. the item isn't found, this returns null.
  6825. */
  6826. LinkedListPointer* findPointerTo (ObjectType* const itemToLookFor) throw()
  6827. {
  6828. LinkedListPointer* l = this;
  6829. while (l->item != 0)
  6830. {
  6831. if (l->item == itemToLookFor)
  6832. return l;
  6833. l = &(l->item->nextListItem);
  6834. }
  6835. return 0;
  6836. }
  6837. /** Copies the items in the list to an array.
  6838. The destArray must contain enough elements to hold the entire list - no checks are
  6839. made for this!
  6840. */
  6841. void copyToArray (ObjectType** destArray) const throw()
  6842. {
  6843. jassert (destArray != 0);
  6844. for (ObjectType* i = item; i != 0; i = i->nextListItem)
  6845. *destArray++ = i;
  6846. }
  6847. /**
  6848. Allows efficient repeated insertions into a list.
  6849. You can create an Appender object which points to the last element in your
  6850. list, and then repeatedly call Appender::append() to add items to the end
  6851. of the list in O(1) time.
  6852. */
  6853. class Appender
  6854. {
  6855. public:
  6856. /** Creates an appender which will add items to the given list.
  6857. */
  6858. Appender (LinkedListPointer& endOfListPointer) throw()
  6859. : endOfList (&endOfListPointer)
  6860. {
  6861. // This can only be used to add to the end of a list.
  6862. jassert (endOfListPointer.item == 0);
  6863. }
  6864. /** Appends an item to the list. */
  6865. void append (ObjectType* const newItem) throw()
  6866. {
  6867. *endOfList = newItem;
  6868. endOfList = &(newItem->nextListItem);
  6869. }
  6870. private:
  6871. LinkedListPointer* endOfList;
  6872. JUCE_DECLARE_NON_COPYABLE (Appender);
  6873. };
  6874. private:
  6875. ObjectType* item;
  6876. JUCE_DECLARE_NON_COPYABLE (LinkedListPointer);
  6877. };
  6878. #endif // __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  6879. /*** End of inlined file: juce_LinkedListPointer.h ***/
  6880. class XmlElement;
  6881. /** Holds a set of named var objects.
  6882. This can be used as a basic structure to hold a set of var object, which can
  6883. be retrieved by using their identifier.
  6884. */
  6885. class JUCE_API NamedValueSet
  6886. {
  6887. public:
  6888. /** Creates an empty set. */
  6889. NamedValueSet() throw();
  6890. /** Creates a copy of another set. */
  6891. NamedValueSet (const NamedValueSet& other);
  6892. /** Replaces this set with a copy of another set. */
  6893. NamedValueSet& operator= (const NamedValueSet& other);
  6894. /** Destructor. */
  6895. ~NamedValueSet();
  6896. bool operator== (const NamedValueSet& other) const;
  6897. bool operator!= (const NamedValueSet& other) const;
  6898. /** Returns the total number of values that the set contains. */
  6899. int size() const throw();
  6900. /** Returns the value of a named item.
  6901. If the name isn't found, this will return a void variant.
  6902. @see getProperty
  6903. */
  6904. const var& operator[] (const Identifier& name) const;
  6905. /** Tries to return the named value, but if no such value is found, this will
  6906. instead return the supplied default value.
  6907. */
  6908. const var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  6909. /** Changes or adds a named value.
  6910. @returns true if a value was changed or added; false if the
  6911. value was already set the the value passed-in.
  6912. */
  6913. bool set (const Identifier& name, const var& newValue);
  6914. /** Returns true if the set contains an item with the specified name. */
  6915. bool contains (const Identifier& name) const;
  6916. /** Removes a value from the set.
  6917. @returns true if a value was removed; false if there was no value
  6918. with the name that was given.
  6919. */
  6920. bool remove (const Identifier& name);
  6921. /** Returns the name of the value at a given index.
  6922. The index must be between 0 and size() - 1.
  6923. */
  6924. const Identifier getName (int index) const;
  6925. /** Returns the value of the item at a given index.
  6926. The index must be between 0 and size() - 1.
  6927. */
  6928. const var getValueAt (int index) const;
  6929. /** Removes all values. */
  6930. void clear();
  6931. /** Returns a pointer to the var that holds a named value, or null if there is
  6932. no value with this name.
  6933. Do not use this method unless you really need access to the internal var object
  6934. for some reason - for normal reading and writing always prefer operator[]() and set().
  6935. */
  6936. var* getVarPointer (const Identifier& name) const;
  6937. /** Sets properties to the values of all of an XML element's attributes. */
  6938. void setFromXmlAttributes (const XmlElement& xml);
  6939. /** Sets attributes in an XML element corresponding to each of this object's
  6940. properties.
  6941. */
  6942. void copyToXmlAttributes (XmlElement& xml) const;
  6943. private:
  6944. class NamedValue
  6945. {
  6946. public:
  6947. NamedValue() throw();
  6948. NamedValue (const NamedValue&);
  6949. NamedValue (const Identifier& name, const var& value);
  6950. NamedValue& operator= (const NamedValue&);
  6951. bool operator== (const NamedValue& other) const throw();
  6952. LinkedListPointer<NamedValue> nextListItem;
  6953. Identifier name;
  6954. var value;
  6955. private:
  6956. JUCE_LEAK_DETECTOR (NamedValue);
  6957. };
  6958. friend class LinkedListPointer<NamedValue>;
  6959. LinkedListPointer<NamedValue> values;
  6960. };
  6961. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  6962. /*** End of inlined file: juce_NamedValueSet.h ***/
  6963. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  6964. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6965. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6966. /**
  6967. Adds reference-counting to an object.
  6968. To add reference-counting to a class, derive it from this class, and
  6969. use the ReferenceCountedObjectPtr class to point to it.
  6970. e.g. @code
  6971. class MyClass : public ReferenceCountedObject
  6972. {
  6973. void foo();
  6974. // This is a neat way of declaring a typedef for a pointer class,
  6975. // rather than typing out the full templated name each time..
  6976. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  6977. };
  6978. MyClass::Ptr p = new MyClass();
  6979. MyClass::Ptr p2 = p;
  6980. p = 0;
  6981. p2->foo();
  6982. @endcode
  6983. Once a new ReferenceCountedObject has been assigned to a pointer, be
  6984. careful not to delete the object manually.
  6985. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  6986. */
  6987. class JUCE_API ReferenceCountedObject
  6988. {
  6989. public:
  6990. /** Increments the object's reference count.
  6991. This is done automatically by the smart pointer, but is public just
  6992. in case it's needed for nefarious purposes.
  6993. */
  6994. inline void incReferenceCount() throw()
  6995. {
  6996. ++refCount;
  6997. }
  6998. /** Decreases the object's reference count.
  6999. If the count gets to zero, the object will be deleted.
  7000. */
  7001. inline void decReferenceCount() throw()
  7002. {
  7003. jassert (getReferenceCount() > 0);
  7004. if (--refCount == 0)
  7005. delete this;
  7006. }
  7007. /** Returns the object's current reference count. */
  7008. inline int getReferenceCount() const throw()
  7009. {
  7010. return refCount.get();
  7011. }
  7012. protected:
  7013. /** Creates the reference-counted object (with an initial ref count of zero). */
  7014. ReferenceCountedObject()
  7015. {
  7016. }
  7017. /** Destructor. */
  7018. virtual ~ReferenceCountedObject()
  7019. {
  7020. // it's dangerous to delete an object that's still referenced by something else!
  7021. jassert (getReferenceCount() == 0);
  7022. }
  7023. private:
  7024. Atomic <int> refCount;
  7025. };
  7026. /**
  7027. Used to point to an object of type ReferenceCountedObject.
  7028. It's wise to use a typedef instead of typing out the templated name
  7029. each time - e.g.
  7030. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  7031. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7032. */
  7033. template <class ReferenceCountedObjectClass>
  7034. class ReferenceCountedObjectPtr
  7035. {
  7036. public:
  7037. /** Creates a pointer to a null object. */
  7038. inline ReferenceCountedObjectPtr() throw()
  7039. : referencedObject (0)
  7040. {
  7041. }
  7042. /** Creates a pointer to an object.
  7043. This will increment the object's reference-count if it is non-null.
  7044. */
  7045. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  7046. : referencedObject (refCountedObject)
  7047. {
  7048. if (refCountedObject != 0)
  7049. refCountedObject->incReferenceCount();
  7050. }
  7051. /** Copies another pointer.
  7052. This will increment the object's reference-count (if it is non-null).
  7053. */
  7054. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  7055. : referencedObject (other.referencedObject)
  7056. {
  7057. if (referencedObject != 0)
  7058. referencedObject->incReferenceCount();
  7059. }
  7060. /** Changes this pointer to point at a different object.
  7061. The reference count of the old object is decremented, and it might be
  7062. deleted if it hits zero. The new object's count is incremented.
  7063. */
  7064. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7065. {
  7066. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7067. if (newObject != referencedObject)
  7068. {
  7069. if (newObject != 0)
  7070. newObject->incReferenceCount();
  7071. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7072. referencedObject = newObject;
  7073. if (oldObject != 0)
  7074. oldObject->decReferenceCount();
  7075. }
  7076. return *this;
  7077. }
  7078. /** Changes this pointer to point at a different object.
  7079. The reference count of the old object is decremented, and it might be
  7080. deleted if it hits zero. The new object's count is incremented.
  7081. */
  7082. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7083. {
  7084. if (referencedObject != newObject)
  7085. {
  7086. if (newObject != 0)
  7087. newObject->incReferenceCount();
  7088. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7089. referencedObject = newObject;
  7090. if (oldObject != 0)
  7091. oldObject->decReferenceCount();
  7092. }
  7093. return *this;
  7094. }
  7095. /** Destructor.
  7096. This will decrement the object's reference-count, and may delete it if it
  7097. gets to zero.
  7098. */
  7099. inline ~ReferenceCountedObjectPtr()
  7100. {
  7101. if (referencedObject != 0)
  7102. referencedObject->decReferenceCount();
  7103. }
  7104. /** Returns the object that this pointer references.
  7105. The pointer returned may be zero, of course.
  7106. */
  7107. inline operator ReferenceCountedObjectClass*() const throw()
  7108. {
  7109. return referencedObject;
  7110. }
  7111. // the -> operator is called on the referenced object
  7112. inline ReferenceCountedObjectClass* operator->() const throw()
  7113. {
  7114. return referencedObject;
  7115. }
  7116. /** Returns the object that this pointer references.
  7117. The pointer returned may be zero, of course.
  7118. */
  7119. inline ReferenceCountedObjectClass* getObject() const throw()
  7120. {
  7121. return referencedObject;
  7122. }
  7123. private:
  7124. ReferenceCountedObjectClass* referencedObject;
  7125. };
  7126. /** Compares two ReferenceCountedObjectPointers. */
  7127. template <class ReferenceCountedObjectClass>
  7128. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectClass* const object2) throw()
  7129. {
  7130. return object1.getObject() == object2;
  7131. }
  7132. /** Compares two ReferenceCountedObjectPointers. */
  7133. template <class ReferenceCountedObjectClass>
  7134. bool operator== (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7135. {
  7136. return object1.getObject() == object2.getObject();
  7137. }
  7138. /** Compares two ReferenceCountedObjectPointers. */
  7139. template <class ReferenceCountedObjectClass>
  7140. bool operator== (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7141. {
  7142. return object1 == object2.getObject();
  7143. }
  7144. /** Compares two ReferenceCountedObjectPointers. */
  7145. template <class ReferenceCountedObjectClass>
  7146. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, const ReferenceCountedObjectClass* object2) throw()
  7147. {
  7148. return object1.getObject() != object2;
  7149. }
  7150. /** Compares two ReferenceCountedObjectPointers. */
  7151. template <class ReferenceCountedObjectClass>
  7152. bool operator!= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7153. {
  7154. return object1.getObject() != object2.getObject();
  7155. }
  7156. /** Compares two ReferenceCountedObjectPointers. */
  7157. template <class ReferenceCountedObjectClass>
  7158. bool operator!= (ReferenceCountedObjectClass* object1, ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& object2) throw()
  7159. {
  7160. return object1 != object2.getObject();
  7161. }
  7162. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7163. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  7164. /**
  7165. Represents a dynamically implemented object.
  7166. This class is primarily intended for wrapping scripting language objects,
  7167. but could be used for other purposes.
  7168. An instance of a DynamicObject can be used to store named properties, and
  7169. by subclassing hasMethod() and invokeMethod(), you can give your object
  7170. methods.
  7171. */
  7172. class JUCE_API DynamicObject : public ReferenceCountedObject
  7173. {
  7174. public:
  7175. DynamicObject();
  7176. /** Destructor. */
  7177. virtual ~DynamicObject();
  7178. /** Returns true if the object has a property with this name.
  7179. Note that if the property is actually a method, this will return false.
  7180. */
  7181. virtual bool hasProperty (const Identifier& propertyName) const;
  7182. /** Returns a named property.
  7183. This returns a void if no such property exists.
  7184. */
  7185. virtual const var getProperty (const Identifier& propertyName) const;
  7186. /** Sets a named property. */
  7187. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  7188. /** Removes a named property. */
  7189. virtual void removeProperty (const Identifier& propertyName);
  7190. /** Checks whether this object has the specified method.
  7191. The default implementation of this just checks whether there's a property
  7192. with this name that's actually a method, but this can be overridden for
  7193. building objects with dynamic invocation.
  7194. */
  7195. virtual bool hasMethod (const Identifier& methodName) const;
  7196. /** Invokes a named method on this object.
  7197. The default implementation looks up the named property, and if it's a method
  7198. call, then it invokes it.
  7199. This method is virtual to allow more dynamic invocation to used for objects
  7200. where the methods may not already be set as properies.
  7201. */
  7202. virtual const var invokeMethod (const Identifier& methodName,
  7203. const var* parameters,
  7204. int numParameters);
  7205. /** Sets up a method.
  7206. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  7207. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  7208. the code easier to read,
  7209. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  7210. @code
  7211. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  7212. @endcode
  7213. */
  7214. void setMethod (const Identifier& methodName,
  7215. var::MethodFunction methodFunction);
  7216. /** Removes all properties and methods from the object. */
  7217. void clear();
  7218. private:
  7219. NamedValueSet properties;
  7220. JUCE_LEAK_DETECTOR (DynamicObject);
  7221. };
  7222. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  7223. /*** End of inlined file: juce_DynamicObject.h ***/
  7224. #endif
  7225. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  7226. #endif
  7227. #ifndef __JUCE_LINKEDLISTPOINTER_JUCEHEADER__
  7228. #endif
  7229. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  7230. #endif
  7231. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  7232. /*** Start of inlined file: juce_OwnedArray.h ***/
  7233. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  7234. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  7235. /** An array designed for holding objects.
  7236. This holds a list of pointers to objects, and will automatically
  7237. delete the objects when they are removed from the array, or when the
  7238. array is itself deleted.
  7239. Declare it in the form: OwnedArray<MyObjectClass>
  7240. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  7241. After adding objects, they are 'owned' by the array and will be deleted when
  7242. removed or replaced.
  7243. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7244. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7245. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  7246. */
  7247. template <class ObjectClass,
  7248. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7249. class OwnedArray
  7250. {
  7251. public:
  7252. /** Creates an empty array. */
  7253. OwnedArray() throw()
  7254. : numUsed (0)
  7255. {
  7256. }
  7257. /** Deletes the array and also deletes any objects inside it.
  7258. To get rid of the array without deleting its objects, use its
  7259. clear (false) method before deleting it.
  7260. */
  7261. ~OwnedArray()
  7262. {
  7263. clear (true);
  7264. }
  7265. /** Clears the array, optionally deleting the objects inside it first. */
  7266. void clear (const bool deleteObjects = true)
  7267. {
  7268. const ScopedLockType lock (getLock());
  7269. if (deleteObjects)
  7270. {
  7271. while (numUsed > 0)
  7272. delete data.elements [--numUsed];
  7273. }
  7274. data.setAllocatedSize (0);
  7275. numUsed = 0;
  7276. }
  7277. /** Returns the number of items currently in the array.
  7278. @see operator[]
  7279. */
  7280. inline int size() const throw()
  7281. {
  7282. return numUsed;
  7283. }
  7284. /** Returns a pointer to the object at this index in the array.
  7285. If the index is out-of-range, this will return a null pointer, (and
  7286. it could be null anyway, because it's ok for the array to hold null
  7287. pointers as well as objects).
  7288. @see getUnchecked
  7289. */
  7290. inline ObjectClass* operator[] (const int index) const throw()
  7291. {
  7292. const ScopedLockType lock (getLock());
  7293. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  7294. : static_cast <ObjectClass*> (0);
  7295. }
  7296. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7297. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7298. it can be used when you're sure the index if always going to be legal.
  7299. */
  7300. inline ObjectClass* getUnchecked (const int index) const throw()
  7301. {
  7302. const ScopedLockType lock (getLock());
  7303. jassert (isPositiveAndBelow (index, numUsed));
  7304. return data.elements [index];
  7305. }
  7306. /** Returns a pointer to the first object in the array.
  7307. This will return a null pointer if the array's empty.
  7308. @see getLast
  7309. */
  7310. inline ObjectClass* getFirst() const throw()
  7311. {
  7312. const ScopedLockType lock (getLock());
  7313. return numUsed > 0 ? data.elements [0]
  7314. : static_cast <ObjectClass*> (0);
  7315. }
  7316. /** Returns a pointer to the last object in the array.
  7317. This will return a null pointer if the array's empty.
  7318. @see getFirst
  7319. */
  7320. inline ObjectClass* getLast() const throw()
  7321. {
  7322. const ScopedLockType lock (getLock());
  7323. return numUsed > 0 ? data.elements [numUsed - 1]
  7324. : static_cast <ObjectClass*> (0);
  7325. }
  7326. /** Returns a pointer to the actual array data.
  7327. This pointer will only be valid until the next time a non-const method
  7328. is called on the array.
  7329. */
  7330. inline ObjectClass** getRawDataPointer() throw()
  7331. {
  7332. return data.elements;
  7333. }
  7334. /** Finds the index of an object which might be in the array.
  7335. @param objectToLookFor the object to look for
  7336. @returns the index at which the object was found, or -1 if it's not found
  7337. */
  7338. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7339. {
  7340. const ScopedLockType lock (getLock());
  7341. ObjectClass* const* e = data.elements.getData();
  7342. ObjectClass* const* const end = e + numUsed;
  7343. while (e != end)
  7344. {
  7345. if (objectToLookFor == *e)
  7346. return static_cast <int> (e - data.elements.getData());
  7347. ++e;
  7348. }
  7349. return -1;
  7350. }
  7351. /** Returns true if the array contains a specified object.
  7352. @param objectToLookFor the object to look for
  7353. @returns true if the object is in the array
  7354. */
  7355. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7356. {
  7357. const ScopedLockType lock (getLock());
  7358. ObjectClass* const* e = data.elements.getData();
  7359. ObjectClass* const* const end = e + numUsed;
  7360. while (e != end)
  7361. {
  7362. if (objectToLookFor == *e)
  7363. return true;
  7364. ++e;
  7365. }
  7366. return false;
  7367. }
  7368. /** Appends a new object to the end of the array.
  7369. Note that the this object will be deleted by the OwnedArray when it
  7370. is removed, so be careful not to delete it somewhere else.
  7371. Also be careful not to add the same object to the array more than once,
  7372. as this will obviously cause deletion of dangling pointers.
  7373. @param newObject the new object to add to the array
  7374. @see set, insert, addIfNotAlreadyThere, addSorted
  7375. */
  7376. void add (const ObjectClass* const newObject) throw()
  7377. {
  7378. const ScopedLockType lock (getLock());
  7379. data.ensureAllocatedSize (numUsed + 1);
  7380. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7381. }
  7382. /** Inserts a new object into the array at the given index.
  7383. Note that the this object will be deleted by the OwnedArray when it
  7384. is removed, so be careful not to delete it somewhere else.
  7385. If the index is less than 0 or greater than the size of the array, the
  7386. element will be added to the end of the array.
  7387. Otherwise, it will be inserted into the array, moving all the later elements
  7388. along to make room.
  7389. Be careful not to add the same object to the array more than once,
  7390. as this will obviously cause deletion of dangling pointers.
  7391. @param indexToInsertAt the index at which the new element should be inserted
  7392. @param newObject the new object to add to the array
  7393. @see add, addSorted, addIfNotAlreadyThere, set
  7394. */
  7395. void insert (int indexToInsertAt,
  7396. const ObjectClass* const newObject) throw()
  7397. {
  7398. if (indexToInsertAt >= 0)
  7399. {
  7400. const ScopedLockType lock (getLock());
  7401. if (indexToInsertAt > numUsed)
  7402. indexToInsertAt = numUsed;
  7403. data.ensureAllocatedSize (numUsed + 1);
  7404. ObjectClass** const e = data.elements + indexToInsertAt;
  7405. const int numToMove = numUsed - indexToInsertAt;
  7406. if (numToMove > 0)
  7407. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7408. *e = const_cast <ObjectClass*> (newObject);
  7409. ++numUsed;
  7410. }
  7411. else
  7412. {
  7413. add (newObject);
  7414. }
  7415. }
  7416. /** Appends a new object at the end of the array as long as the array doesn't
  7417. already contain it.
  7418. If the array already contains a matching object, nothing will be done.
  7419. @param newObject the new object to add to the array
  7420. */
  7421. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  7422. {
  7423. const ScopedLockType lock (getLock());
  7424. if (! contains (newObject))
  7425. add (newObject);
  7426. }
  7427. /** Replaces an object in the array with a different one.
  7428. If the index is less than zero, this method does nothing.
  7429. If the index is beyond the end of the array, the new object is added to the end of the array.
  7430. Be careful not to add the same object to the array more than once,
  7431. as this will obviously cause deletion of dangling pointers.
  7432. @param indexToChange the index whose value you want to change
  7433. @param newObject the new value to set for this index.
  7434. @param deleteOldElement whether to delete the object that's being replaced with the new one
  7435. @see add, insert, remove
  7436. */
  7437. void set (const int indexToChange,
  7438. const ObjectClass* const newObject,
  7439. const bool deleteOldElement = true)
  7440. {
  7441. if (indexToChange >= 0)
  7442. {
  7443. ObjectClass* toDelete = 0;
  7444. {
  7445. const ScopedLockType lock (getLock());
  7446. if (indexToChange < numUsed)
  7447. {
  7448. if (deleteOldElement)
  7449. {
  7450. toDelete = data.elements [indexToChange];
  7451. if (toDelete == newObject)
  7452. toDelete = 0;
  7453. }
  7454. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  7455. }
  7456. else
  7457. {
  7458. data.ensureAllocatedSize (numUsed + 1);
  7459. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  7460. }
  7461. }
  7462. delete toDelete; // don't want to use a ScopedPointer here because if the
  7463. // object has a private destructor, both OwnedArray and
  7464. // ScopedPointer would need to be friend classes..
  7465. }
  7466. else
  7467. {
  7468. jassertfalse; // you're trying to set an object at a negative index, which doesn't have
  7469. // any effect - but since the object is not being added, it may be leaking..
  7470. }
  7471. }
  7472. /** Adds elements from another array to the end of this array.
  7473. @param arrayToAddFrom the array from which to copy the elements
  7474. @param startIndex the first element of the other array to start copying from
  7475. @param numElementsToAdd how many elements to add from the other array. If this
  7476. value is negative or greater than the number of available elements,
  7477. all available elements will be copied.
  7478. @see add
  7479. */
  7480. template <class OtherArrayType>
  7481. void addArray (const OtherArrayType& arrayToAddFrom,
  7482. int startIndex = 0,
  7483. int numElementsToAdd = -1)
  7484. {
  7485. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7486. const ScopedLockType lock2 (getLock());
  7487. if (startIndex < 0)
  7488. {
  7489. jassertfalse;
  7490. startIndex = 0;
  7491. }
  7492. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7493. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7494. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7495. while (--numElementsToAdd >= 0)
  7496. {
  7497. data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++);
  7498. ++numUsed;
  7499. }
  7500. }
  7501. /** Adds copies of the elements in another array to the end of this array.
  7502. The other array must be either an OwnedArray of a compatible type of object, or an Array
  7503. containing pointers to the same kind of object. The objects involved must provide
  7504. a copy constructor, and this will be used to create new copies of each element, and
  7505. add them to this array.
  7506. @param arrayToAddFrom the array from which to copy the elements
  7507. @param startIndex the first element of the other array to start copying from
  7508. @param numElementsToAdd how many elements to add from the other array. If this
  7509. value is negative or greater than the number of available elements,
  7510. all available elements will be copied.
  7511. @see add
  7512. */
  7513. template <class OtherArrayType>
  7514. void addCopiesOf (const OtherArrayType& arrayToAddFrom,
  7515. int startIndex = 0,
  7516. int numElementsToAdd = -1)
  7517. {
  7518. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  7519. const ScopedLockType lock2 (getLock());
  7520. if (startIndex < 0)
  7521. {
  7522. jassertfalse;
  7523. startIndex = 0;
  7524. }
  7525. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7526. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7527. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7528. while (--numElementsToAdd >= 0)
  7529. {
  7530. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  7531. ++numUsed;
  7532. }
  7533. }
  7534. /** Inserts a new object into the array assuming that the array is sorted.
  7535. This will use a comparator to find the position at which the new object
  7536. should go. If the array isn't sorted, the behaviour of this
  7537. method will be unpredictable.
  7538. @param comparator the comparator to use to compare the elements - see the sort method
  7539. for details about this object's structure
  7540. @param newObject the new object to insert to the array
  7541. @see add, sort, indexOfSorted
  7542. */
  7543. template <class ElementComparator>
  7544. void addSorted (ElementComparator& comparator,
  7545. ObjectClass* const newObject) throw()
  7546. {
  7547. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7548. // avoids getting warning messages about the parameter being unused
  7549. const ScopedLockType lock (getLock());
  7550. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  7551. }
  7552. /** Finds the index of an object in the array, assuming that the array is sorted.
  7553. This will use a comparator to do a binary-chop to find the index of the given
  7554. element, if it exists. If the array isn't sorted, the behaviour of this
  7555. method will be unpredictable.
  7556. @param comparator the comparator to use to compare the elements - see the sort()
  7557. method for details about the form this object should take
  7558. @param objectToLookFor the object to search for
  7559. @returns the index of the element, or -1 if it's not found
  7560. @see addSorted, sort
  7561. */
  7562. template <class ElementComparator>
  7563. int indexOfSorted (ElementComparator& comparator,
  7564. const ObjectClass* const objectToLookFor) const throw()
  7565. {
  7566. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7567. // avoids getting warning messages about the parameter being unused
  7568. const ScopedLockType lock (getLock());
  7569. int start = 0;
  7570. int end = numUsed;
  7571. for (;;)
  7572. {
  7573. if (start >= end)
  7574. {
  7575. return -1;
  7576. }
  7577. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  7578. {
  7579. return start;
  7580. }
  7581. else
  7582. {
  7583. const int halfway = (start + end) >> 1;
  7584. if (halfway == start)
  7585. return -1;
  7586. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  7587. start = halfway;
  7588. else
  7589. end = halfway;
  7590. }
  7591. }
  7592. }
  7593. /** Removes an object from the array.
  7594. This will remove the object at a given index (optionally also
  7595. deleting it) and move back all the subsequent objects to close the gap.
  7596. If the index passed in is out-of-range, nothing will happen.
  7597. @param indexToRemove the index of the element to remove
  7598. @param deleteObject whether to delete the object that is removed
  7599. @see removeObject, removeRange
  7600. */
  7601. void remove (const int indexToRemove,
  7602. const bool deleteObject = true)
  7603. {
  7604. ObjectClass* toDelete = 0;
  7605. {
  7606. const ScopedLockType lock (getLock());
  7607. if (isPositiveAndBelow (indexToRemove, numUsed))
  7608. {
  7609. ObjectClass** const e = data.elements + indexToRemove;
  7610. if (deleteObject)
  7611. toDelete = *e;
  7612. --numUsed;
  7613. const int numToShift = numUsed - indexToRemove;
  7614. if (numToShift > 0)
  7615. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  7616. }
  7617. }
  7618. delete toDelete; // don't want to use a ScopedPointer here because if the
  7619. // object has a private destructor, both OwnedArray and
  7620. // ScopedPointer would need to be friend classes..
  7621. if ((numUsed << 1) < data.numAllocated)
  7622. minimiseStorageOverheads();
  7623. }
  7624. /** Removes and returns an object from the array without deleting it.
  7625. This will remove the object at a given index and return it, moving back all
  7626. the subsequent objects to close the gap. If the index passed in is out-of-range,
  7627. nothing will happen.
  7628. @param indexToRemove the index of the element to remove
  7629. @see remove, removeObject, removeRange
  7630. */
  7631. ObjectClass* removeAndReturn (const int indexToRemove)
  7632. {
  7633. ObjectClass* removedItem = 0;
  7634. const ScopedLockType lock (getLock());
  7635. if (isPositiveAndBelow (indexToRemove, numUsed))
  7636. {
  7637. ObjectClass** const e = data.elements + indexToRemove;
  7638. removedItem = *e;
  7639. --numUsed;
  7640. const int numToShift = numUsed - indexToRemove;
  7641. if (numToShift > 0)
  7642. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  7643. if ((numUsed << 1) < data.numAllocated)
  7644. minimiseStorageOverheads();
  7645. }
  7646. return removedItem;
  7647. }
  7648. /** Removes a specified object from the array.
  7649. If the item isn't found, no action is taken.
  7650. @param objectToRemove the object to try to remove
  7651. @param deleteObject whether to delete the object (if it's found)
  7652. @see remove, removeRange
  7653. */
  7654. void removeObject (const ObjectClass* const objectToRemove,
  7655. const bool deleteObject = true)
  7656. {
  7657. const ScopedLockType lock (getLock());
  7658. ObjectClass** e = data.elements.getData();
  7659. for (int i = numUsed; --i >= 0;)
  7660. {
  7661. if (objectToRemove == *e)
  7662. {
  7663. remove (static_cast <int> (e - data.elements.getData()), deleteObject);
  7664. break;
  7665. }
  7666. ++e;
  7667. }
  7668. }
  7669. /** Removes a range of objects from the array.
  7670. This will remove a set of objects, starting from the given index,
  7671. and move any subsequent elements down to close the gap.
  7672. If the range extends beyond the bounds of the array, it will
  7673. be safely clipped to the size of the array.
  7674. @param startIndex the index of the first object to remove
  7675. @param numberToRemove how many objects should be removed
  7676. @param deleteObjects whether to delete the objects that get removed
  7677. @see remove, removeObject
  7678. */
  7679. void removeRange (int startIndex,
  7680. const int numberToRemove,
  7681. const bool deleteObjects = true)
  7682. {
  7683. const ScopedLockType lock (getLock());
  7684. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  7685. startIndex = jlimit (0, numUsed, startIndex);
  7686. if (endIndex > startIndex)
  7687. {
  7688. if (deleteObjects)
  7689. {
  7690. for (int i = startIndex; i < endIndex; ++i)
  7691. {
  7692. delete data.elements [i];
  7693. data.elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  7694. }
  7695. }
  7696. const int rangeSize = endIndex - startIndex;
  7697. ObjectClass** e = data.elements + startIndex;
  7698. int numToShift = numUsed - endIndex;
  7699. numUsed -= rangeSize;
  7700. while (--numToShift >= 0)
  7701. {
  7702. *e = e [rangeSize];
  7703. ++e;
  7704. }
  7705. if ((numUsed << 1) < data.numAllocated)
  7706. minimiseStorageOverheads();
  7707. }
  7708. }
  7709. /** Removes the last n objects from the array.
  7710. @param howManyToRemove how many objects to remove from the end of the array
  7711. @param deleteObjects whether to also delete the objects that are removed
  7712. @see remove, removeObject, removeRange
  7713. */
  7714. void removeLast (int howManyToRemove = 1,
  7715. const bool deleteObjects = true)
  7716. {
  7717. const ScopedLockType lock (getLock());
  7718. if (howManyToRemove >= numUsed)
  7719. clear (deleteObjects);
  7720. else
  7721. removeRange (numUsed - howManyToRemove, howManyToRemove, deleteObjects);
  7722. }
  7723. /** Swaps a pair of objects in the array.
  7724. If either of the indexes passed in is out-of-range, nothing will happen,
  7725. otherwise the two objects at these positions will be exchanged.
  7726. */
  7727. void swap (const int index1,
  7728. const int index2) throw()
  7729. {
  7730. const ScopedLockType lock (getLock());
  7731. if (isPositiveAndBelow (index1, numUsed)
  7732. && isPositiveAndBelow (index2, numUsed))
  7733. {
  7734. swapVariables (data.elements [index1],
  7735. data.elements [index2]);
  7736. }
  7737. }
  7738. /** Moves one of the objects to a different position.
  7739. This will move the object to a specified index, shuffling along
  7740. any intervening elements as required.
  7741. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  7742. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  7743. @param currentIndex the index of the object to be moved. If this isn't a
  7744. valid index, then nothing will be done
  7745. @param newIndex the index at which you'd like this object to end up. If this
  7746. is less than zero, it will be moved to the end of the array
  7747. */
  7748. void move (const int currentIndex,
  7749. int newIndex) throw()
  7750. {
  7751. if (currentIndex != newIndex)
  7752. {
  7753. const ScopedLockType lock (getLock());
  7754. if (isPositiveAndBelow (currentIndex, numUsed))
  7755. {
  7756. if (! isPositiveAndBelow (newIndex, numUsed))
  7757. newIndex = numUsed - 1;
  7758. ObjectClass* const value = data.elements [currentIndex];
  7759. if (newIndex > currentIndex)
  7760. {
  7761. memmove (data.elements + currentIndex,
  7762. data.elements + currentIndex + 1,
  7763. (newIndex - currentIndex) * sizeof (ObjectClass*));
  7764. }
  7765. else
  7766. {
  7767. memmove (data.elements + newIndex + 1,
  7768. data.elements + newIndex,
  7769. (currentIndex - newIndex) * sizeof (ObjectClass*));
  7770. }
  7771. data.elements [newIndex] = value;
  7772. }
  7773. }
  7774. }
  7775. /** This swaps the contents of this array with those of another array.
  7776. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  7777. because it just swaps their internal pointers.
  7778. */
  7779. void swapWithArray (OwnedArray& otherArray) throw()
  7780. {
  7781. const ScopedLockType lock1 (getLock());
  7782. const ScopedLockType lock2 (otherArray.getLock());
  7783. data.swapWith (otherArray.data);
  7784. swapVariables (numUsed, otherArray.numUsed);
  7785. }
  7786. /** Reduces the amount of storage being used by the array.
  7787. Arrays typically allocate slightly more storage than they need, and after
  7788. removing elements, they may have quite a lot of unused space allocated.
  7789. This method will reduce the amount of allocated storage to a minimum.
  7790. */
  7791. void minimiseStorageOverheads() throw()
  7792. {
  7793. const ScopedLockType lock (getLock());
  7794. data.shrinkToNoMoreThan (numUsed);
  7795. }
  7796. /** Increases the array's internal storage to hold a minimum number of elements.
  7797. Calling this before adding a large known number of elements means that
  7798. the array won't have to keep dynamically resizing itself as the elements
  7799. are added, and it'll therefore be more efficient.
  7800. */
  7801. void ensureStorageAllocated (const int minNumElements) throw()
  7802. {
  7803. const ScopedLockType lock (getLock());
  7804. data.ensureAllocatedSize (minNumElements);
  7805. }
  7806. /** Sorts the elements in the array.
  7807. This will use a comparator object to sort the elements into order. The object
  7808. passed must have a method of the form:
  7809. @code
  7810. int compareElements (ElementType first, ElementType second);
  7811. @endcode
  7812. ..and this method must return:
  7813. - a value of < 0 if the first comes before the second
  7814. - a value of 0 if the two objects are equivalent
  7815. - a value of > 0 if the second comes before the first
  7816. To improve performance, the compareElements() method can be declared as static or const.
  7817. @param comparator the comparator to use for comparing elements.
  7818. @param retainOrderOfEquivalentItems if this is true, then items
  7819. which the comparator says are equivalent will be
  7820. kept in the order in which they currently appear
  7821. in the array. This is slower to perform, but may
  7822. be important in some cases. If it's false, a faster
  7823. algorithm is used, but equivalent elements may be
  7824. rearranged.
  7825. @see sortArray, indexOfSorted
  7826. */
  7827. template <class ElementComparator>
  7828. void sort (ElementComparator& comparator,
  7829. const bool retainOrderOfEquivalentItems = false) const throw()
  7830. {
  7831. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7832. // avoids getting warning messages about the parameter being unused
  7833. const ScopedLockType lock (getLock());
  7834. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  7835. }
  7836. /** Returns the CriticalSection that locks this array.
  7837. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  7838. an object of ScopedLockType as an RAII lock for it.
  7839. */
  7840. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  7841. /** Returns the type of scoped lock to use for locking this array */
  7842. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  7843. private:
  7844. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  7845. int numUsed;
  7846. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OwnedArray);
  7847. };
  7848. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  7849. /*** End of inlined file: juce_OwnedArray.h ***/
  7850. #endif
  7851. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  7852. /*** Start of inlined file: juce_PropertySet.h ***/
  7853. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  7854. #define __JUCE_PROPERTYSET_JUCEHEADER__
  7855. /*** Start of inlined file: juce_StringPairArray.h ***/
  7856. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  7857. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  7858. /*** Start of inlined file: juce_StringArray.h ***/
  7859. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  7860. #define __JUCE_STRINGARRAY_JUCEHEADER__
  7861. /**
  7862. A special array for holding a list of strings.
  7863. @see String, StringPairArray
  7864. */
  7865. class JUCE_API StringArray
  7866. {
  7867. public:
  7868. /** Creates an empty string array */
  7869. StringArray() throw();
  7870. /** Creates a copy of another string array */
  7871. StringArray (const StringArray& other);
  7872. /** Creates an array containing a single string. */
  7873. explicit StringArray (const String& firstValue);
  7874. /** Creates a copy of an array of string literals.
  7875. @param strings an array of strings to add. Null pointers in the array will be
  7876. treated as empty strings
  7877. @param numberOfStrings how many items there are in the array
  7878. */
  7879. StringArray (const juce_wchar* const* strings, int numberOfStrings);
  7880. /** Creates a copy of an array of string literals.
  7881. @param strings an array of strings to add. Null pointers in the array will be
  7882. treated as empty strings
  7883. @param numberOfStrings how many items there are in the array
  7884. */
  7885. StringArray (const char* const* strings, int numberOfStrings);
  7886. /** Creates a copy of a null-terminated array of string literals.
  7887. Each item from the array passed-in is added, until it encounters a null pointer,
  7888. at which point it stops.
  7889. */
  7890. explicit StringArray (const juce_wchar* const* strings);
  7891. /** Creates a copy of a null-terminated array of string literals.
  7892. Each item from the array passed-in is added, until it encounters a null pointer,
  7893. at which point it stops.
  7894. */
  7895. explicit StringArray (const char* const* strings);
  7896. /** Destructor. */
  7897. ~StringArray();
  7898. /** Copies the contents of another string array into this one */
  7899. StringArray& operator= (const StringArray& other);
  7900. /** Compares two arrays.
  7901. Comparisons are case-sensitive.
  7902. @returns true only if the other array contains exactly the same strings in the same order
  7903. */
  7904. bool operator== (const StringArray& other) const throw();
  7905. /** Compares two arrays.
  7906. Comparisons are case-sensitive.
  7907. @returns false if the other array contains exactly the same strings in the same order
  7908. */
  7909. bool operator!= (const StringArray& other) const throw();
  7910. /** Returns the number of strings in the array */
  7911. inline int size() const throw() { return strings.size(); };
  7912. /** Returns one of the strings from the array.
  7913. If the index is out-of-range, an empty string is returned.
  7914. Obviously the reference returned shouldn't be stored for later use, as the
  7915. string it refers to may disappear when the array changes.
  7916. */
  7917. const String& operator[] (int index) const throw();
  7918. /** Returns a reference to one of the strings in the array.
  7919. This lets you modify a string in-place in the array, but you must be sure that
  7920. the index is in-range.
  7921. */
  7922. String& getReference (int index) throw();
  7923. /** Searches for a string in the array.
  7924. The comparison will be case-insensitive if the ignoreCase parameter is true.
  7925. @returns true if the string is found inside the array
  7926. */
  7927. bool contains (const String& stringToLookFor,
  7928. bool ignoreCase = false) const;
  7929. /** Searches for a string in the array.
  7930. The comparison will be case-insensitive if the ignoreCase parameter is true.
  7931. @param stringToLookFor the string to try to find
  7932. @param ignoreCase whether the comparison should be case-insensitive
  7933. @param startIndex the first index to start searching from
  7934. @returns the index of the first occurrence of the string in this array,
  7935. or -1 if it isn't found.
  7936. */
  7937. int indexOf (const String& stringToLookFor,
  7938. bool ignoreCase = false,
  7939. int startIndex = 0) const;
  7940. /** Appends a string at the end of the array. */
  7941. void add (const String& stringToAdd);
  7942. /** Inserts a string into the array.
  7943. This will insert a string into the array at the given index, moving
  7944. up the other elements to make room for it.
  7945. If the index is less than zero or greater than the size of the array,
  7946. the new string will be added to the end of the array.
  7947. */
  7948. void insert (int index, const String& stringToAdd);
  7949. /** Adds a string to the array as long as it's not already in there.
  7950. The search can optionally be case-insensitive.
  7951. */
  7952. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  7953. /** Replaces one of the strings in the array with another one.
  7954. If the index is higher than the array's size, the new string will be
  7955. added to the end of the array; if it's less than zero nothing happens.
  7956. */
  7957. void set (int index, const String& newString);
  7958. /** Appends some strings from another array to the end of this one.
  7959. @param other the array to add
  7960. @param startIndex the first element of the other array to add
  7961. @param numElementsToAdd the maximum number of elements to add (if this is
  7962. less than zero, they are all added)
  7963. */
  7964. void addArray (const StringArray& other,
  7965. int startIndex = 0,
  7966. int numElementsToAdd = -1);
  7967. /** Breaks up a string into tokens and adds them to this array.
  7968. This will tokenise the given string using whitespace characters as the
  7969. token delimiters, and will add these tokens to the end of the array.
  7970. @returns the number of tokens added
  7971. */
  7972. int addTokens (const String& stringToTokenise,
  7973. bool preserveQuotedStrings);
  7974. /** Breaks up a string into tokens and adds them to this array.
  7975. This will tokenise the given string (using the string passed in to define the
  7976. token delimiters), and will add these tokens to the end of the array.
  7977. @param stringToTokenise the string to tokenise
  7978. @param breakCharacters a string of characters, any of which will be considered
  7979. to be a token delimiter.
  7980. @param quoteCharacters if this string isn't empty, it defines a set of characters
  7981. which are treated as quotes. Any text occurring
  7982. between quotes is not broken up into tokens.
  7983. @returns the number of tokens added
  7984. */
  7985. int addTokens (const String& stringToTokenise,
  7986. const String& breakCharacters,
  7987. const String& quoteCharacters);
  7988. /** Breaks up a string into lines and adds them to this array.
  7989. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  7990. to the array. Line-break characters are omitted from the strings that are added to
  7991. the array.
  7992. */
  7993. int addLines (const String& stringToBreakUp);
  7994. /** Removes all elements from the array. */
  7995. void clear();
  7996. /** Removes a string from the array.
  7997. If the index is out-of-range, no action will be taken.
  7998. */
  7999. void remove (int index);
  8000. /** Finds a string in the array and removes it.
  8001. This will remove the first occurrence of the given string from the array. The
  8002. comparison may be case-insensitive depending on the ignoreCase parameter.
  8003. */
  8004. void removeString (const String& stringToRemove,
  8005. bool ignoreCase = false);
  8006. /** Removes a range of elements from the array.
  8007. This will remove a set of elements, starting from the given index,
  8008. and move subsequent elements down to close the gap.
  8009. If the range extends beyond the bounds of the array, it will
  8010. be safely clipped to the size of the array.
  8011. @param startIndex the index of the first element to remove
  8012. @param numberToRemove how many elements should be removed
  8013. */
  8014. void removeRange (int startIndex, int numberToRemove);
  8015. /** Removes any duplicated elements from the array.
  8016. If any string appears in the array more than once, only the first occurrence of
  8017. it will be retained.
  8018. @param ignoreCase whether to use a case-insensitive comparison
  8019. */
  8020. void removeDuplicates (bool ignoreCase);
  8021. /** Removes empty strings from the array.
  8022. @param removeWhitespaceStrings if true, strings that only contain whitespace
  8023. characters will also be removed
  8024. */
  8025. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  8026. /** Moves one of the strings to a different position.
  8027. This will move the string to a specified index, shuffling along
  8028. any intervening elements as required.
  8029. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8030. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8031. @param currentIndex the index of the value to be moved. If this isn't a
  8032. valid index, then nothing will be done
  8033. @param newIndex the index at which you'd like this value to end up. If this
  8034. is less than zero, the value will be moved to the end
  8035. of the array
  8036. */
  8037. void move (int currentIndex, int newIndex) throw();
  8038. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  8039. void trim();
  8040. /** Adds numbers to the strings in the array, to make each string unique.
  8041. This will add numbers to the ends of groups of similar strings.
  8042. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  8043. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  8044. @param appendNumberToFirstInstance whether the first of a group of similar strings
  8045. also has a number appended to it.
  8046. @param preNumberString when adding a number, this string is added before the number.
  8047. If you pass 0, a default string will be used, which adds
  8048. brackets around the number.
  8049. @param postNumberString this string is appended after any numbers that are added.
  8050. If you pass 0, a default string will be used, which adds
  8051. brackets around the number.
  8052. */
  8053. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  8054. bool appendNumberToFirstInstance,
  8055. CharPointer_UTF8 preNumberString = CharPointer_UTF8 (0),
  8056. CharPointer_UTF8 postNumberString = CharPointer_UTF8 (0));
  8057. /** Joins the strings in the array together into one string.
  8058. This will join a range of elements from the array into a string, separating
  8059. them with a given string.
  8060. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  8061. @param separatorString the string to insert between all the strings
  8062. @param startIndex the first element to join
  8063. @param numberOfElements how many elements to join together. If this is less
  8064. than zero, all available elements will be used.
  8065. */
  8066. const String joinIntoString (const String& separatorString,
  8067. int startIndex = 0,
  8068. int numberOfElements = -1) const;
  8069. /** Sorts the array into alphabetical order.
  8070. @param ignoreCase if true, the comparisons used will be case-sensitive.
  8071. */
  8072. void sort (bool ignoreCase);
  8073. /** Reduces the amount of storage being used by the array.
  8074. Arrays typically allocate slightly more storage than they need, and after
  8075. removing elements, they may have quite a lot of unused space allocated.
  8076. This method will reduce the amount of allocated storage to a minimum.
  8077. */
  8078. void minimiseStorageOverheads();
  8079. private:
  8080. Array <String> strings;
  8081. JUCE_LEAK_DETECTOR (StringArray);
  8082. };
  8083. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  8084. /*** End of inlined file: juce_StringArray.h ***/
  8085. /**
  8086. A container for holding a set of strings which are keyed by another string.
  8087. @see StringArray
  8088. */
  8089. class JUCE_API StringPairArray
  8090. {
  8091. public:
  8092. /** Creates an empty array */
  8093. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  8094. /** Creates a copy of another array */
  8095. StringPairArray (const StringPairArray& other);
  8096. /** Destructor. */
  8097. ~StringPairArray();
  8098. /** Copies the contents of another string array into this one */
  8099. StringPairArray& operator= (const StringPairArray& other);
  8100. /** Compares two arrays.
  8101. Comparisons are case-sensitive.
  8102. @returns true only if the other array contains exactly the same strings with the same keys
  8103. */
  8104. bool operator== (const StringPairArray& other) const;
  8105. /** Compares two arrays.
  8106. Comparisons are case-sensitive.
  8107. @returns false if the other array contains exactly the same strings with the same keys
  8108. */
  8109. bool operator!= (const StringPairArray& other) const;
  8110. /** Finds the value corresponding to a key string.
  8111. If no such key is found, this will just return an empty string. To check whether
  8112. a given key actually exists (because it might actually be paired with an empty string), use
  8113. the getAllKeys() method to obtain a list.
  8114. Obviously the reference returned shouldn't be stored for later use, as the
  8115. string it refers to may disappear when the array changes.
  8116. @see getValue
  8117. */
  8118. const String& operator[] (const String& key) const;
  8119. /** Finds the value corresponding to a key string.
  8120. If no such key is found, this will just return the value provided as a default.
  8121. @see operator[]
  8122. */
  8123. const String getValue (const String& key, const String& defaultReturnValue) const;
  8124. /** Returns a list of all keys in the array. */
  8125. const StringArray& getAllKeys() const throw() { return keys; }
  8126. /** Returns a list of all values in the array. */
  8127. const StringArray& getAllValues() const throw() { return values; }
  8128. /** Returns the number of strings in the array */
  8129. inline int size() const throw() { return keys.size(); };
  8130. /** Adds or amends a key/value pair.
  8131. If a value already exists with this key, its value will be overwritten,
  8132. otherwise the key/value pair will be added to the array.
  8133. */
  8134. void set (const String& key, const String& value);
  8135. /** Adds the items from another array to this one.
  8136. This is equivalent to using set() to add each of the pairs from the other array.
  8137. */
  8138. void addArray (const StringPairArray& other);
  8139. /** Removes all elements from the array. */
  8140. void clear();
  8141. /** Removes a string from the array based on its key.
  8142. If the key isn't found, nothing will happen.
  8143. */
  8144. void remove (const String& key);
  8145. /** Removes a string from the array based on its index.
  8146. If the index is out-of-range, no action will be taken.
  8147. */
  8148. void remove (int index);
  8149. /** Indicates whether to use a case-insensitive search when looking up a key string.
  8150. */
  8151. void setIgnoresCase (bool shouldIgnoreCase);
  8152. /** Returns a descriptive string containing the items.
  8153. This is handy for dumping the contents of an array.
  8154. */
  8155. const String getDescription() const;
  8156. /** Reduces the amount of storage being used by the array.
  8157. Arrays typically allocate slightly more storage than they need, and after
  8158. removing elements, they may have quite a lot of unused space allocated.
  8159. This method will reduce the amount of allocated storage to a minimum.
  8160. */
  8161. void minimiseStorageOverheads();
  8162. private:
  8163. StringArray keys, values;
  8164. bool ignoreCase;
  8165. JUCE_LEAK_DETECTOR (StringPairArray);
  8166. };
  8167. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  8168. /*** End of inlined file: juce_StringPairArray.h ***/
  8169. /*** Start of inlined file: juce_XmlElement.h ***/
  8170. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  8171. #define __JUCE_XMLELEMENT_JUCEHEADER__
  8172. /*** Start of inlined file: juce_File.h ***/
  8173. #ifndef __JUCE_FILE_JUCEHEADER__
  8174. #define __JUCE_FILE_JUCEHEADER__
  8175. /*** Start of inlined file: juce_Time.h ***/
  8176. #ifndef __JUCE_TIME_JUCEHEADER__
  8177. #define __JUCE_TIME_JUCEHEADER__
  8178. /*** Start of inlined file: juce_RelativeTime.h ***/
  8179. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  8180. #define __JUCE_RELATIVETIME_JUCEHEADER__
  8181. /** A relative measure of time.
  8182. The time is stored as a number of seconds, at double-precision floating
  8183. point accuracy, and may be positive or negative.
  8184. If you need an absolute time, (i.e. a date + time), see the Time class.
  8185. */
  8186. class JUCE_API RelativeTime
  8187. {
  8188. public:
  8189. /** Creates a RelativeTime.
  8190. @param seconds the number of seconds, which may be +ve or -ve.
  8191. @see milliseconds, minutes, hours, days, weeks
  8192. */
  8193. explicit RelativeTime (double seconds = 0.0) throw();
  8194. /** Copies another relative time. */
  8195. RelativeTime (const RelativeTime& other) throw();
  8196. /** Copies another relative time. */
  8197. RelativeTime& operator= (const RelativeTime& other) throw();
  8198. /** Destructor. */
  8199. ~RelativeTime() throw();
  8200. /** Creates a new RelativeTime object representing a number of milliseconds.
  8201. @see minutes, hours, days, weeks
  8202. */
  8203. static const RelativeTime milliseconds (int milliseconds) throw();
  8204. /** Creates a new RelativeTime object representing a number of milliseconds.
  8205. @see minutes, hours, days, weeks
  8206. */
  8207. static const RelativeTime milliseconds (int64 milliseconds) throw();
  8208. /** Creates a new RelativeTime object representing a number of minutes.
  8209. @see milliseconds, hours, days, weeks
  8210. */
  8211. static const RelativeTime minutes (double numberOfMinutes) throw();
  8212. /** Creates a new RelativeTime object representing a number of hours.
  8213. @see milliseconds, minutes, days, weeks
  8214. */
  8215. static const RelativeTime hours (double numberOfHours) throw();
  8216. /** Creates a new RelativeTime object representing a number of days.
  8217. @see milliseconds, minutes, hours, weeks
  8218. */
  8219. static const RelativeTime days (double numberOfDays) throw();
  8220. /** Creates a new RelativeTime object representing a number of weeks.
  8221. @see milliseconds, minutes, hours, days
  8222. */
  8223. static const RelativeTime weeks (double numberOfWeeks) throw();
  8224. /** Returns the number of milliseconds this time represents.
  8225. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  8226. */
  8227. int64 inMilliseconds() const throw();
  8228. /** Returns the number of seconds this time represents.
  8229. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  8230. */
  8231. double inSeconds() const throw() { return seconds; }
  8232. /** Returns the number of minutes this time represents.
  8233. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  8234. */
  8235. double inMinutes() const throw();
  8236. /** Returns the number of hours this time represents.
  8237. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  8238. */
  8239. double inHours() const throw();
  8240. /** Returns the number of days this time represents.
  8241. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  8242. */
  8243. double inDays() const throw();
  8244. /** Returns the number of weeks this time represents.
  8245. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  8246. */
  8247. double inWeeks() const throw();
  8248. /** Returns a readable textual description of the time.
  8249. The exact format of the string returned will depend on
  8250. the magnitude of the time - e.g.
  8251. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  8252. so that only the two most significant units are printed.
  8253. The returnValueForZeroTime value is the result that is returned if the
  8254. length is zero. Depending on your application you might want to use this
  8255. to return something more relevant like "empty" or "0 secs", etc.
  8256. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  8257. */
  8258. const String getDescription (const String& returnValueForZeroTime = "0") const;
  8259. /** Adds another RelativeTime to this one. */
  8260. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  8261. /** Subtracts another RelativeTime from this one. */
  8262. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  8263. /** Adds a number of seconds to this time. */
  8264. const RelativeTime& operator+= (double secondsToAdd) throw();
  8265. /** Subtracts a number of seconds from this time. */
  8266. const RelativeTime& operator-= (double secondsToSubtract) throw();
  8267. private:
  8268. double seconds;
  8269. };
  8270. /** Compares two RelativeTimes. */
  8271. bool operator== (const RelativeTime& t1, const RelativeTime& t2) throw();
  8272. /** Compares two RelativeTimes. */
  8273. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) throw();
  8274. /** Compares two RelativeTimes. */
  8275. bool operator> (const RelativeTime& t1, const RelativeTime& t2) throw();
  8276. /** Compares two RelativeTimes. */
  8277. bool operator< (const RelativeTime& t1, const RelativeTime& t2) throw();
  8278. /** Compares two RelativeTimes. */
  8279. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) throw();
  8280. /** Compares two RelativeTimes. */
  8281. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) throw();
  8282. /** Adds two RelativeTimes together. */
  8283. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) throw();
  8284. /** Subtracts two RelativeTimes. */
  8285. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) throw();
  8286. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  8287. /*** End of inlined file: juce_RelativeTime.h ***/
  8288. /**
  8289. Holds an absolute date and time.
  8290. Internally, the time is stored at millisecond precision.
  8291. @see RelativeTime
  8292. */
  8293. class JUCE_API Time
  8294. {
  8295. public:
  8296. /** Creates a Time object.
  8297. This default constructor creates a time of 1st January 1970, (which is
  8298. represented internally as 0ms).
  8299. To create a time object representing the current time, use getCurrentTime().
  8300. @see getCurrentTime
  8301. */
  8302. Time() throw();
  8303. /** Creates a time based on a number of milliseconds.
  8304. The internal millisecond count is set to 0 (1st January 1970). To create a
  8305. time object set to the current time, use getCurrentTime().
  8306. @param millisecondsSinceEpoch the number of milliseconds since the unix
  8307. 'epoch' (midnight Jan 1st 1970).
  8308. @see getCurrentTime, currentTimeMillis
  8309. */
  8310. explicit Time (int64 millisecondsSinceEpoch) throw();
  8311. /** Creates a time from a set of date components.
  8312. The timezone is assumed to be whatever the system is using as its locale.
  8313. @param year the year, in 4-digit format, e.g. 2004
  8314. @param month the month, in the range 0 to 11
  8315. @param day the day of the month, in the range 1 to 31
  8316. @param hours hours in 24-hour clock format, 0 to 23
  8317. @param minutes minutes 0 to 59
  8318. @param seconds seconds 0 to 59
  8319. @param milliseconds milliseconds 0 to 999
  8320. @param useLocalTime if true, encode using the current machine's local time; if
  8321. false, it will always work in GMT.
  8322. */
  8323. Time (int year,
  8324. int month,
  8325. int day,
  8326. int hours,
  8327. int minutes,
  8328. int seconds = 0,
  8329. int milliseconds = 0,
  8330. bool useLocalTime = true) throw();
  8331. /** Creates a copy of another Time object. */
  8332. Time (const Time& other) throw();
  8333. /** Destructor. */
  8334. ~Time() throw();
  8335. /** Copies this time from another one. */
  8336. Time& operator= (const Time& other) throw();
  8337. /** Returns a Time object that is set to the current system time.
  8338. @see currentTimeMillis
  8339. */
  8340. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  8341. /** Returns the time as a number of milliseconds.
  8342. @returns the number of milliseconds this Time object represents, since
  8343. midnight jan 1st 1970.
  8344. @see getMilliseconds
  8345. */
  8346. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  8347. /** Returns the year.
  8348. A 4-digit format is used, e.g. 2004.
  8349. */
  8350. int getYear() const throw();
  8351. /** Returns the number of the month.
  8352. The value returned is in the range 0 to 11.
  8353. @see getMonthName
  8354. */
  8355. int getMonth() const throw();
  8356. /** Returns the name of the month.
  8357. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  8358. it'll return the long form, e.g. "January"
  8359. @see getMonth
  8360. */
  8361. const String getMonthName (bool threeLetterVersion) const;
  8362. /** Returns the day of the month.
  8363. The value returned is in the range 1 to 31.
  8364. */
  8365. int getDayOfMonth() const throw();
  8366. /** Returns the number of the day of the week.
  8367. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  8368. */
  8369. int getDayOfWeek() const throw();
  8370. /** Returns the name of the weekday.
  8371. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  8372. false, it'll return the full version, e.g. "Tuesday".
  8373. */
  8374. const String getWeekdayName (bool threeLetterVersion) const;
  8375. /** Returns the number of hours since midnight.
  8376. This is in 24-hour clock format, in the range 0 to 23.
  8377. @see getHoursInAmPmFormat, isAfternoon
  8378. */
  8379. int getHours() const throw();
  8380. /** Returns true if the time is in the afternoon.
  8381. So it returns true for "PM", false for "AM".
  8382. @see getHoursInAmPmFormat, getHours
  8383. */
  8384. bool isAfternoon() const throw();
  8385. /** Returns the hours in 12-hour clock format.
  8386. This will return a value 1 to 12 - use isAfternoon() to find out
  8387. whether this is in the afternoon or morning.
  8388. @see getHours, isAfternoon
  8389. */
  8390. int getHoursInAmPmFormat() const throw();
  8391. /** Returns the number of minutes, 0 to 59. */
  8392. int getMinutes() const throw();
  8393. /** Returns the number of seconds, 0 to 59. */
  8394. int getSeconds() const throw();
  8395. /** Returns the number of milliseconds, 0 to 999.
  8396. Unlike toMilliseconds(), this just returns the position within the
  8397. current second rather than the total number since the epoch.
  8398. @see toMilliseconds
  8399. */
  8400. int getMilliseconds() const throw();
  8401. /** Returns true if the local timezone uses a daylight saving correction. */
  8402. bool isDaylightSavingTime() const throw();
  8403. /** Returns a 3-character string to indicate the local timezone. */
  8404. const String getTimeZone() const throw();
  8405. /** Quick way of getting a string version of a date and time.
  8406. For a more powerful way of formatting the date and time, see the formatted() method.
  8407. @param includeDate whether to include the date in the string
  8408. @param includeTime whether to include the time in the string
  8409. @param includeSeconds if the time is being included, this provides an option not to include
  8410. the seconds in it
  8411. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  8412. hour notation.
  8413. @see formatted
  8414. */
  8415. const String toString (bool includeDate,
  8416. bool includeTime,
  8417. bool includeSeconds = true,
  8418. bool use24HourClock = false) const throw();
  8419. /** Converts this date/time to a string with a user-defined format.
  8420. This uses the C strftime() function to format this time as a string. To save you
  8421. looking it up, these are the escape codes that strftime uses (other codes might
  8422. work on some platforms and not others, but these are the common ones):
  8423. %a is replaced by the locale's abbreviated weekday name.
  8424. %A is replaced by the locale's full weekday name.
  8425. %b is replaced by the locale's abbreviated month name.
  8426. %B is replaced by the locale's full month name.
  8427. %c is replaced by the locale's appropriate date and time representation.
  8428. %d is replaced by the day of the month as a decimal number [01,31].
  8429. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  8430. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  8431. %j is replaced by the day of the year as a decimal number [001,366].
  8432. %m is replaced by the month as a decimal number [01,12].
  8433. %M is replaced by the minute as a decimal number [00,59].
  8434. %p is replaced by the locale's equivalent of either a.m. or p.m.
  8435. %S is replaced by the second as a decimal number [00,61].
  8436. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  8437. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  8438. %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.
  8439. %x is replaced by the locale's appropriate date representation.
  8440. %X is replaced by the locale's appropriate time representation.
  8441. %y is replaced by the year without century as a decimal number [00,99].
  8442. %Y is replaced by the year with century as a decimal number.
  8443. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  8444. %% is replaced by %.
  8445. @see toString
  8446. */
  8447. const String formatted (const String& format) const;
  8448. /** Adds a RelativeTime to this time. */
  8449. Time& operator+= (const RelativeTime& delta);
  8450. /** Subtracts a RelativeTime from this time. */
  8451. Time& operator-= (const RelativeTime& delta);
  8452. /** Tries to set the computer's clock.
  8453. @returns true if this succeeds, although depending on the system, the
  8454. application might not have sufficient privileges to do this.
  8455. */
  8456. bool setSystemTimeToThisTime() const;
  8457. /** Returns the name of a day of the week.
  8458. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  8459. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  8460. false, it'll return the full version, e.g. "Tuesday".
  8461. */
  8462. static const String getWeekdayName (int dayNumber,
  8463. bool threeLetterVersion);
  8464. /** Returns the name of one of the months.
  8465. @param monthNumber the month, 0 to 11
  8466. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  8467. it'll return the long form, e.g. "January"
  8468. */
  8469. static const String getMonthName (int monthNumber,
  8470. bool threeLetterVersion);
  8471. // Static methods for getting system timers directly..
  8472. /** Returns the current system time.
  8473. Returns the number of milliseconds since midnight jan 1st 1970.
  8474. Should be accurate to within a few millisecs, depending on platform,
  8475. hardware, etc.
  8476. */
  8477. static int64 currentTimeMillis() throw();
  8478. /** Returns the number of millisecs since a fixed event (usually system startup).
  8479. This returns a monotonically increasing value which it unaffected by changes to the
  8480. system clock. It should be accurate to within a few millisecs, depending on platform,
  8481. hardware, etc.
  8482. @see getApproximateMillisecondCounter
  8483. */
  8484. static uint32 getMillisecondCounter() throw();
  8485. /** Returns the number of millisecs since a fixed event (usually system startup).
  8486. This has the same function as getMillisecondCounter(), but returns a more accurate
  8487. value, using a higher-resolution timer if one is available.
  8488. @see getMillisecondCounter
  8489. */
  8490. static double getMillisecondCounterHiRes() throw();
  8491. /** Waits until the getMillisecondCounter() reaches a given value.
  8492. This will make the thread sleep as efficiently as it can while it's waiting.
  8493. */
  8494. static void waitForMillisecondCounter (uint32 targetTime) throw();
  8495. /** Less-accurate but faster version of getMillisecondCounter().
  8496. This will return the last value that getMillisecondCounter() returned, so doesn't
  8497. need to make a system call, but is less accurate - it shouldn't be more than
  8498. 100ms away from the correct time, though, so is still accurate enough for a
  8499. lot of purposes.
  8500. @see getMillisecondCounter
  8501. */
  8502. static uint32 getApproximateMillisecondCounter() throw();
  8503. // High-resolution timers..
  8504. /** Returns the current high-resolution counter's tick-count.
  8505. This is a similar idea to getMillisecondCounter(), but with a higher
  8506. resolution.
  8507. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  8508. secondsToHighResolutionTicks
  8509. */
  8510. static int64 getHighResolutionTicks() throw();
  8511. /** Returns the resolution of the high-resolution counter in ticks per second.
  8512. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  8513. secondsToHighResolutionTicks
  8514. */
  8515. static int64 getHighResolutionTicksPerSecond() throw();
  8516. /** Converts a number of high-resolution ticks into seconds.
  8517. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  8518. secondsToHighResolutionTicks
  8519. */
  8520. static double highResolutionTicksToSeconds (int64 ticks) throw();
  8521. /** Converts a number seconds into high-resolution ticks.
  8522. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  8523. highResolutionTicksToSeconds
  8524. */
  8525. static int64 secondsToHighResolutionTicks (double seconds) throw();
  8526. private:
  8527. int64 millisSinceEpoch;
  8528. };
  8529. /** Adds a RelativeTime to a Time. */
  8530. const Time operator+ (const Time& time, const RelativeTime& delta);
  8531. /** Adds a RelativeTime to a Time. */
  8532. const Time operator+ (const RelativeTime& delta, const Time& time);
  8533. /** Subtracts a RelativeTime from a Time. */
  8534. const Time operator- (const Time& time, const RelativeTime& delta);
  8535. /** Returns the relative time difference between two times. */
  8536. const RelativeTime operator- (const Time& time1, const Time& time2);
  8537. /** Compares two Time objects. */
  8538. bool operator== (const Time& time1, const Time& time2);
  8539. /** Compares two Time objects. */
  8540. bool operator!= (const Time& time1, const Time& time2);
  8541. /** Compares two Time objects. */
  8542. bool operator< (const Time& time1, const Time& time2);
  8543. /** Compares two Time objects. */
  8544. bool operator<= (const Time& time1, const Time& time2);
  8545. /** Compares two Time objects. */
  8546. bool operator> (const Time& time1, const Time& time2);
  8547. /** Compares two Time objects. */
  8548. bool operator>= (const Time& time1, const Time& time2);
  8549. #endif // __JUCE_TIME_JUCEHEADER__
  8550. /*** End of inlined file: juce_Time.h ***/
  8551. /*** Start of inlined file: juce_ScopedPointer.h ***/
  8552. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8553. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8554. /**
  8555. This class holds a pointer which is automatically deleted when this object goes
  8556. out of scope.
  8557. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  8558. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  8559. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  8560. created objects.
  8561. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  8562. to an object. If you use the assignment operator to assign a different object to a
  8563. ScopedPointer, the old one will be automatically deleted.
  8564. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  8565. object to which it points during its lifetime. This means that making a copy of a const
  8566. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  8567. old one.
  8568. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  8569. can use the release() method.
  8570. */
  8571. template <class ObjectType>
  8572. class ScopedPointer
  8573. {
  8574. public:
  8575. /** Creates a ScopedPointer containing a null pointer. */
  8576. inline ScopedPointer() throw() : object (0)
  8577. {
  8578. }
  8579. /** Creates a ScopedPointer that owns the specified object. */
  8580. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) throw()
  8581. : object (objectToTakePossessionOf)
  8582. {
  8583. }
  8584. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  8585. Because a pointer can only belong to one ScopedPointer, this transfers
  8586. the pointer from the other object to this one, and the other object is reset to
  8587. be a null pointer.
  8588. */
  8589. ScopedPointer (ScopedPointer& objectToTransferFrom) throw()
  8590. : object (objectToTransferFrom.object)
  8591. {
  8592. objectToTransferFrom.object = 0;
  8593. }
  8594. /** Destructor.
  8595. This will delete the object that this ScopedPointer currently refers to.
  8596. */
  8597. inline ~ScopedPointer() { delete object; }
  8598. /** Changes this ScopedPointer to point to a new object.
  8599. Because a pointer can only belong to one ScopedPointer, this transfers
  8600. the pointer from the other object to this one, and the other object is reset to
  8601. be a null pointer.
  8602. If this ScopedPointer already points to an object, that object
  8603. will first be deleted.
  8604. */
  8605. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  8606. {
  8607. if (this != objectToTransferFrom.getAddress())
  8608. {
  8609. // Two ScopedPointers should never be able to refer to the same object - if
  8610. // this happens, you must have done something dodgy!
  8611. jassert (object == 0 || object != objectToTransferFrom.object);
  8612. ObjectType* const oldObject = object;
  8613. object = objectToTransferFrom.object;
  8614. objectToTransferFrom.object = 0;
  8615. delete oldObject;
  8616. }
  8617. return *this;
  8618. }
  8619. /** Changes this ScopedPointer to point to a new object.
  8620. If this ScopedPointer already points to an object, that object
  8621. will first be deleted.
  8622. The pointer that you pass is may be null.
  8623. */
  8624. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  8625. {
  8626. if (object != newObjectToTakePossessionOf)
  8627. {
  8628. ObjectType* const oldObject = object;
  8629. object = newObjectToTakePossessionOf;
  8630. delete oldObject;
  8631. }
  8632. return *this;
  8633. }
  8634. /** Returns the object that this ScopedPointer refers to.
  8635. */
  8636. inline operator ObjectType*() const throw() { return object; }
  8637. /** Returns the object that this ScopedPointer refers to.
  8638. */
  8639. inline ObjectType& operator*() const throw() { return *object; }
  8640. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  8641. inline ObjectType* operator->() const throw() { return object; }
  8642. /** Removes the current object from this ScopedPointer without deleting it.
  8643. This will return the current object, and set the ScopedPointer to a null pointer.
  8644. */
  8645. ObjectType* release() throw() { ObjectType* const o = object; object = 0; return o; }
  8646. /** Swaps this object with that of another ScopedPointer.
  8647. The two objects simply exchange their pointers.
  8648. */
  8649. void swapWith (ScopedPointer <ObjectType>& other) throw()
  8650. {
  8651. // Two ScopedPointers should never be able to refer to the same object - if
  8652. // this happens, you must have done something dodgy!
  8653. jassert (object != other.object);
  8654. swapVariables (object, other.object);
  8655. }
  8656. private:
  8657. ObjectType* object;
  8658. // (Required as an alternative to the overloaded & operator).
  8659. const ScopedPointer* getAddress() const throw() { return this; }
  8660. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  8661. /* This is private to stop people accidentally copying a const ScopedPointer (the compiler
  8662. would let you do so by implicitly casting the source to its raw object pointer).
  8663. A side effect of this is that you may hit a puzzling compiler error when you write something
  8664. like this:
  8665. ScopedPointer<MyClass> m = new MyClass(); // Compile error: copy constructor is private.
  8666. Even though the compiler would normally ignore the assignment here, it can't do so when the
  8667. copy constructor is private. It's very easy to fis though - just write it like this:
  8668. ScopedPointer<MyClass> m (new MyClass()); // Compiles OK
  8669. It's good practice to always use the latter form when writing your object declarations anyway,
  8670. rather than writing them as assignments and assuming (or hoping) that the compiler will be
  8671. smart enough to replace your construction + assignment with a single constructor.
  8672. */
  8673. ScopedPointer (const ScopedPointer&);
  8674. #endif
  8675. };
  8676. /** Compares a ScopedPointer with another pointer.
  8677. This can be handy for checking whether this is a null pointer.
  8678. */
  8679. template <class ObjectType>
  8680. bool operator== (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) throw()
  8681. {
  8682. return static_cast <ObjectType*> (pointer1) == pointer2;
  8683. }
  8684. /** Compares a ScopedPointer with another pointer.
  8685. This can be handy for checking whether this is a null pointer.
  8686. */
  8687. template <class ObjectType>
  8688. bool operator!= (const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) throw()
  8689. {
  8690. return static_cast <ObjectType*> (pointer1) != pointer2;
  8691. }
  8692. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8693. /*** End of inlined file: juce_ScopedPointer.h ***/
  8694. class FileInputStream;
  8695. class FileOutputStream;
  8696. /**
  8697. Represents a local file or directory.
  8698. This class encapsulates the absolute pathname of a file or directory, and
  8699. has methods for finding out about the file and changing its properties.
  8700. To read or write to the file, there are methods for returning an input or
  8701. output stream.
  8702. @see FileInputStream, FileOutputStream
  8703. */
  8704. class JUCE_API File
  8705. {
  8706. public:
  8707. /** Creates an (invalid) file object.
  8708. The file is initially set to an empty path, so getFullPath() will return
  8709. an empty string, and comparing the file to File::nonexistent will return
  8710. true.
  8711. You can use its operator= method to point it at a proper file.
  8712. */
  8713. File() {}
  8714. /** Creates a file from an absolute path.
  8715. If the path supplied is a relative path, it is taken to be relative
  8716. to the current working directory (see File::getCurrentWorkingDirectory()),
  8717. but this isn't a recommended way of creating a file, because you
  8718. never know what the CWD is going to be.
  8719. On the Mac/Linux, the path can include "~" notation for referring to
  8720. user home directories.
  8721. */
  8722. File (const String& path);
  8723. /** Creates a copy of another file object. */
  8724. File (const File& other);
  8725. /** Destructor. */
  8726. ~File() {}
  8727. /** Sets the file based on an absolute pathname.
  8728. If the path supplied is a relative path, it is taken to be relative
  8729. to the current working directory (see File::getCurrentWorkingDirectory()),
  8730. but this isn't a recommended way of creating a file, because you
  8731. never know what the CWD is going to be.
  8732. On the Mac/Linux, the path can include "~" notation for referring to
  8733. user home directories.
  8734. */
  8735. File& operator= (const String& newFilePath);
  8736. /** Copies from another file object. */
  8737. File& operator= (const File& otherFile);
  8738. /** This static constant is used for referring to an 'invalid' file. */
  8739. static const File nonexistent;
  8740. /** Checks whether the file actually exists.
  8741. @returns true if the file exists, either as a file or a directory.
  8742. @see existsAsFile, isDirectory
  8743. */
  8744. bool exists() const;
  8745. /** Checks whether the file exists and is a file rather than a directory.
  8746. @returns true only if this is a real file, false if it's a directory
  8747. or doesn't exist
  8748. @see exists, isDirectory
  8749. */
  8750. bool existsAsFile() const;
  8751. /** Checks whether the file is a directory that exists.
  8752. @returns true only if the file is a directory which actually exists, so
  8753. false if it's a file or doesn't exist at all
  8754. @see exists, existsAsFile
  8755. */
  8756. bool isDirectory() const;
  8757. /** Returns the size of the file in bytes.
  8758. @returns the number of bytes in the file, or 0 if it doesn't exist.
  8759. */
  8760. int64 getSize() const;
  8761. /** Utility function to convert a file size in bytes to a neat string description.
  8762. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  8763. 2000000 would produce "2 MB", etc.
  8764. */
  8765. static const String descriptionOfSizeInBytes (int64 bytes);
  8766. /** Returns the complete, absolute path of this file.
  8767. This includes the filename and all its parent folders. On Windows it'll
  8768. also include the drive letter prefix; on Mac or Linux it'll be a complete
  8769. path starting from the root folder.
  8770. If you just want the file's name, you should use getFileName() or
  8771. getFileNameWithoutExtension().
  8772. @see getFileName, getRelativePathFrom
  8773. */
  8774. const String& getFullPathName() const throw() { return fullPath; }
  8775. /** Returns the last section of the pathname.
  8776. Returns just the final part of the path - e.g. if the whole path
  8777. is "/moose/fish/foo.txt" this will return "foo.txt".
  8778. For a directory, it returns the final part of the path - e.g. for the
  8779. directory "/moose/fish" it'll return "fish".
  8780. If the filename begins with a dot, it'll return the whole filename, e.g. for
  8781. "/moose/.fish", it'll return ".fish"
  8782. @see getFullPathName, getFileNameWithoutExtension
  8783. */
  8784. const String getFileName() const;
  8785. /** Creates a relative path that refers to a file relatively to a given directory.
  8786. e.g. File ("/moose/foo.txt").getRelativePathFrom (File ("/moose/fish/haddock"))
  8787. would return "../../foo.txt".
  8788. If it's not possible to navigate from one file to the other, an absolute
  8789. path is returned. If the paths are invalid, an empty string may also be
  8790. returned.
  8791. @param directoryToBeRelativeTo the directory which the resultant string will
  8792. be relative to. If this is actually a file rather than
  8793. a directory, its parent directory will be used instead.
  8794. If it doesn't exist, it's assumed to be a directory.
  8795. @see getChildFile, isAbsolutePath
  8796. */
  8797. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  8798. /** Returns the file's extension.
  8799. Returns the file extension of this file, also including the dot.
  8800. e.g. "/moose/fish/foo.txt" would return ".txt"
  8801. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  8802. */
  8803. const String getFileExtension() const;
  8804. /** Checks whether the file has a given extension.
  8805. @param extensionToTest the extension to look for - it doesn't matter whether or
  8806. not this string has a dot at the start, so ".wav" and "wav"
  8807. will have the same effect. The comparison used is
  8808. case-insensitve. To compare with multiple extensions, this
  8809. parameter can contain multiple strings, separated by semi-colons -
  8810. so, for example: hasFileExtension (".jpeg;png;gif") would return
  8811. true if the file has any of those three extensions.
  8812. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  8813. */
  8814. bool hasFileExtension (const String& extensionToTest) const;
  8815. /** Returns a version of this file with a different file extension.
  8816. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  8817. @param newExtension the new extension, either with or without a dot at the start (this
  8818. doesn't make any difference). To get remove a file's extension altogether,
  8819. pass an empty string into this function.
  8820. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  8821. */
  8822. const File withFileExtension (const String& newExtension) const;
  8823. /** Returns the last part of the filename, without its file extension.
  8824. e.g. for "/moose/fish/foo.txt" this will return "foo".
  8825. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  8826. */
  8827. const String getFileNameWithoutExtension() const;
  8828. /** Returns a 32-bit hash-code that identifies this file.
  8829. This is based on the filename. Obviously it's possible, although unlikely, that
  8830. two files will have the same hash-code.
  8831. */
  8832. int hashCode() const;
  8833. /** Returns a 64-bit hash-code that identifies this file.
  8834. This is based on the filename. Obviously it's possible, although unlikely, that
  8835. two files will have the same hash-code.
  8836. */
  8837. int64 hashCode64() const;
  8838. /** Returns a file based on a relative path.
  8839. This will find a child file or directory of the current object.
  8840. e.g.
  8841. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  8842. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  8843. If the string is actually an absolute path, it will be treated as such, e.g.
  8844. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  8845. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  8846. */
  8847. const File getChildFile (String relativePath) const;
  8848. /** Returns a file which is in the same directory as this one.
  8849. This is equivalent to getParentDirectory().getChildFile (name).
  8850. @see getChildFile, getParentDirectory
  8851. */
  8852. const File getSiblingFile (const String& siblingFileName) const;
  8853. /** Returns the directory that contains this file or directory.
  8854. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  8855. */
  8856. const File getParentDirectory() const;
  8857. /** Checks whether a file is somewhere inside a directory.
  8858. Returns true if this file is somewhere inside a subdirectory of the directory
  8859. that is passed in. Neither file actually has to exist, because the function
  8860. just checks the paths for similarities.
  8861. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  8862. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  8863. */
  8864. bool isAChildOf (const File& potentialParentDirectory) const;
  8865. /** Chooses a filename relative to this one that doesn't already exist.
  8866. If this file is a directory, this will return a child file of this
  8867. directory that doesn't exist, by adding numbers to a prefix and suffix until
  8868. it finds one that isn't already there.
  8869. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  8870. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  8871. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  8872. @param prefix the string to use for the filename before the number
  8873. @param suffix the string to add to the filename after the number
  8874. @param putNumbersInBrackets if true, this will create filenames in the
  8875. format "prefix(number)suffix", if false, it will leave the
  8876. brackets out.
  8877. */
  8878. const File getNonexistentChildFile (const String& prefix,
  8879. const String& suffix,
  8880. bool putNumbersInBrackets = true) const;
  8881. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  8882. If this file doesn't exist, this will just return itself, otherwise it
  8883. will return an appropriate sibling that doesn't exist, e.g. if a file
  8884. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  8885. @param putNumbersInBrackets whether to add brackets around the numbers that
  8886. get appended to the new filename.
  8887. */
  8888. const File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  8889. /** Compares the pathnames for two files. */
  8890. bool operator== (const File& otherFile) const;
  8891. /** Compares the pathnames for two files. */
  8892. bool operator!= (const File& otherFile) const;
  8893. /** Compares the pathnames for two files. */
  8894. bool operator< (const File& otherFile) const;
  8895. /** Compares the pathnames for two files. */
  8896. bool operator> (const File& otherFile) const;
  8897. /** Checks whether a file can be created or written to.
  8898. @returns true if it's possible to create and write to this file. If the file
  8899. doesn't already exist, this will check its parent directory to
  8900. see if writing is allowed.
  8901. @see setReadOnly
  8902. */
  8903. bool hasWriteAccess() const;
  8904. /** Changes the write-permission of a file or directory.
  8905. @param shouldBeReadOnly whether to add or remove write-permission
  8906. @param applyRecursively if the file is a directory and this is true, it will
  8907. recurse through all the subfolders changing the permissions
  8908. of all files
  8909. @returns true if it manages to change the file's permissions.
  8910. @see hasWriteAccess
  8911. */
  8912. bool setReadOnly (bool shouldBeReadOnly,
  8913. bool applyRecursively = false) const;
  8914. /** Returns true if this file is a hidden or system file.
  8915. The criteria for deciding whether a file is hidden are platform-dependent.
  8916. */
  8917. bool isHidden() const;
  8918. /** If this file is a link, this returns the file that it points to.
  8919. If this file isn't actually link, it'll just return itself.
  8920. */
  8921. const File getLinkedTarget() const;
  8922. /** Returns the last modification time of this file.
  8923. @returns the time, or an invalid time if the file doesn't exist.
  8924. @see setLastModificationTime, getLastAccessTime, getCreationTime
  8925. */
  8926. const Time getLastModificationTime() const;
  8927. /** Returns the last time this file was accessed.
  8928. @returns the time, or an invalid time if the file doesn't exist.
  8929. @see setLastAccessTime, getLastModificationTime, getCreationTime
  8930. */
  8931. const Time getLastAccessTime() const;
  8932. /** Returns the time that this file was created.
  8933. @returns the time, or an invalid time if the file doesn't exist.
  8934. @see getLastModificationTime, getLastAccessTime
  8935. */
  8936. const Time getCreationTime() const;
  8937. /** Changes the modification time for this file.
  8938. @param newTime the time to apply to the file
  8939. @returns true if it manages to change the file's time.
  8940. @see getLastModificationTime, setLastAccessTime, setCreationTime
  8941. */
  8942. bool setLastModificationTime (const Time& newTime) const;
  8943. /** Changes the last-access time for this file.
  8944. @param newTime the time to apply to the file
  8945. @returns true if it manages to change the file's time.
  8946. @see getLastAccessTime, setLastModificationTime, setCreationTime
  8947. */
  8948. bool setLastAccessTime (const Time& newTime) const;
  8949. /** Changes the creation date for this file.
  8950. @param newTime the time to apply to the file
  8951. @returns true if it manages to change the file's time.
  8952. @see getCreationTime, setLastModificationTime, setLastAccessTime
  8953. */
  8954. bool setCreationTime (const Time& newTime) const;
  8955. /** If possible, this will try to create a version string for the given file.
  8956. The OS may be able to look at the file and give a version for it - e.g. with
  8957. executables, bundles, dlls, etc. If no version is available, this will
  8958. return an empty string.
  8959. */
  8960. const String getVersion() const;
  8961. /** Creates an empty file if it doesn't already exist.
  8962. If the file that this object refers to doesn't exist, this will create a file
  8963. of zero size.
  8964. If it already exists or is a directory, this method will do nothing.
  8965. @returns true if the file has been created (or if it already existed).
  8966. @see createDirectory
  8967. */
  8968. bool create() const;
  8969. /** Creates a new directory for this filename.
  8970. This will try to create the file as a directory, and fill also create
  8971. any parent directories it needs in order to complete the operation.
  8972. @returns true if the directory has been created successfully, (or if it
  8973. already existed beforehand).
  8974. @see create
  8975. */
  8976. bool createDirectory() const;
  8977. /** Deletes a file.
  8978. If this file is actually a directory, it may not be deleted correctly if it
  8979. contains files. See deleteRecursively() as a better way of deleting directories.
  8980. @returns true if the file has been successfully deleted (or if it didn't exist to
  8981. begin with).
  8982. @see deleteRecursively
  8983. */
  8984. bool deleteFile() const;
  8985. /** Deletes a file or directory and all its subdirectories.
  8986. If this file is a directory, this will try to delete it and all its subfolders. If
  8987. it's just a file, it will just try to delete the file.
  8988. @returns true if the file and all its subfolders have been successfully deleted
  8989. (or if it didn't exist to begin with).
  8990. @see deleteFile
  8991. */
  8992. bool deleteRecursively() const;
  8993. /** Moves this file or folder to the trash.
  8994. @returns true if the operation succeeded. It could fail if the trash is full, or
  8995. if the file is write-protected, so you should check the return value
  8996. and act appropriately.
  8997. */
  8998. bool moveToTrash() const;
  8999. /** Moves or renames a file.
  9000. Tries to move a file to a different location.
  9001. If the target file already exists, this will attempt to delete it first, and
  9002. will fail if this can't be done.
  9003. Note that the destination file isn't the directory to put it in, it's the actual
  9004. filename that you want the new file to have.
  9005. @returns true if the operation succeeds
  9006. */
  9007. bool moveFileTo (const File& targetLocation) const;
  9008. /** Copies a file.
  9009. Tries to copy a file to a different location.
  9010. If the target file already exists, this will attempt to delete it first, and
  9011. will fail if this can't be done.
  9012. @returns true if the operation succeeds
  9013. */
  9014. bool copyFileTo (const File& targetLocation) const;
  9015. /** Copies a directory.
  9016. Tries to copy an entire directory, recursively.
  9017. If this file isn't a directory or if any target files can't be created, this
  9018. will return false.
  9019. @param newDirectory the directory that this one should be copied to. Note that this
  9020. is the name of the actual directory to create, not the directory
  9021. into which the new one should be placed, so there must be enough
  9022. write privileges to create it if it doesn't exist. Any files inside
  9023. it will be overwritten by similarly named ones that are copied.
  9024. */
  9025. bool copyDirectoryTo (const File& newDirectory) const;
  9026. /** Used in file searching, to specify whether to return files, directories, or both.
  9027. */
  9028. enum TypesOfFileToFind
  9029. {
  9030. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  9031. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  9032. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  9033. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  9034. };
  9035. /** Searches inside a directory for files matching a wildcard pattern.
  9036. Assuming that this file is a directory, this method will search it
  9037. for either files or subdirectories whose names match a filename pattern.
  9038. @param results an array to which File objects will be added for the
  9039. files that the search comes up with
  9040. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9041. return files, directories, or both. If the ignoreHiddenFiles flag
  9042. is also added to this value, hidden files won't be returned
  9043. @param searchRecursively if true, all subdirectories will be recursed into to do
  9044. an exhaustive search
  9045. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9046. @returns the number of results that have been found
  9047. @see getNumberOfChildFiles, DirectoryIterator
  9048. */
  9049. int findChildFiles (Array<File>& results,
  9050. int whatToLookFor,
  9051. bool searchRecursively,
  9052. const String& wildCardPattern = "*") const;
  9053. /** Searches inside a directory and counts how many files match a wildcard pattern.
  9054. Assuming that this file is a directory, this method will search it
  9055. for either files or subdirectories whose names match a filename pattern,
  9056. and will return the number of matches found.
  9057. This isn't a recursive call, and will only search this directory, not
  9058. its children.
  9059. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  9060. count files, directories, or both. If the ignoreHiddenFiles flag
  9061. is also added to this value, hidden files won't be counted
  9062. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  9063. @returns the number of matches found
  9064. @see findChildFiles, DirectoryIterator
  9065. */
  9066. int getNumberOfChildFiles (int whatToLookFor,
  9067. const String& wildCardPattern = "*") const;
  9068. /** Returns true if this file is a directory that contains one or more subdirectories.
  9069. @see isDirectory, findChildFiles
  9070. */
  9071. bool containsSubDirectories() const;
  9072. /** Creates a stream to read from this file.
  9073. @returns a stream that will read from this file (initially positioned at the
  9074. start of the file), or 0 if the file can't be opened for some reason
  9075. @see createOutputStream, loadFileAsData
  9076. */
  9077. FileInputStream* createInputStream() const;
  9078. /** Creates a stream to write to this file.
  9079. If the file exists, the stream that is returned will be positioned ready for
  9080. writing at the end of the file, so you might want to use deleteFile() first
  9081. to write to an empty file.
  9082. @returns a stream that will write to this file (initially positioned at the
  9083. end of the file), or 0 if the file can't be opened for some reason
  9084. @see createInputStream, appendData, appendText
  9085. */
  9086. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  9087. /** Loads a file's contents into memory as a block of binary data.
  9088. Of course, trying to load a very large file into memory will blow up, so
  9089. it's better to check first.
  9090. @param result the data block to which the file's contents should be appended - note
  9091. that if the memory block might already contain some data, you
  9092. might want to clear it first
  9093. @returns true if the file could all be read into memory
  9094. */
  9095. bool loadFileAsData (MemoryBlock& result) const;
  9096. /** Reads a file into memory as a string.
  9097. Attempts to load the entire file as a zero-terminated string.
  9098. This makes use of InputStream::readEntireStreamAsString, which should
  9099. automatically cope with unicode/acsii file formats.
  9100. */
  9101. const String loadFileAsString() const;
  9102. /** Appends a block of binary data to the end of the file.
  9103. This will try to write the given buffer to the end of the file.
  9104. @returns false if it can't write to the file for some reason
  9105. */
  9106. bool appendData (const void* dataToAppend,
  9107. int numberOfBytes) const;
  9108. /** Replaces this file's contents with a given block of data.
  9109. This will delete the file and replace it with the given data.
  9110. A nice feature of this method is that it's safe - instead of deleting
  9111. the file first and then re-writing it, it creates a new temporary file,
  9112. writes the data to that, and then moves the new file to replace the existing
  9113. file. This means that if the power gets pulled out or something crashes,
  9114. you're a lot less likely to end up with a corrupted or unfinished file..
  9115. Returns true if the operation succeeds, or false if it fails.
  9116. @see appendText
  9117. */
  9118. bool replaceWithData (const void* dataToWrite,
  9119. int numberOfBytes) const;
  9120. /** Appends a string to the end of the file.
  9121. This will try to append a text string to the file, as either 16-bit unicode
  9122. or 8-bit characters in the default system encoding.
  9123. It can also write the 'ff fe' unicode header bytes before the text to indicate
  9124. the endianness of the file.
  9125. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  9126. @see replaceWithText
  9127. */
  9128. bool appendText (const String& textToAppend,
  9129. bool asUnicode = false,
  9130. bool writeUnicodeHeaderBytes = false) const;
  9131. /** Replaces this file's contents with a given text string.
  9132. This will delete the file and replace it with the given text.
  9133. A nice feature of this method is that it's safe - instead of deleting
  9134. the file first and then re-writing it, it creates a new temporary file,
  9135. writes the text to that, and then moves the new file to replace the existing
  9136. file. This means that if the power gets pulled out or something crashes,
  9137. you're a lot less likely to end up with an empty file..
  9138. For an explanation of the parameters here, see the appendText() method.
  9139. Returns true if the operation succeeds, or false if it fails.
  9140. @see appendText
  9141. */
  9142. bool replaceWithText (const String& textToWrite,
  9143. bool asUnicode = false,
  9144. bool writeUnicodeHeaderBytes = false) const;
  9145. /** Attempts to scan the contents of this file and compare it to another file, returning
  9146. true if this is possible and they match byte-for-byte.
  9147. */
  9148. bool hasIdenticalContentTo (const File& other) const;
  9149. /** Creates a set of files to represent each file root.
  9150. e.g. on Windows this will create files for "c:\", "d:\" etc according
  9151. to which ones are available. On the Mac/Linux, this will probably
  9152. just add a single entry for "/".
  9153. */
  9154. static void findFileSystemRoots (Array<File>& results);
  9155. /** Finds the name of the drive on which this file lives.
  9156. @returns the volume label of the drive, or an empty string if this isn't possible
  9157. */
  9158. const String getVolumeLabel() const;
  9159. /** Returns the serial number of the volume on which this file lives.
  9160. @returns the serial number, or zero if there's a problem doing this
  9161. */
  9162. int getVolumeSerialNumber() const;
  9163. /** Returns the number of bytes free on the drive that this file lives on.
  9164. @returns the number of bytes free, or 0 if there's a problem finding this out
  9165. @see getVolumeTotalSize
  9166. */
  9167. int64 getBytesFreeOnVolume() const;
  9168. /** Returns the total size of the drive that contains this file.
  9169. @returns the total number of bytes that the volume can hold
  9170. @see getBytesFreeOnVolume
  9171. */
  9172. int64 getVolumeTotalSize() const;
  9173. /** Returns true if this file is on a CD or DVD drive. */
  9174. bool isOnCDRomDrive() const;
  9175. /** Returns true if this file is on a hard disk.
  9176. This will fail if it's a network drive, but will still be true for
  9177. removable hard-disks.
  9178. */
  9179. bool isOnHardDisk() const;
  9180. /** Returns true if this file is on a removable disk drive.
  9181. This might be a usb-drive, a CD-rom, or maybe a network drive.
  9182. */
  9183. bool isOnRemovableDrive() const;
  9184. /** Launches the file as a process.
  9185. - if the file is executable, this will run it.
  9186. - if it's a document of some kind, it will launch the document with its
  9187. default viewer application.
  9188. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  9189. @see revealToUser
  9190. */
  9191. bool startAsProcess (const String& parameters = String::empty) const;
  9192. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  9193. @see startAsProcess
  9194. */
  9195. void revealToUser() const;
  9196. /** A set of types of location that can be passed to the getSpecialLocation() method.
  9197. */
  9198. enum SpecialLocationType
  9199. {
  9200. /** The user's home folder. This is the same as using File ("~"). */
  9201. userHomeDirectory,
  9202. /** The user's default documents folder. On Windows, this might be the user's
  9203. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  9204. doesn't tend to have one of these, so it might just return their home folder.
  9205. */
  9206. userDocumentsDirectory,
  9207. /** The folder that contains the user's desktop objects. */
  9208. userDesktopDirectory,
  9209. /** The folder in which applications store their persistent user-specific settings.
  9210. On Windows, this might be "\Documents and Settings\username\Application Data".
  9211. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  9212. always create your own sub-folder to put them in, to avoid making a mess.
  9213. */
  9214. userApplicationDataDirectory,
  9215. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  9216. of the computer, rather than just the current user.
  9217. On the Mac it'll be "/Library", on Windows, it could be something like
  9218. "\Documents and Settings\All Users\Application Data".
  9219. Depending on the setup, this folder may be read-only.
  9220. */
  9221. commonApplicationDataDirectory,
  9222. /** The folder that should be used for temporary files.
  9223. Always delete them when you're finished, to keep the user's computer tidy!
  9224. */
  9225. tempDirectory,
  9226. /** Returns this application's executable file.
  9227. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  9228. host app.
  9229. On the mac this will return the unix binary, not the package folder - see
  9230. currentApplicationFile for that.
  9231. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  9232. file link, invokedExecutableFile will return the name of the link.
  9233. */
  9234. currentExecutableFile,
  9235. /** Returns this application's location.
  9236. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  9237. host app.
  9238. On the mac this will return the package folder (if it's in one), not the unix binary
  9239. that's inside it - compare with currentExecutableFile.
  9240. */
  9241. currentApplicationFile,
  9242. /** Returns the file that was invoked to launch this executable.
  9243. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  9244. will return the name of the link that was used, whereas currentExecutableFile will return
  9245. the actual location of the target executable.
  9246. */
  9247. invokedExecutableFile,
  9248. /** In a plugin, this will return the path of the host executable. */
  9249. hostApplicationPath,
  9250. /** The directory in which applications normally get installed.
  9251. So on windows, this would be something like "c:\program files", on the
  9252. Mac "/Applications", or "/usr" on linux.
  9253. */
  9254. globalApplicationsDirectory,
  9255. /** The most likely place where a user might store their music files.
  9256. */
  9257. userMusicDirectory,
  9258. /** The most likely place where a user might store their movie files.
  9259. */
  9260. userMoviesDirectory,
  9261. };
  9262. /** Finds the location of a special type of file or directory, such as a home folder or
  9263. documents folder.
  9264. @see SpecialLocationType
  9265. */
  9266. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  9267. /** Returns a temporary file in the system's temp directory.
  9268. This will try to return the name of a non-existent temp file.
  9269. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  9270. */
  9271. static const File createTempFile (const String& fileNameEnding);
  9272. /** Returns the current working directory.
  9273. @see setAsCurrentWorkingDirectory
  9274. */
  9275. static const File getCurrentWorkingDirectory();
  9276. /** Sets the current working directory to be this file.
  9277. For this to work the file must point to a valid directory.
  9278. @returns true if the current directory has been changed.
  9279. @see getCurrentWorkingDirectory
  9280. */
  9281. bool setAsCurrentWorkingDirectory() const;
  9282. /** The system-specific file separator character.
  9283. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  9284. */
  9285. static const juce_wchar separator;
  9286. /** The system-specific file separator character, as a string.
  9287. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  9288. */
  9289. static const String separatorString;
  9290. /** Removes illegal characters from a filename.
  9291. This will return a copy of the given string after removing characters
  9292. that are not allowed in a legal filename, and possibly shortening the
  9293. string if it's too long.
  9294. Because this will remove slashes, don't use it on an absolute pathname.
  9295. @see createLegalPathName
  9296. */
  9297. static const String createLegalFileName (const String& fileNameToFix);
  9298. /** Removes illegal characters from a pathname.
  9299. Similar to createLegalFileName(), but this won't remove slashes, so can
  9300. be used on a complete pathname.
  9301. @see createLegalFileName
  9302. */
  9303. static const String createLegalPathName (const String& pathNameToFix);
  9304. /** Indicates whether filenames are case-sensitive on the current operating system.
  9305. */
  9306. static bool areFileNamesCaseSensitive();
  9307. /** Returns true if the string seems to be a fully-specified absolute path.
  9308. */
  9309. static bool isAbsolutePath (const String& path);
  9310. /** Creates a file that simply contains this string, without doing the sanity-checking
  9311. that the normal constructors do.
  9312. Best to avoid this unless you really know what you're doing.
  9313. */
  9314. static const File createFileWithoutCheckingPath (const String& path);
  9315. /** Adds a separator character to the end of a path if it doesn't already have one. */
  9316. static const String addTrailingSeparator (const String& path);
  9317. private:
  9318. String fullPath;
  9319. // internal way of contructing a file without checking the path
  9320. friend class DirectoryIterator;
  9321. File (const String&, int);
  9322. const String getPathUpToLastSlash() const;
  9323. void createDirectoryInternal (const String& fileName) const;
  9324. bool copyInternal (const File& dest) const;
  9325. bool moveInternal (const File& dest) const;
  9326. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  9327. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  9328. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  9329. static const String parseAbsolutePath (const String& path);
  9330. JUCE_LEAK_DETECTOR (File);
  9331. };
  9332. #endif // __JUCE_FILE_JUCEHEADER__
  9333. /*** End of inlined file: juce_File.h ***/
  9334. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  9335. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  9336. will be the name of a pointer to each child element.
  9337. E.g. @code
  9338. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  9339. forEachXmlChildElement (*myParentXml, child)
  9340. {
  9341. if (child->hasTagName ("FOO"))
  9342. doSomethingWithXmlElement (child);
  9343. }
  9344. @endcode
  9345. @see forEachXmlChildElementWithTagName
  9346. */
  9347. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  9348. \
  9349. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  9350. childElementVariableName != 0; \
  9351. childElementVariableName = childElementVariableName->getNextElement())
  9352. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  9353. which have a specified tag.
  9354. This does the same job as the forEachXmlChildElement macro, but only for those
  9355. elements that have a particular tag name.
  9356. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  9357. will be the name of a pointer to each child element. The requiredTagName is the
  9358. tag name to match.
  9359. E.g. @code
  9360. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  9361. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  9362. {
  9363. // the child object is now guaranteed to be a <MYTAG> element..
  9364. doSomethingWithMYTAGElement (child);
  9365. }
  9366. @endcode
  9367. @see forEachXmlChildElement
  9368. */
  9369. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  9370. \
  9371. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  9372. childElementVariableName != 0; \
  9373. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  9374. /** Used to build a tree of elements representing an XML document.
  9375. An XML document can be parsed into a tree of XmlElements, each of which
  9376. represents an XML tag structure, and which may itself contain other
  9377. nested elements.
  9378. An XmlElement can also be converted back into a text document, and has
  9379. lots of useful methods for manipulating its attributes and sub-elements,
  9380. so XmlElements can actually be used as a handy general-purpose data
  9381. structure.
  9382. Here's an example of parsing some elements: @code
  9383. // check we're looking at the right kind of document..
  9384. if (myElement->hasTagName ("ANIMALS"))
  9385. {
  9386. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  9387. forEachXmlChildElement (*myElement, e)
  9388. {
  9389. if (e->hasTagName ("GIRAFFE"))
  9390. {
  9391. // found a giraffe, so use some of its attributes..
  9392. String giraffeName = e->getStringAttribute ("name");
  9393. int giraffeAge = e->getIntAttribute ("age");
  9394. bool isFriendly = e->getBoolAttribute ("friendly");
  9395. }
  9396. }
  9397. }
  9398. @endcode
  9399. And here's an example of how to create an XML document from scratch: @code
  9400. // create an outer node called "ANIMALS"
  9401. XmlElement animalsList ("ANIMALS");
  9402. for (int i = 0; i < numAnimals; ++i)
  9403. {
  9404. // create an inner element..
  9405. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  9406. giraffe->setAttribute ("name", "nigel");
  9407. giraffe->setAttribute ("age", 10);
  9408. giraffe->setAttribute ("friendly", true);
  9409. // ..and add our new element to the parent node
  9410. animalsList.addChildElement (giraffe);
  9411. }
  9412. // now we can turn the whole thing into a text document..
  9413. String myXmlDoc = animalsList.createDocument (String::empty);
  9414. @endcode
  9415. @see XmlDocument
  9416. */
  9417. class JUCE_API XmlElement
  9418. {
  9419. public:
  9420. /** Creates an XmlElement with this tag name. */
  9421. explicit XmlElement (const String& tagName) throw();
  9422. /** Creates a (deep) copy of another element. */
  9423. XmlElement (const XmlElement& other);
  9424. /** Creates a (deep) copy of another element. */
  9425. XmlElement& operator= (const XmlElement& other);
  9426. /** Deleting an XmlElement will also delete all its child elements. */
  9427. ~XmlElement() throw();
  9428. /** Compares two XmlElements to see if they contain the same text and attiributes.
  9429. The elements are only considered equivalent if they contain the same attiributes
  9430. with the same values, and have the same sub-nodes.
  9431. @param other the other element to compare to
  9432. @param ignoreOrderOfAttributes if true, this means that two elements with the
  9433. same attributes in a different order will be
  9434. considered the same; if false, the attributes must
  9435. be in the same order as well
  9436. */
  9437. bool isEquivalentTo (const XmlElement* other,
  9438. bool ignoreOrderOfAttributes) const throw();
  9439. /** Returns an XML text document that represents this element.
  9440. The string returned can be parsed to recreate the same XmlElement that
  9441. was used to create it.
  9442. @param dtdToUse the DTD to add to the document
  9443. @param allOnOneLine if true, this means that the document will not contain any
  9444. linefeeds, so it'll be smaller but not very easy to read.
  9445. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  9446. document
  9447. @param encodingType the character encoding format string to put into the xml
  9448. header
  9449. @param lineWrapLength the line length that will be used before items get placed on
  9450. a new line. This isn't an absolute maximum length, it just
  9451. determines how lists of attributes get broken up
  9452. @see writeToStream, writeToFile
  9453. */
  9454. const String createDocument (const String& dtdToUse,
  9455. bool allOnOneLine = false,
  9456. bool includeXmlHeader = true,
  9457. const String& encodingType = "UTF-8",
  9458. int lineWrapLength = 60) const;
  9459. /** Writes the document to a stream as UTF-8.
  9460. @param output the stream to write to
  9461. @param dtdToUse the DTD to add to the document
  9462. @param allOnOneLine if true, this means that the document will not contain any
  9463. linefeeds, so it'll be smaller but not very easy to read.
  9464. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  9465. document
  9466. @param encodingType the character encoding format string to put into the xml
  9467. header
  9468. @param lineWrapLength the line length that will be used before items get placed on
  9469. a new line. This isn't an absolute maximum length, it just
  9470. determines how lists of attributes get broken up
  9471. @see writeToFile, createDocument
  9472. */
  9473. void writeToStream (OutputStream& output,
  9474. const String& dtdToUse,
  9475. bool allOnOneLine = false,
  9476. bool includeXmlHeader = true,
  9477. const String& encodingType = "UTF-8",
  9478. int lineWrapLength = 60) const;
  9479. /** Writes the element to a file as an XML document.
  9480. To improve safety in case something goes wrong while writing the file, this
  9481. will actually write the document to a new temporary file in the same
  9482. directory as the destination file, and if this succeeds, it will rename this
  9483. new file as the destination file (overwriting any existing file that was there).
  9484. @param destinationFile the file to write to. If this already exists, it will be
  9485. overwritten.
  9486. @param dtdToUse the DTD to add to the document
  9487. @param encodingType the character encoding format string to put into the xml
  9488. header
  9489. @param lineWrapLength the line length that will be used before items get placed on
  9490. a new line. This isn't an absolute maximum length, it just
  9491. determines how lists of attributes get broken up
  9492. @returns true if the file is written successfully; false if something goes wrong
  9493. in the process
  9494. @see createDocument
  9495. */
  9496. bool writeToFile (const File& destinationFile,
  9497. const String& dtdToUse,
  9498. const String& encodingType = "UTF-8",
  9499. int lineWrapLength = 60) const;
  9500. /** Returns this element's tag type name.
  9501. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  9502. "MOOSE".
  9503. @see hasTagName
  9504. */
  9505. inline const String& getTagName() const throw() { return tagName; }
  9506. /** Tests whether this element has a particular tag name.
  9507. @param possibleTagName the tag name you're comparing it with
  9508. @see getTagName
  9509. */
  9510. bool hasTagName (const String& possibleTagName) const throw();
  9511. /** Returns the number of XML attributes this element contains.
  9512. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  9513. return 2.
  9514. */
  9515. int getNumAttributes() const throw();
  9516. /** Returns the name of one of the elements attributes.
  9517. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  9518. getAttributeName(1) would return "antlers".
  9519. @see getAttributeValue, getStringAttribute
  9520. */
  9521. const String& getAttributeName (int attributeIndex) const throw();
  9522. /** Returns the value of one of the elements attributes.
  9523. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  9524. getAttributeName(1) would return "2".
  9525. @see getAttributeName, getStringAttribute
  9526. */
  9527. const String& getAttributeValue (int attributeIndex) const throw();
  9528. // Attribute-handling methods..
  9529. /** Checks whether the element contains an attribute with a certain name. */
  9530. bool hasAttribute (const String& attributeName) const throw();
  9531. /** Returns the value of a named attribute.
  9532. @param attributeName the name of the attribute to look up
  9533. */
  9534. const String& getStringAttribute (const String& attributeName) const throw();
  9535. /** Returns the value of a named attribute.
  9536. @param attributeName the name of the attribute to look up
  9537. @param defaultReturnValue a value to return if the element doesn't have an attribute
  9538. with this name
  9539. */
  9540. const String getStringAttribute (const String& attributeName,
  9541. const String& defaultReturnValue) const;
  9542. /** Compares the value of a named attribute with a value passed-in.
  9543. @param attributeName the name of the attribute to look up
  9544. @param stringToCompareAgainst the value to compare it with
  9545. @param ignoreCase whether the comparison should be case-insensitive
  9546. @returns true if the value of the attribute is the same as the string passed-in;
  9547. false if it's different (or if no such attribute exists)
  9548. */
  9549. bool compareAttribute (const String& attributeName,
  9550. const String& stringToCompareAgainst,
  9551. bool ignoreCase = false) const throw();
  9552. /** Returns the value of a named attribute as an integer.
  9553. This will try to find the attribute and convert it to an integer (using
  9554. the String::getIntValue() method).
  9555. @param attributeName the name of the attribute to look up
  9556. @param defaultReturnValue a value to return if the element doesn't have an attribute
  9557. with this name
  9558. @see setAttribute
  9559. */
  9560. int getIntAttribute (const String& attributeName,
  9561. int defaultReturnValue = 0) const;
  9562. /** Returns the value of a named attribute as floating-point.
  9563. This will try to find the attribute and convert it to an integer (using
  9564. the String::getDoubleValue() method).
  9565. @param attributeName the name of the attribute to look up
  9566. @param defaultReturnValue a value to return if the element doesn't have an attribute
  9567. with this name
  9568. @see setAttribute
  9569. */
  9570. double getDoubleAttribute (const String& attributeName,
  9571. double defaultReturnValue = 0.0) const;
  9572. /** Returns the value of a named attribute as a boolean.
  9573. This will try to find the attribute and interpret it as a boolean. To do this,
  9574. it'll return true if the value is "1", "true", "y", etc, or false for other
  9575. values.
  9576. @param attributeName the name of the attribute to look up
  9577. @param defaultReturnValue a value to return if the element doesn't have an attribute
  9578. with this name
  9579. */
  9580. bool getBoolAttribute (const String& attributeName,
  9581. bool defaultReturnValue = false) const;
  9582. /** Adds a named attribute to the element.
  9583. If the element already contains an attribute with this name, it's value will
  9584. be updated to the new value. If there's no such attribute yet, a new one will
  9585. be added.
  9586. Note that there are other setAttribute() methods that take integers,
  9587. doubles, etc. to make it easy to store numbers.
  9588. @param attributeName the name of the attribute to set
  9589. @param newValue the value to set it to
  9590. @see removeAttribute
  9591. */
  9592. void setAttribute (const String& attributeName,
  9593. const String& newValue);
  9594. /** Adds a named attribute to the element, setting it to an integer value.
  9595. If the element already contains an attribute with this name, it's value will
  9596. be updated to the new value. If there's no such attribute yet, a new one will
  9597. be added.
  9598. Note that there are other setAttribute() methods that take integers,
  9599. doubles, etc. to make it easy to store numbers.
  9600. @param attributeName the name of the attribute to set
  9601. @param newValue the value to set it to
  9602. */
  9603. void setAttribute (const String& attributeName,
  9604. int newValue);
  9605. /** Adds a named attribute to the element, setting it to a floating-point value.
  9606. If the element already contains an attribute with this name, it's value will
  9607. be updated to the new value. If there's no such attribute yet, a new one will
  9608. be added.
  9609. Note that there are other setAttribute() methods that take integers,
  9610. doubles, etc. to make it easy to store numbers.
  9611. @param attributeName the name of the attribute to set
  9612. @param newValue the value to set it to
  9613. */
  9614. void setAttribute (const String& attributeName,
  9615. double newValue);
  9616. /** Removes a named attribute from the element.
  9617. @param attributeName the name of the attribute to remove
  9618. @see removeAllAttributes
  9619. */
  9620. void removeAttribute (const String& attributeName) throw();
  9621. /** Removes all attributes from this element.
  9622. */
  9623. void removeAllAttributes() throw();
  9624. // Child element methods..
  9625. /** Returns the first of this element's sub-elements.
  9626. see getNextElement() for an example of how to iterate the sub-elements.
  9627. @see forEachXmlChildElement
  9628. */
  9629. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  9630. /** Returns the next of this element's siblings.
  9631. This can be used for iterating an element's sub-elements, e.g.
  9632. @code
  9633. XmlElement* child = myXmlDocument->getFirstChildElement();
  9634. while (child != 0)
  9635. {
  9636. ...do stuff with this child..
  9637. child = child->getNextElement();
  9638. }
  9639. @endcode
  9640. Note that when iterating the child elements, some of them might be
  9641. text elements as well as XML tags - use isTextElement() to work this
  9642. out.
  9643. Also, it's much easier and neater to use this method indirectly via the
  9644. forEachXmlChildElement macro.
  9645. @returns the sibling element that follows this one, or zero if this is the last
  9646. element in its parent
  9647. @see getNextElement, isTextElement, forEachXmlChildElement
  9648. */
  9649. inline XmlElement* getNextElement() const throw() { return nextListItem; }
  9650. /** Returns the next of this element's siblings which has the specified tag
  9651. name.
  9652. This is like getNextElement(), but will scan through the list until it
  9653. finds an element with the given tag name.
  9654. @see getNextElement, forEachXmlChildElementWithTagName
  9655. */
  9656. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  9657. /** Returns the number of sub-elements in this element.
  9658. @see getChildElement
  9659. */
  9660. int getNumChildElements() const throw();
  9661. /** Returns the sub-element at a certain index.
  9662. It's not very efficient to iterate the sub-elements by index - see
  9663. getNextElement() for an example of how best to iterate.
  9664. @returns the n'th child of this element, or 0 if the index is out-of-range
  9665. @see getNextElement, isTextElement, getChildByName
  9666. */
  9667. XmlElement* getChildElement (int index) const throw();
  9668. /** Returns the first sub-element with a given tag-name.
  9669. @param tagNameToLookFor the tag name of the element you want to find
  9670. @returns the first element with this tag name, or 0 if none is found
  9671. @see getNextElement, isTextElement, getChildElement
  9672. */
  9673. XmlElement* getChildByName (const String& tagNameToLookFor) const throw();
  9674. /** Appends an element to this element's list of children.
  9675. Child elements are deleted automatically when their parent is deleted, so
  9676. make sure the object that you pass in will not be deleted by anything else,
  9677. and make sure it's not already the child of another element.
  9678. @see getFirstChildElement, getNextElement, getNumChildElements,
  9679. getChildElement, removeChildElement
  9680. */
  9681. void addChildElement (XmlElement* newChildElement) throw();
  9682. /** Inserts an element into this element's list of children.
  9683. Child elements are deleted automatically when their parent is deleted, so
  9684. make sure the object that you pass in will not be deleted by anything else,
  9685. and make sure it's not already the child of another element.
  9686. @param newChildNode the element to add
  9687. @param indexToInsertAt the index at which to insert the new element - if this is
  9688. below zero, it will be added to the end of the list
  9689. @see addChildElement, insertChildElement
  9690. */
  9691. void insertChildElement (XmlElement* newChildNode,
  9692. int indexToInsertAt) throw();
  9693. /** Creates a new element with the given name and returns it, after adding it
  9694. as a child element.
  9695. This is a handy method that means that instead of writing this:
  9696. @code
  9697. XmlElement* newElement = new XmlElement ("foobar");
  9698. myParentElement->addChildElement (newElement);
  9699. @endcode
  9700. ..you could just write this:
  9701. @code
  9702. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  9703. @endcode
  9704. */
  9705. XmlElement* createNewChildElement (const String& tagName);
  9706. /** Replaces one of this element's children with another node.
  9707. If the current element passed-in isn't actually a child of this element,
  9708. this will return false and the new one won't be added. Otherwise, the
  9709. existing element will be deleted, replaced with the new one, and it
  9710. will return true.
  9711. */
  9712. bool replaceChildElement (XmlElement* currentChildElement,
  9713. XmlElement* newChildNode) throw();
  9714. /** Removes a child element.
  9715. @param childToRemove the child to look for and remove
  9716. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  9717. just remove it
  9718. */
  9719. void removeChildElement (XmlElement* childToRemove,
  9720. bool shouldDeleteTheChild) throw();
  9721. /** Deletes all the child elements in the element.
  9722. @see removeChildElement, deleteAllChildElementsWithTagName
  9723. */
  9724. void deleteAllChildElements() throw();
  9725. /** Deletes all the child elements with a given tag name.
  9726. @see removeChildElement
  9727. */
  9728. void deleteAllChildElementsWithTagName (const String& tagName) throw();
  9729. /** Returns true if the given element is a child of this one. */
  9730. bool containsChildElement (const XmlElement* possibleChild) const throw();
  9731. /** Recursively searches all sub-elements to find one that contains the specified
  9732. child element.
  9733. */
  9734. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) throw();
  9735. /** Sorts the child elements using a comparator.
  9736. This will use a comparator object to sort the elements into order. The object
  9737. passed must have a method of the form:
  9738. @code
  9739. int compareElements (const XmlElement* first, const XmlElement* second);
  9740. @endcode
  9741. ..and this method must return:
  9742. - a value of < 0 if the first comes before the second
  9743. - a value of 0 if the two objects are equivalent
  9744. - a value of > 0 if the second comes before the first
  9745. To improve performance, the compareElements() method can be declared as static or const.
  9746. @param comparator the comparator to use for comparing elements.
  9747. @param retainOrderOfEquivalentItems if this is true, then items which the comparator
  9748. says are equivalent will be kept in the order in which they
  9749. currently appear in the array. This is slower to perform, but
  9750. may be important in some cases. If it's false, a faster algorithm
  9751. is used, but equivalent elements may be rearranged.
  9752. */
  9753. template <class ElementComparator>
  9754. void sortChildElements (ElementComparator& comparator,
  9755. bool retainOrderOfEquivalentItems = false)
  9756. {
  9757. const int num = getNumChildElements();
  9758. if (num > 1)
  9759. {
  9760. HeapBlock <XmlElement*> elems (num);
  9761. getChildElementsAsArray (elems);
  9762. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  9763. reorderChildElements (elems, num);
  9764. }
  9765. }
  9766. /** Returns true if this element is a section of text.
  9767. Elements can either be an XML tag element or a secton of text, so this
  9768. is used to find out what kind of element this one is.
  9769. @see getAllText, addTextElement, deleteAllTextElements
  9770. */
  9771. bool isTextElement() const throw();
  9772. /** Returns the text for a text element.
  9773. Note that if you have an element like this:
  9774. @code<xyz>hello</xyz>@endcode
  9775. then calling getText on the "xyz" element won't return "hello", because that is
  9776. actually stored in a special text sub-element inside the xyz element. To get the
  9777. "hello" string, you could either call getText on the (unnamed) sub-element, or
  9778. use getAllSubText() to do this automatically.
  9779. Note that leading and trailing whitespace will be included in the string - to remove
  9780. if, just call String::trim() on the result.
  9781. @see isTextElement, getAllSubText, getChildElementAllSubText
  9782. */
  9783. const String& getText() const throw();
  9784. /** Sets the text in a text element.
  9785. Note that this is only a valid call if this element is a text element. If it's
  9786. not, then no action will be performed.
  9787. */
  9788. void setText (const String& newText);
  9789. /** Returns all the text from this element's child nodes.
  9790. This iterates all the child elements and when it finds text elements,
  9791. it concatenates their text into a big string which it returns.
  9792. E.g. @code<xyz>hello <x>there</x> world</xyz>@endcode
  9793. if you called getAllSubText on the "xyz" element, it'd return "hello there world".
  9794. Note that leading and trailing whitespace will be included in the string - to remove
  9795. if, just call String::trim() on the result.
  9796. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  9797. */
  9798. const String getAllSubText() const;
  9799. /** Returns all the sub-text of a named child element.
  9800. If there is a child element with the given tag name, this will return
  9801. all of its sub-text (by calling getAllSubText() on it). If there is
  9802. no such child element, this will return the default string passed-in.
  9803. @see getAllSubText
  9804. */
  9805. const String getChildElementAllSubText (const String& childTagName,
  9806. const String& defaultReturnValue) const;
  9807. /** Appends a section of text to this element.
  9808. @see isTextElement, getText, getAllSubText
  9809. */
  9810. void addTextElement (const String& text);
  9811. /** Removes all the text elements from this element.
  9812. @see isTextElement, getText, getAllSubText, addTextElement
  9813. */
  9814. void deleteAllTextElements() throw();
  9815. /** Creates a text element that can be added to a parent element.
  9816. */
  9817. static XmlElement* createTextElement (const String& text);
  9818. private:
  9819. struct XmlAttributeNode
  9820. {
  9821. XmlAttributeNode (const XmlAttributeNode& other) throw();
  9822. XmlAttributeNode (const String& name, const String& value) throw();
  9823. LinkedListPointer<XmlAttributeNode> nextListItem;
  9824. String name, value;
  9825. bool hasName (const String& name) const throw();
  9826. private:
  9827. XmlAttributeNode& operator= (const XmlAttributeNode&);
  9828. };
  9829. friend class XmlDocument;
  9830. friend class LinkedListPointer<XmlAttributeNode>;
  9831. friend class LinkedListPointer <XmlElement>;
  9832. friend class LinkedListPointer <XmlElement>::Appender;
  9833. LinkedListPointer <XmlElement> nextListItem;
  9834. LinkedListPointer <XmlElement> firstChildElement;
  9835. LinkedListPointer <XmlAttributeNode> attributes;
  9836. String tagName;
  9837. XmlElement (int) throw();
  9838. void copyChildrenAndAttributesFrom (const XmlElement& other);
  9839. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  9840. void getChildElementsAsArray (XmlElement**) const throw();
  9841. void reorderChildElements (XmlElement**, int) throw();
  9842. JUCE_LEAK_DETECTOR (XmlElement);
  9843. };
  9844. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  9845. /*** End of inlined file: juce_XmlElement.h ***/
  9846. /**
  9847. A set of named property values, which can be strings, integers, floating point, etc.
  9848. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  9849. to load and save types other than strings.
  9850. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  9851. messages and saves/loads the list from a file.
  9852. */
  9853. class JUCE_API PropertySet
  9854. {
  9855. public:
  9856. /** Creates an empty PropertySet.
  9857. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  9858. case-insensitive way
  9859. */
  9860. PropertySet (bool ignoreCaseOfKeyNames = false);
  9861. /** Creates a copy of another PropertySet.
  9862. */
  9863. PropertySet (const PropertySet& other);
  9864. /** Copies another PropertySet over this one.
  9865. */
  9866. PropertySet& operator= (const PropertySet& other);
  9867. /** Destructor. */
  9868. virtual ~PropertySet();
  9869. /** Returns one of the properties as a string.
  9870. If the value isn't found in this set, then this will look for it in a fallback
  9871. property set (if you've specified one with the setFallbackPropertySet() method),
  9872. and if it can't find one there, it'll return the default value passed-in.
  9873. @param keyName the name of the property to retrieve
  9874. @param defaultReturnValue a value to return if the named property doesn't actually exist
  9875. */
  9876. const String getValue (const String& keyName,
  9877. const String& defaultReturnValue = String::empty) const throw();
  9878. /** Returns one of the properties as an integer.
  9879. If the value isn't found in this set, then this will look for it in a fallback
  9880. property set (if you've specified one with the setFallbackPropertySet() method),
  9881. and if it can't find one there, it'll return the default value passed-in.
  9882. @param keyName the name of the property to retrieve
  9883. @param defaultReturnValue a value to return if the named property doesn't actually exist
  9884. */
  9885. int getIntValue (const String& keyName,
  9886. const int defaultReturnValue = 0) const throw();
  9887. /** Returns one of the properties as an double.
  9888. If the value isn't found in this set, then this will look for it in a fallback
  9889. property set (if you've specified one with the setFallbackPropertySet() method),
  9890. and if it can't find one there, it'll return the default value passed-in.
  9891. @param keyName the name of the property to retrieve
  9892. @param defaultReturnValue a value to return if the named property doesn't actually exist
  9893. */
  9894. double getDoubleValue (const String& keyName,
  9895. const double defaultReturnValue = 0.0) const throw();
  9896. /** Returns one of the properties as an boolean.
  9897. The result will be true if the string found for this key name can be parsed as a non-zero
  9898. integer.
  9899. If the value isn't found in this set, then this will look for it in a fallback
  9900. property set (if you've specified one with the setFallbackPropertySet() method),
  9901. and if it can't find one there, it'll return the default value passed-in.
  9902. @param keyName the name of the property to retrieve
  9903. @param defaultReturnValue a value to return if the named property doesn't actually exist
  9904. */
  9905. bool getBoolValue (const String& keyName,
  9906. const bool defaultReturnValue = false) const throw();
  9907. /** Returns one of the properties as an XML element.
  9908. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  9909. key isn't found, or if the entry contains an string that isn't valid XML.
  9910. If the value isn't found in this set, then this will look for it in a fallback
  9911. property set (if you've specified one with the setFallbackPropertySet() method),
  9912. and if it can't find one there, it'll return the default value passed-in.
  9913. @param keyName the name of the property to retrieve
  9914. */
  9915. XmlElement* getXmlValue (const String& keyName) const;
  9916. /** Sets a named property.
  9917. @param keyName the name of the property to set. (This mustn't be an empty string)
  9918. @param value the new value to set it to
  9919. */
  9920. void setValue (const String& keyName, const var& value);
  9921. /** Sets a named property to an XML element.
  9922. @param keyName the name of the property to set. (This mustn't be an empty string)
  9923. @param xml the new element to set it to. If this is zero, the value will be set to
  9924. an empty string
  9925. @see getXmlValue
  9926. */
  9927. void setValue (const String& keyName, const XmlElement* xml);
  9928. /** Deletes a property.
  9929. @param keyName the name of the property to delete. (This mustn't be an empty string)
  9930. */
  9931. void removeValue (const String& keyName);
  9932. /** Returns true if the properies include the given key. */
  9933. bool containsKey (const String& keyName) const throw();
  9934. /** Removes all values. */
  9935. void clear();
  9936. /** Returns the keys/value pair array containing all the properties. */
  9937. StringPairArray& getAllProperties() throw() { return properties; }
  9938. /** Returns the lock used when reading or writing to this set */
  9939. const CriticalSection& getLock() const throw() { return lock; }
  9940. /** Returns an XML element which encapsulates all the items in this property set.
  9941. The string parameter is the tag name that should be used for the node.
  9942. @see restoreFromXml
  9943. */
  9944. XmlElement* createXml (const String& nodeName) const;
  9945. /** Reloads a set of properties that were previously stored as XML.
  9946. The node passed in must have been created by the createXml() method.
  9947. @see createXml
  9948. */
  9949. void restoreFromXml (const XmlElement& xml);
  9950. /** Sets up a second PopertySet that will be used to look up any values that aren't
  9951. set in this one.
  9952. If you set this up to be a pointer to a second property set, then whenever one
  9953. of the getValue() methods fails to find an entry in this set, it will look up that
  9954. value in the fallback set, and if it finds it, it will return that.
  9955. Make sure that you don't delete the fallback set while it's still being used by
  9956. another set! To remove the fallback set, just call this method with a null pointer.
  9957. @see getFallbackPropertySet
  9958. */
  9959. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  9960. /** Returns the fallback property set.
  9961. @see setFallbackPropertySet
  9962. */
  9963. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  9964. protected:
  9965. /** Subclasses can override this to be told when one of the properies has been changed. */
  9966. virtual void propertyChanged();
  9967. private:
  9968. StringPairArray properties;
  9969. PropertySet* fallbackProperties;
  9970. CriticalSection lock;
  9971. bool ignoreCaseOfKeys;
  9972. JUCE_LEAK_DETECTOR (PropertySet);
  9973. };
  9974. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  9975. /*** End of inlined file: juce_PropertySet.h ***/
  9976. #endif
  9977. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  9978. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  9979. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  9980. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  9981. /**
  9982. Holds a list of objects derived from ReferenceCountedObject.
  9983. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  9984. and takes care of incrementing and decrementing their ref counts when they
  9985. are added and removed from the array.
  9986. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  9987. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  9988. @see Array, OwnedArray, StringArray
  9989. */
  9990. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  9991. class ReferenceCountedArray
  9992. {
  9993. public:
  9994. typedef ReferenceCountedObjectPtr<ObjectClass> ObjectClassPtr;
  9995. /** Creates an empty array.
  9996. @see ReferenceCountedObject, Array, OwnedArray
  9997. */
  9998. ReferenceCountedArray() throw()
  9999. : numUsed (0)
  10000. {
  10001. }
  10002. /** Creates a copy of another array */
  10003. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  10004. {
  10005. const ScopedLockType lock (other.getLock());
  10006. numUsed = other.numUsed;
  10007. data.setAllocatedSize (numUsed);
  10008. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  10009. for (int i = numUsed; --i >= 0;)
  10010. if (data.elements[i] != 0)
  10011. data.elements[i]->incReferenceCount();
  10012. }
  10013. /** Copies another array into this one.
  10014. Any existing objects in this array will first be released.
  10015. */
  10016. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  10017. {
  10018. if (this != &other)
  10019. {
  10020. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  10021. swapWithArray (otherCopy);
  10022. }
  10023. return *this;
  10024. }
  10025. /** Destructor.
  10026. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  10027. */
  10028. ~ReferenceCountedArray()
  10029. {
  10030. clear();
  10031. }
  10032. /** Removes all objects from the array.
  10033. Any objects in the array that are not referenced from elsewhere will be deleted.
  10034. */
  10035. void clear()
  10036. {
  10037. const ScopedLockType lock (getLock());
  10038. while (numUsed > 0)
  10039. if (data.elements [--numUsed] != 0)
  10040. data.elements [numUsed]->decReferenceCount();
  10041. jassert (numUsed == 0);
  10042. data.setAllocatedSize (0);
  10043. }
  10044. /** Returns the current number of objects in the array. */
  10045. inline int size() const throw()
  10046. {
  10047. return numUsed;
  10048. }
  10049. /** Returns a pointer to the object at this index in the array.
  10050. If the index is out-of-range, this will return a null pointer, (and
  10051. it could be null anyway, because it's ok for the array to hold null
  10052. pointers as well as objects).
  10053. @see getUnchecked
  10054. */
  10055. inline const ObjectClassPtr operator[] (const int index) const throw()
  10056. {
  10057. const ScopedLockType lock (getLock());
  10058. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  10059. : static_cast <ObjectClass*> (0);
  10060. }
  10061. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  10062. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  10063. it can be used when you're sure the index if always going to be legal.
  10064. */
  10065. inline const ObjectClassPtr getUnchecked (const int index) const throw()
  10066. {
  10067. const ScopedLockType lock (getLock());
  10068. jassert (isPositiveAndBelow (index, numUsed));
  10069. return data.elements [index];
  10070. }
  10071. /** Returns a pointer to the first object in the array.
  10072. This will return a null pointer if the array's empty.
  10073. @see getLast
  10074. */
  10075. inline const ObjectClassPtr getFirst() const throw()
  10076. {
  10077. const ScopedLockType lock (getLock());
  10078. return numUsed > 0 ? data.elements [0]
  10079. : static_cast <ObjectClass*> (0);
  10080. }
  10081. /** Returns a pointer to the last object in the array.
  10082. This will return a null pointer if the array's empty.
  10083. @see getFirst
  10084. */
  10085. inline const ObjectClassPtr getLast() const throw()
  10086. {
  10087. const ScopedLockType lock (getLock());
  10088. return numUsed > 0 ? data.elements [numUsed - 1]
  10089. : static_cast <ObjectClass*> (0);
  10090. }
  10091. /** Finds the index of the first occurrence of an object in the array.
  10092. @param objectToLookFor the object to look for
  10093. @returns the index at which the object was found, or -1 if it's not found
  10094. */
  10095. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  10096. {
  10097. const ScopedLockType lock (getLock());
  10098. ObjectClass** e = data.elements.getData();
  10099. ObjectClass** const end = e + numUsed;
  10100. while (e != end)
  10101. {
  10102. if (objectToLookFor == *e)
  10103. return static_cast <int> (e - data.elements.getData());
  10104. ++e;
  10105. }
  10106. return -1;
  10107. }
  10108. /** Returns true if the array contains a specified object.
  10109. @param objectToLookFor the object to look for
  10110. @returns true if the object is in the array
  10111. */
  10112. bool contains (const ObjectClass* const objectToLookFor) const throw()
  10113. {
  10114. const ScopedLockType lock (getLock());
  10115. ObjectClass** e = data.elements.getData();
  10116. ObjectClass** const end = e + numUsed;
  10117. while (e != end)
  10118. {
  10119. if (objectToLookFor == *e)
  10120. return true;
  10121. ++e;
  10122. }
  10123. return false;
  10124. }
  10125. /** Appends a new object to the end of the array.
  10126. This will increase the new object's reference count.
  10127. @param newObject the new object to add to the array
  10128. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  10129. */
  10130. void add (ObjectClass* const newObject) throw()
  10131. {
  10132. const ScopedLockType lock (getLock());
  10133. data.ensureAllocatedSize (numUsed + 1);
  10134. data.elements [numUsed++] = newObject;
  10135. if (newObject != 0)
  10136. newObject->incReferenceCount();
  10137. }
  10138. /** Inserts a new object into the array at the given index.
  10139. If the index is less than 0 or greater than the size of the array, the
  10140. element will be added to the end of the array.
  10141. Otherwise, it will be inserted into the array, moving all the later elements
  10142. along to make room.
  10143. This will increase the new object's reference count.
  10144. @param indexToInsertAt the index at which the new element should be inserted
  10145. @param newObject the new object to add to the array
  10146. @see add, addSorted, addIfNotAlreadyThere, set
  10147. */
  10148. void insert (int indexToInsertAt,
  10149. ObjectClass* const newObject) throw()
  10150. {
  10151. if (indexToInsertAt >= 0)
  10152. {
  10153. const ScopedLockType lock (getLock());
  10154. if (indexToInsertAt > numUsed)
  10155. indexToInsertAt = numUsed;
  10156. data.ensureAllocatedSize (numUsed + 1);
  10157. ObjectClass** const e = data.elements + indexToInsertAt;
  10158. const int numToMove = numUsed - indexToInsertAt;
  10159. if (numToMove > 0)
  10160. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  10161. *e = newObject;
  10162. if (newObject != 0)
  10163. newObject->incReferenceCount();
  10164. ++numUsed;
  10165. }
  10166. else
  10167. {
  10168. add (newObject);
  10169. }
  10170. }
  10171. /** Appends a new object at the end of the array as long as the array doesn't
  10172. already contain it.
  10173. If the array already contains a matching object, nothing will be done.
  10174. @param newObject the new object to add to the array
  10175. */
  10176. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  10177. {
  10178. const ScopedLockType lock (getLock());
  10179. if (! contains (newObject))
  10180. add (newObject);
  10181. }
  10182. /** Replaces an object in the array with a different one.
  10183. If the index is less than zero, this method does nothing.
  10184. If the index is beyond the end of the array, the new object is added to the end of the array.
  10185. The object being added has its reference count increased, and if it's replacing
  10186. another object, then that one has its reference count decreased, and may be deleted.
  10187. @param indexToChange the index whose value you want to change
  10188. @param newObject the new value to set for this index.
  10189. @see add, insert, remove
  10190. */
  10191. void set (const int indexToChange,
  10192. ObjectClass* const newObject)
  10193. {
  10194. if (indexToChange >= 0)
  10195. {
  10196. const ScopedLockType lock (getLock());
  10197. if (newObject != 0)
  10198. newObject->incReferenceCount();
  10199. if (indexToChange < numUsed)
  10200. {
  10201. if (data.elements [indexToChange] != 0)
  10202. data.elements [indexToChange]->decReferenceCount();
  10203. data.elements [indexToChange] = newObject;
  10204. }
  10205. else
  10206. {
  10207. data.ensureAllocatedSize (numUsed + 1);
  10208. data.elements [numUsed++] = newObject;
  10209. }
  10210. }
  10211. }
  10212. /** Adds elements from another array to the end of this array.
  10213. @param arrayToAddFrom the array from which to copy the elements
  10214. @param startIndex the first element of the other array to start copying from
  10215. @param numElementsToAdd how many elements to add from the other array. If this
  10216. value is negative or greater than the number of available elements,
  10217. all available elements will be copied.
  10218. @see add
  10219. */
  10220. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  10221. int startIndex = 0,
  10222. int numElementsToAdd = -1) throw()
  10223. {
  10224. const ScopedLockType lock1 (arrayToAddFrom.getLock());
  10225. {
  10226. const ScopedLockType lock2 (getLock());
  10227. if (startIndex < 0)
  10228. {
  10229. jassertfalse;
  10230. startIndex = 0;
  10231. }
  10232. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  10233. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  10234. if (numElementsToAdd > 0)
  10235. {
  10236. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  10237. while (--numElementsToAdd >= 0)
  10238. add (arrayToAddFrom.getUnchecked (startIndex++));
  10239. }
  10240. }
  10241. }
  10242. /** Inserts a new object into the array assuming that the array is sorted.
  10243. This will use a comparator to find the position at which the new object
  10244. should go. If the array isn't sorted, the behaviour of this
  10245. method will be unpredictable.
  10246. @param comparator the comparator object to use to compare the elements - see the
  10247. sort() method for details about this object's form
  10248. @param newObject the new object to insert to the array
  10249. @see add, sort
  10250. */
  10251. template <class ElementComparator>
  10252. void addSorted (ElementComparator& comparator,
  10253. ObjectClass* newObject) throw()
  10254. {
  10255. const ScopedLockType lock (getLock());
  10256. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  10257. }
  10258. /** Inserts or replaces an object in the array, assuming it is sorted.
  10259. This is similar to addSorted, but if a matching element already exists, then it will be
  10260. replaced by the new one, rather than the new one being added as well.
  10261. */
  10262. template <class ElementComparator>
  10263. void addOrReplaceSorted (ElementComparator& comparator,
  10264. ObjectClass* newObject) throw()
  10265. {
  10266. const ScopedLockType lock (getLock());
  10267. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  10268. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  10269. set (index - 1, newObject); // replace an existing object that matches
  10270. else
  10271. insert (index, newObject); // no match, so insert the new one
  10272. }
  10273. /** Removes an object from the array.
  10274. This will remove the object at a given index and move back all the
  10275. subsequent objects to close the gap.
  10276. If the index passed in is out-of-range, nothing will happen.
  10277. The object that is removed will have its reference count decreased,
  10278. and may be deleted if not referenced from elsewhere.
  10279. @param indexToRemove the index of the element to remove
  10280. @see removeObject, removeRange
  10281. */
  10282. void remove (const int indexToRemove)
  10283. {
  10284. const ScopedLockType lock (getLock());
  10285. if (isPositiveAndBelow (indexToRemove, numUsed))
  10286. {
  10287. ObjectClass** const e = data.elements + indexToRemove;
  10288. if (*e != 0)
  10289. (*e)->decReferenceCount();
  10290. --numUsed;
  10291. const int numberToShift = numUsed - indexToRemove;
  10292. if (numberToShift > 0)
  10293. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  10294. if ((numUsed << 1) < data.numAllocated)
  10295. minimiseStorageOverheads();
  10296. }
  10297. }
  10298. /** Removes and returns an object from the array.
  10299. This will remove the object at a given index and return it, moving back all
  10300. the subsequent objects to close the gap. If the index passed in is out-of-range,
  10301. nothing will happen and a null pointer will be returned.
  10302. @param indexToRemove the index of the element to remove
  10303. @see remove, removeObject, removeRange
  10304. */
  10305. const ObjectClassPtr removeAndReturn (const int indexToRemove)
  10306. {
  10307. ObjectClassPtr removedItem;
  10308. const ScopedLockType lock (getLock());
  10309. if (isPositiveAndBelow (indexToRemove, numUsed))
  10310. {
  10311. ObjectClass** const e = data.elements + indexToRemove;
  10312. if (*e != 0)
  10313. {
  10314. removedItem = *e;
  10315. (*e)->decReferenceCount();
  10316. }
  10317. --numUsed;
  10318. const int numberToShift = numUsed - indexToRemove;
  10319. if (numberToShift > 0)
  10320. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  10321. if ((numUsed << 1) < data.numAllocated)
  10322. minimiseStorageOverheads();
  10323. }
  10324. return removedItem;
  10325. }
  10326. /** Removes the first occurrence of a specified object from the array.
  10327. If the item isn't found, no action is taken. If it is found, it is
  10328. removed and has its reference count decreased.
  10329. @param objectToRemove the object to try to remove
  10330. @see remove, removeRange
  10331. */
  10332. void removeObject (ObjectClass* const objectToRemove)
  10333. {
  10334. const ScopedLockType lock (getLock());
  10335. remove (indexOf (objectToRemove));
  10336. }
  10337. /** Removes a range of objects from the array.
  10338. This will remove a set of objects, starting from the given index,
  10339. and move any subsequent elements down to close the gap.
  10340. If the range extends beyond the bounds of the array, it will
  10341. be safely clipped to the size of the array.
  10342. The objects that are removed will have their reference counts decreased,
  10343. and may be deleted if not referenced from elsewhere.
  10344. @param startIndex the index of the first object to remove
  10345. @param numberToRemove how many objects should be removed
  10346. @see remove, removeObject
  10347. */
  10348. void removeRange (const int startIndex,
  10349. const int numberToRemove)
  10350. {
  10351. const ScopedLockType lock (getLock());
  10352. const int start = jlimit (0, numUsed, startIndex);
  10353. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  10354. if (end > start)
  10355. {
  10356. int i;
  10357. for (i = start; i < end; ++i)
  10358. {
  10359. if (data.elements[i] != 0)
  10360. {
  10361. data.elements[i]->decReferenceCount();
  10362. data.elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  10363. }
  10364. }
  10365. const int rangeSize = end - start;
  10366. ObjectClass** e = data.elements + start;
  10367. i = numUsed - end;
  10368. numUsed -= rangeSize;
  10369. while (--i >= 0)
  10370. {
  10371. *e = e [rangeSize];
  10372. ++e;
  10373. }
  10374. if ((numUsed << 1) < data.numAllocated)
  10375. minimiseStorageOverheads();
  10376. }
  10377. }
  10378. /** Removes the last n objects from the array.
  10379. The objects that are removed will have their reference counts decreased,
  10380. and may be deleted if not referenced from elsewhere.
  10381. @param howManyToRemove how many objects to remove from the end of the array
  10382. @see remove, removeObject, removeRange
  10383. */
  10384. void removeLast (int howManyToRemove = 1)
  10385. {
  10386. const ScopedLockType lock (getLock());
  10387. if (howManyToRemove > numUsed)
  10388. howManyToRemove = numUsed;
  10389. while (--howManyToRemove >= 0)
  10390. remove (numUsed - 1);
  10391. }
  10392. /** Swaps a pair of objects in the array.
  10393. If either of the indexes passed in is out-of-range, nothing will happen,
  10394. otherwise the two objects at these positions will be exchanged.
  10395. */
  10396. void swap (const int index1,
  10397. const int index2) throw()
  10398. {
  10399. const ScopedLockType lock (getLock());
  10400. if (isPositiveAndBelow (index1, numUsed)
  10401. && isPositiveAndBelow (index2, numUsed))
  10402. {
  10403. swapVariables (data.elements [index1],
  10404. data.elements [index2]);
  10405. }
  10406. }
  10407. /** Moves one of the objects to a different position.
  10408. This will move the object to a specified index, shuffling along
  10409. any intervening elements as required.
  10410. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  10411. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  10412. @param currentIndex the index of the object to be moved. If this isn't a
  10413. valid index, then nothing will be done
  10414. @param newIndex the index at which you'd like this object to end up. If this
  10415. is less than zero, it will be moved to the end of the array
  10416. */
  10417. void move (const int currentIndex,
  10418. int newIndex) throw()
  10419. {
  10420. if (currentIndex != newIndex)
  10421. {
  10422. const ScopedLockType lock (getLock());
  10423. if (isPositiveAndBelow (currentIndex, numUsed))
  10424. {
  10425. if (! isPositiveAndBelow (newIndex, numUsed))
  10426. newIndex = numUsed - 1;
  10427. ObjectClass* const value = data.elements [currentIndex];
  10428. if (newIndex > currentIndex)
  10429. {
  10430. memmove (data.elements + currentIndex,
  10431. data.elements + currentIndex + 1,
  10432. (newIndex - currentIndex) * sizeof (ObjectClass*));
  10433. }
  10434. else
  10435. {
  10436. memmove (data.elements + newIndex + 1,
  10437. data.elements + newIndex,
  10438. (currentIndex - newIndex) * sizeof (ObjectClass*));
  10439. }
  10440. data.elements [newIndex] = value;
  10441. }
  10442. }
  10443. }
  10444. /** This swaps the contents of this array with those of another array.
  10445. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  10446. because it just swaps their internal pointers.
  10447. */
  10448. void swapWithArray (ReferenceCountedArray& otherArray) throw()
  10449. {
  10450. const ScopedLockType lock1 (getLock());
  10451. const ScopedLockType lock2 (otherArray.getLock());
  10452. data.swapWith (otherArray.data);
  10453. swapVariables (numUsed, otherArray.numUsed);
  10454. }
  10455. /** Compares this array to another one.
  10456. @returns true only if the other array contains the same objects in the same order
  10457. */
  10458. bool operator== (const ReferenceCountedArray& other) const throw()
  10459. {
  10460. const ScopedLockType lock2 (other.getLock());
  10461. const ScopedLockType lock1 (getLock());
  10462. if (numUsed != other.numUsed)
  10463. return false;
  10464. for (int i = numUsed; --i >= 0;)
  10465. if (data.elements [i] != other.data.elements [i])
  10466. return false;
  10467. return true;
  10468. }
  10469. /** Compares this array to another one.
  10470. @see operator==
  10471. */
  10472. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  10473. {
  10474. return ! operator== (other);
  10475. }
  10476. /** Sorts the elements in the array.
  10477. This will use a comparator object to sort the elements into order. The object
  10478. passed must have a method of the form:
  10479. @code
  10480. int compareElements (ElementType first, ElementType second);
  10481. @endcode
  10482. ..and this method must return:
  10483. - a value of < 0 if the first comes before the second
  10484. - a value of 0 if the two objects are equivalent
  10485. - a value of > 0 if the second comes before the first
  10486. To improve performance, the compareElements() method can be declared as static or const.
  10487. @param comparator the comparator to use for comparing elements.
  10488. @param retainOrderOfEquivalentItems if this is true, then items
  10489. which the comparator says are equivalent will be
  10490. kept in the order in which they currently appear
  10491. in the array. This is slower to perform, but may
  10492. be important in some cases. If it's false, a faster
  10493. algorithm is used, but equivalent elements may be
  10494. rearranged.
  10495. @see sortArray
  10496. */
  10497. template <class ElementComparator>
  10498. void sort (ElementComparator& comparator,
  10499. const bool retainOrderOfEquivalentItems = false) const throw()
  10500. {
  10501. (void) comparator; // if you pass in an object with a static compareElements() method, this
  10502. // avoids getting warning messages about the parameter being unused
  10503. const ScopedLockType lock (getLock());
  10504. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  10505. }
  10506. /** Reduces the amount of storage being used by the array.
  10507. Arrays typically allocate slightly more storage than they need, and after
  10508. removing elements, they may have quite a lot of unused space allocated.
  10509. This method will reduce the amount of allocated storage to a minimum.
  10510. */
  10511. void minimiseStorageOverheads() throw()
  10512. {
  10513. const ScopedLockType lock (getLock());
  10514. data.shrinkToNoMoreThan (numUsed);
  10515. }
  10516. /** Returns the CriticalSection that locks this array.
  10517. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  10518. an object of ScopedLockType as an RAII lock for it.
  10519. */
  10520. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  10521. /** Returns the type of scoped lock to use for locking this array */
  10522. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  10523. private:
  10524. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  10525. int numUsed;
  10526. };
  10527. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  10528. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  10529. #endif
  10530. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  10531. /*** Start of inlined file: juce_ScopedValueSetter.h ***/
  10532. #ifndef __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  10533. #define __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  10534. /**
  10535. Helper class providing an RAII-based mechanism for temporarily setting and
  10536. then re-setting a value.
  10537. E.g. @code
  10538. int x = 1;
  10539. {
  10540. ScopedValueSetter setter (x, 2);
  10541. // x is now 2
  10542. }
  10543. // x is now 1 again
  10544. {
  10545. ScopedValueSetter setter (x, 3, 4);
  10546. // x is now 3
  10547. }
  10548. // x is now 4
  10549. @endcode
  10550. */
  10551. template <typename ValueType>
  10552. class ScopedValueSetter
  10553. {
  10554. public:
  10555. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  10556. given new value, and will then reset it to its original value when this object is deleted.
  10557. */
  10558. ScopedValueSetter (ValueType& valueToSet,
  10559. const ValueType& newValue)
  10560. : value (valueToSet),
  10561. originalValue (valueToSet)
  10562. {
  10563. valueToSet = newValue;
  10564. }
  10565. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  10566. given new value, and will then reset it to be valueWhenDeleted when this object is deleted.
  10567. */
  10568. ScopedValueSetter (ValueType& valueToSet,
  10569. const ValueType& newValue,
  10570. const ValueType& valueWhenDeleted)
  10571. : value (valueToSet),
  10572. originalValue (valueWhenDeleted)
  10573. {
  10574. valueToSet = newValue;
  10575. }
  10576. ~ScopedValueSetter()
  10577. {
  10578. value = originalValue;
  10579. }
  10580. private:
  10581. ValueType& value;
  10582. const ValueType originalValue;
  10583. JUCE_DECLARE_NON_COPYABLE (ScopedValueSetter);
  10584. };
  10585. #endif // __JUCE_SCOPEDVALUESETTER_JUCEHEADER__
  10586. /*** End of inlined file: juce_ScopedValueSetter.h ***/
  10587. #endif
  10588. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  10589. /*** Start of inlined file: juce_SortedSet.h ***/
  10590. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  10591. #define __JUCE_SORTEDSET_JUCEHEADER__
  10592. #if JUCE_MSVC
  10593. #pragma warning (push)
  10594. #pragma warning (disable: 4512)
  10595. #endif
  10596. /**
  10597. Holds a set of unique primitive objects, such as ints or doubles.
  10598. A set can only hold one item with a given value, so if for example it's a
  10599. set of integers, attempting to add the same integer twice will do nothing
  10600. the second time.
  10601. Internally, the list of items is kept sorted (which means that whatever
  10602. kind of primitive type is used must support the ==, <, >, <= and >= operators
  10603. to determine the order), and searching the set for known values is very fast
  10604. because it uses a binary-chop method.
  10605. Note that if you're using a class or struct as the element type, it must be
  10606. capable of being copied or moved with a straightforward memcpy, rather than
  10607. needing construction and destruction code.
  10608. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  10609. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  10610. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  10611. */
  10612. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  10613. class SortedSet
  10614. {
  10615. public:
  10616. /** Creates an empty set. */
  10617. SortedSet() throw()
  10618. : numUsed (0)
  10619. {
  10620. }
  10621. /** Creates a copy of another set.
  10622. @param other the set to copy
  10623. */
  10624. SortedSet (const SortedSet& other) throw()
  10625. {
  10626. const ScopedLockType lock (other.getLock());
  10627. numUsed = other.numUsed;
  10628. data.setAllocatedSize (other.numUsed);
  10629. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  10630. }
  10631. /** Destructor. */
  10632. ~SortedSet() throw()
  10633. {
  10634. }
  10635. /** Copies another set over this one.
  10636. @param other the set to copy
  10637. */
  10638. SortedSet& operator= (const SortedSet& other) throw()
  10639. {
  10640. if (this != &other)
  10641. {
  10642. const ScopedLockType lock1 (other.getLock());
  10643. const ScopedLockType lock2 (getLock());
  10644. data.ensureAllocatedSize (other.size());
  10645. numUsed = other.numUsed;
  10646. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  10647. minimiseStorageOverheads();
  10648. }
  10649. return *this;
  10650. }
  10651. /** Compares this set to another one.
  10652. Two sets are considered equal if they both contain the same set of
  10653. elements.
  10654. @param other the other set to compare with
  10655. */
  10656. bool operator== (const SortedSet<ElementType>& other) const throw()
  10657. {
  10658. const ScopedLockType lock (getLock());
  10659. if (numUsed != other.numUsed)
  10660. return false;
  10661. for (int i = numUsed; --i >= 0;)
  10662. if (data.elements[i] != other.data.elements[i])
  10663. return false;
  10664. return true;
  10665. }
  10666. /** Compares this set to another one.
  10667. Two sets are considered equal if they both contain the same set of
  10668. elements.
  10669. @param other the other set to compare with
  10670. */
  10671. bool operator!= (const SortedSet<ElementType>& other) const throw()
  10672. {
  10673. return ! operator== (other);
  10674. }
  10675. /** Removes all elements from the set.
  10676. This will remove all the elements, and free any storage that the set is
  10677. using. To clear it without freeing the storage, use the clearQuick()
  10678. method instead.
  10679. @see clearQuick
  10680. */
  10681. void clear() throw()
  10682. {
  10683. const ScopedLockType lock (getLock());
  10684. data.setAllocatedSize (0);
  10685. numUsed = 0;
  10686. }
  10687. /** Removes all elements from the set without freeing the array's allocated storage.
  10688. @see clear
  10689. */
  10690. void clearQuick() throw()
  10691. {
  10692. const ScopedLockType lock (getLock());
  10693. numUsed = 0;
  10694. }
  10695. /** Returns the current number of elements in the set.
  10696. */
  10697. inline int size() const throw()
  10698. {
  10699. return numUsed;
  10700. }
  10701. /** Returns one of the elements in the set.
  10702. If the index passed in is beyond the range of valid elements, this
  10703. will return zero.
  10704. If you're certain that the index will always be a valid element, you
  10705. can call getUnchecked() instead, which is faster.
  10706. @param index the index of the element being requested (0 is the first element in the set)
  10707. @see getUnchecked, getFirst, getLast
  10708. */
  10709. inline ElementType operator[] (const int index) const throw()
  10710. {
  10711. const ScopedLockType lock (getLock());
  10712. return isPositiveAndBelow (index, numUsed) ? data.elements [index]
  10713. : ElementType();
  10714. }
  10715. /** Returns one of the elements in the set, without checking the index passed in.
  10716. Unlike the operator[] method, this will try to return an element without
  10717. checking that the index is within the bounds of the set, so should only
  10718. be used when you're confident that it will always be a valid index.
  10719. @param index the index of the element being requested (0 is the first element in the set)
  10720. @see operator[], getFirst, getLast
  10721. */
  10722. inline ElementType getUnchecked (const int index) const throw()
  10723. {
  10724. const ScopedLockType lock (getLock());
  10725. jassert (isPositiveAndBelow (index, numUsed));
  10726. return data.elements [index];
  10727. }
  10728. /** Returns the first element in the set, or 0 if the set is empty.
  10729. @see operator[], getUnchecked, getLast
  10730. */
  10731. inline ElementType getFirst() const throw()
  10732. {
  10733. const ScopedLockType lock (getLock());
  10734. return numUsed > 0 ? data.elements [0] : ElementType();
  10735. }
  10736. /** Returns the last element in the set, or 0 if the set is empty.
  10737. @see operator[], getUnchecked, getFirst
  10738. */
  10739. inline ElementType getLast() const throw()
  10740. {
  10741. const ScopedLockType lock (getLock());
  10742. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  10743. }
  10744. /** Finds the index of the first element which matches the value passed in.
  10745. This will search the set for the given object, and return the index
  10746. of its first occurrence. If the object isn't found, the method will return -1.
  10747. @param elementToLookFor the value or object to look for
  10748. @returns the index of the object, or -1 if it's not found
  10749. */
  10750. int indexOf (const ElementType elementToLookFor) const throw()
  10751. {
  10752. const ScopedLockType lock (getLock());
  10753. int start = 0;
  10754. int end = numUsed;
  10755. for (;;)
  10756. {
  10757. if (start >= end)
  10758. {
  10759. return -1;
  10760. }
  10761. else if (elementToLookFor == data.elements [start])
  10762. {
  10763. return start;
  10764. }
  10765. else
  10766. {
  10767. const int halfway = (start + end) >> 1;
  10768. if (halfway == start)
  10769. return -1;
  10770. else if (elementToLookFor >= data.elements [halfway])
  10771. start = halfway;
  10772. else
  10773. end = halfway;
  10774. }
  10775. }
  10776. }
  10777. /** Returns true if the set contains at least one occurrence of an object.
  10778. @param elementToLookFor the value or object to look for
  10779. @returns true if the item is found
  10780. */
  10781. bool contains (const ElementType elementToLookFor) const throw()
  10782. {
  10783. const ScopedLockType lock (getLock());
  10784. int start = 0;
  10785. int end = numUsed;
  10786. for (;;)
  10787. {
  10788. if (start >= end)
  10789. {
  10790. return false;
  10791. }
  10792. else if (elementToLookFor == data.elements [start])
  10793. {
  10794. return true;
  10795. }
  10796. else
  10797. {
  10798. const int halfway = (start + end) >> 1;
  10799. if (halfway == start)
  10800. return false;
  10801. else if (elementToLookFor >= data.elements [halfway])
  10802. start = halfway;
  10803. else
  10804. end = halfway;
  10805. }
  10806. }
  10807. }
  10808. /** Adds a new element to the set, (as long as it's not already in there).
  10809. @param newElement the new object to add to the set
  10810. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  10811. */
  10812. void add (const ElementType newElement) throw()
  10813. {
  10814. const ScopedLockType lock (getLock());
  10815. int start = 0;
  10816. int end = numUsed;
  10817. for (;;)
  10818. {
  10819. if (start >= end)
  10820. {
  10821. jassert (start <= end);
  10822. insertInternal (start, newElement);
  10823. break;
  10824. }
  10825. else if (newElement == data.elements [start])
  10826. {
  10827. break;
  10828. }
  10829. else
  10830. {
  10831. const int halfway = (start + end) >> 1;
  10832. if (halfway == start)
  10833. {
  10834. if (newElement >= data.elements [halfway])
  10835. insertInternal (start + 1, newElement);
  10836. else
  10837. insertInternal (start, newElement);
  10838. break;
  10839. }
  10840. else if (newElement >= data.elements [halfway])
  10841. start = halfway;
  10842. else
  10843. end = halfway;
  10844. }
  10845. }
  10846. }
  10847. /** Adds elements from an array to this set.
  10848. @param elementsToAdd the array of elements to add
  10849. @param numElementsToAdd how many elements are in this other array
  10850. @see add
  10851. */
  10852. void addArray (const ElementType* elementsToAdd,
  10853. int numElementsToAdd) throw()
  10854. {
  10855. const ScopedLockType lock (getLock());
  10856. while (--numElementsToAdd >= 0)
  10857. add (*elementsToAdd++);
  10858. }
  10859. /** Adds elements from another set to this one.
  10860. @param setToAddFrom the set from which to copy the elements
  10861. @param startIndex the first element of the other set to start copying from
  10862. @param numElementsToAdd how many elements to add from the other set. If this
  10863. value is negative or greater than the number of available elements,
  10864. all available elements will be copied.
  10865. @see add
  10866. */
  10867. template <class OtherSetType>
  10868. void addSet (const OtherSetType& setToAddFrom,
  10869. int startIndex = 0,
  10870. int numElementsToAdd = -1) throw()
  10871. {
  10872. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  10873. {
  10874. const ScopedLockType lock2 (getLock());
  10875. jassert (this != &setToAddFrom);
  10876. if (this != &setToAddFrom)
  10877. {
  10878. if (startIndex < 0)
  10879. {
  10880. jassertfalse;
  10881. startIndex = 0;
  10882. }
  10883. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  10884. numElementsToAdd = setToAddFrom.size() - startIndex;
  10885. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  10886. }
  10887. }
  10888. }
  10889. /** Removes an element from the set.
  10890. This will remove the element at a given index.
  10891. If the index passed in is out-of-range, nothing will happen.
  10892. @param indexToRemove the index of the element to remove
  10893. @returns the element that has been removed
  10894. @see removeValue, removeRange
  10895. */
  10896. ElementType remove (const int indexToRemove) throw()
  10897. {
  10898. const ScopedLockType lock (getLock());
  10899. if (isPositiveAndBelow (indexToRemove, numUsed))
  10900. {
  10901. --numUsed;
  10902. ElementType* const e = data.elements + indexToRemove;
  10903. ElementType const removed = *e;
  10904. const int numberToShift = numUsed - indexToRemove;
  10905. if (numberToShift > 0)
  10906. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  10907. if ((numUsed << 1) < data.numAllocated)
  10908. minimiseStorageOverheads();
  10909. return removed;
  10910. }
  10911. return 0;
  10912. }
  10913. /** Removes an item from the set.
  10914. This will remove the given element from the set, if it's there.
  10915. @param valueToRemove the object to try to remove
  10916. @see remove, removeRange
  10917. */
  10918. void removeValue (const ElementType valueToRemove) throw()
  10919. {
  10920. const ScopedLockType lock (getLock());
  10921. remove (indexOf (valueToRemove));
  10922. }
  10923. /** Removes any elements which are also in another set.
  10924. @param otherSet the other set in which to look for elements to remove
  10925. @see removeValuesNotIn, remove, removeValue, removeRange
  10926. */
  10927. template <class OtherSetType>
  10928. void removeValuesIn (const OtherSetType& otherSet) throw()
  10929. {
  10930. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  10931. const ScopedLockType lock2 (getLock());
  10932. if (this == &otherSet)
  10933. {
  10934. clear();
  10935. }
  10936. else
  10937. {
  10938. if (otherSet.size() > 0)
  10939. {
  10940. for (int i = numUsed; --i >= 0;)
  10941. if (otherSet.contains (data.elements [i]))
  10942. remove (i);
  10943. }
  10944. }
  10945. }
  10946. /** Removes any elements which are not found in another set.
  10947. Only elements which occur in this other set will be retained.
  10948. @param otherSet the set in which to look for elements NOT to remove
  10949. @see removeValuesIn, remove, removeValue, removeRange
  10950. */
  10951. template <class OtherSetType>
  10952. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  10953. {
  10954. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  10955. const ScopedLockType lock2 (getLock());
  10956. if (this != &otherSet)
  10957. {
  10958. if (otherSet.size() <= 0)
  10959. {
  10960. clear();
  10961. }
  10962. else
  10963. {
  10964. for (int i = numUsed; --i >= 0;)
  10965. if (! otherSet.contains (data.elements [i]))
  10966. remove (i);
  10967. }
  10968. }
  10969. }
  10970. /** Reduces the amount of storage being used by the set.
  10971. Sets typically allocate slightly more storage than they need, and after
  10972. removing elements, they may have quite a lot of unused space allocated.
  10973. This method will reduce the amount of allocated storage to a minimum.
  10974. */
  10975. void minimiseStorageOverheads() throw()
  10976. {
  10977. const ScopedLockType lock (getLock());
  10978. data.shrinkToNoMoreThan (numUsed);
  10979. }
  10980. /** Returns the CriticalSection that locks this array.
  10981. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  10982. an object of ScopedLockType as an RAII lock for it.
  10983. */
  10984. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  10985. /** Returns the type of scoped lock to use for locking this array */
  10986. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  10987. private:
  10988. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  10989. int numUsed;
  10990. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  10991. {
  10992. data.ensureAllocatedSize (numUsed + 1);
  10993. ElementType* const insertPos = data.elements + indexToInsertAt;
  10994. const int numberToMove = numUsed - indexToInsertAt;
  10995. if (numberToMove > 0)
  10996. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  10997. *insertPos = newElement;
  10998. ++numUsed;
  10999. }
  11000. };
  11001. #if JUCE_MSVC
  11002. #pragma warning (pop)
  11003. #endif
  11004. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  11005. /*** End of inlined file: juce_SortedSet.h ***/
  11006. #endif
  11007. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11008. /*** Start of inlined file: juce_SparseSet.h ***/
  11009. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  11010. #define __JUCE_SPARSESET_JUCEHEADER__
  11011. /*** Start of inlined file: juce_Range.h ***/
  11012. #ifndef __JUCE_RANGE_JUCEHEADER__
  11013. #define __JUCE_RANGE_JUCEHEADER__
  11014. /** A general-purpose range object, that simply represents any linear range with
  11015. a start and end point.
  11016. The templated parameter is expected to be a primitive integer or floating point
  11017. type, though class types could also be used if they behave in a number-like way.
  11018. */
  11019. template <typename ValueType>
  11020. class Range
  11021. {
  11022. public:
  11023. /** Constructs an empty range. */
  11024. Range() throw()
  11025. : start (ValueType()), end (ValueType())
  11026. {
  11027. }
  11028. /** Constructs a range with given start and end values. */
  11029. Range (const ValueType start_, const ValueType end_) throw()
  11030. : start (start_), end (jmax (start_, end_))
  11031. {
  11032. }
  11033. /** Constructs a copy of another range. */
  11034. Range (const Range& other) throw()
  11035. : start (other.start), end (other.end)
  11036. {
  11037. }
  11038. /** Copies another range object. */
  11039. Range& operator= (const Range& other) throw()
  11040. {
  11041. start = other.start;
  11042. end = other.end;
  11043. return *this;
  11044. }
  11045. /** Destructor. */
  11046. ~Range() throw()
  11047. {
  11048. }
  11049. /** Returns the range that lies between two positions (in either order). */
  11050. static const Range between (const ValueType position1, const ValueType position2) throw()
  11051. {
  11052. return (position1 < position2) ? Range (position1, position2)
  11053. : Range (position2, position1);
  11054. }
  11055. /** Returns a range with the specified start position and a length of zero. */
  11056. static const Range emptyRange (const ValueType start) throw()
  11057. {
  11058. return Range (start, start);
  11059. }
  11060. /** Returns the start of the range. */
  11061. inline ValueType getStart() const throw() { return start; }
  11062. /** Returns the length of the range. */
  11063. inline ValueType getLength() const throw() { return end - start; }
  11064. /** Returns the end of the range. */
  11065. inline ValueType getEnd() const throw() { return end; }
  11066. /** Returns true if the range has a length of zero. */
  11067. inline bool isEmpty() const throw() { return start == end; }
  11068. /** Changes the start position of the range, leaving the end position unchanged.
  11069. If the new start position is higher than the current end of the range, the end point
  11070. will be pushed along to equal it, leaving an empty range at the new position.
  11071. */
  11072. void setStart (const ValueType newStart) throw()
  11073. {
  11074. start = newStart;
  11075. if (end < newStart)
  11076. end = newStart;
  11077. }
  11078. /** Returns a range with the same end as this one, but a different start.
  11079. If the new start position is higher than the current end of the range, the end point
  11080. will be pushed along to equal it, returning an empty range at the new position.
  11081. */
  11082. const Range withStart (const ValueType newStart) const throw()
  11083. {
  11084. return Range (newStart, jmax (newStart, end));
  11085. }
  11086. /** Returns a range with the same length as this one, but moved to have the given start position. */
  11087. const Range movedToStartAt (const ValueType newStart) const throw()
  11088. {
  11089. return Range (newStart, end + (newStart - start));
  11090. }
  11091. /** Changes the end position of the range, leaving the start unchanged.
  11092. If the new end position is below the current start of the range, the start point
  11093. will be pushed back to equal the new end point.
  11094. */
  11095. void setEnd (const ValueType newEnd) throw()
  11096. {
  11097. end = newEnd;
  11098. if (newEnd < start)
  11099. start = newEnd;
  11100. }
  11101. /** Returns a range with the same start position as this one, but a different end.
  11102. If the new end position is below the current start of the range, the start point
  11103. will be pushed back to equal the new end point.
  11104. */
  11105. const Range withEnd (const ValueType newEnd) const throw()
  11106. {
  11107. return Range (jmin (start, newEnd), newEnd);
  11108. }
  11109. /** Returns a range with the same length as this one, but moved to have the given start position. */
  11110. const Range movedToEndAt (const ValueType newEnd) const throw()
  11111. {
  11112. return Range (start + (newEnd - end), newEnd);
  11113. }
  11114. /** Changes the length of the range.
  11115. Lengths less than zero are treated as zero.
  11116. */
  11117. void setLength (const ValueType newLength) throw()
  11118. {
  11119. end = start + jmax (ValueType(), newLength);
  11120. }
  11121. /** Returns a range with the same start as this one, but a different length.
  11122. Lengths less than zero are treated as zero.
  11123. */
  11124. const Range withLength (const ValueType newLength) const throw()
  11125. {
  11126. return Range (start, start + newLength);
  11127. }
  11128. /** Adds an amount to the start and end of the range. */
  11129. inline const Range& operator+= (const ValueType amountToAdd) throw()
  11130. {
  11131. start += amountToAdd;
  11132. end += amountToAdd;
  11133. return *this;
  11134. }
  11135. /** Subtracts an amount from the start and end of the range. */
  11136. inline const Range& operator-= (const ValueType amountToSubtract) throw()
  11137. {
  11138. start -= amountToSubtract;
  11139. end -= amountToSubtract;
  11140. return *this;
  11141. }
  11142. /** Returns a range that is equal to this one with an amount added to its
  11143. start and end.
  11144. */
  11145. const Range operator+ (const ValueType amountToAdd) const throw()
  11146. {
  11147. return Range (start + amountToAdd, end + amountToAdd);
  11148. }
  11149. /** Returns a range that is equal to this one with the specified amount
  11150. subtracted from its start and end. */
  11151. const Range operator- (const ValueType amountToSubtract) const throw()
  11152. {
  11153. return Range (start - amountToSubtract, end - amountToSubtract);
  11154. }
  11155. bool operator== (const Range& other) const throw() { return start == other.start && end == other.end; }
  11156. bool operator!= (const Range& other) const throw() { return start != other.start || end != other.end; }
  11157. /** Returns true if the given position lies inside this range. */
  11158. bool contains (const ValueType position) const throw()
  11159. {
  11160. return start <= position && position < end;
  11161. }
  11162. /** Returns the nearest value to the one supplied, which lies within the range. */
  11163. ValueType clipValue (const ValueType value) const throw()
  11164. {
  11165. return jlimit (start, end, value);
  11166. }
  11167. /** Returns true if the given range lies entirely inside this range. */
  11168. bool contains (const Range& other) const throw()
  11169. {
  11170. return start <= other.start && end >= other.end;
  11171. }
  11172. /** Returns true if the given range intersects this one. */
  11173. bool intersects (const Range& other) const throw()
  11174. {
  11175. return other.start < end && start < other.end;
  11176. }
  11177. /** Returns the range that is the intersection of the two ranges, or an empty range
  11178. with an undefined start position if they don't overlap. */
  11179. const Range getIntersectionWith (const Range& other) const throw()
  11180. {
  11181. return Range (jmax (start, other.start),
  11182. jmin (end, other.end));
  11183. }
  11184. /** Returns the smallest range that contains both this one and the other one. */
  11185. const Range getUnionWith (const Range& other) const throw()
  11186. {
  11187. return Range (jmin (start, other.start),
  11188. jmax (end, other.end));
  11189. }
  11190. /** Returns a given range, after moving it forwards or backwards to fit it
  11191. within this range.
  11192. If the supplied range has a greater length than this one, the return value
  11193. will be this range.
  11194. Otherwise, if the supplied range is smaller than this one, the return value
  11195. will be the new range, shifted forwards or backwards so that it doesn't extend
  11196. beyond this one, but keeping its original length.
  11197. */
  11198. const Range constrainRange (const Range& rangeToConstrain) const throw()
  11199. {
  11200. const ValueType otherLen = rangeToConstrain.getLength();
  11201. return getLength() <= otherLen
  11202. ? *this
  11203. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  11204. }
  11205. private:
  11206. ValueType start, end;
  11207. };
  11208. #endif // __JUCE_RANGE_JUCEHEADER__
  11209. /*** End of inlined file: juce_Range.h ***/
  11210. /**
  11211. Holds a set of primitive values, storing them as a set of ranges.
  11212. This container acts like an array, but can efficiently hold large continguous
  11213. ranges of values. It's quite a specialised class, mostly useful for things
  11214. like keeping the set of selected rows in a listbox.
  11215. The type used as a template paramter must be an integer type, such as int, short,
  11216. int64, etc.
  11217. */
  11218. template <class Type>
  11219. class SparseSet
  11220. {
  11221. public:
  11222. /** Creates a new empty set. */
  11223. SparseSet()
  11224. {
  11225. }
  11226. /** Creates a copy of another SparseSet. */
  11227. SparseSet (const SparseSet<Type>& other)
  11228. : values (other.values)
  11229. {
  11230. }
  11231. /** Clears the set. */
  11232. void clear()
  11233. {
  11234. values.clear();
  11235. }
  11236. /** Checks whether the set is empty.
  11237. This is much quicker than using (size() == 0).
  11238. */
  11239. bool isEmpty() const throw()
  11240. {
  11241. return values.size() == 0;
  11242. }
  11243. /** Returns the number of values in the set.
  11244. Because of the way the data is stored, this method can take longer if there
  11245. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  11246. are any items.
  11247. */
  11248. Type size() const
  11249. {
  11250. Type total (0);
  11251. for (int i = 0; i < values.size(); i += 2)
  11252. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  11253. return total;
  11254. }
  11255. /** Returns one of the values in the set.
  11256. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  11257. @returns the value at this index, or 0 if it's out-of-range
  11258. */
  11259. Type operator[] (Type index) const
  11260. {
  11261. for (int i = 0; i < values.size(); i += 2)
  11262. {
  11263. const Type start (values.getUnchecked (i));
  11264. const Type len (values.getUnchecked (i + 1) - start);
  11265. if (index < len)
  11266. return start + index;
  11267. index -= len;
  11268. }
  11269. return Type();
  11270. }
  11271. /** Checks whether a particular value is in the set. */
  11272. bool contains (const Type valueToLookFor) const
  11273. {
  11274. for (int i = 0; i < values.size(); ++i)
  11275. if (valueToLookFor < values.getUnchecked(i))
  11276. return (i & 1) != 0;
  11277. return false;
  11278. }
  11279. /** Returns the number of contiguous blocks of values.
  11280. @see getRange
  11281. */
  11282. int getNumRanges() const throw()
  11283. {
  11284. return values.size() >> 1;
  11285. }
  11286. /** Returns one of the contiguous ranges of values stored.
  11287. @param rangeIndex the index of the range to look up, between 0
  11288. and (getNumRanges() - 1)
  11289. @see getTotalRange
  11290. */
  11291. const Range<Type> getRange (const int rangeIndex) const
  11292. {
  11293. if (isPositiveAndBelow (rangeIndex, getNumRanges()))
  11294. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  11295. values.getUnchecked ((rangeIndex << 1) + 1));
  11296. else
  11297. return Range<Type>();
  11298. }
  11299. /** Returns the range between the lowest and highest values in the set.
  11300. @see getRange
  11301. */
  11302. const Range<Type> getTotalRange() const
  11303. {
  11304. if (values.size() > 0)
  11305. {
  11306. jassert ((values.size() & 1) == 0);
  11307. return Range<Type> (values.getUnchecked (0),
  11308. values.getUnchecked (values.size() - 1));
  11309. }
  11310. return Range<Type>();
  11311. }
  11312. /** Adds a range of contiguous values to the set.
  11313. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  11314. */
  11315. void addRange (const Range<Type>& range)
  11316. {
  11317. jassert (range.getLength() >= 0);
  11318. if (range.getLength() > 0)
  11319. {
  11320. removeRange (range);
  11321. values.addUsingDefaultSort (range.getStart());
  11322. values.addUsingDefaultSort (range.getEnd());
  11323. simplify();
  11324. }
  11325. }
  11326. /** Removes a range of values from the set.
  11327. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  11328. */
  11329. void removeRange (const Range<Type>& rangeToRemove)
  11330. {
  11331. jassert (rangeToRemove.getLength() >= 0);
  11332. if (rangeToRemove.getLength() > 0
  11333. && values.size() > 0
  11334. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  11335. && values.getUnchecked(0) < rangeToRemove.getEnd())
  11336. {
  11337. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  11338. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  11339. const bool onAtEnd = contains (lastValue);
  11340. for (int i = values.size(); --i >= 0;)
  11341. {
  11342. if (values.getUnchecked(i) <= lastValue)
  11343. {
  11344. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  11345. {
  11346. values.remove (i);
  11347. if (--i < 0)
  11348. break;
  11349. }
  11350. break;
  11351. }
  11352. }
  11353. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  11354. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  11355. simplify();
  11356. }
  11357. }
  11358. /** Does an XOR of the values in a given range. */
  11359. void invertRange (const Range<Type>& range)
  11360. {
  11361. SparseSet newItems;
  11362. newItems.addRange (range);
  11363. int i;
  11364. for (i = getNumRanges(); --i >= 0;)
  11365. newItems.removeRange (getRange (i));
  11366. removeRange (range);
  11367. for (i = newItems.getNumRanges(); --i >= 0;)
  11368. addRange (newItems.getRange(i));
  11369. }
  11370. /** Checks whether any part of a given range overlaps any part of this set. */
  11371. bool overlapsRange (const Range<Type>& range)
  11372. {
  11373. if (range.getLength() > 0)
  11374. {
  11375. for (int i = getNumRanges(); --i >= 0;)
  11376. {
  11377. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  11378. return false;
  11379. if (values.getUnchecked (i << 1) < range.getEnd())
  11380. return true;
  11381. }
  11382. }
  11383. return false;
  11384. }
  11385. /** Checks whether the whole of a given range is contained within this one. */
  11386. bool containsRange (const Range<Type>& range)
  11387. {
  11388. if (range.getLength() > 0)
  11389. {
  11390. for (int i = getNumRanges(); --i >= 0;)
  11391. {
  11392. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  11393. return false;
  11394. if (values.getUnchecked (i << 1) <= range.getStart()
  11395. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  11396. return true;
  11397. }
  11398. }
  11399. return false;
  11400. }
  11401. bool operator== (const SparseSet<Type>& other) throw()
  11402. {
  11403. return values == other.values;
  11404. }
  11405. bool operator!= (const SparseSet<Type>& other) throw()
  11406. {
  11407. return values != other.values;
  11408. }
  11409. private:
  11410. // alternating start/end values of ranges of values that are present.
  11411. Array<Type, DummyCriticalSection> values;
  11412. void simplify()
  11413. {
  11414. jassert ((values.size() & 1) == 0);
  11415. for (int i = values.size(); --i > 0;)
  11416. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  11417. values.removeRange (--i, 2);
  11418. }
  11419. };
  11420. #endif // __JUCE_SPARSESET_JUCEHEADER__
  11421. /*** End of inlined file: juce_SparseSet.h ***/
  11422. #endif
  11423. #ifndef __JUCE_VALUE_JUCEHEADER__
  11424. /*** Start of inlined file: juce_Value.h ***/
  11425. #ifndef __JUCE_VALUE_JUCEHEADER__
  11426. #define __JUCE_VALUE_JUCEHEADER__
  11427. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  11428. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  11429. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  11430. /*** Start of inlined file: juce_CallbackMessage.h ***/
  11431. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  11432. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  11433. /*** Start of inlined file: juce_Message.h ***/
  11434. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  11435. #define __JUCE_MESSAGE_JUCEHEADER__
  11436. class MessageListener;
  11437. class MessageManager;
  11438. /** The base class for objects that can be delivered to a MessageListener.
  11439. The simplest Message object contains a few integer and pointer parameters
  11440. that the user can set, and this is enough for a lot of purposes. For passing more
  11441. complex data, subclasses of Message can also be used.
  11442. @see MessageListener, MessageManager, ActionListener, ChangeListener
  11443. */
  11444. class JUCE_API Message : public ReferenceCountedObject
  11445. {
  11446. public:
  11447. /** Creates an uninitialised message.
  11448. The class's variables will also be left uninitialised.
  11449. */
  11450. Message() throw();
  11451. /** Creates a message object, filling in the member variables.
  11452. The corresponding public member variables will be set from the parameters
  11453. passed in.
  11454. */
  11455. Message (int intParameter1,
  11456. int intParameter2,
  11457. int intParameter3,
  11458. void* pointerParameter) throw();
  11459. /** Destructor. */
  11460. virtual ~Message();
  11461. // These values can be used for carrying simple data that the application needs to
  11462. // pass around. For more complex messages, just create a subclass.
  11463. int intParameter1; /**< user-defined integer value. */
  11464. int intParameter2; /**< user-defined integer value. */
  11465. int intParameter3; /**< user-defined integer value. */
  11466. void* pointerParameter; /**< user-defined pointer value. */
  11467. /** A typedef for pointers to messages. */
  11468. typedef ReferenceCountedObjectPtr <Message> Ptr;
  11469. private:
  11470. friend class MessageListener;
  11471. friend class MessageManager;
  11472. MessageListener* messageRecipient;
  11473. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Message);
  11474. };
  11475. #endif // __JUCE_MESSAGE_JUCEHEADER__
  11476. /*** End of inlined file: juce_Message.h ***/
  11477. /**
  11478. A message that calls a custom function when it gets delivered.
  11479. You can use this class to fire off actions that you want to be performed later
  11480. on the message thread.
  11481. Unlike other Message objects, these don't get sent to a MessageListener, you
  11482. just call the post() method to send them, and when they arrive, your
  11483. messageCallback() method will automatically be invoked.
  11484. Always create an instance of a CallbackMessage on the heap, as it will be
  11485. deleted automatically after the message has been delivered.
  11486. @see MessageListener, MessageManager, ActionListener, ChangeListener
  11487. */
  11488. class JUCE_API CallbackMessage : public Message
  11489. {
  11490. public:
  11491. CallbackMessage() throw();
  11492. /** Destructor. */
  11493. ~CallbackMessage();
  11494. /** Called when the message is delivered.
  11495. You should implement this method and make it do whatever action you want
  11496. to perform.
  11497. Note that like all other messages, this object will be deleted immediately
  11498. after this method has been invoked.
  11499. */
  11500. virtual void messageCallback() = 0;
  11501. /** Instead of sending this message to a MessageListener, just call this method
  11502. to post it to the event queue.
  11503. After you've called this, this object will belong to the MessageManager,
  11504. which will delete it later. So make sure you don't delete the object yourself,
  11505. call post() more than once, or call post() on a stack-based obect!
  11506. */
  11507. void post();
  11508. private:
  11509. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallbackMessage);
  11510. };
  11511. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  11512. /*** End of inlined file: juce_CallbackMessage.h ***/
  11513. /**
  11514. Has a callback method that is triggered asynchronously.
  11515. This object allows an asynchronous callback function to be triggered, for
  11516. tasks such as coalescing multiple updates into a single callback later on.
  11517. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  11518. message thread calling handleAsyncUpdate() as soon as it can.
  11519. */
  11520. class JUCE_API AsyncUpdater
  11521. {
  11522. public:
  11523. /** Creates an AsyncUpdater object. */
  11524. AsyncUpdater();
  11525. /** Destructor.
  11526. If there are any pending callbacks when the object is deleted, these are lost.
  11527. */
  11528. virtual ~AsyncUpdater();
  11529. /** Causes the callback to be triggered at a later time.
  11530. This method returns immediately, having made sure that a callback
  11531. to the handleAsyncUpdate() method will occur as soon as possible.
  11532. If an update callback is already pending but hasn't happened yet, calls
  11533. to this method will be ignored.
  11534. It's thread-safe to call this method from any number of threads without
  11535. needing to worry about locking.
  11536. */
  11537. void triggerAsyncUpdate();
  11538. /** This will stop any pending updates from happening.
  11539. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  11540. callback happens, this will cancel the handleAsyncUpdate() callback.
  11541. Note that this method simply cancels the next callback - if a callback is already
  11542. in progress on a different thread, this won't block until it finishes, so there's
  11543. no guarantee that the callback isn't still running when you return from
  11544. */
  11545. void cancelPendingUpdate() throw();
  11546. /** If an update has been triggered and is pending, this will invoke it
  11547. synchronously.
  11548. Use this as a kind of "flush" operation - if an update is pending, the
  11549. handleAsyncUpdate() method will be called immediately; if no update is
  11550. pending, then nothing will be done.
  11551. Because this may invoke the callback, this method must only be called on
  11552. the main event thread.
  11553. */
  11554. void handleUpdateNowIfNeeded();
  11555. /** Returns true if there's an update callback in the pipeline. */
  11556. bool isUpdatePending() const throw();
  11557. /** Called back to do whatever your class needs to do.
  11558. This method is called by the message thread at the next convenient time
  11559. after the triggerAsyncUpdate() method has been called.
  11560. */
  11561. virtual void handleAsyncUpdate() = 0;
  11562. private:
  11563. ReferenceCountedObjectPtr<CallbackMessage> message;
  11564. Atomic<int>& getDeliveryFlag() const throw();
  11565. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AsyncUpdater);
  11566. };
  11567. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  11568. /*** End of inlined file: juce_AsyncUpdater.h ***/
  11569. /*** Start of inlined file: juce_ListenerList.h ***/
  11570. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  11571. #define __JUCE_LISTENERLIST_JUCEHEADER__
  11572. /**
  11573. Holds a set of objects and can invoke a member function callback on each object
  11574. in the set with a single call.
  11575. Use a ListenerList to manage a set of objects which need a callback, and you
  11576. can invoke a member function by simply calling call() or callChecked().
  11577. E.g.
  11578. @code
  11579. class MyListenerType
  11580. {
  11581. public:
  11582. void myCallbackMethod (int foo, bool bar);
  11583. };
  11584. ListenerList <MyListenerType> listeners;
  11585. listeners.add (someCallbackObjects...);
  11586. // This will invoke myCallbackMethod (1234, true) on each of the objects
  11587. // in the list...
  11588. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  11589. @endcode
  11590. If you add or remove listeners from the list during one of the callbacks - i.e. while
  11591. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  11592. will be mistakenly called after they've been removed, but it may mean that some of the
  11593. listeners could be called more than once, or not at all, depending on the list's order.
  11594. Sometimes, there's a chance that invoking one of the callbacks might result in the
  11595. list itself being deleted while it's still iterating - to survive this situation, you can
  11596. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  11597. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  11598. the list will check this after each callback to determine whether it should abort the
  11599. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  11600. which can be used to check when a Component has been deleted. See also
  11601. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  11602. */
  11603. template <class ListenerClass,
  11604. class ArrayType = Array <ListenerClass*> >
  11605. class ListenerList
  11606. {
  11607. // Horrible macros required to support VC6/7..
  11608. #ifndef DOXYGEN
  11609. #if JUCE_VC8_OR_EARLIER
  11610. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  11611. #define LL_PARAM(a) Q##a& param##a
  11612. #else
  11613. #define LL_TEMPLATE(a) typename P##a
  11614. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  11615. #endif
  11616. #endif
  11617. public:
  11618. /** Creates an empty list. */
  11619. ListenerList()
  11620. {
  11621. }
  11622. /** Destructor. */
  11623. ~ListenerList()
  11624. {
  11625. }
  11626. /** Adds a listener to the list.
  11627. A listener can only be added once, so if the listener is already in the list,
  11628. this method has no effect.
  11629. @see remove
  11630. */
  11631. void add (ListenerClass* const listenerToAdd)
  11632. {
  11633. // Listeners can't be null pointers!
  11634. jassert (listenerToAdd != 0);
  11635. if (listenerToAdd != 0)
  11636. listeners.addIfNotAlreadyThere (listenerToAdd);
  11637. }
  11638. /** Removes a listener from the list.
  11639. If the listener wasn't in the list, this has no effect.
  11640. */
  11641. void remove (ListenerClass* const listenerToRemove)
  11642. {
  11643. // Listeners can't be null pointers!
  11644. jassert (listenerToRemove != 0);
  11645. listeners.removeValue (listenerToRemove);
  11646. }
  11647. /** Returns the number of registered listeners. */
  11648. int size() const throw()
  11649. {
  11650. return listeners.size();
  11651. }
  11652. /** Returns true if any listeners are registered. */
  11653. bool isEmpty() const throw()
  11654. {
  11655. return listeners.size() == 0;
  11656. }
  11657. /** Clears the list. */
  11658. void clear()
  11659. {
  11660. listeners.clear();
  11661. }
  11662. /** Returns true if the specified listener has been added to the list. */
  11663. bool contains (ListenerClass* const listener) const throw()
  11664. {
  11665. return listeners.contains (listener);
  11666. }
  11667. /** Calls a member function on each listener in the list, with no parameters. */
  11668. void call (void (ListenerClass::*callbackFunction) ())
  11669. {
  11670. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  11671. }
  11672. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  11673. See the class description for info about writing a bail-out checker. */
  11674. template <class BailOutCheckerType>
  11675. void callChecked (const BailOutCheckerType& bailOutChecker,
  11676. void (ListenerClass::*callbackFunction) ())
  11677. {
  11678. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11679. (iter.getListener()->*callbackFunction) ();
  11680. }
  11681. /** Calls a member function on each listener in the list, with 1 parameter. */
  11682. template <LL_TEMPLATE(1)>
  11683. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  11684. {
  11685. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  11686. (iter.getListener()->*callbackFunction) (param1);
  11687. }
  11688. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  11689. See the class description for info about writing a bail-out checker. */
  11690. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  11691. void callChecked (const BailOutCheckerType& bailOutChecker,
  11692. void (ListenerClass::*callbackFunction) (P1),
  11693. LL_PARAM(1))
  11694. {
  11695. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11696. (iter.getListener()->*callbackFunction) (param1);
  11697. }
  11698. /** Calls a member function on each listener in the list, with 2 parameters. */
  11699. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  11700. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  11701. LL_PARAM(1), LL_PARAM(2))
  11702. {
  11703. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  11704. (iter.getListener()->*callbackFunction) (param1, param2);
  11705. }
  11706. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  11707. See the class description for info about writing a bail-out checker. */
  11708. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  11709. void callChecked (const BailOutCheckerType& bailOutChecker,
  11710. void (ListenerClass::*callbackFunction) (P1, P2),
  11711. LL_PARAM(1), LL_PARAM(2))
  11712. {
  11713. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11714. (iter.getListener()->*callbackFunction) (param1, param2);
  11715. }
  11716. /** Calls a member function on each listener in the list, with 3 parameters. */
  11717. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  11718. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  11719. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  11720. {
  11721. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  11722. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  11723. }
  11724. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  11725. See the class description for info about writing a bail-out checker. */
  11726. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  11727. void callChecked (const BailOutCheckerType& bailOutChecker,
  11728. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  11729. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  11730. {
  11731. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11732. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  11733. }
  11734. /** Calls a member function on each listener in the list, with 4 parameters. */
  11735. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  11736. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  11737. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  11738. {
  11739. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  11740. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  11741. }
  11742. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  11743. See the class description for info about writing a bail-out checker. */
  11744. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  11745. void callChecked (const BailOutCheckerType& bailOutChecker,
  11746. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  11747. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  11748. {
  11749. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11750. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  11751. }
  11752. /** Calls a member function on each listener in the list, with 5 parameters. */
  11753. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  11754. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  11755. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  11756. {
  11757. for (Iterator<DummyBailOutChecker, ThisType> iter (*this); iter.next();)
  11758. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  11759. }
  11760. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  11761. See the class description for info about writing a bail-out checker. */
  11762. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  11763. void callChecked (const BailOutCheckerType& bailOutChecker,
  11764. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  11765. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  11766. {
  11767. for (Iterator<BailOutCheckerType, ThisType> iter (*this); iter.next (bailOutChecker);)
  11768. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  11769. }
  11770. /** A dummy bail-out checker that always returns false.
  11771. See the ListenerList notes for more info about bail-out checkers.
  11772. */
  11773. class DummyBailOutChecker
  11774. {
  11775. public:
  11776. inline bool shouldBailOut() const throw() { return false; }
  11777. };
  11778. /** Iterates the listeners in a ListenerList. */
  11779. template <class BailOutCheckerType, class ListType>
  11780. class Iterator
  11781. {
  11782. public:
  11783. Iterator (const ListType& list_)
  11784. : list (list_), index (list_.size())
  11785. {}
  11786. ~Iterator() {}
  11787. bool next()
  11788. {
  11789. if (index <= 0)
  11790. return false;
  11791. const int listSize = list.size();
  11792. if (--index < listSize)
  11793. return true;
  11794. index = listSize - 1;
  11795. return index >= 0;
  11796. }
  11797. bool next (const BailOutCheckerType& bailOutChecker)
  11798. {
  11799. return (! bailOutChecker.shouldBailOut()) && next();
  11800. }
  11801. typename ListType::ListenerType* getListener() const throw()
  11802. {
  11803. return list.getListeners().getUnchecked (index);
  11804. }
  11805. private:
  11806. const ListType& list;
  11807. int index;
  11808. JUCE_DECLARE_NON_COPYABLE (Iterator);
  11809. };
  11810. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  11811. typedef ListenerClass ListenerType;
  11812. const ArrayType& getListeners() const throw() { return listeners; }
  11813. private:
  11814. ArrayType listeners;
  11815. JUCE_DECLARE_NON_COPYABLE (ListenerList);
  11816. #undef LL_TEMPLATE
  11817. #undef LL_PARAM
  11818. };
  11819. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  11820. /*** End of inlined file: juce_ListenerList.h ***/
  11821. /**
  11822. Represents a shared variant value.
  11823. A Value object contains a reference to a var object, and can get and set its value.
  11824. Listeners can be attached to be told when the value is changed.
  11825. The Value class is a wrapper around a shared, reference-counted underlying data
  11826. object - this means that multiple Value objects can all refer to the same piece of
  11827. data, allowing all of them to be notified when any of them changes it.
  11828. When you create a Value with its default constructor, it acts as a wrapper around a
  11829. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  11830. you can map the Value onto any kind of underlying data.
  11831. */
  11832. class JUCE_API Value
  11833. {
  11834. public:
  11835. /** Creates an empty Value, containing a void var. */
  11836. Value();
  11837. /** Creates a Value that refers to the same value as another one.
  11838. Note that this doesn't make a copy of the other value - both this and the other
  11839. Value will share the same underlying value, so that when either one alters it, both
  11840. will see it change.
  11841. */
  11842. Value (const Value& other);
  11843. /** Creates a Value that is set to the specified value. */
  11844. explicit Value (const var& initialValue);
  11845. /** Destructor. */
  11846. ~Value();
  11847. /** Returns the current value. */
  11848. const var getValue() const;
  11849. /** Returns the current value. */
  11850. operator const var() const;
  11851. /** Returns the value as a string.
  11852. This is alternative to writing things like "myValue.getValue().toString()".
  11853. */
  11854. const String toString() const;
  11855. /** Sets the current value.
  11856. You can also use operator= to set the value.
  11857. If there are any listeners registered, they will be notified of the
  11858. change asynchronously.
  11859. */
  11860. void setValue (const var& newValue);
  11861. /** Sets the current value.
  11862. This is the same as calling setValue().
  11863. If there are any listeners registered, they will be notified of the
  11864. change asynchronously.
  11865. */
  11866. Value& operator= (const var& newValue);
  11867. /** Makes this object refer to the same underlying ValueSource as another one.
  11868. Once this object has been connected to another one, changing either one
  11869. will update the other.
  11870. Existing listeners will still be registered after you call this method, and
  11871. they'll continue to receive messages when the new value changes.
  11872. */
  11873. void referTo (const Value& valueToReferTo);
  11874. /** Returns true if this value and the other one are references to the same value.
  11875. */
  11876. bool refersToSameSourceAs (const Value& other) const;
  11877. /** Compares two values.
  11878. This is a compare-by-value comparison, so is effectively the same as
  11879. saying (this->getValue() == other.getValue()).
  11880. */
  11881. bool operator== (const Value& other) const;
  11882. /** Compares two values.
  11883. This is a compare-by-value comparison, so is effectively the same as
  11884. saying (this->getValue() != other.getValue()).
  11885. */
  11886. bool operator!= (const Value& other) const;
  11887. /** Receives callbacks when a Value object changes.
  11888. @see Value::addListener
  11889. */
  11890. class JUCE_API Listener
  11891. {
  11892. public:
  11893. Listener() {}
  11894. virtual ~Listener() {}
  11895. /** Called when a Value object is changed.
  11896. Note that the Value object passed as a parameter may not be exactly the same
  11897. object that you registered the listener with - it might be a copy that refers
  11898. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  11899. */
  11900. virtual void valueChanged (Value& value) = 0;
  11901. };
  11902. /** Adds a listener to receive callbacks when the value changes.
  11903. The listener is added to this specific Value object, and not to the shared
  11904. object that it refers to. When this object is deleted, all the listeners will
  11905. be lost, even if other references to the same Value still exist. So when you're
  11906. adding a listener, make sure that you add it to a ValueTree instance that will last
  11907. for as long as you need the listener. In general, you'd never want to add a listener
  11908. to a local stack-based ValueTree, but more likely to one that's a member variable.
  11909. @see removeListener
  11910. */
  11911. void addListener (Listener* listener);
  11912. /** Removes a listener that was previously added with addListener(). */
  11913. void removeListener (Listener* listener);
  11914. /**
  11915. Used internally by the Value class as the base class for its shared value objects.
  11916. The Value class is essentially a reference-counted pointer to a shared instance
  11917. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  11918. ValueSource classes to allow Value objects to represent your own custom data items.
  11919. */
  11920. class JUCE_API ValueSource : public ReferenceCountedObject,
  11921. public AsyncUpdater
  11922. {
  11923. public:
  11924. ValueSource();
  11925. virtual ~ValueSource();
  11926. /** Returns the current value of this object. */
  11927. virtual const var getValue() const = 0;
  11928. /** Changes the current value.
  11929. This must also trigger a change message if the value actually changes.
  11930. */
  11931. virtual void setValue (const var& newValue) = 0;
  11932. /** Delivers a change message to all the listeners that are registered with
  11933. this value.
  11934. If dispatchSynchronously is true, the method will call all the listeners
  11935. before returning; otherwise it'll dispatch a message and make the call later.
  11936. */
  11937. void sendChangeMessage (bool dispatchSynchronously);
  11938. protected:
  11939. friend class Value;
  11940. SortedSet <Value*> valuesWithListeners;
  11941. void handleAsyncUpdate();
  11942. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueSource);
  11943. };
  11944. /** Creates a Value object that uses this valueSource object as its underlying data. */
  11945. explicit Value (ValueSource* valueSource);
  11946. /** Returns the ValueSource that this value is referring to. */
  11947. ValueSource& getValueSource() throw() { return *value; }
  11948. private:
  11949. friend class ValueSource;
  11950. ReferenceCountedObjectPtr <ValueSource> value;
  11951. ListenerList <Listener> listeners;
  11952. void callListeners();
  11953. // This is disallowed to avoid confusion about whether it should
  11954. // do a by-value or by-reference copy.
  11955. Value& operator= (const Value& other);
  11956. };
  11957. /** Writes a Value to an OutputStream as a UTF8 string. */
  11958. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  11959. /** This typedef is just for compatibility with old code - newer code should use the Value::Listener class directly. */
  11960. typedef Value::Listener ValueListener;
  11961. #endif // __JUCE_VALUE_JUCEHEADER__
  11962. /*** End of inlined file: juce_Value.h ***/
  11963. #endif
  11964. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  11965. /*** Start of inlined file: juce_ValueTree.h ***/
  11966. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  11967. #define __JUCE_VALUETREE_JUCEHEADER__
  11968. /*** Start of inlined file: juce_UndoManager.h ***/
  11969. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  11970. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  11971. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  11972. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  11973. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  11974. /*** Start of inlined file: juce_ChangeListener.h ***/
  11975. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  11976. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  11977. class ChangeBroadcaster;
  11978. /**
  11979. Receives change event callbacks that are sent out by a ChangeBroadcaster.
  11980. A ChangeBroadcaster keeps a set of listeners to which it broadcasts a message when
  11981. the ChangeBroadcaster::sendChangeMessage() method is called. A subclass of
  11982. ChangeListener is used to receive these callbacks.
  11983. Note that the major difference between an ActionListener and a ChangeListener
  11984. is that for a ChangeListener, multiple changes will be coalesced into fewer
  11985. callbacks, but ActionListeners perform one callback for every event posted.
  11986. @see ChangeBroadcaster, ActionListener
  11987. */
  11988. class JUCE_API ChangeListener
  11989. {
  11990. public:
  11991. /** Destructor. */
  11992. virtual ~ChangeListener() {}
  11993. /** Your subclass should implement this method to receive the callback.
  11994. @param source the ChangeBroadcaster that triggered the callback.
  11995. */
  11996. virtual void changeListenerCallback (ChangeBroadcaster* source) = 0;
  11997. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  11998. // This method's signature has changed to take a ChangeBroadcaster parameter - please update your code!
  11999. private: virtual int changeListenerCallback (void*) { return 0; }
  12000. #endif
  12001. };
  12002. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  12003. /*** End of inlined file: juce_ChangeListener.h ***/
  12004. /**
  12005. Holds a list of ChangeListeners, and sends messages to them when instructed.
  12006. @see ChangeListener
  12007. */
  12008. class JUCE_API ChangeBroadcaster
  12009. {
  12010. public:
  12011. /** Creates an ChangeBroadcaster. */
  12012. ChangeBroadcaster() throw();
  12013. /** Destructor. */
  12014. virtual ~ChangeBroadcaster();
  12015. /** Registers a listener to receive change callbacks from this broadcaster.
  12016. Trying to add a listener that's already on the list will have no effect.
  12017. */
  12018. void addChangeListener (ChangeListener* listener);
  12019. /** Unregisters a listener from the list.
  12020. If the listener isn't on the list, this won't have any effect.
  12021. */
  12022. void removeChangeListener (ChangeListener* listener);
  12023. /** Removes all listeners from the list. */
  12024. void removeAllChangeListeners();
  12025. /** Causes an asynchronous change message to be sent to all the registered listeners.
  12026. The message will be delivered asynchronously by the main message thread, so this
  12027. method will return immediately. To call the listeners synchronously use
  12028. sendSynchronousChangeMessage().
  12029. */
  12030. void sendChangeMessage();
  12031. /** Sends a synchronous change message to all the registered listeners.
  12032. This will immediately call all the listeners that are registered. For thread-safety
  12033. reasons, you must only call this method on the main message thread.
  12034. @see dispatchPendingMessages
  12035. */
  12036. void sendSynchronousChangeMessage();
  12037. /** If a change message has been sent but not yet dispatched, this will call
  12038. sendSynchronousChangeMessage() to make the callback immediately.
  12039. For thread-safety reasons, you must only call this method on the main message thread.
  12040. */
  12041. void dispatchPendingMessages();
  12042. private:
  12043. class ChangeBroadcasterCallback : public AsyncUpdater
  12044. {
  12045. public:
  12046. ChangeBroadcasterCallback();
  12047. void handleAsyncUpdate();
  12048. ChangeBroadcaster* owner;
  12049. };
  12050. friend class ChangeBroadcasterCallback;
  12051. ChangeBroadcasterCallback callback;
  12052. ListenerList <ChangeListener> changeListeners;
  12053. void callListeners();
  12054. JUCE_DECLARE_NON_COPYABLE (ChangeBroadcaster);
  12055. };
  12056. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  12057. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  12058. /*** Start of inlined file: juce_UndoableAction.h ***/
  12059. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  12060. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  12061. /**
  12062. Used by the UndoManager class to store an action which can be done
  12063. and undone.
  12064. @see UndoManager
  12065. */
  12066. class JUCE_API UndoableAction
  12067. {
  12068. protected:
  12069. /** Creates an action. */
  12070. UndoableAction() throw() {}
  12071. public:
  12072. /** Destructor. */
  12073. virtual ~UndoableAction() {}
  12074. /** Overridden by a subclass to perform the action.
  12075. This method is called by the UndoManager, and shouldn't be used directly by
  12076. applications.
  12077. Be careful not to make any calls in a perform() method that could call
  12078. recursively back into the UndoManager::perform() method
  12079. @returns true if the action could be performed.
  12080. @see UndoManager::perform
  12081. */
  12082. virtual bool perform() = 0;
  12083. /** Overridden by a subclass to undo the action.
  12084. This method is called by the UndoManager, and shouldn't be used directly by
  12085. applications.
  12086. Be careful not to make any calls in an undo() method that could call
  12087. recursively back into the UndoManager::perform() method
  12088. @returns true if the action could be undone without any errors.
  12089. @see UndoManager::perform
  12090. */
  12091. virtual bool undo() = 0;
  12092. /** Returns a value to indicate how much memory this object takes up.
  12093. Because the UndoManager keeps a list of UndoableActions, this is used
  12094. to work out how much space each one will take up, so that the UndoManager
  12095. can work out how many to keep.
  12096. The default value returned here is 10 - units are arbitrary and
  12097. don't have to be accurate.
  12098. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  12099. UndoManager::setMaxNumberOfStoredUnits
  12100. */
  12101. virtual int getSizeInUnits() { return 10; }
  12102. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  12103. If possible, this method should create and return a single action that does the same job as
  12104. this one followed by the supplied action.
  12105. If it's not possible to merge the two actions, the method should return zero.
  12106. */
  12107. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return 0; }
  12108. };
  12109. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  12110. /*** End of inlined file: juce_UndoableAction.h ***/
  12111. /**
  12112. Manages a list of undo/redo commands.
  12113. An UndoManager object keeps a list of past actions and can use these actions
  12114. to move backwards and forwards through an undo history.
  12115. To use it, create subclasses of UndoableAction which perform all the
  12116. actions you need, then when you need to actually perform an action, create one
  12117. and pass it to the UndoManager's perform() method.
  12118. The manager also uses the concept of 'transactions' to group the actions
  12119. together - all actions performed between calls to beginNewTransaction() are
  12120. grouped together and are all undone/redone as a group.
  12121. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  12122. when actions are performed or undone.
  12123. @see UndoableAction
  12124. */
  12125. class JUCE_API UndoManager : public ChangeBroadcaster
  12126. {
  12127. public:
  12128. /** Creates an UndoManager.
  12129. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  12130. to indicate how much storage it takes up
  12131. (UndoableAction::getSizeInUnits()), so this
  12132. lets you specify the maximum total number of
  12133. units that the undomanager is allowed to
  12134. keep in memory before letting the older actions
  12135. drop off the end of the list.
  12136. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  12137. that will be kept, even if this involves exceeding
  12138. the amount of space specified in maxNumberOfUnitsToKeep
  12139. */
  12140. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  12141. int minimumTransactionsToKeep = 30);
  12142. /** Destructor. */
  12143. ~UndoManager();
  12144. /** Deletes all stored actions in the list. */
  12145. void clearUndoHistory();
  12146. /** Returns the current amount of space to use for storing UndoableAction objects.
  12147. @see setMaxNumberOfStoredUnits
  12148. */
  12149. int getNumberOfUnitsTakenUpByStoredCommands() const;
  12150. /** Sets the amount of space that can be used for storing UndoableAction objects.
  12151. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  12152. to indicate how much storage it takes up
  12153. (UndoableAction::getSizeInUnits()), so this
  12154. lets you specify the maximum total number of
  12155. units that the undomanager is allowed to
  12156. keep in memory before letting the older actions
  12157. drop off the end of the list.
  12158. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  12159. that will be kept, even if this involves exceeding
  12160. the amount of space specified in maxNumberOfUnitsToKeep
  12161. @see getNumberOfUnitsTakenUpByStoredCommands
  12162. */
  12163. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  12164. int minimumTransactionsToKeep);
  12165. /** Performs an action and adds it to the undo history list.
  12166. @param action the action to perform - this will be deleted by the UndoManager
  12167. when no longer needed
  12168. @param actionName if this string is non-empty, the current transaction will be
  12169. given this name; if it's empty, the current transaction name will
  12170. be left unchanged. See setCurrentTransactionName()
  12171. @returns true if the command succeeds - see UndoableAction::perform
  12172. @see beginNewTransaction
  12173. */
  12174. bool perform (UndoableAction* action,
  12175. const String& actionName = String::empty);
  12176. /** Starts a new group of actions that together will be treated as a single transaction.
  12177. All actions that are passed to the perform() method between calls to this
  12178. method are grouped together and undone/redone together by a single call to
  12179. undo() or redo().
  12180. @param actionName a description of the transaction that is about to be
  12181. performed
  12182. */
  12183. void beginNewTransaction (const String& actionName = String::empty);
  12184. /** Changes the name stored for the current transaction.
  12185. Each transaction is given a name when the beginNewTransaction() method is
  12186. called, but this can be used to change that name without starting a new
  12187. transaction.
  12188. */
  12189. void setCurrentTransactionName (const String& newName);
  12190. /** Returns true if there's at least one action in the list to undo.
  12191. @see getUndoDescription, undo, canRedo
  12192. */
  12193. bool canUndo() const;
  12194. /** Returns the description of the transaction that would be next to get undone.
  12195. The description returned is the one that was passed into beginNewTransaction
  12196. before the set of actions was performed.
  12197. @see undo
  12198. */
  12199. const String getUndoDescription() const;
  12200. /** Tries to roll-back the last transaction.
  12201. @returns true if the transaction can be undone, and false if it fails, or
  12202. if there aren't any transactions to undo
  12203. */
  12204. bool undo();
  12205. /** Tries to roll-back any actions that were added to the current transaction.
  12206. This will perform an undo() only if there are some actions in the undo list
  12207. that were added after the last call to beginNewTransaction().
  12208. This is useful because it lets you call beginNewTransaction(), then
  12209. perform an operation which may or may not actually perform some actions, and
  12210. then call this method to get rid of any actions that might have been done
  12211. without it rolling back the previous transaction if nothing was actually
  12212. done.
  12213. @returns true if any actions were undone.
  12214. */
  12215. bool undoCurrentTransactionOnly();
  12216. /** Returns a list of the UndoableAction objects that have been performed during the
  12217. transaction that is currently open.
  12218. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  12219. were to be called now.
  12220. The first item in the list is the earliest action performed.
  12221. */
  12222. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  12223. /** Returns the number of UndoableAction objects that have been performed during the
  12224. transaction that is currently open.
  12225. @see getActionsInCurrentTransaction
  12226. */
  12227. int getNumActionsInCurrentTransaction() const;
  12228. /** Returns true if there's at least one action in the list to redo.
  12229. @see getRedoDescription, redo, canUndo
  12230. */
  12231. bool canRedo() const;
  12232. /** Returns the description of the transaction that would be next to get redone.
  12233. The description returned is the one that was passed into beginNewTransaction
  12234. before the set of actions was performed.
  12235. @see redo
  12236. */
  12237. const String getRedoDescription() const;
  12238. /** Tries to redo the last transaction that was undone.
  12239. @returns true if the transaction can be redone, and false if it fails, or
  12240. if there aren't any transactions to redo
  12241. */
  12242. bool redo();
  12243. private:
  12244. OwnedArray <OwnedArray <UndoableAction> > transactions;
  12245. StringArray transactionNames;
  12246. String currentTransactionName;
  12247. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  12248. bool newTransaction, reentrancyCheck;
  12249. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UndoManager);
  12250. };
  12251. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  12252. /*** End of inlined file: juce_UndoManager.h ***/
  12253. /**
  12254. A powerful tree structure that can be used to hold free-form data, and which can
  12255. handle its own undo and redo behaviour.
  12256. A ValueTree contains a list of named properties as var objects, and also holds
  12257. any number of sub-trees.
  12258. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  12259. they're simply a lightweight reference to a shared data container. Creating a copy
  12260. of another ValueTree simply creates a new reference to the same underlying object - to
  12261. make a separate, deep copy of a tree you should explicitly call createCopy().
  12262. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  12263. and much of the structure of a ValueTree is similar to an XmlElement tree.
  12264. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  12265. contain text elements, the conversion works well and makes a good serialisation
  12266. format. They can also be serialised to a binary format, which is very fast and compact.
  12267. All the methods that change data take an optional UndoManager, which will be used
  12268. to track any changes to the object. For this to work, you have to be careful to
  12269. consistently always use the same UndoManager for all operations to any node inside
  12270. the tree.
  12271. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  12272. one tree to another, be careful to always remove it first, before adding it. This
  12273. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  12274. assertions if you try to do anything dangerous, but there are still plenty of ways it
  12275. could go wrong.
  12276. Listeners can be added to a ValueTree to be told when properies change and when
  12277. nodes are added or removed.
  12278. @see var, XmlElement
  12279. */
  12280. class JUCE_API ValueTree
  12281. {
  12282. public:
  12283. /** Creates an empty, invalid ValueTree.
  12284. A ValueTree that is created with this constructor can't actually be used for anything,
  12285. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  12286. To create a real one, use the constructor that takes a string.
  12287. @see ValueTree::invalid
  12288. */
  12289. ValueTree() throw();
  12290. /** Creates an empty ValueTree with the given type name.
  12291. Like an XmlElement, each ValueTree node has a type, which you can access with
  12292. getType() and hasType().
  12293. */
  12294. explicit ValueTree (const Identifier& type);
  12295. /** Creates a reference to another ValueTree. */
  12296. ValueTree (const ValueTree& other);
  12297. /** Makes this object reference another node. */
  12298. ValueTree& operator= (const ValueTree& other);
  12299. /** Destructor. */
  12300. ~ValueTree();
  12301. /** Returns true if both this and the other tree node refer to the same underlying structure.
  12302. Note that this isn't a value comparison - two independently-created trees which
  12303. contain identical data are not considered equal.
  12304. */
  12305. bool operator== (const ValueTree& other) const throw();
  12306. /** Returns true if this and the other node refer to different underlying structures.
  12307. Note that this isn't a value comparison - two independently-created trees which
  12308. contain identical data are not considered equal.
  12309. */
  12310. bool operator!= (const ValueTree& other) const throw();
  12311. /** Performs a deep comparison between the properties and children of two trees.
  12312. If all the properties and children of the two trees are the same (recursively), this
  12313. returns true.
  12314. The normal operator==() only checks whether two trees refer to the same shared data
  12315. structure, so use this method if you need to do a proper value comparison.
  12316. */
  12317. bool isEquivalentTo (const ValueTree& other) const;
  12318. /** Returns true if this node refers to some valid data.
  12319. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  12320. call to getChild().
  12321. */
  12322. bool isValid() const { return object != 0; }
  12323. /** Returns a deep copy of this tree and all its sub-nodes. */
  12324. ValueTree createCopy() const;
  12325. /** Returns the type of this node.
  12326. The type is specified when the ValueTree is created.
  12327. @see hasType
  12328. */
  12329. const Identifier getType() const;
  12330. /** Returns true if the node has this type.
  12331. The comparison is case-sensitive.
  12332. */
  12333. bool hasType (const Identifier& typeName) const;
  12334. /** Returns the value of a named property.
  12335. If no such property has been set, this will return a void variant.
  12336. You can also use operator[] to get a property.
  12337. @see var, setProperty, hasProperty
  12338. */
  12339. const var& getProperty (const Identifier& name) const;
  12340. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  12341. If no such property has been set, this will return the value of defaultReturnValue.
  12342. You can also use operator[] and getProperty to get a property.
  12343. @see var, getProperty, setProperty, hasProperty
  12344. */
  12345. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  12346. /** Returns the value of a named property.
  12347. If no such property has been set, this will return a void variant. This is the same as
  12348. calling getProperty().
  12349. @see getProperty
  12350. */
  12351. const var& operator[] (const Identifier& name) const;
  12352. /** Changes a named property of the node.
  12353. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12354. so that this change can be undone.
  12355. @see var, getProperty, removeProperty
  12356. */
  12357. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  12358. /** Returns true if the node contains a named property. */
  12359. bool hasProperty (const Identifier& name) const;
  12360. /** Removes a property from the node.
  12361. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12362. so that this change can be undone.
  12363. */
  12364. void removeProperty (const Identifier& name, UndoManager* undoManager);
  12365. /** Removes all properties from the node.
  12366. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12367. so that this change can be undone.
  12368. */
  12369. void removeAllProperties (UndoManager* undoManager);
  12370. /** Returns the total number of properties that the node contains.
  12371. @see getProperty.
  12372. */
  12373. int getNumProperties() const;
  12374. /** Returns the identifier of the property with a given index.
  12375. @see getNumProperties
  12376. */
  12377. const Identifier getPropertyName (int index) const;
  12378. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  12379. The Value object will maintain a reference to this tree, and will use the undo manager when
  12380. it needs to change the value. Attaching a Value::Listener to the value object will provide
  12381. callbacks whenever the property changes.
  12382. */
  12383. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  12384. /** Returns the number of child nodes belonging to this one.
  12385. @see getChild
  12386. */
  12387. int getNumChildren() const;
  12388. /** Returns one of this node's child nodes.
  12389. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  12390. whether a node is valid).
  12391. */
  12392. ValueTree getChild (int index) const;
  12393. /** Returns the first child node with the speficied type name.
  12394. If no such node is found, it'll return an invalid node. (See isValid() to find out
  12395. whether a node is valid).
  12396. @see getOrCreateChildWithName
  12397. */
  12398. ValueTree getChildWithName (const Identifier& type) const;
  12399. /** Returns the first child node with the speficied type name, creating and adding
  12400. a child with this name if there wasn't already one there.
  12401. The only time this will return an invalid object is when the object that you're calling
  12402. the method on is itself invalid.
  12403. @see getChildWithName
  12404. */
  12405. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  12406. /** Looks for the first child node that has the speficied property value.
  12407. This will scan the child nodes in order, until it finds one that has property that matches
  12408. the specified value.
  12409. If no such node is found, it'll return an invalid node. (See isValid() to find out
  12410. whether a node is valid).
  12411. */
  12412. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  12413. /** Adds a child to this node.
  12414. Make sure that the child is removed from any former parent node before calling this, or
  12415. you'll hit an assertion.
  12416. If the index is < 0 or greater than the current number of child nodes, the new node will
  12417. be added at the end of the list.
  12418. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12419. so that this change can be undone.
  12420. */
  12421. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  12422. /** Removes the specified child from this node's child-list.
  12423. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12424. so that this change can be undone.
  12425. */
  12426. void removeChild (const ValueTree& child, UndoManager* undoManager);
  12427. /** Removes a child from this node's child-list.
  12428. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12429. so that this change can be undone.
  12430. */
  12431. void removeChild (int childIndex, UndoManager* undoManager);
  12432. /** Removes all child-nodes from this node.
  12433. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  12434. so that this change can be undone.
  12435. */
  12436. void removeAllChildren (UndoManager* undoManager);
  12437. /** Moves one of the children to a different index.
  12438. This will move the child to a specified index, shuffling along any intervening
  12439. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  12440. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  12441. @param currentIndex the index of the item to be moved. If this isn't a
  12442. valid index, then nothing will be done
  12443. @param newIndex the index at which you'd like this item to end up. If this
  12444. is less than zero, the value will be moved to the end
  12445. of the list
  12446. @param undoManager the optional UndoManager to use to store this transaction
  12447. */
  12448. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  12449. /** Returns true if this node is anywhere below the specified parent node.
  12450. This returns true if the node is a child-of-a-child, as well as a direct child.
  12451. */
  12452. bool isAChildOf (const ValueTree& possibleParent) const;
  12453. /** Returns the index of a child item in this parent.
  12454. If the child isn't found, this returns -1.
  12455. */
  12456. int indexOf (const ValueTree& child) const;
  12457. /** Returns the parent node that contains this one.
  12458. If the node has no parent, this will return an invalid node. (See isValid() to find out
  12459. whether a node is valid).
  12460. */
  12461. ValueTree getParent() const;
  12462. /** Returns one of this node's siblings in its parent's child list.
  12463. The delta specifies how far to move through the list, so a value of 1 would return the node
  12464. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  12465. If the requested position is beyond the range of available nodes, this will return ValueTree::invalid.
  12466. */
  12467. ValueTree getSibling (int delta) const;
  12468. /** Creates an XmlElement that holds a complete image of this node and all its children.
  12469. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  12470. be used to recreate a similar node by calling fromXml()
  12471. @see fromXml
  12472. */
  12473. XmlElement* createXml() const;
  12474. /** Tries to recreate a node from its XML representation.
  12475. This isn't designed to cope with random XML data - for a sensible result, it should only
  12476. be fed XML that was created by the createXml() method.
  12477. */
  12478. static ValueTree fromXml (const XmlElement& xml);
  12479. /** Stores this tree (and all its children) in a binary format.
  12480. Once written, the data can be read back with readFromStream().
  12481. It's much faster to load/save your tree in binary form than as XML, but
  12482. obviously isn't human-readable.
  12483. */
  12484. void writeToStream (OutputStream& output);
  12485. /** Reloads a tree from a stream that was written with writeToStream(). */
  12486. static ValueTree readFromStream (InputStream& input);
  12487. /** Reloads a tree from a data block that was written with writeToStream(). */
  12488. static ValueTree readFromData (const void* data, size_t numBytes);
  12489. /** Listener class for events that happen to a ValueTree.
  12490. To get events from a ValueTree, make your class implement this interface, and use
  12491. ValueTree::addListener() and ValueTree::removeListener() to register it.
  12492. */
  12493. class JUCE_API Listener
  12494. {
  12495. public:
  12496. /** Destructor. */
  12497. virtual ~Listener() {}
  12498. /** This method is called when a property of this node (or of one of its sub-nodes) has
  12499. changed.
  12500. The tree parameter indicates which tree has had its property changed, and the property
  12501. parameter indicates the property.
  12502. Note that when you register a listener to a tree, it will receive this callback for
  12503. property changes in that tree, and also for any of its children, (recursively, at any depth).
  12504. If your tree has sub-trees but you only want to know about changes to the top level tree,
  12505. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  12506. */
  12507. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  12508. const Identifier& property) = 0;
  12509. /** This method is called when a child sub-tree is added.
  12510. Note that when you register a listener to a tree, it will receive this callback for
  12511. child changes in both that tree and any of its children, (recursively, at any depth).
  12512. If your tree has sub-trees but you only want to know about changes to the top level tree,
  12513. just check the parentTree parameter to make sure it's the one that you're interested in.
  12514. */
  12515. virtual void valueTreeChildAdded (ValueTree& parentTree,
  12516. ValueTree& childWhichHasBeenAdded) = 0;
  12517. /** This method is called when a child sub-tree is removed.
  12518. Note that when you register a listener to a tree, it will receive this callback for
  12519. child changes in both that tree and any of its children, (recursively, at any depth).
  12520. If your tree has sub-trees but you only want to know about changes to the top level tree,
  12521. just check the parentTree parameter to make sure it's the one that you're interested in.
  12522. */
  12523. virtual void valueTreeChildRemoved (ValueTree& parentTree,
  12524. ValueTree& childWhichHasBeenRemoved) = 0;
  12525. /** This method is called when a tree's children have been re-shuffled.
  12526. Note that when you register a listener to a tree, it will receive this callback for
  12527. child changes in both that tree and any of its children, (recursively, at any depth).
  12528. If your tree has sub-trees but you only want to know about changes to the top level tree,
  12529. just check the parameter to make sure it's the tree that you're interested in.
  12530. */
  12531. virtual void valueTreeChildOrderChanged (ValueTree& parentTreeWhoseChildrenHaveMoved) = 0;
  12532. /** This method is called when a tree has been added or removed from a parent node.
  12533. This callback happens when the tree to which the listener was registered is added or
  12534. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  12535. the listener is registered, and not to any of its children.
  12536. */
  12537. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  12538. };
  12539. /** Adds a listener to receive callbacks when this node is changed.
  12540. The listener is added to this specific ValueTree object, and not to the shared
  12541. object that it refers to. When this object is deleted, all the listeners will
  12542. be lost, even if other references to the same ValueTree still exist. And if you
  12543. use the operator= to make this refer to a different ValueTree, any listeners will
  12544. begin listening to changes to the new tree instead of the old one.
  12545. When you're adding a listener, make sure that you add it to a ValueTree instance that
  12546. will last for as long as you need the listener. In general, you'd never want to add a
  12547. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  12548. @see removeListener
  12549. */
  12550. void addListener (Listener* listener);
  12551. /** Removes a listener that was previously added with addListener(). */
  12552. void removeListener (Listener* listener);
  12553. /** This method uses a comparator object to sort the tree's children into order.
  12554. The object provided must have a method of the form:
  12555. @code
  12556. int compareElements (const ValueTree& first, const ValueTree& second);
  12557. @endcode
  12558. ..and this method must return:
  12559. - a value of < 0 if the first comes before the second
  12560. - a value of 0 if the two objects are equivalent
  12561. - a value of > 0 if the second comes before the first
  12562. To improve performance, the compareElements() method can be declared as static or const.
  12563. @param comparator the comparator to use for comparing elements.
  12564. @param undoManager optional UndoManager for storing the changes
  12565. @param retainOrderOfEquivalentItems if this is true, then items which the comparator says are
  12566. equivalent will be kept in the order in which they currently appear in the array.
  12567. This is slower to perform, but may be important in some cases. If it's false, a
  12568. faster algorithm is used, but equivalent elements may be rearranged.
  12569. */
  12570. template <typename ElementComparator>
  12571. void sort (ElementComparator& comparator, UndoManager* undoManager, bool retainOrderOfEquivalentItems)
  12572. {
  12573. if (object != 0)
  12574. {
  12575. ReferenceCountedArray <SharedObject> sortedList (object->children);
  12576. ComparatorAdapter <ElementComparator> adapter (comparator);
  12577. sortedList.sort (adapter, retainOrderOfEquivalentItems);
  12578. object->reorderChildren (sortedList, undoManager);
  12579. }
  12580. }
  12581. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  12582. This invalid object is equivalent to ValueTree created with its default constructor.
  12583. */
  12584. static const ValueTree invalid;
  12585. private:
  12586. class SetPropertyAction;
  12587. friend class SetPropertyAction;
  12588. class AddOrRemoveChildAction;
  12589. friend class AddOrRemoveChildAction;
  12590. class MoveChildAction;
  12591. friend class MoveChildAction;
  12592. class JUCE_API SharedObject : public ReferenceCountedObject
  12593. {
  12594. public:
  12595. explicit SharedObject (const Identifier& type);
  12596. SharedObject (const SharedObject& other);
  12597. ~SharedObject();
  12598. const Identifier type;
  12599. NamedValueSet properties;
  12600. ReferenceCountedArray <SharedObject> children;
  12601. SortedSet <ValueTree*> valueTreesWithListeners;
  12602. SharedObject* parent;
  12603. void sendPropertyChangeMessage (const Identifier& property);
  12604. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  12605. void sendChildAddedMessage (ValueTree& parent, ValueTree& child);
  12606. void sendChildAddedMessage (ValueTree child);
  12607. void sendChildRemovedMessage (ValueTree& parent, ValueTree& child);
  12608. void sendChildRemovedMessage (ValueTree child);
  12609. void sendChildOrderChangedMessage (ValueTree& parent);
  12610. void sendChildOrderChangedMessage();
  12611. void sendParentChangeMessage();
  12612. const var& getProperty (const Identifier& name) const;
  12613. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  12614. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  12615. bool hasProperty (const Identifier& name) const;
  12616. void removeProperty (const Identifier& name, UndoManager*);
  12617. void removeAllProperties (UndoManager*);
  12618. bool isAChildOf (const SharedObject* possibleParent) const;
  12619. int indexOf (const ValueTree& child) const;
  12620. ValueTree getChildWithName (const Identifier& type) const;
  12621. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  12622. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  12623. void addChild (SharedObject* child, int index, UndoManager*);
  12624. void removeChild (int childIndex, UndoManager*);
  12625. void removeAllChildren (UndoManager*);
  12626. void moveChild (int currentIndex, int newIndex, UndoManager*);
  12627. void reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager*);
  12628. bool isEquivalentTo (const SharedObject& other) const;
  12629. XmlElement* createXml() const;
  12630. private:
  12631. SharedObject& operator= (const SharedObject&);
  12632. JUCE_LEAK_DETECTOR (SharedObject);
  12633. };
  12634. template <typename ElementComparator>
  12635. class ComparatorAdapter
  12636. {
  12637. public:
  12638. ComparatorAdapter (ElementComparator& comparator_) throw() : comparator (comparator_) {}
  12639. int compareElements (SharedObject* const first, SharedObject* const second)
  12640. {
  12641. return comparator.compareElements (ValueTree (first), ValueTree (second));
  12642. }
  12643. private:
  12644. ElementComparator& comparator;
  12645. JUCE_DECLARE_NON_COPYABLE (ComparatorAdapter);
  12646. };
  12647. friend class SharedObject;
  12648. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  12649. SharedObjectPtr object;
  12650. ListenerList <Listener> listeners;
  12651. #if JUCE_MSVC && ! DOXYGEN
  12652. public: // (workaround for VC6)
  12653. #endif
  12654. explicit ValueTree (SharedObject*);
  12655. };
  12656. #endif // __JUCE_VALUETREE_JUCEHEADER__
  12657. /*** End of inlined file: juce_ValueTree.h ***/
  12658. #endif
  12659. #ifndef __JUCE_VARIANT_JUCEHEADER__
  12660. #endif
  12661. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  12662. /*** Start of inlined file: juce_FileLogger.h ***/
  12663. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  12664. #define __JUCE_FILELOGGER_JUCEHEADER__
  12665. /**
  12666. A simple implemenation of a Logger that writes to a file.
  12667. @see Logger
  12668. */
  12669. class JUCE_API FileLogger : public Logger
  12670. {
  12671. public:
  12672. /** Creates a FileLogger for a given file.
  12673. @param fileToWriteTo the file that to use - new messages will be appended
  12674. to the file. If the file doesn't exist, it will be created,
  12675. along with any parent directories that are needed.
  12676. @param welcomeMessage when opened, the logger will write a header to the log, along
  12677. with the current date and time, and this welcome message
  12678. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  12679. but is larger than this number of bytes, then the start of the
  12680. file will be truncated to keep the size down. This prevents a log
  12681. file getting ridiculously large over time. The file will be truncated
  12682. at a new-line boundary. If this value is less than zero, no size limit
  12683. will be imposed; if it's zero, the file will always be deleted. Note that
  12684. the size is only checked once when this object is created - any logging
  12685. that is done later will be appended without any checking
  12686. */
  12687. FileLogger (const File& fileToWriteTo,
  12688. const String& welcomeMessage,
  12689. const int maxInitialFileSizeBytes = 128 * 1024);
  12690. /** Destructor. */
  12691. ~FileLogger();
  12692. void logMessage (const String& message);
  12693. const File getLogFile() const { return logFile; }
  12694. /** Helper function to create a log file in the correct place for this platform.
  12695. On Windows this will return a logger with a path such as:
  12696. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  12697. On the Mac it'll create something like:
  12698. ~/Library/Logs/[logFileName]
  12699. The method might return 0 if the file can't be created for some reason.
  12700. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  12701. it's best to use the something like the name of your application here.
  12702. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  12703. call it "log.txt" because if it goes in a directory with logs
  12704. from other applications (as it will do on the Mac) then no-one
  12705. will know which one is yours!
  12706. @param welcomeMessage a message that will be written to the log when it's opened.
  12707. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  12708. */
  12709. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  12710. const String& logFileName,
  12711. const String& welcomeMessage,
  12712. const int maxInitialFileSizeBytes = 128 * 1024);
  12713. private:
  12714. File logFile;
  12715. CriticalSection logLock;
  12716. void trimFileSize (int maxFileSizeBytes) const;
  12717. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileLogger);
  12718. };
  12719. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  12720. /*** End of inlined file: juce_FileLogger.h ***/
  12721. #endif
  12722. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  12723. /*** Start of inlined file: juce_Initialisation.h ***/
  12724. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  12725. #define __JUCE_INITIALISATION_JUCEHEADER__
  12726. /** Initialises Juce's GUI classes.
  12727. If you're embedding Juce into an application that uses its own event-loop rather
  12728. than using the START_JUCE_APPLICATION macro, call this function before making any
  12729. Juce calls, to make sure things are initialised correctly.
  12730. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  12731. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  12732. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  12733. */
  12734. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI();
  12735. /** Clears up any static data being used by Juce's GUI classes.
  12736. If you're embedding Juce into an application that uses its own event-loop rather
  12737. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  12738. code to clean up any juce objects that might be lying around.
  12739. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  12740. */
  12741. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  12742. /** Initialises the core parts of Juce.
  12743. If you're embedding Juce into either a command-line program, call this function
  12744. at the start of your main() function to make sure that Juce is initialised correctly.
  12745. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  12746. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  12747. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  12748. */
  12749. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI();
  12750. /** Clears up any static data being used by Juce's non-gui core classes.
  12751. If you're embedding Juce into either a command-line program, call this function
  12752. at the end of your main() function if you want to make sure any Juce objects are
  12753. cleaned up correctly.
  12754. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  12755. */
  12756. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI();
  12757. /** A utility object that helps you initialise and shutdown Juce correctly
  12758. using an RAII pattern.
  12759. When an instance of this class is created, it calls initialiseJuce_NonGUI(),
  12760. and when it's deleted, it calls shutdownJuce_NonGUI(), which lets you easily
  12761. make sure that these functions are matched correctly.
  12762. This class is particularly handy to use at the beginning of a console app's
  12763. main() function, because it'll take care of shutting down whenever you return
  12764. from the main() call.
  12765. @see ScopedJuceInitialiser_GUI
  12766. */
  12767. class ScopedJuceInitialiser_NonGUI
  12768. {
  12769. public:
  12770. /** The constructor simply calls initialiseJuce_NonGUI(). */
  12771. ScopedJuceInitialiser_NonGUI() { initialiseJuce_NonGUI(); }
  12772. /** The destructor simply calls shutdownJuce_NonGUI(). */
  12773. ~ScopedJuceInitialiser_NonGUI() { shutdownJuce_NonGUI(); }
  12774. };
  12775. /** A utility object that helps you initialise and shutdown Juce correctly
  12776. using an RAII pattern.
  12777. When an instance of this class is created, it calls initialiseJuce_GUI(),
  12778. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  12779. make sure that these functions are matched correctly.
  12780. This class is particularly handy to use at the beginning of a console app's
  12781. main() function, because it'll take care of shutting down whenever you return
  12782. from the main() call.
  12783. @see ScopedJuceInitialiser_NonGUI
  12784. */
  12785. class ScopedJuceInitialiser_GUI
  12786. {
  12787. public:
  12788. /** The constructor simply calls initialiseJuce_GUI(). */
  12789. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  12790. /** The destructor simply calls shutdownJuce_GUI(). */
  12791. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  12792. };
  12793. /*
  12794. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  12795. AppSubClass is the name of a class derived from JUCEApplication.
  12796. See the JUCEApplication class documentation (juce_Application.h) for more details.
  12797. */
  12798. #if JUCE_ANDROID
  12799. #define START_JUCE_APPLICATION(AppClass) \
  12800. JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); }
  12801. #elif defined (JUCE_GCC) || defined (__MWERKS__)
  12802. #define START_JUCE_APPLICATION(AppClass) \
  12803. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  12804. int main (int argc, char* argv[]) \
  12805. { \
  12806. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  12807. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv); \
  12808. }
  12809. #elif JUCE_WINDOWS
  12810. #ifdef _CONSOLE
  12811. #define START_JUCE_APPLICATION(AppClass) \
  12812. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  12813. int main (int, char* argv[]) \
  12814. { \
  12815. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  12816. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  12817. }
  12818. #elif ! defined (_AFXDLL)
  12819. #ifdef _WINDOWS_
  12820. #define START_JUCE_APPLICATION(AppClass) \
  12821. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  12822. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  12823. { \
  12824. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  12825. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  12826. }
  12827. #else
  12828. #define START_JUCE_APPLICATION(AppClass) \
  12829. static JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication() { return new AppClass(); } \
  12830. int __stdcall WinMain (int, int, const char*, int) \
  12831. { \
  12832. JUCE_NAMESPACE::JUCEApplication::createInstance = &juce_CreateApplication; \
  12833. return JUCE_NAMESPACE::JUCEApplication::main (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  12834. }
  12835. #endif
  12836. #endif
  12837. #endif
  12838. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  12839. /*** End of inlined file: juce_Initialisation.h ***/
  12840. #endif
  12841. #ifndef __JUCE_LOGGER_JUCEHEADER__
  12842. #endif
  12843. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  12844. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  12845. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  12846. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  12847. /** A timer for measuring performance of code and dumping the results to a file.
  12848. e.g. @code
  12849. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  12850. for (;;)
  12851. {
  12852. pc.start();
  12853. doSomethingFishy();
  12854. pc.stop();
  12855. }
  12856. @endcode
  12857. In this example, the time of each period between calling start/stop will be
  12858. measured and averaged over 50 runs, and the results printed to a file
  12859. every 50 times round the loop.
  12860. */
  12861. class JUCE_API PerformanceCounter
  12862. {
  12863. public:
  12864. /** Creates a PerformanceCounter object.
  12865. @param counterName the name used when printing out the statistics
  12866. @param runsPerPrintout the number of start/stop iterations before calling
  12867. printStatistics()
  12868. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  12869. the results are just written to the debugger output
  12870. */
  12871. PerformanceCounter (const String& counterName,
  12872. int runsPerPrintout = 100,
  12873. const File& loggingFile = File::nonexistent);
  12874. /** Destructor. */
  12875. ~PerformanceCounter();
  12876. /** Starts timing.
  12877. @see stop
  12878. */
  12879. void start();
  12880. /** Stops timing and prints out the results.
  12881. The number of iterations before doing a printout of the
  12882. results is set in the constructor.
  12883. @see start
  12884. */
  12885. void stop();
  12886. /** Dumps the current metrics to the debugger output and to a file.
  12887. As well as using Logger::outputDebugString to print the results,
  12888. this will write then to the file specified in the constructor (if
  12889. this was valid).
  12890. */
  12891. void printStatistics();
  12892. private:
  12893. String name;
  12894. int numRuns, runsPerPrint;
  12895. double totalTime;
  12896. int64 started;
  12897. File outputFile;
  12898. };
  12899. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  12900. /*** End of inlined file: juce_PerformanceCounter.h ***/
  12901. #endif
  12902. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  12903. #endif
  12904. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  12905. /*** Start of inlined file: juce_PlatformUtilities.h ***/
  12906. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  12907. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  12908. /**
  12909. A collection of miscellaneous platform-specific utilities.
  12910. */
  12911. class JUCE_API PlatformUtilities
  12912. {
  12913. public:
  12914. /** Plays the operating system's default alert 'beep' sound. */
  12915. static void beep();
  12916. /** Tries to launch the system's default reader for a given file or URL. */
  12917. static bool openDocument (const String& documentURL, const String& parameters);
  12918. /** Tries to launch the system's default email app to let the user create an email.
  12919. */
  12920. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  12921. const String& emailSubject,
  12922. const String& bodyText,
  12923. const StringArray& filesToAttach);
  12924. #if JUCE_MAC || JUCE_IOS || DOXYGEN
  12925. /** MAC ONLY - Turns a Core CF String into a juce one. */
  12926. static const String cfStringToJuceString (CFStringRef cfString);
  12927. /** MAC ONLY - Turns a juce string into a Core CF one. */
  12928. static CFStringRef juceStringToCFString (const String& s);
  12929. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  12930. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  12931. /** MAC ONLY - Turns an FSRef into a juce string path. */
  12932. static const String makePathFromFSRef (FSRef* file);
  12933. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  12934. their precomposed equivalents.
  12935. */
  12936. static const String convertToPrecomposedUnicode (const String& s);
  12937. /** MAC ONLY - Gets the type of a file from the file's resources. */
  12938. static OSType getTypeOfFile (const String& filename);
  12939. /** MAC ONLY - Returns true if this file is actually a bundle. */
  12940. static bool isBundle (const String& filename);
  12941. /** MAC ONLY - Adds an item to the dock */
  12942. static void addItemToDock (const File& file);
  12943. /** MAC ONLY - Returns the current OS version number.
  12944. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  12945. */
  12946. static int getOSXMinorVersionNumber();
  12947. #endif
  12948. #if JUCE_WINDOWS || DOXYGEN
  12949. // Some registry helper functions:
  12950. /** WIN32 ONLY - Returns a string from the registry.
  12951. The path is a string for the entire path of a value in the registry,
  12952. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  12953. */
  12954. static const String getRegistryValue (const String& regValuePath,
  12955. const String& defaultValue = String::empty);
  12956. /** WIN32 ONLY - Sets a registry value as a string.
  12957. This will take care of creating any groups needed to get to the given
  12958. registry value.
  12959. */
  12960. static void setRegistryValue (const String& regValuePath,
  12961. const String& value);
  12962. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  12963. static bool registryValueExists (const String& regValuePath);
  12964. /** WIN32 ONLY - Deletes a registry value. */
  12965. static void deleteRegistryValue (const String& regValuePath);
  12966. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  12967. static void deleteRegistryKey (const String& regKeyPath);
  12968. /** WIN32 ONLY - Creates a file association in the registry.
  12969. This lets you set the exe that should be launched by a given file extension.
  12970. @param fileExtension the file extension to associate, including the
  12971. initial dot, e.g. ".txt"
  12972. @param symbolicDescription a space-free short token to identify the file type
  12973. @param fullDescription a human-readable description of the file type
  12974. @param targetExecutable the executable that should be launched
  12975. @param iconResourceNumber the icon that gets displayed for the file type will be
  12976. found by looking up this resource number in the
  12977. executable. Pass 0 here to not use an icon
  12978. */
  12979. static void registerFileAssociation (const String& fileExtension,
  12980. const String& symbolicDescription,
  12981. const String& fullDescription,
  12982. const File& targetExecutable,
  12983. int iconResourceNumber);
  12984. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  12985. In a normal Juce application this will be set to the module handle
  12986. of the application executable.
  12987. If you're writing a DLL using Juce and plan to use any Juce messaging or
  12988. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  12989. to set the correct module handle in your DllMain() function, because
  12990. the win32 system relies on the correct instance handle when opening windows.
  12991. */
  12992. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  12993. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  12994. @see getCurrentModuleInstanceHandle()
  12995. */
  12996. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  12997. /** WIN32 ONLY - Gets the command-line params as a string.
  12998. This is needed to avoid unicode problems with the argc type params.
  12999. */
  13000. static const String JUCE_CALLTYPE getCurrentCommandLineParams();
  13001. #endif
  13002. /** Clears the floating point unit's flags.
  13003. Only has an effect under win32, currently.
  13004. */
  13005. static void fpuReset();
  13006. #if JUCE_LINUX || JUCE_WINDOWS
  13007. /** Loads a dynamically-linked library into the process's address space.
  13008. @param pathOrFilename the platform-dependent name and search path
  13009. @returns a handle which can be used by getProcedureEntryPoint(), or
  13010. zero if it fails.
  13011. @see freeDynamicLibrary, getProcedureEntryPoint
  13012. */
  13013. static void* loadDynamicLibrary (const String& pathOrFilename);
  13014. /** Frees a dynamically-linked library.
  13015. @param libraryHandle a handle created by loadDynamicLibrary
  13016. @see loadDynamicLibrary, getProcedureEntryPoint
  13017. */
  13018. static void freeDynamicLibrary (void* libraryHandle);
  13019. /** Finds a procedure call in a dynamically-linked library.
  13020. @param libraryHandle a library handle returned by loadDynamicLibrary
  13021. @param procedureName the name of the procedure call to try to load
  13022. @returns a pointer to the function if found, or 0 if it fails
  13023. @see loadDynamicLibrary
  13024. */
  13025. static void* getProcedureEntryPoint (void* libraryHandle,
  13026. const String& procedureName);
  13027. #endif
  13028. private:
  13029. PlatformUtilities();
  13030. JUCE_DECLARE_NON_COPYABLE (PlatformUtilities);
  13031. };
  13032. #if JUCE_MAC || JUCE_IOS
  13033. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  13034. using RAII.
  13035. */
  13036. class ScopedAutoReleasePool
  13037. {
  13038. public:
  13039. ScopedAutoReleasePool();
  13040. ~ScopedAutoReleasePool();
  13041. private:
  13042. void* pool;
  13043. JUCE_DECLARE_NON_COPYABLE (ScopedAutoReleasePool);
  13044. };
  13045. #define JUCE_AUTORELEASEPOOL const JUCE_NAMESPACE::ScopedAutoReleasePool pool;
  13046. #else
  13047. #define JUCE_AUTORELEASEPOOL
  13048. #endif
  13049. #if JUCE_LINUX
  13050. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  13051. using an RAII approach.
  13052. */
  13053. class ScopedXLock
  13054. {
  13055. public:
  13056. /** Creating a ScopedXLock object locks the X display.
  13057. This uses XLockDisplay() to grab the display that Juce is using.
  13058. */
  13059. ScopedXLock();
  13060. /** Deleting a ScopedXLock object unlocks the X display.
  13061. This calls XUnlockDisplay() to release the lock.
  13062. */
  13063. ~ScopedXLock();
  13064. };
  13065. #endif
  13066. #if JUCE_MAC
  13067. /**
  13068. A wrapper class for picking up events from an Apple IR remote control device.
  13069. To use it, just create a subclass of this class, implementing the buttonPressed()
  13070. callback, then call start() and stop() to start or stop receiving events.
  13071. */
  13072. class JUCE_API AppleRemoteDevice
  13073. {
  13074. public:
  13075. AppleRemoteDevice();
  13076. virtual ~AppleRemoteDevice();
  13077. /** The set of buttons that may be pressed.
  13078. @see buttonPressed
  13079. */
  13080. enum ButtonType
  13081. {
  13082. menuButton = 0, /**< The menu button (if it's held for a short time). */
  13083. playButton, /**< The play button. */
  13084. plusButton, /**< The plus or volume-up button. */
  13085. minusButton, /**< The minus or volume-down button. */
  13086. rightButton, /**< The right button (if it's held for a short time). */
  13087. leftButton, /**< The left button (if it's held for a short time). */
  13088. rightButton_Long, /**< The right button (if it's held for a long time). */
  13089. leftButton_Long, /**< The menu button (if it's held for a long time). */
  13090. menuButton_Long, /**< The menu button (if it's held for a long time). */
  13091. playButtonSleepMode,
  13092. switched
  13093. };
  13094. /** Override this method to receive the callback about a button press.
  13095. The callback will happen on the application's message thread.
  13096. Some buttons trigger matching up and down events, in which the isDown parameter
  13097. will be true and then false. Others only send a single event when the
  13098. button is pressed.
  13099. */
  13100. virtual void buttonPressed (ButtonType buttonId, bool isDown) = 0;
  13101. /** Starts the device running and responding to events.
  13102. Returns true if it managed to open the device.
  13103. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  13104. and will not be available to any other part of the system. If
  13105. false, it will be shared with other apps.
  13106. @see stop
  13107. */
  13108. bool start (bool inExclusiveMode);
  13109. /** Stops the device running.
  13110. @see start
  13111. */
  13112. void stop();
  13113. /** Returns true if the device has been started successfully.
  13114. */
  13115. bool isActive() const;
  13116. /** Returns the ID number of the remote, if it has sent one.
  13117. */
  13118. int getRemoteId() const { return remoteId; }
  13119. /** @internal */
  13120. void handleCallbackInternal();
  13121. private:
  13122. void* device;
  13123. void* queue;
  13124. int remoteId;
  13125. bool open (bool openInExclusiveMode);
  13126. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AppleRemoteDevice);
  13127. };
  13128. #endif
  13129. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  13130. /*** End of inlined file: juce_PlatformUtilities.h ***/
  13131. #endif
  13132. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  13133. #endif
  13134. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  13135. /*** Start of inlined file: juce_Singleton.h ***/
  13136. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  13137. #define __JUCE_SINGLETON_JUCEHEADER__
  13138. /*** Start of inlined file: juce_ScopedLock.h ***/
  13139. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  13140. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  13141. /**
  13142. Automatically locks and unlocks a CriticalSection object.
  13143. Use one of these as a local variable to control access to a CriticalSection.
  13144. e.g. @code
  13145. CriticalSection myCriticalSection;
  13146. for (;;)
  13147. {
  13148. const ScopedLock myScopedLock (myCriticalSection);
  13149. // myCriticalSection is now locked
  13150. ...do some stuff...
  13151. // myCriticalSection gets unlocked here.
  13152. }
  13153. @endcode
  13154. @see CriticalSection, ScopedUnlock
  13155. */
  13156. class JUCE_API ScopedLock
  13157. {
  13158. public:
  13159. /** Creates a ScopedLock.
  13160. As soon as it is created, this will lock the CriticalSection, and
  13161. when the ScopedLock object is deleted, the CriticalSection will
  13162. be unlocked.
  13163. Make sure this object is created and deleted by the same thread,
  13164. otherwise there are no guarantees what will happen! Best just to use it
  13165. as a local stack object, rather than creating one with the new() operator.
  13166. */
  13167. inline explicit ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  13168. /** Destructor.
  13169. The CriticalSection will be unlocked when the destructor is called.
  13170. Make sure this object is created and deleted by the same thread,
  13171. otherwise there are no guarantees what will happen!
  13172. */
  13173. inline ~ScopedLock() throw() { lock_.exit(); }
  13174. private:
  13175. const CriticalSection& lock_;
  13176. JUCE_DECLARE_NON_COPYABLE (ScopedLock);
  13177. };
  13178. /**
  13179. Automatically unlocks and re-locks a CriticalSection object.
  13180. This is the reverse of a ScopedLock object - instead of locking the critical
  13181. section for the lifetime of this object, it unlocks it.
  13182. Make sure you don't try to unlock critical sections that aren't actually locked!
  13183. e.g. @code
  13184. CriticalSection myCriticalSection;
  13185. for (;;)
  13186. {
  13187. const ScopedLock myScopedLock (myCriticalSection);
  13188. // myCriticalSection is now locked
  13189. ... do some stuff with it locked ..
  13190. while (xyz)
  13191. {
  13192. ... do some stuff with it locked ..
  13193. const ScopedUnlock unlocker (myCriticalSection);
  13194. // myCriticalSection is now unlocked for the remainder of this block,
  13195. // and re-locked at the end.
  13196. ...do some stuff with it unlocked ...
  13197. }
  13198. // myCriticalSection gets unlocked here.
  13199. }
  13200. @endcode
  13201. @see CriticalSection, ScopedLock
  13202. */
  13203. class ScopedUnlock
  13204. {
  13205. public:
  13206. /** Creates a ScopedUnlock.
  13207. As soon as it is created, this will unlock the CriticalSection, and
  13208. when the ScopedLock object is deleted, the CriticalSection will
  13209. be re-locked.
  13210. Make sure this object is created and deleted by the same thread,
  13211. otherwise there are no guarantees what will happen! Best just to use it
  13212. as a local stack object, rather than creating one with the new() operator.
  13213. */
  13214. inline explicit ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  13215. /** Destructor.
  13216. The CriticalSection will be unlocked when the destructor is called.
  13217. Make sure this object is created and deleted by the same thread,
  13218. otherwise there are no guarantees what will happen!
  13219. */
  13220. inline ~ScopedUnlock() throw() { lock_.enter(); }
  13221. private:
  13222. const CriticalSection& lock_;
  13223. JUCE_DECLARE_NON_COPYABLE (ScopedUnlock);
  13224. };
  13225. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  13226. /*** End of inlined file: juce_ScopedLock.h ***/
  13227. /**
  13228. Macro to declare member variables and methods for a singleton class.
  13229. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  13230. to the class's definition.
  13231. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  13232. implementation code.
  13233. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  13234. destructor, in case it is deleted by other means than deleteInstance()
  13235. Clients can then call the static method MyClass::getInstance() to get a pointer
  13236. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  13237. no instance currently exists.
  13238. e.g. @code
  13239. class MySingleton
  13240. {
  13241. public:
  13242. MySingleton()
  13243. {
  13244. }
  13245. ~MySingleton()
  13246. {
  13247. // this ensures that no dangling pointers are left when the
  13248. // singleton is deleted.
  13249. clearSingletonInstance();
  13250. }
  13251. juce_DeclareSingleton (MySingleton, false)
  13252. };
  13253. juce_ImplementSingleton (MySingleton)
  13254. // example of usage:
  13255. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  13256. ...
  13257. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  13258. @endcode
  13259. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  13260. than once during the process's lifetime - i.e. after you've created and deleted the
  13261. object, getInstance() will refuse to create another one. This can be useful to stop
  13262. objects being accidentally re-created during your app's shutdown code.
  13263. If you know that your object will only be created and deleted by a single thread, you
  13264. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  13265. of this one.
  13266. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  13267. */
  13268. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  13269. \
  13270. static classname* _singletonInstance; \
  13271. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  13272. \
  13273. static classname* JUCE_CALLTYPE getInstance() \
  13274. { \
  13275. if (_singletonInstance == 0) \
  13276. {\
  13277. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  13278. \
  13279. if (_singletonInstance == 0) \
  13280. { \
  13281. static bool alreadyInside = false; \
  13282. static bool createdOnceAlready = false; \
  13283. \
  13284. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  13285. jassert (! problem); \
  13286. if (! problem) \
  13287. { \
  13288. createdOnceAlready = true; \
  13289. alreadyInside = true; \
  13290. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  13291. alreadyInside = false; \
  13292. \
  13293. _singletonInstance = newObject; \
  13294. } \
  13295. } \
  13296. } \
  13297. \
  13298. return _singletonInstance; \
  13299. } \
  13300. \
  13301. static inline classname* JUCE_CALLTYPE getInstanceWithoutCreating() throw() \
  13302. { \
  13303. return _singletonInstance; \
  13304. } \
  13305. \
  13306. static void JUCE_CALLTYPE deleteInstance() \
  13307. { \
  13308. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  13309. if (_singletonInstance != 0) \
  13310. { \
  13311. classname* const old = _singletonInstance; \
  13312. _singletonInstance = 0; \
  13313. delete old; \
  13314. } \
  13315. } \
  13316. \
  13317. void clearSingletonInstance() throw() \
  13318. { \
  13319. if (_singletonInstance == this) \
  13320. _singletonInstance = 0; \
  13321. }
  13322. /** This is a counterpart to the juce_DeclareSingleton macro.
  13323. After adding the juce_DeclareSingleton to the class definition, this macro has
  13324. to be used in the cpp file.
  13325. */
  13326. #define juce_ImplementSingleton(classname) \
  13327. \
  13328. classname* classname::_singletonInstance = 0; \
  13329. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  13330. /**
  13331. Macro to declare member variables and methods for a singleton class.
  13332. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  13333. section to make access to it thread-safe. If you know that your object will
  13334. only ever be created or deleted by a single thread, then this is a
  13335. more efficient version to use.
  13336. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  13337. than once during the process's lifetime - i.e. after you've created and deleted the
  13338. object, getInstance() will refuse to create another one. This can be useful to stop
  13339. objects being accidentally re-created during your app's shutdown code.
  13340. See the documentation for juce_DeclareSingleton for more information about
  13341. how to use it, the only difference being that you have to use
  13342. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  13343. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  13344. */
  13345. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  13346. \
  13347. static classname* _singletonInstance; \
  13348. \
  13349. static classname* getInstance() \
  13350. { \
  13351. if (_singletonInstance == 0) \
  13352. { \
  13353. static bool alreadyInside = false; \
  13354. static bool createdOnceAlready = false; \
  13355. \
  13356. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  13357. jassert (! problem); \
  13358. if (! problem) \
  13359. { \
  13360. createdOnceAlready = true; \
  13361. alreadyInside = true; \
  13362. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  13363. alreadyInside = false; \
  13364. \
  13365. _singletonInstance = newObject; \
  13366. } \
  13367. } \
  13368. \
  13369. return _singletonInstance; \
  13370. } \
  13371. \
  13372. static inline classname* getInstanceWithoutCreating() throw() \
  13373. { \
  13374. return _singletonInstance; \
  13375. } \
  13376. \
  13377. static void deleteInstance() \
  13378. { \
  13379. if (_singletonInstance != 0) \
  13380. { \
  13381. classname* const old = _singletonInstance; \
  13382. _singletonInstance = 0; \
  13383. delete old; \
  13384. } \
  13385. } \
  13386. \
  13387. void clearSingletonInstance() throw() \
  13388. { \
  13389. if (_singletonInstance == this) \
  13390. _singletonInstance = 0; \
  13391. }
  13392. /**
  13393. Macro to declare member variables and methods for a singleton class.
  13394. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  13395. for recursion or repeated instantiation. It's intended for use as a lightweight
  13396. version of a singleton, where you're using it in very straightforward
  13397. circumstances and don't need the extra checking.
  13398. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  13399. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  13400. See the documentation for juce_DeclareSingleton for more information about
  13401. how to use it, the only difference being that you have to use
  13402. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  13403. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  13404. */
  13405. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  13406. \
  13407. static classname* _singletonInstance; \
  13408. \
  13409. static classname* getInstance() \
  13410. { \
  13411. if (_singletonInstance == 0) \
  13412. _singletonInstance = new classname(); \
  13413. \
  13414. return _singletonInstance; \
  13415. } \
  13416. \
  13417. static inline classname* getInstanceWithoutCreating() throw() \
  13418. { \
  13419. return _singletonInstance; \
  13420. } \
  13421. \
  13422. static void deleteInstance() \
  13423. { \
  13424. if (_singletonInstance != 0) \
  13425. { \
  13426. classname* const old = _singletonInstance; \
  13427. _singletonInstance = 0; \
  13428. delete old; \
  13429. } \
  13430. } \
  13431. \
  13432. void clearSingletonInstance() throw() \
  13433. { \
  13434. if (_singletonInstance == this) \
  13435. _singletonInstance = 0; \
  13436. }
  13437. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  13438. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  13439. to the class definition, this macro has to be used somewhere in the cpp file.
  13440. */
  13441. #define juce_ImplementSingleton_SingleThreaded(classname) \
  13442. \
  13443. classname* classname::_singletonInstance = 0;
  13444. #endif // __JUCE_SINGLETON_JUCEHEADER__
  13445. /*** End of inlined file: juce_Singleton.h ***/
  13446. #endif
  13447. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  13448. #endif
  13449. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  13450. /*** Start of inlined file: juce_SystemStats.h ***/
  13451. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  13452. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  13453. /**
  13454. Contains methods for finding out about the current hardware and OS configuration.
  13455. */
  13456. class JUCE_API SystemStats
  13457. {
  13458. public:
  13459. /** Returns the current version of JUCE,
  13460. (just in case you didn't already know at compile-time.)
  13461. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  13462. */
  13463. static const String getJUCEVersion();
  13464. /** The set of possible results of the getOperatingSystemType() method.
  13465. */
  13466. enum OperatingSystemType
  13467. {
  13468. UnknownOS = 0,
  13469. MacOSX = 0x1000,
  13470. Linux = 0x2000,
  13471. Android = 0x3000,
  13472. Win95 = 0x4001,
  13473. Win98 = 0x4002,
  13474. WinNT351 = 0x4103,
  13475. WinNT40 = 0x4104,
  13476. Win2000 = 0x4105,
  13477. WinXP = 0x4106,
  13478. WinVista = 0x4107,
  13479. Windows7 = 0x4108,
  13480. Windows = 0x4000, /**< To test whether any version of Windows is running,
  13481. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  13482. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  13483. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  13484. };
  13485. /** Returns the type of operating system we're running on.
  13486. @returns one of the values from the OperatingSystemType enum.
  13487. @see getOperatingSystemName
  13488. */
  13489. static OperatingSystemType getOperatingSystemType();
  13490. /** Returns the name of the type of operating system we're running on.
  13491. @returns a string describing the OS type.
  13492. @see getOperatingSystemType
  13493. */
  13494. static const String getOperatingSystemName();
  13495. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  13496. */
  13497. static bool isOperatingSystem64Bit();
  13498. /** Returns the current user's name, if available.
  13499. @see getFullUserName()
  13500. */
  13501. static const String getLogonName();
  13502. /** Returns the current user's full name, if available.
  13503. On some OSes, this may just return the same value as getLogonName().
  13504. @see getLogonName()
  13505. */
  13506. static const String getFullUserName();
  13507. // CPU and memory information..
  13508. /** Returns the approximate CPU speed.
  13509. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  13510. what year you're reading this...)
  13511. */
  13512. static int getCpuSpeedInMegaherz();
  13513. /** Returns a string to indicate the CPU vendor.
  13514. Might not be known on some systems.
  13515. */
  13516. static const String getCpuVendor();
  13517. /** Checks whether Intel MMX instructions are available. */
  13518. static bool hasMMX() throw() { return cpuFlags.hasMMX; }
  13519. /** Checks whether Intel SSE instructions are available. */
  13520. static bool hasSSE() throw() { return cpuFlags.hasSSE; }
  13521. /** Checks whether Intel SSE2 instructions are available. */
  13522. static bool hasSSE2() throw() { return cpuFlags.hasSSE2; }
  13523. /** Checks whether AMD 3DNOW instructions are available. */
  13524. static bool has3DNow() throw() { return cpuFlags.has3DNow; }
  13525. /** Returns the number of CPUs. */
  13526. static int getNumCpus() throw() { return cpuFlags.numCpus; }
  13527. /** Finds out how much RAM is in the machine.
  13528. @returns the approximate number of megabytes of memory, or zero if
  13529. something goes wrong when finding out.
  13530. */
  13531. static int getMemorySizeInMegabytes();
  13532. /** Returns the system page-size.
  13533. This is only used by programmers with beards.
  13534. */
  13535. static int getPageSize();
  13536. // not-for-public-use platform-specific method gets called at startup to initialise things.
  13537. static void initialiseStats();
  13538. private:
  13539. struct CPUFlags
  13540. {
  13541. int numCpus;
  13542. bool hasMMX : 1;
  13543. bool hasSSE : 1;
  13544. bool hasSSE2 : 1;
  13545. bool has3DNow : 1;
  13546. };
  13547. static CPUFlags cpuFlags;
  13548. SystemStats();
  13549. JUCE_DECLARE_NON_COPYABLE (SystemStats);
  13550. };
  13551. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  13552. /*** End of inlined file: juce_SystemStats.h ***/
  13553. #endif
  13554. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  13555. #endif
  13556. #ifndef __JUCE_TIME_JUCEHEADER__
  13557. #endif
  13558. #ifndef __JUCE_UUID_JUCEHEADER__
  13559. /*** Start of inlined file: juce_Uuid.h ***/
  13560. #ifndef __JUCE_UUID_JUCEHEADER__
  13561. #define __JUCE_UUID_JUCEHEADER__
  13562. /**
  13563. A universally unique 128-bit identifier.
  13564. This class generates very random unique numbers based on the system time
  13565. and MAC addresses if any are available. It's extremely unlikely that two identical
  13566. UUIDs would ever be created by chance.
  13567. The class includes methods for saving the ID as a string or as raw binary data.
  13568. */
  13569. class JUCE_API Uuid
  13570. {
  13571. public:
  13572. /** Creates a new unique ID. */
  13573. Uuid();
  13574. /** Destructor. */
  13575. ~Uuid() throw();
  13576. /** Creates a copy of another UUID. */
  13577. Uuid (const Uuid& other);
  13578. /** Copies another UUID. */
  13579. Uuid& operator= (const Uuid& other);
  13580. /** Returns true if the ID is zero. */
  13581. bool isNull() const throw();
  13582. /** Compares two UUIDs. */
  13583. bool operator== (const Uuid& other) const;
  13584. /** Compares two UUIDs. */
  13585. bool operator!= (const Uuid& other) const;
  13586. /** Returns a stringified version of this UUID.
  13587. A Uuid object can later be reconstructed from this string using operator= or
  13588. the constructor that takes a string parameter.
  13589. @returns a 32 character hex string.
  13590. */
  13591. const String toString() const;
  13592. /** Creates an ID from an encoded string version.
  13593. @see toString
  13594. */
  13595. Uuid (const String& uuidString);
  13596. /** Copies from a stringified UUID.
  13597. The string passed in should be one that was created with the toString() method.
  13598. */
  13599. Uuid& operator= (const String& uuidString);
  13600. /** Returns a pointer to the internal binary representation of the ID.
  13601. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  13602. the constructor or operator= method that takes an array of uint8s.
  13603. */
  13604. const uint8* getRawData() const throw() { return value.asBytes; }
  13605. /** Creates a UUID from a 16-byte array.
  13606. @see getRawData
  13607. */
  13608. Uuid (const uint8* rawData);
  13609. /** Sets this UUID from 16-bytes of raw data. */
  13610. Uuid& operator= (const uint8* rawData);
  13611. private:
  13612. #ifndef DOXYGEN
  13613. union
  13614. {
  13615. uint8 asBytes [16];
  13616. int asInt[4];
  13617. int64 asInt64[2];
  13618. } value;
  13619. #endif
  13620. JUCE_LEAK_DETECTOR (Uuid);
  13621. };
  13622. #endif // __JUCE_UUID_JUCEHEADER__
  13623. /*** End of inlined file: juce_Uuid.h ***/
  13624. #endif
  13625. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  13626. /*** Start of inlined file: juce_BlowFish.h ***/
  13627. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  13628. #define __JUCE_BLOWFISH_JUCEHEADER__
  13629. /**
  13630. BlowFish encryption class.
  13631. */
  13632. class JUCE_API BlowFish
  13633. {
  13634. public:
  13635. /** Creates an object that can encode/decode based on the specified key.
  13636. The key data can be up to 72 bytes long.
  13637. */
  13638. BlowFish (const void* keyData, int keyBytes);
  13639. /** Creates a copy of another blowfish object. */
  13640. BlowFish (const BlowFish& other);
  13641. /** Copies another blowfish object. */
  13642. BlowFish& operator= (const BlowFish& other);
  13643. /** Destructor. */
  13644. ~BlowFish();
  13645. /** Encrypts a pair of 32-bit integers. */
  13646. void encrypt (uint32& data1, uint32& data2) const throw();
  13647. /** Decrypts a pair of 32-bit integers. */
  13648. void decrypt (uint32& data1, uint32& data2) const throw();
  13649. private:
  13650. uint32 p[18];
  13651. HeapBlock <uint32> s[4];
  13652. uint32 F (uint32 x) const throw();
  13653. JUCE_LEAK_DETECTOR (BlowFish);
  13654. };
  13655. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  13656. /*** End of inlined file: juce_BlowFish.h ***/
  13657. #endif
  13658. #ifndef __JUCE_MD5_JUCEHEADER__
  13659. /*** Start of inlined file: juce_MD5.h ***/
  13660. #ifndef __JUCE_MD5_JUCEHEADER__
  13661. #define __JUCE_MD5_JUCEHEADER__
  13662. /**
  13663. MD5 checksum class.
  13664. Create one of these with a block of source data or a string, and it calculates the
  13665. MD5 checksum of that data.
  13666. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  13667. */
  13668. class JUCE_API MD5
  13669. {
  13670. public:
  13671. /** Creates a null MD5 object. */
  13672. MD5();
  13673. /** Creates a copy of another MD5. */
  13674. MD5 (const MD5& other);
  13675. /** Copies another MD5. */
  13676. MD5& operator= (const MD5& other);
  13677. /** Creates a checksum for a block of binary data. */
  13678. explicit MD5 (const MemoryBlock& data);
  13679. /** Creates a checksum for a block of binary data. */
  13680. MD5 (const void* data, size_t numBytes);
  13681. /** Creates a checksum for a string.
  13682. Note that this operates on the string as a block of unicode characters, so the
  13683. result you get will differ from the value you'd get if the string was treated
  13684. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  13685. of this method with a checksum created by a different framework, which may have
  13686. used a different encoding.
  13687. */
  13688. explicit MD5 (const String& text);
  13689. /** Creates a checksum for the input from a stream.
  13690. This will read up to the given number of bytes from the stream, and produce the
  13691. checksum of that. If the number of bytes to read is negative, it'll read
  13692. until the stream is exhausted.
  13693. */
  13694. MD5 (InputStream& input, int64 numBytesToRead = -1);
  13695. /** Creates a checksum for a file. */
  13696. explicit MD5 (const File& file);
  13697. /** Destructor. */
  13698. ~MD5();
  13699. /** Returns the checksum as a 16-byte block of data. */
  13700. const MemoryBlock getRawChecksumData() const;
  13701. /** Returns the checksum as a 32-digit hex string. */
  13702. const String toHexString() const;
  13703. /** Compares this to another MD5. */
  13704. bool operator== (const MD5& other) const;
  13705. /** Compares this to another MD5. */
  13706. bool operator!= (const MD5& other) const;
  13707. private:
  13708. uint8 result [16];
  13709. struct ProcessContext
  13710. {
  13711. uint8 buffer [64];
  13712. uint32 state [4];
  13713. uint32 count [2];
  13714. ProcessContext();
  13715. void processBlock (const void* data, size_t dataSize);
  13716. void transform (const void* buffer);
  13717. void finish (void* result);
  13718. };
  13719. void processStream (InputStream& input, int64 numBytesToRead);
  13720. JUCE_LEAK_DETECTOR (MD5);
  13721. };
  13722. #endif // __JUCE_MD5_JUCEHEADER__
  13723. /*** End of inlined file: juce_MD5.h ***/
  13724. #endif
  13725. #ifndef __JUCE_PRIMES_JUCEHEADER__
  13726. /*** Start of inlined file: juce_Primes.h ***/
  13727. #ifndef __JUCE_PRIMES_JUCEHEADER__
  13728. #define __JUCE_PRIMES_JUCEHEADER__
  13729. /*** Start of inlined file: juce_BigInteger.h ***/
  13730. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  13731. #define __JUCE_BIGINTEGER_JUCEHEADER__
  13732. class MemoryBlock;
  13733. /**
  13734. An arbitrarily large integer class.
  13735. A BigInteger can be used in a similar way to a normal integer, but has no size
  13736. limit (except for memory and performance constraints).
  13737. Negative values are possible, but the value isn't stored as 2s-complement, so
  13738. be careful if you use negative values and look at the values of individual bits.
  13739. */
  13740. class JUCE_API BigInteger
  13741. {
  13742. public:
  13743. /** Creates an empty BigInteger */
  13744. BigInteger();
  13745. /** Creates a BigInteger containing an integer value in its low bits.
  13746. The low 32 bits of the number are initialised with this value.
  13747. */
  13748. BigInteger (uint32 value);
  13749. /** Creates a BigInteger containing an integer value in its low bits.
  13750. The low 32 bits of the number are initialised with the absolute value
  13751. passed in, and its sign is set to reflect the sign of the number.
  13752. */
  13753. BigInteger (int32 value);
  13754. /** Creates a BigInteger containing an integer value in its low bits.
  13755. The low 64 bits of the number are initialised with the absolute value
  13756. passed in, and its sign is set to reflect the sign of the number.
  13757. */
  13758. BigInteger (int64 value);
  13759. /** Creates a copy of another BigInteger. */
  13760. BigInteger (const BigInteger& other);
  13761. /** Destructor. */
  13762. ~BigInteger();
  13763. /** Copies another BigInteger onto this one. */
  13764. BigInteger& operator= (const BigInteger& other);
  13765. /** Swaps the internal contents of this with another object. */
  13766. void swapWith (BigInteger& other) throw();
  13767. /** Returns the value of a specified bit in the number.
  13768. If the index is out-of-range, the result will be false.
  13769. */
  13770. bool operator[] (int bit) const throw();
  13771. /** Returns true if no bits are set. */
  13772. bool isZero() const throw();
  13773. /** Returns true if the value is 1. */
  13774. bool isOne() const throw();
  13775. /** Attempts to get the lowest bits of the value as an integer.
  13776. If the value is bigger than the integer limits, this will return only the lower bits.
  13777. */
  13778. int toInteger() const throw();
  13779. /** Resets the value to 0. */
  13780. void clear();
  13781. /** Clears a particular bit in the number. */
  13782. void clearBit (int bitNumber) throw();
  13783. /** Sets a specified bit to 1. */
  13784. void setBit (int bitNumber);
  13785. /** Sets or clears a specified bit. */
  13786. void setBit (int bitNumber, bool shouldBeSet);
  13787. /** Sets a range of bits to be either on or off.
  13788. @param startBit the first bit to change
  13789. @param numBits the number of bits to change
  13790. @param shouldBeSet whether to turn these bits on or off
  13791. */
  13792. void setRange (int startBit, int numBits, bool shouldBeSet);
  13793. /** Inserts a bit an a given position, shifting up any bits above it. */
  13794. void insertBit (int bitNumber, bool shouldBeSet);
  13795. /** Returns a range of bits as a new BigInteger.
  13796. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  13797. @see getBitRangeAsInt
  13798. */
  13799. const BigInteger getBitRange (int startBit, int numBits) const;
  13800. /** Returns a range of bits as an integer value.
  13801. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  13802. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  13803. getBitRange().
  13804. */
  13805. int getBitRangeAsInt (int startBit, int numBits) const throw();
  13806. /** Sets a range of bits to an integer value.
  13807. Copies the given integer onto a range of bits, starting at startBit,
  13808. and using up to numBits of the available bits.
  13809. */
  13810. void setBitRangeAsInt (int startBit, int numBits, uint32 valueToSet);
  13811. /** Shifts a section of bits left or right.
  13812. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  13813. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  13814. */
  13815. void shiftBits (int howManyBitsLeft, int startBit);
  13816. /** Returns the total number of set bits in the value. */
  13817. int countNumberOfSetBits() const throw();
  13818. /** Looks for the index of the next set bit after a given starting point.
  13819. This searches from startIndex (inclusive) upwards for the first set bit,
  13820. and returns its index. If no set bits are found, it returns -1.
  13821. */
  13822. int findNextSetBit (int startIndex = 0) const throw();
  13823. /** Looks for the index of the next clear bit after a given starting point.
  13824. This searches from startIndex (inclusive) upwards for the first clear bit,
  13825. and returns its index.
  13826. */
  13827. int findNextClearBit (int startIndex = 0) const throw();
  13828. /** Returns the index of the highest set bit in the number.
  13829. If the value is zero, this will return -1.
  13830. */
  13831. int getHighestBit() const throw();
  13832. // All the standard arithmetic ops...
  13833. BigInteger& operator+= (const BigInteger& other);
  13834. BigInteger& operator-= (const BigInteger& other);
  13835. BigInteger& operator*= (const BigInteger& other);
  13836. BigInteger& operator/= (const BigInteger& other);
  13837. BigInteger& operator|= (const BigInteger& other);
  13838. BigInteger& operator&= (const BigInteger& other);
  13839. BigInteger& operator^= (const BigInteger& other);
  13840. BigInteger& operator%= (const BigInteger& other);
  13841. BigInteger& operator<<= (int numBitsToShift);
  13842. BigInteger& operator>>= (int numBitsToShift);
  13843. BigInteger& operator++();
  13844. BigInteger& operator--();
  13845. const BigInteger operator++ (int);
  13846. const BigInteger operator-- (int);
  13847. const BigInteger operator-() const;
  13848. const BigInteger operator+ (const BigInteger& other) const;
  13849. const BigInteger operator- (const BigInteger& other) const;
  13850. const BigInteger operator* (const BigInteger& other) const;
  13851. const BigInteger operator/ (const BigInteger& other) const;
  13852. const BigInteger operator| (const BigInteger& other) const;
  13853. const BigInteger operator& (const BigInteger& other) const;
  13854. const BigInteger operator^ (const BigInteger& other) const;
  13855. const BigInteger operator% (const BigInteger& other) const;
  13856. const BigInteger operator<< (int numBitsToShift) const;
  13857. const BigInteger operator>> (int numBitsToShift) const;
  13858. bool operator== (const BigInteger& other) const throw();
  13859. bool operator!= (const BigInteger& other) const throw();
  13860. bool operator< (const BigInteger& other) const throw();
  13861. bool operator<= (const BigInteger& other) const throw();
  13862. bool operator> (const BigInteger& other) const throw();
  13863. bool operator>= (const BigInteger& other) const throw();
  13864. /** Does a signed comparison of two BigIntegers.
  13865. Return values are:
  13866. - 0 if the numbers are the same
  13867. - < 0 if this number is smaller than the other
  13868. - > 0 if this number is bigger than the other
  13869. */
  13870. int compare (const BigInteger& other) const throw();
  13871. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  13872. Return values are:
  13873. - 0 if the numbers are the same
  13874. - < 0 if this number is smaller than the other
  13875. - > 0 if this number is bigger than the other
  13876. */
  13877. int compareAbsolute (const BigInteger& other) const throw();
  13878. /** Divides this value by another one and returns the remainder.
  13879. This number is divided by other, leaving the quotient in this number,
  13880. with the remainder being copied to the other BigInteger passed in.
  13881. */
  13882. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  13883. /** Returns the largest value that will divide both this value and the one passed-in.
  13884. */
  13885. const BigInteger findGreatestCommonDivisor (BigInteger other) const;
  13886. /** Performs a combined exponent and modulo operation.
  13887. This BigInteger's value becomes (this ^ exponent) % modulus.
  13888. */
  13889. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  13890. /** Performs an inverse modulo on the value.
  13891. i.e. the result is (this ^ -1) mod (modulus).
  13892. */
  13893. void inverseModulo (const BigInteger& modulus);
  13894. /** Returns true if the value is less than zero.
  13895. @see setNegative, negate
  13896. */
  13897. bool isNegative() const throw();
  13898. /** Changes the sign of the number to be positive or negative.
  13899. @see isNegative, negate
  13900. */
  13901. void setNegative (bool shouldBeNegative) throw();
  13902. /** Inverts the sign of the number.
  13903. @see isNegative, setNegative
  13904. */
  13905. void negate() throw();
  13906. /** Converts the number to a string.
  13907. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  13908. If minimumNumCharacters is greater than 0, the returned string will be
  13909. padded with leading zeros to reach at least that length.
  13910. */
  13911. const String toString (int base, int minimumNumCharacters = 1) const;
  13912. /** Reads the numeric value from a string.
  13913. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  13914. Any invalid characters will be ignored.
  13915. */
  13916. void parseString (const String& text, int base);
  13917. /** Turns the number into a block of binary data.
  13918. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  13919. of the number, and so on.
  13920. @see loadFromMemoryBlock
  13921. */
  13922. const MemoryBlock toMemoryBlock() const;
  13923. /** Converts a block of raw data into a number.
  13924. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  13925. of the number, and so on.
  13926. @see toMemoryBlock
  13927. */
  13928. void loadFromMemoryBlock (const MemoryBlock& data);
  13929. private:
  13930. HeapBlock <uint32> values;
  13931. int numValues, highestBit;
  13932. bool negative;
  13933. void ensureSize (int numVals);
  13934. static const BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  13935. static inline int bitToIndex (const int bit) throw() { return bit >> 5; }
  13936. static inline uint32 bitToMask (const int bit) throw() { return 1 << (bit & 31); }
  13937. JUCE_LEAK_DETECTOR (BigInteger);
  13938. };
  13939. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  13940. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  13941. #ifndef DOXYGEN
  13942. // For backwards compatibility, BitArray is defined as an alias for BigInteger.
  13943. typedef BigInteger BitArray;
  13944. #endif
  13945. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  13946. /*** End of inlined file: juce_BigInteger.h ***/
  13947. /**
  13948. Prime number creation class.
  13949. This class contains static methods for generating and testing prime numbers.
  13950. @see BigInteger
  13951. */
  13952. class JUCE_API Primes
  13953. {
  13954. public:
  13955. /** Creates a random prime number with a given bit-length.
  13956. The certainty parameter specifies how many iterations to use when testing
  13957. for primality. A safe value might be anything over about 20-30.
  13958. The randomSeeds parameter lets you optionally pass it a set of values with
  13959. which to seed the random number generation, improving the security of the
  13960. keys generated.
  13961. */
  13962. static const BigInteger createProbablePrime (int bitLength,
  13963. int certainty,
  13964. const int* randomSeeds = 0,
  13965. int numRandomSeeds = 0);
  13966. /** Tests a number to see if it's prime.
  13967. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  13968. whether the number is prime.
  13969. The certainty parameter specifies how many iterations to use when testing - a
  13970. safe value might be anything over about 20-30.
  13971. */
  13972. static bool isProbablyPrime (const BigInteger& number, int certainty);
  13973. private:
  13974. Primes();
  13975. JUCE_DECLARE_NON_COPYABLE (Primes);
  13976. };
  13977. #endif // __JUCE_PRIMES_JUCEHEADER__
  13978. /*** End of inlined file: juce_Primes.h ***/
  13979. #endif
  13980. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  13981. /*** Start of inlined file: juce_RSAKey.h ***/
  13982. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  13983. #define __JUCE_RSAKEY_JUCEHEADER__
  13984. /**
  13985. RSA public/private key-pair encryption class.
  13986. An object of this type makes up one half of a public/private RSA key pair. Use the
  13987. createKeyPair() method to create a matching pair for encoding/decoding.
  13988. */
  13989. class JUCE_API RSAKey
  13990. {
  13991. public:
  13992. /** Creates a null key object.
  13993. Initialise a pair of objects for use with the createKeyPair() method.
  13994. */
  13995. RSAKey();
  13996. /** Loads a key from an encoded string representation.
  13997. This reloads a key from a string created by the toString() method.
  13998. */
  13999. explicit RSAKey (const String& stringRepresentation);
  14000. /** Destructor. */
  14001. ~RSAKey();
  14002. bool operator== (const RSAKey& other) const throw();
  14003. bool operator!= (const RSAKey& other) const throw();
  14004. /** Turns the key into a string representation.
  14005. This can be reloaded using the constructor that takes a string.
  14006. */
  14007. const String toString() const;
  14008. /** Encodes or decodes a value.
  14009. Call this on the public key object to encode some data, then use the matching
  14010. private key object to decode it.
  14011. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  14012. initialised correctly.
  14013. NOTE: This method dumbly applies this key to this data. If you encode some data
  14014. and then try to decode it with a key that doesn't match, this method will still
  14015. happily do its job and return true, but the result won't be what you were expecting.
  14016. It's your responsibility to check that the result is what you wanted.
  14017. */
  14018. bool applyToValue (BigInteger& value) const;
  14019. /** Creates a public/private key-pair.
  14020. Each key will perform one-way encryption that can only be reversed by
  14021. using the other key.
  14022. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  14023. sizes are more secure, but this method will take longer to execute.
  14024. The randomSeeds parameter lets you optionally pass it a set of values with
  14025. which to seed the random number generation, improving the security of the
  14026. keys generated. If you supply these, make sure you provide more than 2 values,
  14027. and the more your provide, the better the security.
  14028. */
  14029. static void createKeyPair (RSAKey& publicKey,
  14030. RSAKey& privateKey,
  14031. int numBits,
  14032. const int* randomSeeds = 0,
  14033. int numRandomSeeds = 0);
  14034. protected:
  14035. BigInteger part1, part2;
  14036. private:
  14037. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q);
  14038. JUCE_LEAK_DETECTOR (RSAKey);
  14039. };
  14040. #endif // __JUCE_RSAKEY_JUCEHEADER__
  14041. /*** End of inlined file: juce_RSAKey.h ***/
  14042. #endif
  14043. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14044. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  14045. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14046. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14047. /**
  14048. Searches through a the files in a directory, returning each file that is found.
  14049. A DirectoryIterator will search through a directory and its subdirectories using
  14050. a wildcard filepattern match.
  14051. If you may be finding a large number of files, this is better than
  14052. using File::findChildFiles() because it doesn't block while it finds them
  14053. all, and this is more memory-efficient.
  14054. It can also guess how far it's got using a wildly inaccurate algorithm.
  14055. */
  14056. class JUCE_API DirectoryIterator
  14057. {
  14058. public:
  14059. /** Creates a DirectoryIterator for a given directory.
  14060. After creating one of these, call its next() method to get the
  14061. first file - e.g. @code
  14062. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  14063. while (iter.next())
  14064. {
  14065. File theFileItFound (iter.getFile());
  14066. ... etc
  14067. }
  14068. @endcode
  14069. @param directory the directory to search in
  14070. @param isRecursive whether all the subdirectories should also be searched
  14071. @param wildCard the file pattern to match
  14072. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  14073. whether to look for files, directories, or both.
  14074. */
  14075. DirectoryIterator (const File& directory,
  14076. bool isRecursive,
  14077. const String& wildCard = "*",
  14078. int whatToLookFor = File::findFiles);
  14079. /** Destructor. */
  14080. ~DirectoryIterator();
  14081. /** Moves the iterator along to the next file.
  14082. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14083. false if there are no more matching files.
  14084. */
  14085. bool next();
  14086. /** Moves the iterator along to the next file, and returns various properties of that file.
  14087. If you need to find out details about the file, it's more efficient to call this method than
  14088. to call the normal next() method and then find out the details afterwards.
  14089. All the parameters are optional, so pass null pointers for any items that you're not
  14090. interested in.
  14091. @returns true if a file was found (you can then use getFile() to see what it was) - or
  14092. false if there are no more matching files. If it returns false, then none of the
  14093. parameters will be filled-in.
  14094. */
  14095. bool next (bool* isDirectory, bool* isHidden, int64* fileSize,
  14096. Time* modTime, Time* creationTime, bool* isReadOnly);
  14097. /** Returns the file that the iterator is currently pointing at.
  14098. The result of this call is only valid after a call to next() has returned true.
  14099. */
  14100. const File getFile() const;
  14101. /** Returns a guess of how far through the search the iterator has got.
  14102. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  14103. very accurate.
  14104. */
  14105. float getEstimatedProgress() const;
  14106. private:
  14107. class NativeIterator
  14108. {
  14109. public:
  14110. NativeIterator (const File& directory, const String& wildCard);
  14111. ~NativeIterator();
  14112. bool next (String& filenameFound,
  14113. bool* isDirectory, bool* isHidden, int64* fileSize,
  14114. Time* modTime, Time* creationTime, bool* isReadOnly);
  14115. class Pimpl;
  14116. private:
  14117. friend class DirectoryIterator;
  14118. friend class ScopedPointer<Pimpl>;
  14119. ScopedPointer<Pimpl> pimpl;
  14120. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeIterator);
  14121. };
  14122. friend class ScopedPointer<NativeIterator::Pimpl>;
  14123. NativeIterator fileFinder;
  14124. String wildCard, path;
  14125. int index;
  14126. mutable int totalNumFiles;
  14127. const int whatToLookFor;
  14128. const bool isRecursive;
  14129. bool hasBeenAdvanced;
  14130. ScopedPointer <DirectoryIterator> subIterator;
  14131. File currentFile;
  14132. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryIterator);
  14133. };
  14134. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  14135. /*** End of inlined file: juce_DirectoryIterator.h ***/
  14136. #endif
  14137. #ifndef __JUCE_FILE_JUCEHEADER__
  14138. #endif
  14139. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14140. /*** Start of inlined file: juce_FileInputStream.h ***/
  14141. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14142. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14143. /**
  14144. An input stream that reads from a local file.
  14145. @see InputStream, FileOutputStream, File::createInputStream
  14146. */
  14147. class JUCE_API FileInputStream : public InputStream
  14148. {
  14149. public:
  14150. /** Creates a FileInputStream.
  14151. @param fileToRead the file to read from - if the file can't be accessed for some
  14152. reason, then the stream will just contain no data
  14153. */
  14154. explicit FileInputStream (const File& fileToRead);
  14155. /** Destructor. */
  14156. ~FileInputStream();
  14157. const File& getFile() const throw() { return file; }
  14158. int64 getTotalLength();
  14159. int read (void* destBuffer, int maxBytesToRead);
  14160. bool isExhausted();
  14161. int64 getPosition();
  14162. bool setPosition (int64 pos);
  14163. private:
  14164. File file;
  14165. void* fileHandle;
  14166. int64 currentPosition, totalSize;
  14167. bool needToSeek;
  14168. void openHandle();
  14169. void closeHandle();
  14170. size_t readInternal (void* buffer, size_t numBytes);
  14171. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputStream);
  14172. };
  14173. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  14174. /*** End of inlined file: juce_FileInputStream.h ***/
  14175. #endif
  14176. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14177. /*** Start of inlined file: juce_FileOutputStream.h ***/
  14178. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14179. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14180. /**
  14181. An output stream that writes into a local file.
  14182. @see OutputStream, FileInputStream, File::createOutputStream
  14183. */
  14184. class JUCE_API FileOutputStream : public OutputStream
  14185. {
  14186. public:
  14187. /** Creates a FileOutputStream.
  14188. If the file doesn't exist, it will first be created. If the file can't be
  14189. created or opened, the failedToOpen() method will return
  14190. true.
  14191. If the file already exists when opened, the stream's write-postion will
  14192. be set to the end of the file. To overwrite an existing file,
  14193. use File::deleteFile() before opening the stream, or use setPosition(0)
  14194. after it's opened (although this won't truncate the file).
  14195. It's better to use File::createOutputStream() to create one of these, rather
  14196. than using the class directly.
  14197. @see TemporaryFile
  14198. */
  14199. FileOutputStream (const File& fileToWriteTo,
  14200. int bufferSizeToUse = 16384);
  14201. /** Destructor. */
  14202. ~FileOutputStream();
  14203. /** Returns the file that this stream is writing to.
  14204. */
  14205. const File& getFile() const { return file; }
  14206. /** Returns true if the stream couldn't be opened for some reason.
  14207. */
  14208. bool failedToOpen() const { return fileHandle == 0; }
  14209. void flush();
  14210. int64 getPosition();
  14211. bool setPosition (int64 pos);
  14212. bool write (const void* data, int numBytes);
  14213. private:
  14214. File file;
  14215. void* fileHandle;
  14216. int64 currentPosition;
  14217. int bufferSize, bytesInBuffer;
  14218. HeapBlock <char> buffer;
  14219. void openHandle();
  14220. void closeHandle();
  14221. void flushInternal();
  14222. int64 setPositionInternal (int64 newPosition);
  14223. int writeInternal (const void* data, int numBytes);
  14224. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileOutputStream);
  14225. };
  14226. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  14227. /*** End of inlined file: juce_FileOutputStream.h ***/
  14228. #endif
  14229. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  14230. /*** Start of inlined file: juce_FileSearchPath.h ***/
  14231. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  14232. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  14233. /**
  14234. Encapsulates a set of folders that make up a search path.
  14235. @see File
  14236. */
  14237. class JUCE_API FileSearchPath
  14238. {
  14239. public:
  14240. /** Creates an empty search path. */
  14241. FileSearchPath();
  14242. /** Creates a search path from a string of pathnames.
  14243. The path can be semicolon- or comma-separated, e.g.
  14244. "/foo/bar;/foo/moose;/fish/moose"
  14245. The separate folders are tokenised and added to the search path.
  14246. */
  14247. FileSearchPath (const String& path);
  14248. /** Creates a copy of another search path. */
  14249. FileSearchPath (const FileSearchPath& other);
  14250. /** Destructor. */
  14251. ~FileSearchPath();
  14252. /** Uses a string containing a list of pathnames to re-initialise this list.
  14253. This search path is cleared and the semicolon- or comma-separated folders
  14254. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  14255. */
  14256. FileSearchPath& operator= (const String& path);
  14257. /** Returns the number of folders in this search path.
  14258. @see operator[]
  14259. */
  14260. int getNumPaths() const;
  14261. /** Returns one of the folders in this search path.
  14262. The file returned isn't guaranteed to actually be a valid directory.
  14263. @see getNumPaths
  14264. */
  14265. const File operator[] (int index) const;
  14266. /** Returns the search path as a semicolon-separated list of directories. */
  14267. const String toString() const;
  14268. /** Adds a new directory to the search path.
  14269. The new directory is added to the end of the list if the insertIndex parameter is
  14270. less than zero, otherwise it is inserted at the given index.
  14271. */
  14272. void add (const File& directoryToAdd,
  14273. int insertIndex = -1);
  14274. /** Adds a new directory to the search path if it's not already in there. */
  14275. void addIfNotAlreadyThere (const File& directoryToAdd);
  14276. /** Removes a directory from the search path. */
  14277. void remove (int indexToRemove);
  14278. /** Merges another search path into this one.
  14279. This will remove any duplicate directories.
  14280. */
  14281. void addPath (const FileSearchPath& other);
  14282. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  14283. If the search is intended to be recursive, there's no point having nested folders in the search
  14284. path, because they'll just get searched twice and you'll get duplicate results.
  14285. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  14286. */
  14287. void removeRedundantPaths();
  14288. /** Removes any directories that don't actually exist. */
  14289. void removeNonExistentPaths();
  14290. /** Searches the path for a wildcard.
  14291. This will search all the directories in the search path in order, adding any
  14292. matching files to the results array.
  14293. @param results an array to append the results to
  14294. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  14295. return files, directories, or both.
  14296. @param searchRecursively whether to recursively search the subdirectories too
  14297. @param wildCardPattern a pattern to match against the filenames
  14298. @returns the number of files added to the array
  14299. @see File::findChildFiles
  14300. */
  14301. int findChildFiles (Array<File>& results,
  14302. int whatToLookFor,
  14303. bool searchRecursively,
  14304. const String& wildCardPattern = "*") const;
  14305. /** Finds out whether a file is inside one of the path's directories.
  14306. This will return true if the specified file is a child of one of the
  14307. directories specified by this path. Note that this doesn't actually do any
  14308. searching or check that the files exist - it just looks at the pathnames
  14309. to work out whether the file would be inside a directory.
  14310. @param fileToCheck the file to look for
  14311. @param checkRecursively if true, then this will return true if the file is inside a
  14312. subfolder of one of the path's directories (at any depth). If false
  14313. it will only return true if the file is actually a direct child
  14314. of one of the directories.
  14315. @see File::isAChildOf
  14316. */
  14317. bool isFileInPath (const File& fileToCheck,
  14318. bool checkRecursively) const;
  14319. private:
  14320. StringArray directories;
  14321. void init (const String& path);
  14322. JUCE_LEAK_DETECTOR (FileSearchPath);
  14323. };
  14324. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  14325. /*** End of inlined file: juce_FileSearchPath.h ***/
  14326. #endif
  14327. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  14328. /*** Start of inlined file: juce_NamedPipe.h ***/
  14329. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  14330. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  14331. /**
  14332. A cross-process pipe that can have data written to and read from it.
  14333. Two or more processes can use these for inter-process communication.
  14334. @see InterprocessConnection
  14335. */
  14336. class JUCE_API NamedPipe
  14337. {
  14338. public:
  14339. /** Creates a NamedPipe. */
  14340. NamedPipe();
  14341. /** Destructor. */
  14342. ~NamedPipe();
  14343. /** Tries to open a pipe that already exists.
  14344. Returns true if it succeeds.
  14345. */
  14346. bool openExisting (const String& pipeName);
  14347. /** Tries to create a new pipe.
  14348. Returns true if it succeeds.
  14349. */
  14350. bool createNewPipe (const String& pipeName);
  14351. /** Closes the pipe, if it's open. */
  14352. void close();
  14353. /** True if the pipe is currently open. */
  14354. bool isOpen() const;
  14355. /** Returns the last name that was used to try to open this pipe. */
  14356. const String getName() const;
  14357. /** Reads data from the pipe.
  14358. This will block until another thread has written enough data into the pipe to fill
  14359. the number of bytes specified, or until another thread calls the cancelPendingReads()
  14360. method.
  14361. If the operation fails, it returns -1, otherwise, it will return the number of
  14362. bytes read.
  14363. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  14364. this is a maximum timeout for reading from the pipe.
  14365. */
  14366. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  14367. /** Writes some data to the pipe.
  14368. If the operation fails, it returns -1, otherwise, it will return the number of
  14369. bytes written.
  14370. */
  14371. int write (const void* sourceBuffer, int numBytesToWrite,
  14372. int timeOutMilliseconds = 2000);
  14373. /** If any threads are currently blocked on a read operation, this tells them to abort.
  14374. */
  14375. void cancelPendingReads();
  14376. private:
  14377. void* internal;
  14378. String currentPipeName;
  14379. CriticalSection lock;
  14380. bool openInternal (const String& pipeName, const bool createPipe);
  14381. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NamedPipe);
  14382. };
  14383. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  14384. /*** End of inlined file: juce_NamedPipe.h ***/
  14385. #endif
  14386. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  14387. /*** Start of inlined file: juce_TemporaryFile.h ***/
  14388. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  14389. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  14390. /**
  14391. Manages a temporary file, which will be deleted when this object is deleted.
  14392. This object is intended to be used as a stack based object, using its scope
  14393. to make sure the temporary file isn't left lying around.
  14394. For example:
  14395. @code
  14396. {
  14397. File myTargetFile ("~/myfile.txt");
  14398. // this will choose a file called something like "~/myfile_temp239348.txt"
  14399. // which definitely doesn't exist at the time the constructor is called.
  14400. TemporaryFile temp (myTargetFile);
  14401. // create a stream to the temporary file, and write some data to it...
  14402. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  14403. if (out != 0)
  14404. {
  14405. out->write ( ...etc )
  14406. out->flush();
  14407. out = 0; // (deletes the stream)
  14408. // ..now we've finished writing, this will rename the temp file to
  14409. // make it replace the target file we specified above.
  14410. bool succeeded = temp.overwriteTargetFileWithTemporary();
  14411. }
  14412. // ..and even if something went wrong and our overwrite failed,
  14413. // as the TemporaryFile object goes out of scope here, it'll make sure
  14414. // that the temp file gets deleted.
  14415. }
  14416. @endcode
  14417. @see File, FileOutputStream
  14418. */
  14419. class JUCE_API TemporaryFile
  14420. {
  14421. public:
  14422. enum OptionFlags
  14423. {
  14424. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  14425. i.e. its name should start with a dot. */
  14426. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  14427. the file is unique, they should go in brackets rather
  14428. than just being appended (see File::getNonexistentSibling() )*/
  14429. };
  14430. /** Creates a randomly-named temporary file in the default temp directory.
  14431. @param suffix a file suffix to use for the file
  14432. @param optionFlags a combination of the values listed in the OptionFlags enum
  14433. The file will not be created until you write to it. And remember that when
  14434. this object is deleted, the file will also be deleted!
  14435. */
  14436. TemporaryFile (const String& suffix = String::empty,
  14437. int optionFlags = 0);
  14438. /** Creates a temporary file in the same directory as a specified file.
  14439. This is useful if you have a file that you want to overwrite, but don't
  14440. want to harm the original file if the write operation fails. You can
  14441. use this to create a temporary file next to the target file, then
  14442. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  14443. to replace the target file with the one you've just written.
  14444. This class won't create any files until you actually write to them. And remember
  14445. that when this object is deleted, the temporary file will also be deleted!
  14446. @param targetFile the file that you intend to overwrite - the temporary
  14447. file will be created in the same directory as this
  14448. @param optionFlags a combination of the values listed in the OptionFlags enum
  14449. */
  14450. TemporaryFile (const File& targetFile,
  14451. int optionFlags = 0);
  14452. /** Destructor.
  14453. When this object is deleted it will make sure that its temporary file is
  14454. also deleted! If the operation fails, it'll throw an assertion in debug
  14455. mode.
  14456. */
  14457. ~TemporaryFile();
  14458. /** Returns the temporary file. */
  14459. const File getFile() const { return temporaryFile; }
  14460. /** Returns the target file that was specified in the constructor. */
  14461. const File getTargetFile() const { return targetFile; }
  14462. /** Tries to move the temporary file to overwrite the target file that was
  14463. specified in the constructor.
  14464. If you used the constructor that specified a target file, this will attempt
  14465. to replace that file with the temporary one.
  14466. Before calling this, make sure:
  14467. - that you've actually written to the temporary file
  14468. - that you've closed any open streams that you were using to write to it
  14469. - and that you don't have any streams open to the target file, which would
  14470. prevent it being overwritten
  14471. If the file move succeeds, this returns false, and the temporary file will
  14472. have disappeared. If it fails, the temporary file will probably still exist,
  14473. but will be deleted when this object is destroyed.
  14474. */
  14475. bool overwriteTargetFileWithTemporary() const;
  14476. /** Attempts to delete the temporary file, if it exists.
  14477. @returns true if the file is successfully deleted (or if it didn't exist).
  14478. */
  14479. bool deleteTemporaryFile() const;
  14480. private:
  14481. File temporaryFile, targetFile;
  14482. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  14483. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryFile);
  14484. };
  14485. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  14486. /*** End of inlined file: juce_TemporaryFile.h ***/
  14487. #endif
  14488. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  14489. /*** Start of inlined file: juce_ZipFile.h ***/
  14490. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  14491. #define __JUCE_ZIPFILE_JUCEHEADER__
  14492. /*** Start of inlined file: juce_InputSource.h ***/
  14493. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  14494. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  14495. /**
  14496. A lightweight object that can create a stream to read some kind of resource.
  14497. This may be used to refer to a file, or some other kind of source, allowing a
  14498. caller to create an input stream that can read from it when required.
  14499. @see FileInputSource
  14500. */
  14501. class JUCE_API InputSource
  14502. {
  14503. public:
  14504. InputSource() throw() {}
  14505. /** Destructor. */
  14506. virtual ~InputSource() {}
  14507. /** Returns a new InputStream to read this item.
  14508. @returns an inputstream that the caller will delete, or 0 if
  14509. the filename isn't found.
  14510. */
  14511. virtual InputStream* createInputStream() = 0;
  14512. /** Returns a new InputStream to read an item, relative.
  14513. @param relatedItemPath the relative pathname of the resource that is required
  14514. @returns an inputstream that the caller will delete, or 0 if
  14515. the item isn't found.
  14516. */
  14517. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  14518. /** Returns a hash code that uniquely represents this item.
  14519. */
  14520. virtual int64 hashCode() const = 0;
  14521. private:
  14522. JUCE_LEAK_DETECTOR (InputSource);
  14523. };
  14524. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  14525. /*** End of inlined file: juce_InputSource.h ***/
  14526. /**
  14527. Decodes a ZIP file from a stream.
  14528. This can enumerate the items in a ZIP file and can create suitable stream objects
  14529. to read each one.
  14530. */
  14531. class JUCE_API ZipFile
  14532. {
  14533. public:
  14534. /** Creates a ZipFile for a given stream.
  14535. @param inputStream the stream to read from
  14536. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  14537. will be deleted when this ZipFile object is deleted
  14538. */
  14539. ZipFile (InputStream* inputStream, bool deleteStreamWhenDestroyed);
  14540. /** Creates a ZipFile based for a file. */
  14541. ZipFile (const File& file);
  14542. /** Creates a ZipFile for an input source.
  14543. The inputSource object will be owned by the zip file, which will delete
  14544. it later when not needed.
  14545. */
  14546. ZipFile (InputSource* inputSource);
  14547. /** Destructor. */
  14548. ~ZipFile();
  14549. /**
  14550. Contains information about one of the entries in a ZipFile.
  14551. @see ZipFile::getEntry
  14552. */
  14553. struct ZipEntry
  14554. {
  14555. /** The name of the file, which may also include a partial pathname. */
  14556. String filename;
  14557. /** The file's original size. */
  14558. unsigned int uncompressedSize;
  14559. /** The last time the file was modified. */
  14560. Time fileTime;
  14561. };
  14562. /** Returns the number of items in the zip file. */
  14563. int getNumEntries() const throw();
  14564. /** Returns a structure that describes one of the entries in the zip file.
  14565. This may return zero if the index is out of range.
  14566. @see ZipFile::ZipEntry
  14567. */
  14568. const ZipEntry* getEntry (int index) const throw();
  14569. /** Returns the index of the first entry with a given filename.
  14570. This uses a case-sensitive comparison to look for a filename in the
  14571. list of entries. It might return -1 if no match is found.
  14572. @see ZipFile::ZipEntry
  14573. */
  14574. int getIndexOfFileName (const String& fileName) const throw();
  14575. /** Returns a structure that describes one of the entries in the zip file.
  14576. This uses a case-sensitive comparison to look for a filename in the
  14577. list of entries. It might return 0 if no match is found.
  14578. @see ZipFile::ZipEntry
  14579. */
  14580. const ZipEntry* getEntry (const String& fileName) const throw();
  14581. /** Sorts the list of entries, based on the filename.
  14582. */
  14583. void sortEntriesByFilename();
  14584. /** Creates a stream that can read from one of the zip file's entries.
  14585. The stream that is returned must be deleted by the caller (and
  14586. zero might be returned if a stream can't be opened for some reason).
  14587. The stream must not be used after the ZipFile object that created
  14588. has been deleted.
  14589. */
  14590. InputStream* createStreamForEntry (int index);
  14591. /** Creates a stream that can read from one of the zip file's entries.
  14592. The stream that is returned must be deleted by the caller (and
  14593. zero might be returned if a stream can't be opened for some reason).
  14594. The stream must not be used after the ZipFile object that created
  14595. has been deleted.
  14596. */
  14597. InputStream* createStreamForEntry (ZipEntry& entry);
  14598. /** Uncompresses all of the files in the zip file.
  14599. This will expand all the entries into a target directory. The relative
  14600. paths of the entries are used.
  14601. @param targetDirectory the root folder to uncompress to
  14602. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  14603. @returns true if all the files are successfully unzipped
  14604. */
  14605. bool uncompressTo (const File& targetDirectory,
  14606. bool shouldOverwriteFiles = true);
  14607. /** Uncompresses one of the entries from the zip file.
  14608. This will expand the entry and write it in a target directory. The entry's path is used to
  14609. determine which subfolder of the target should contain the new file.
  14610. @param index the index of the entry to uncompress
  14611. @param targetDirectory the root folder to uncompress into
  14612. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  14613. @returns true if the files is successfully unzipped
  14614. */
  14615. bool uncompressEntry (int index,
  14616. const File& targetDirectory,
  14617. bool shouldOverwriteFiles = true);
  14618. private:
  14619. class ZipInputStream;
  14620. class ZipFilenameComparator;
  14621. class ZipEntryInfo;
  14622. friend class ZipInputStream;
  14623. friend class ZipFilenameComparator;
  14624. friend class ZipEntryInfo;
  14625. OwnedArray <ZipEntryInfo> entries;
  14626. CriticalSection lock;
  14627. InputStream* inputStream;
  14628. ScopedPointer <InputStream> streamToDelete;
  14629. ScopedPointer <InputSource> inputSource;
  14630. #if JUCE_DEBUG
  14631. int numOpenStreams;
  14632. #endif
  14633. void init();
  14634. int findEndOfZipEntryTable (InputStream& input, int& numEntries);
  14635. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  14636. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipFile);
  14637. };
  14638. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  14639. /*** End of inlined file: juce_ZipFile.h ***/
  14640. #endif
  14641. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  14642. /*** Start of inlined file: juce_MACAddress.h ***/
  14643. #ifndef __JUCE_MACADDRESS_JUCEHEADER__
  14644. #define __JUCE_MACADDRESS_JUCEHEADER__
  14645. /**
  14646. A wrapper for a streaming (TCP) socket.
  14647. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  14648. sockets, you could also try the InterprocessConnection class.
  14649. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  14650. */
  14651. class JUCE_API MACAddress
  14652. {
  14653. public:
  14654. /** Populates a list of the MAC addresses of all the available network cards. */
  14655. static void findAllAddresses (Array<MACAddress>& results);
  14656. /** Creates a null address (00-00-00-00-00-00). */
  14657. MACAddress();
  14658. /** Creates a copy of another address. */
  14659. MACAddress (const MACAddress& other);
  14660. /** Creates a copy of another address. */
  14661. MACAddress& operator= (const MACAddress& other);
  14662. /** Creates an address from 6 bytes. */
  14663. explicit MACAddress (const uint8 bytes[6]);
  14664. /** Returns a pointer to the 6 bytes that make up this address. */
  14665. const uint8* getBytes() const throw() { return asBytes; }
  14666. /** Returns a dash-separated string in the form "11-22-33-44-55-66" */
  14667. const String toString() const;
  14668. /** Returns the address in the lower 6 bytes of an int64.
  14669. This uses a little-endian arrangement, with the first byte of the address being
  14670. stored in the least-significant byte of the result value.
  14671. */
  14672. int64 toInt64() const throw();
  14673. /** Returns true if this address is null (00-00-00-00-00-00). */
  14674. bool isNull() const throw();
  14675. bool operator== (const MACAddress& other) const throw();
  14676. bool operator!= (const MACAddress& other) const throw();
  14677. private:
  14678. #ifndef DOXYGEN
  14679. union
  14680. {
  14681. uint64 asInt64;
  14682. uint8 asBytes[6];
  14683. };
  14684. #endif
  14685. };
  14686. #endif // __JUCE_MACADDRESS_JUCEHEADER__
  14687. /*** End of inlined file: juce_MACAddress.h ***/
  14688. #endif
  14689. #ifndef __JUCE_SOCKET_JUCEHEADER__
  14690. /*** Start of inlined file: juce_Socket.h ***/
  14691. #ifndef __JUCE_SOCKET_JUCEHEADER__
  14692. #define __JUCE_SOCKET_JUCEHEADER__
  14693. /**
  14694. A wrapper for a streaming (TCP) socket.
  14695. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  14696. sockets, you could also try the InterprocessConnection class.
  14697. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  14698. */
  14699. class JUCE_API StreamingSocket
  14700. {
  14701. public:
  14702. /** Creates an uninitialised socket.
  14703. To connect it, use the connect() method, after which you can read() or write()
  14704. to it.
  14705. To wait for other sockets to connect to this one, the createListener() method
  14706. enters "listener" mode, and can be used to spawn new sockets for each connection
  14707. that comes along.
  14708. */
  14709. StreamingSocket();
  14710. /** Destructor. */
  14711. ~StreamingSocket();
  14712. /** Binds the socket to the specified local port.
  14713. @returns true on success; false may indicate that another socket is already bound
  14714. on the same port
  14715. */
  14716. bool bindToPort (int localPortNumber);
  14717. /** Tries to connect the socket to hostname:port.
  14718. If timeOutMillisecs is 0, then this method will block until the operating system
  14719. rejects the connection (which could take a long time).
  14720. @returns true if it succeeds.
  14721. @see isConnected
  14722. */
  14723. bool connect (const String& remoteHostname,
  14724. int remotePortNumber,
  14725. int timeOutMillisecs = 3000);
  14726. /** True if the socket is currently connected. */
  14727. bool isConnected() const throw() { return connected; }
  14728. /** Closes the connection. */
  14729. void close();
  14730. /** Returns the name of the currently connected host. */
  14731. const String& getHostName() const throw() { return hostName; }
  14732. /** Returns the port number that's currently open. */
  14733. int getPort() const throw() { return portNumber; }
  14734. /** True if the socket is connected to this machine rather than over the network. */
  14735. bool isLocal() const throw();
  14736. /** Waits until the socket is ready for reading or writing.
  14737. If readyForReading is true, it will wait until the socket is ready for
  14738. reading; if false, it will wait until it's ready for writing.
  14739. If the timeout is < 0, it will wait forever, or else will give up after
  14740. the specified time.
  14741. If the socket is ready on return, this returns 1. If it times-out before
  14742. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  14743. */
  14744. int waitUntilReady (bool readyForReading,
  14745. int timeoutMsecs) const;
  14746. /** Reads bytes from the socket.
  14747. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  14748. maxBytesToRead bytes have been read, (or until an error occurs). If this
  14749. flag is false, the method will return as much data as is currently available
  14750. without blocking.
  14751. @returns the number of bytes read, or -1 if there was an error.
  14752. @see waitUntilReady
  14753. */
  14754. int read (void* destBuffer, int maxBytesToRead,
  14755. bool blockUntilSpecifiedAmountHasArrived);
  14756. /** Writes bytes to the socket from a buffer.
  14757. Note that this method will block unless you have checked the socket is ready
  14758. for writing before calling it (see the waitUntilReady() method).
  14759. @returns the number of bytes written, or -1 if there was an error.
  14760. */
  14761. int write (const void* sourceBuffer, int numBytesToWrite);
  14762. /** Puts this socket into "listener" mode.
  14763. When in this mode, your thread can call waitForNextConnection() repeatedly,
  14764. which will spawn new sockets for each new connection, so that these can
  14765. be handled in parallel by other threads.
  14766. @param portNumber the port number to listen on
  14767. @param localHostName the interface address to listen on - pass an empty
  14768. string to listen on all addresses
  14769. @returns true if it manages to open the socket successfully.
  14770. @see waitForNextConnection
  14771. */
  14772. bool createListener (int portNumber, const String& localHostName = String::empty);
  14773. /** When in "listener" mode, this waits for a connection and spawns it as a new
  14774. socket.
  14775. The object that gets returned will be owned by the caller.
  14776. This method can only be called after using createListener().
  14777. @see createListener
  14778. */
  14779. StreamingSocket* waitForNextConnection() const;
  14780. private:
  14781. String hostName;
  14782. int volatile portNumber, handle;
  14783. bool connected, isListener;
  14784. StreamingSocket (const String& hostname, int portNumber, int handle);
  14785. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StreamingSocket);
  14786. };
  14787. /**
  14788. A wrapper for a datagram (UDP) socket.
  14789. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  14790. sockets, you could also try the InterprocessConnection class.
  14791. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  14792. */
  14793. class JUCE_API DatagramSocket
  14794. {
  14795. public:
  14796. /**
  14797. Creates an (uninitialised) datagram socket.
  14798. The localPortNumber is the port on which to bind this socket. If this value is 0,
  14799. the port number is assigned by the operating system.
  14800. To use the socket for sending, call the connect() method. This will not immediately
  14801. make a connection, but will save the destination you've provided. After this, you can
  14802. call read() or write().
  14803. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  14804. (may require extra privileges on linux)
  14805. To wait for other sockets to connect to this one, call waitForNextConnection().
  14806. */
  14807. DatagramSocket (int localPortNumber,
  14808. bool enableBroadcasting = false);
  14809. /** Destructor. */
  14810. ~DatagramSocket();
  14811. /** Binds the socket to the specified local port.
  14812. @returns true on success; false may indicate that another socket is already bound
  14813. on the same port
  14814. */
  14815. bool bindToPort (int localPortNumber);
  14816. /** Tries to connect the socket to hostname:port.
  14817. If timeOutMillisecs is 0, then this method will block until the operating system
  14818. rejects the connection (which could take a long time).
  14819. @returns true if it succeeds.
  14820. @see isConnected
  14821. */
  14822. bool connect (const String& remoteHostname,
  14823. int remotePortNumber,
  14824. int timeOutMillisecs = 3000);
  14825. /** True if the socket is currently connected. */
  14826. bool isConnected() const throw() { return connected; }
  14827. /** Closes the connection. */
  14828. void close();
  14829. /** Returns the name of the currently connected host. */
  14830. const String& getHostName() const throw() { return hostName; }
  14831. /** Returns the port number that's currently open. */
  14832. int getPort() const throw() { return portNumber; }
  14833. /** True if the socket is connected to this machine rather than over the network. */
  14834. bool isLocal() const throw();
  14835. /** Waits until the socket is ready for reading or writing.
  14836. If readyForReading is true, it will wait until the socket is ready for
  14837. reading; if false, it will wait until it's ready for writing.
  14838. If the timeout is < 0, it will wait forever, or else will give up after
  14839. the specified time.
  14840. If the socket is ready on return, this returns 1. If it times-out before
  14841. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  14842. */
  14843. int waitUntilReady (bool readyForReading,
  14844. int timeoutMsecs) const;
  14845. /** Reads bytes from the socket.
  14846. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  14847. maxBytesToRead bytes have been read, (or until an error occurs). If this
  14848. flag is false, the method will return as much data as is currently available
  14849. without blocking.
  14850. @returns the number of bytes read, or -1 if there was an error.
  14851. @see waitUntilReady
  14852. */
  14853. int read (void* destBuffer, int maxBytesToRead,
  14854. bool blockUntilSpecifiedAmountHasArrived);
  14855. /** Writes bytes to the socket from a buffer.
  14856. Note that this method will block unless you have checked the socket is ready
  14857. for writing before calling it (see the waitUntilReady() method).
  14858. @returns the number of bytes written, or -1 if there was an error.
  14859. */
  14860. int write (const void* sourceBuffer, int numBytesToWrite);
  14861. /** This waits for incoming data to be sent, and returns a socket that can be used
  14862. to read it.
  14863. The object that gets returned is owned by the caller, and can't be used for
  14864. sending, but can be used to read the data.
  14865. */
  14866. DatagramSocket* waitForNextConnection() const;
  14867. private:
  14868. String hostName;
  14869. int volatile portNumber, handle;
  14870. bool connected, allowBroadcast;
  14871. void* serverAddress;
  14872. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  14873. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DatagramSocket);
  14874. };
  14875. #endif // __JUCE_SOCKET_JUCEHEADER__
  14876. /*** End of inlined file: juce_Socket.h ***/
  14877. #endif
  14878. #ifndef __JUCE_URL_JUCEHEADER__
  14879. /*** Start of inlined file: juce_URL.h ***/
  14880. #ifndef __JUCE_URL_JUCEHEADER__
  14881. #define __JUCE_URL_JUCEHEADER__
  14882. /**
  14883. Represents a URL and has a bunch of useful functions to manipulate it.
  14884. This class can be used to launch URLs in browsers, and also to create
  14885. InputStreams that can read from remote http or ftp sources.
  14886. */
  14887. class JUCE_API URL
  14888. {
  14889. public:
  14890. /** Creates an empty URL. */
  14891. URL();
  14892. /** Creates a URL from a string. */
  14893. URL (const String& url);
  14894. /** Creates a copy of another URL. */
  14895. URL (const URL& other);
  14896. /** Destructor. */
  14897. ~URL();
  14898. /** Copies this URL from another one. */
  14899. URL& operator= (const URL& other);
  14900. /** Returns a string version of the URL.
  14901. If includeGetParameters is true and any parameters have been set with the
  14902. withParameter() method, then the string will have these appended on the
  14903. end and url-encoded.
  14904. */
  14905. const String toString (bool includeGetParameters) const;
  14906. /** True if it seems to be valid. */
  14907. bool isWellFormed() const;
  14908. /** Returns just the domain part of the URL.
  14909. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  14910. */
  14911. const String getDomain() const;
  14912. /** Returns the path part of the URL.
  14913. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  14914. */
  14915. const String getSubPath() const;
  14916. /** Returns the scheme of the URL.
  14917. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  14918. include the colon).
  14919. */
  14920. const String getScheme() const;
  14921. /** Returns a new version of this URL that uses a different sub-path.
  14922. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  14923. "bar", it'll return "http://www.xyz.com/bar?x=1".
  14924. */
  14925. const URL withNewSubPath (const String& newPath) const;
  14926. /** Returns a copy of this URL, with a GET or POST parameter added to the end.
  14927. Any control characters in the value will be encoded.
  14928. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  14929. would produce a new url whose toString(true) method would return
  14930. "www.fish.com?amount=some+fish".
  14931. */
  14932. const URL withParameter (const String& parameterName,
  14933. const String& parameterValue) const;
  14934. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  14935. When performing a POST where one of your parameters is a binary file, this
  14936. lets you specify the file.
  14937. Note that the filename is stored, but the file itself won't actually be read
  14938. until this URL is later used to create a network input stream.
  14939. */
  14940. const URL withFileToUpload (const String& parameterName,
  14941. const File& fileToUpload,
  14942. const String& mimeType) const;
  14943. /** Returns a set of all the parameters encoded into the url.
  14944. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  14945. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  14946. The values returned will have been cleaned up to remove any escape characters.
  14947. @see getNamedParameter, withParameter
  14948. */
  14949. const StringPairArray& getParameters() const;
  14950. /** Returns the set of files that should be uploaded as part of a POST operation.
  14951. This is the set of files that were added to the URL with the withFileToUpload()
  14952. method.
  14953. */
  14954. const StringPairArray& getFilesToUpload() const;
  14955. /** Returns the set of mime types associated with each of the upload files.
  14956. */
  14957. const StringPairArray& getMimeTypesOfUploadFiles() const;
  14958. /** Returns a copy of this URL, with a block of data to send as the POST data.
  14959. If you're setting the POST data, be careful not to have any parameters set
  14960. as well, otherwise it'll all get thrown in together, and might not have the
  14961. desired effect.
  14962. If the URL already contains some POST data, this will replace it, rather
  14963. than being appended to it.
  14964. This data will only be used if you specify a post operation when you call
  14965. createInputStream().
  14966. */
  14967. const URL withPOSTData (const String& postData) const;
  14968. /** Returns the data that was set using withPOSTData().
  14969. */
  14970. const String getPostData() const { return postData; }
  14971. /** Tries to launch the system's default browser to open the URL.
  14972. Returns true if this seems to have worked.
  14973. */
  14974. bool launchInDefaultBrowser() const;
  14975. /** Takes a guess as to whether a string might be a valid website address.
  14976. This isn't foolproof!
  14977. */
  14978. static bool isProbablyAWebsiteURL (const String& possibleURL);
  14979. /** Takes a guess as to whether a string might be a valid email address.
  14980. This isn't foolproof!
  14981. */
  14982. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  14983. /** This callback function can be used by the createInputStream() method.
  14984. It allows your app to receive progress updates during a lengthy POST operation. If you
  14985. want to continue the operation, this should return true, or false to abort.
  14986. */
  14987. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  14988. /** Attempts to open a stream that can read from this URL.
  14989. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  14990. the paramters, otherwise it'll encode them into the
  14991. URL and do a 'GET'.
  14992. @param progressCallback if this is non-zero, it lets you supply a callback function
  14993. to keep track of the operation's progress. This can be useful
  14994. for lengthy POST operations, so that you can provide user feedback.
  14995. @param progressCallbackContext if a callback is specified, this value will be passed to
  14996. the function
  14997. @param extraHeaders if not empty, this string is appended onto the headers that
  14998. are used for the request. It must therefore be a valid set of HTML
  14999. header directives, separated by newlines.
  15000. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  15001. a negative number, it will be infinite. Otherwise it specifies a
  15002. time in milliseconds.
  15003. @param responseHeaders if this is non-zero, all the (key, value) pairs received as headers
  15004. in the response will be stored in this array
  15005. @returns an input stream that the caller must delete, or a null pointer if there was an
  15006. error trying to open it.
  15007. */
  15008. InputStream* createInputStream (bool usePostCommand,
  15009. OpenStreamProgressCallback* progressCallback = 0,
  15010. void* progressCallbackContext = 0,
  15011. const String& extraHeaders = String::empty,
  15012. int connectionTimeOutMs = 0,
  15013. StringPairArray* responseHeaders = 0) const;
  15014. /** Tries to download the entire contents of this URL into a binary data block.
  15015. If it succeeds, this will return true and append the data it read onto the end
  15016. of the memory block.
  15017. @param destData the memory block to append the new data to
  15018. @param usePostCommand whether to use a POST command to get the data (uses
  15019. a GET command if this is false)
  15020. @see readEntireTextStream, readEntireXmlStream
  15021. */
  15022. bool readEntireBinaryStream (MemoryBlock& destData,
  15023. bool usePostCommand = false) const;
  15024. /** Tries to download the entire contents of this URL as a string.
  15025. If it fails, this will return an empty string, otherwise it will return the
  15026. contents of the downloaded file. If you need to distinguish between a read
  15027. operation that fails and one that returns an empty string, you'll need to use
  15028. a different method, such as readEntireBinaryStream().
  15029. @param usePostCommand whether to use a POST command to get the data (uses
  15030. a GET command if this is false)
  15031. @see readEntireBinaryStream, readEntireXmlStream
  15032. */
  15033. const String readEntireTextStream (bool usePostCommand = false) const;
  15034. /** Tries to download the entire contents of this URL and parse it as XML.
  15035. If it fails, or if the text that it reads can't be parsed as XML, this will
  15036. return 0.
  15037. When it returns a valid XmlElement object, the caller is responsibile for deleting
  15038. this object when no longer needed.
  15039. @param usePostCommand whether to use a POST command to get the data (uses
  15040. a GET command if this is false)
  15041. @see readEntireBinaryStream, readEntireTextStream
  15042. */
  15043. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  15044. /** Adds escape sequences to a string to encode any characters that aren't
  15045. legal in a URL.
  15046. E.g. any spaces will be replaced with "%20".
  15047. This is the opposite of removeEscapeChars().
  15048. If isParameter is true, it means that the string is going to be used
  15049. as a parameter, so it also encodes '$' and ',' (which would otherwise
  15050. be legal in a URL.
  15051. @see removeEscapeChars
  15052. */
  15053. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  15054. bool isParameter);
  15055. /** Replaces any escape character sequences in a string with their original
  15056. character codes.
  15057. E.g. any instances of "%20" will be replaced by a space.
  15058. This is the opposite of addEscapeChars().
  15059. @see addEscapeChars
  15060. */
  15061. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  15062. private:
  15063. String url, postData;
  15064. StringPairArray parameters, filesToUpload, mimeTypes;
  15065. static InputStream* createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  15066. OpenStreamProgressCallback* progressCallback,
  15067. void* progressCallbackContext, const String& headers,
  15068. const int timeOutMs, StringPairArray* responseHeaders);
  15069. JUCE_LEAK_DETECTOR (URL);
  15070. };
  15071. #endif // __JUCE_URL_JUCEHEADER__
  15072. /*** End of inlined file: juce_URL.h ***/
  15073. #endif
  15074. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15075. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  15076. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15077. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15078. /** Wraps another input stream, and reads from it using an intermediate buffer
  15079. If you're using an input stream such as a file input stream, and making lots of
  15080. small read accesses to it, it's probably sensible to wrap it in one of these,
  15081. so that the source stream gets accessed in larger chunk sizes, meaning less
  15082. work for the underlying stream.
  15083. */
  15084. class JUCE_API BufferedInputStream : public InputStream
  15085. {
  15086. public:
  15087. /** Creates a BufferedInputStream from an input source.
  15088. @param sourceStream the source stream to read from
  15089. @param bufferSize the size of reservoir to use to buffer the source
  15090. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  15091. deleted by this object when it is itself deleted.
  15092. */
  15093. BufferedInputStream (InputStream* sourceStream,
  15094. int bufferSize,
  15095. bool deleteSourceWhenDestroyed);
  15096. /** Creates a BufferedInputStream from an input source.
  15097. @param sourceStream the source stream to read from - the source stream must not
  15098. be deleted until this object has been destroyed.
  15099. @param bufferSize the size of reservoir to use to buffer the source
  15100. */
  15101. BufferedInputStream (InputStream& sourceStream, int bufferSize);
  15102. /** Destructor.
  15103. This may also delete the source stream, if that option was chosen when the
  15104. buffered stream was created.
  15105. */
  15106. ~BufferedInputStream();
  15107. int64 getTotalLength();
  15108. int64 getPosition();
  15109. bool setPosition (int64 newPosition);
  15110. int read (void* destBuffer, int maxBytesToRead);
  15111. const String readString();
  15112. bool isExhausted();
  15113. private:
  15114. InputStream* const source;
  15115. ScopedPointer <InputStream> sourceToDelete;
  15116. int bufferSize;
  15117. int64 position, lastReadPos, bufferStart, bufferOverlap;
  15118. HeapBlock <char> buffer;
  15119. void ensureBuffered();
  15120. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferedInputStream);
  15121. };
  15122. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  15123. /*** End of inlined file: juce_BufferedInputStream.h ***/
  15124. #endif
  15125. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15126. /*** Start of inlined file: juce_FileInputSource.h ***/
  15127. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15128. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15129. /**
  15130. A type of InputSource that represents a normal file.
  15131. @see InputSource
  15132. */
  15133. class JUCE_API FileInputSource : public InputSource
  15134. {
  15135. public:
  15136. FileInputSource (const File& file, bool useFileTimeInHashGeneration = false);
  15137. ~FileInputSource();
  15138. InputStream* createInputStream();
  15139. InputStream* createInputStreamFor (const String& relatedItemPath);
  15140. int64 hashCode() const;
  15141. private:
  15142. const File file;
  15143. bool useFileTimeInHashGeneration;
  15144. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileInputSource);
  15145. };
  15146. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  15147. /*** End of inlined file: juce_FileInputSource.h ***/
  15148. #endif
  15149. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15150. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  15151. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15152. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15153. /**
  15154. A stream which uses zlib to compress the data written into it.
  15155. @see GZIPDecompressorInputStream
  15156. */
  15157. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  15158. {
  15159. public:
  15160. /** Creates a compression stream.
  15161. @param destStream the stream into which the compressed data should
  15162. be written
  15163. @param compressionLevel how much to compress the data, between 1 and 9, where
  15164. 1 is the fastest/lowest compression, and 9 is the
  15165. slowest/highest compression. Any value outside this range
  15166. indicates that a default compression level should be used.
  15167. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  15168. this stream is destroyed
  15169. @param windowBits this is used internally to change the window size used
  15170. by zlib - leave it as 0 unless you specifically need to set
  15171. its value for some reason
  15172. */
  15173. GZIPCompressorOutputStream (OutputStream* destStream,
  15174. int compressionLevel = 0,
  15175. bool deleteDestStreamWhenDestroyed = false,
  15176. int windowBits = 0);
  15177. /** Destructor. */
  15178. ~GZIPCompressorOutputStream();
  15179. void flush();
  15180. int64 getPosition();
  15181. bool setPosition (int64 newPosition);
  15182. bool write (const void* destBuffer, int howMany);
  15183. /** These are preset values that can be used for the constructor's windowBits paramter.
  15184. For more info about this, see the zlib documentation for its windowBits parameter.
  15185. */
  15186. enum WindowBitsValues
  15187. {
  15188. windowBitsRaw = -15,
  15189. windowBitsGZIP = 15 + 16
  15190. };
  15191. private:
  15192. OutputStream* const destStream;
  15193. ScopedPointer <OutputStream> streamToDelete;
  15194. HeapBlock <uint8> buffer;
  15195. class GZIPCompressorHelper;
  15196. friend class ScopedPointer <GZIPCompressorHelper>;
  15197. ScopedPointer <GZIPCompressorHelper> helper;
  15198. bool doNextBlock();
  15199. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPCompressorOutputStream);
  15200. };
  15201. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  15202. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  15203. #endif
  15204. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  15205. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  15206. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  15207. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  15208. /**
  15209. This stream will decompress a source-stream using zlib.
  15210. Tip: if you're reading lots of small items from one of these streams, you
  15211. can increase the performance enormously by passing it through a
  15212. BufferedInputStream, so that it has to read larger blocks less often.
  15213. @see GZIPCompressorOutputStream
  15214. */
  15215. class JUCE_API GZIPDecompressorInputStream : public InputStream
  15216. {
  15217. public:
  15218. /** Creates a decompressor stream.
  15219. @param sourceStream the stream to read from
  15220. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  15221. when this object is destroyed
  15222. @param noWrap this is used internally by the ZipFile class
  15223. and should be ignored by user applications
  15224. @param uncompressedStreamLength if the creator knows the length that the
  15225. uncompressed stream will be, then it can supply this
  15226. value, which will be returned by getTotalLength()
  15227. */
  15228. GZIPDecompressorInputStream (InputStream* sourceStream,
  15229. bool deleteSourceWhenDestroyed,
  15230. bool noWrap = false,
  15231. int64 uncompressedStreamLength = -1);
  15232. /** Creates a decompressor stream.
  15233. @param sourceStream the stream to read from - the source stream must not be
  15234. deleted until this object has been destroyed
  15235. */
  15236. GZIPDecompressorInputStream (InputStream& sourceStream);
  15237. /** Destructor. */
  15238. ~GZIPDecompressorInputStream();
  15239. int64 getPosition();
  15240. bool setPosition (int64 pos);
  15241. int64 getTotalLength();
  15242. bool isExhausted();
  15243. int read (void* destBuffer, int maxBytesToRead);
  15244. private:
  15245. InputStream* const sourceStream;
  15246. ScopedPointer <InputStream> streamToDelete;
  15247. const int64 uncompressedStreamLength;
  15248. const bool noWrap;
  15249. bool isEof;
  15250. int activeBufferSize;
  15251. int64 originalSourcePos, currentPos;
  15252. HeapBlock <uint8> buffer;
  15253. class GZIPDecompressHelper;
  15254. friend class ScopedPointer <GZIPDecompressHelper>;
  15255. ScopedPointer <GZIPDecompressHelper> helper;
  15256. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GZIPDecompressorInputStream);
  15257. };
  15258. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  15259. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  15260. #endif
  15261. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  15262. #endif
  15263. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  15264. #endif
  15265. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  15266. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  15267. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  15268. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  15269. /**
  15270. Allows a block of data and to be accessed as a stream.
  15271. This can either be used to refer to a shared block of memory, or can make its
  15272. own internal copy of the data when the MemoryInputStream is created.
  15273. */
  15274. class JUCE_API MemoryInputStream : public InputStream
  15275. {
  15276. public:
  15277. /** Creates a MemoryInputStream.
  15278. @param sourceData the block of data to use as the stream's source
  15279. @param sourceDataSize the number of bytes in the source data block
  15280. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  15281. the source data, so this data shouldn't be changed
  15282. for the lifetime of the stream; if this parameter is
  15283. true, the stream will make its own copy of the
  15284. data and use that.
  15285. */
  15286. MemoryInputStream (const void* sourceData,
  15287. size_t sourceDataSize,
  15288. bool keepInternalCopyOfData);
  15289. /** Creates a MemoryInputStream.
  15290. @param data a block of data to use as the stream's source
  15291. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  15292. the source data, so this data shouldn't be changed
  15293. for the lifetime of the stream; if this parameter is
  15294. true, the stream will make its own copy of the
  15295. data and use that.
  15296. */
  15297. MemoryInputStream (const MemoryBlock& data,
  15298. bool keepInternalCopyOfData);
  15299. /** Destructor. */
  15300. ~MemoryInputStream();
  15301. int64 getPosition();
  15302. bool setPosition (int64 pos);
  15303. int64 getTotalLength();
  15304. bool isExhausted();
  15305. int read (void* destBuffer, int maxBytesToRead);
  15306. private:
  15307. const char* data;
  15308. size_t dataSize, position;
  15309. MemoryBlock internalCopy;
  15310. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryInputStream);
  15311. };
  15312. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  15313. /*** End of inlined file: juce_MemoryInputStream.h ***/
  15314. #endif
  15315. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  15316. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  15317. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  15318. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  15319. /**
  15320. Writes data to an internal memory buffer, which grows as required.
  15321. The data that was written into the stream can then be accessed later as
  15322. a contiguous block of memory.
  15323. */
  15324. class JUCE_API MemoryOutputStream : public OutputStream
  15325. {
  15326. public:
  15327. /** Creates an empty memory stream ready for writing into.
  15328. @param initialSize the intial amount of capacity to allocate for writing into
  15329. */
  15330. MemoryOutputStream (size_t initialSize = 256);
  15331. /** Creates a memory stream for writing into into a pre-existing MemoryBlock object.
  15332. Note that the destination block will always be larger than the amount of data
  15333. that has been written to the stream, because the MemoryOutputStream keeps some
  15334. spare capactity at its end. To trim the block's size down to fit the actual
  15335. data, call flush(), or delete the MemoryOutputStream.
  15336. @param memoryBlockToWriteTo the block into which new data will be written.
  15337. @param appendToExistingBlockContent if this is true, the contents of the block will be
  15338. kept, and new data will be appended to it. If false,
  15339. the block will be cleared before use
  15340. */
  15341. MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  15342. bool appendToExistingBlockContent);
  15343. /** Destructor.
  15344. This will free any data that was written to it.
  15345. */
  15346. ~MemoryOutputStream();
  15347. /** Returns a pointer to the data that has been written to the stream.
  15348. @see getDataSize
  15349. */
  15350. const void* getData() const throw();
  15351. /** Returns the number of bytes of data that have been written to the stream.
  15352. @see getData
  15353. */
  15354. size_t getDataSize() const throw() { return size; }
  15355. /** Resets the stream, clearing any data that has been written to it so far. */
  15356. void reset() throw();
  15357. /** Increases the internal storage capacity to be able to contain at least the specified
  15358. amount of data without needing to be resized.
  15359. */
  15360. void preallocate (size_t bytesToPreallocate);
  15361. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  15362. const String toUTF8() const;
  15363. /** Attempts to detect the encoding of the data and convert it to a string.
  15364. @see String::createStringFromData
  15365. */
  15366. const String toString() const;
  15367. /** If the stream is writing to a user-supplied MemoryBlock, this will trim any excess
  15368. capacity off the block, so that its length matches the amount of actual data that
  15369. has been written so far.
  15370. */
  15371. void flush();
  15372. bool write (const void* buffer, int howMany);
  15373. int64 getPosition() { return position; }
  15374. bool setPosition (int64 newPosition);
  15375. int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  15376. private:
  15377. MemoryBlock& data;
  15378. MemoryBlock internalBlock;
  15379. size_t position, size;
  15380. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryOutputStream);
  15381. };
  15382. /** Copies all the data that has been written to a MemoryOutputStream into another stream. */
  15383. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead);
  15384. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  15385. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  15386. #endif
  15387. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  15388. #endif
  15389. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  15390. /*** Start of inlined file: juce_SubregionStream.h ***/
  15391. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  15392. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  15393. /** Wraps another input stream, and reads from a specific part of it.
  15394. This lets you take a subsection of a stream and present it as an entire
  15395. stream in its own right.
  15396. */
  15397. class JUCE_API SubregionStream : public InputStream
  15398. {
  15399. public:
  15400. /** Creates a SubregionStream from an input source.
  15401. @param sourceStream the source stream to read from
  15402. @param startPositionInSourceStream this is the position in the source stream that
  15403. corresponds to position 0 in this stream
  15404. @param lengthOfSourceStream this specifies the maximum number of bytes
  15405. from the source stream that will be passed through
  15406. by this stream. When the position of this stream
  15407. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  15408. If the length passed in here is greater than the length
  15409. of the source stream (as returned by getTotalLength()),
  15410. then the smaller value will be used.
  15411. Passing a negative value for this parameter means it
  15412. will keep reading until the source's end-of-stream.
  15413. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  15414. deleted by this object when it is itself deleted.
  15415. */
  15416. SubregionStream (InputStream* sourceStream,
  15417. int64 startPositionInSourceStream,
  15418. int64 lengthOfSourceStream,
  15419. bool deleteSourceWhenDestroyed);
  15420. /** Destructor.
  15421. This may also delete the source stream, if that option was chosen when the
  15422. buffered stream was created.
  15423. */
  15424. ~SubregionStream();
  15425. int64 getTotalLength();
  15426. int64 getPosition();
  15427. bool setPosition (int64 newPosition);
  15428. int read (void* destBuffer, int maxBytesToRead);
  15429. bool isExhausted();
  15430. private:
  15431. InputStream* const source;
  15432. ScopedPointer <InputStream> sourceToDelete;
  15433. const int64 startPositionInSourceStream, lengthOfSourceStream;
  15434. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubregionStream);
  15435. };
  15436. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  15437. /*** End of inlined file: juce_SubregionStream.h ***/
  15438. #endif
  15439. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  15440. #endif
  15441. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  15442. /*** Start of inlined file: juce_Expression.h ***/
  15443. #ifndef __JUCE_EXPRESSION_JUCEHEADER__
  15444. #define __JUCE_EXPRESSION_JUCEHEADER__
  15445. /**
  15446. A class for dynamically evaluating simple numeric expressions.
  15447. This class can parse a simple C-style string expression involving floating point
  15448. numbers, named symbols and functions. The basic arithmetic operations of +, -, *, /
  15449. are supported, as well as parentheses, and any alphanumeric identifiers are
  15450. assumed to be named symbols which will be resolved when the expression is
  15451. evaluated.
  15452. Expressions which use identifiers and functions require a subclass of
  15453. Expression::Scope to be supplied when evaluating them, and this object
  15454. is expected to be able to resolve the symbol names and perform the functions that
  15455. are used.
  15456. */
  15457. class JUCE_API Expression
  15458. {
  15459. public:
  15460. /** Creates a simple expression with a value of 0. */
  15461. Expression();
  15462. /** Destructor. */
  15463. ~Expression();
  15464. /** Creates a simple expression with a specified constant value. */
  15465. explicit Expression (double constant);
  15466. /** Creates a copy of an expression. */
  15467. Expression (const Expression& other);
  15468. /** Copies another expression. */
  15469. Expression& operator= (const Expression& other);
  15470. /** Creates an expression by parsing a string.
  15471. If there's a syntax error in the string, this will throw a ParseError exception.
  15472. @throws ParseError
  15473. */
  15474. explicit Expression (const String& stringToParse);
  15475. /** Returns a string version of the expression. */
  15476. const String toString() const;
  15477. /** Returns an expression which is an addtion operation of two existing expressions. */
  15478. const Expression operator+ (const Expression& other) const;
  15479. /** Returns an expression which is a subtraction operation of two existing expressions. */
  15480. const Expression operator- (const Expression& other) const;
  15481. /** Returns an expression which is a multiplication operation of two existing expressions. */
  15482. const Expression operator* (const Expression& other) const;
  15483. /** Returns an expression which is a division operation of two existing expressions. */
  15484. const Expression operator/ (const Expression& other) const;
  15485. /** Returns an expression which performs a negation operation on an existing expression. */
  15486. const Expression operator-() const;
  15487. /** Returns an Expression which is an identifier reference. */
  15488. static const Expression symbol (const String& symbol);
  15489. /** Returns an Expression which is a function call. */
  15490. static const Expression function (const String& functionName, const Array<Expression>& parameters);
  15491. /** Returns an Expression which parses a string from a character pointer, and updates the pointer
  15492. to indicate where it finished.
  15493. The pointer is incremented so that on return, it indicates the character that follows
  15494. the end of the expression that was parsed.
  15495. If there's a syntax error in the string, this will throw a ParseError exception.
  15496. @throws ParseError
  15497. */
  15498. static const Expression parse (String::CharPointerType& stringToParse);
  15499. /** When evaluating an Expression object, this class is used to resolve symbols and
  15500. perform functions that the expression uses.
  15501. */
  15502. class JUCE_API Scope
  15503. {
  15504. public:
  15505. Scope();
  15506. virtual ~Scope();
  15507. /** Returns some kind of globally unique ID that identifies this scope. */
  15508. virtual const String getScopeUID() const;
  15509. /** Returns the value of a symbol.
  15510. If the symbol is unknown, this can throw an Expression::EvaluationError exception.
  15511. The member value is set to the part of the symbol that followed the dot, if there is
  15512. one, e.g. for "foo.bar", symbol = "foo" and member = "bar".
  15513. @throws Expression::EvaluationError
  15514. */
  15515. virtual const Expression getSymbolValue (const String& symbol) const;
  15516. /** Executes a named function.
  15517. If the function name is unknown, this can throw an Expression::EvaluationError exception.
  15518. @throws Expression::EvaluationError
  15519. */
  15520. virtual double evaluateFunction (const String& functionName,
  15521. const double* parameters, int numParameters) const;
  15522. /** Used as a callback by the Scope::visitRelativeScope() method.
  15523. You should never create an instance of this class yourself, it's used by the
  15524. expression evaluation code.
  15525. */
  15526. class Visitor
  15527. {
  15528. public:
  15529. virtual ~Visitor() {}
  15530. virtual void visit (const Scope&) = 0;
  15531. };
  15532. /** Creates a Scope object for a named scope, and then calls a visitor
  15533. to do some kind of processing with this new scope.
  15534. If the name is valid, this method must create a suitable (temporary) Scope
  15535. object to represent it, and must call the Visitor::visit() method with this
  15536. new scope.
  15537. */
  15538. virtual void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  15539. };
  15540. /** Evaluates this expression, without using a Scope.
  15541. Without a Scope, no symbols can be used, and only basic functions such as sin, cos, tan,
  15542. min, max are available.
  15543. To find out about any errors during evaluation, use the other version of this method which
  15544. takes a String parameter.
  15545. */
  15546. double evaluate() const;
  15547. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  15548. or functions that it uses.
  15549. To find out about any errors during evaluation, use the other version of this method which
  15550. takes a String parameter.
  15551. */
  15552. double evaluate (const Scope& scope) const;
  15553. /** Evaluates this expression, providing a scope that should be able to evaluate any symbols
  15554. or functions that it uses.
  15555. */
  15556. double evaluate (const Scope& scope, String& evaluationError) const;
  15557. /** Attempts to return an expression which is a copy of this one, but with a constant adjusted
  15558. to make the expression resolve to a target value.
  15559. E.g. if the expression is "x + 10" and x is 5, then asking for a target value of 8 will return
  15560. the expression "x + 3". Obviously some expressions can't be reversed in this way, in which
  15561. case they might just be adjusted by adding a constant to the original expression.
  15562. @throws Expression::EvaluationError
  15563. */
  15564. const Expression adjustedToGiveNewResult (double targetValue, const Scope& scope) const;
  15565. /** Represents a symbol that is used in an Expression. */
  15566. struct Symbol
  15567. {
  15568. Symbol (const String& scopeUID, const String& symbolName);
  15569. bool operator== (const Symbol&) const throw();
  15570. bool operator!= (const Symbol&) const throw();
  15571. String scopeUID; /**< The unique ID of the Scope that contains this symbol. */
  15572. String symbolName; /**< The name of the symbol. */
  15573. };
  15574. /** Returns a copy of this expression in which all instances of a given symbol have been renamed. */
  15575. const Expression withRenamedSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope) const;
  15576. /** Returns true if this expression makes use of the specified symbol.
  15577. If a suitable scope is supplied, the search will dereference and recursively check
  15578. all symbols, so that it can be determined whether this expression relies on the given
  15579. symbol at any level in its evaluation. If the scope parameter is null, this just checks
  15580. whether the expression contains any direct references to the symbol.
  15581. @throws Expression::EvaluationError
  15582. */
  15583. bool referencesSymbol (const Symbol& symbol, const Scope& scope) const;
  15584. /** Returns true if this expression contains any symbols. */
  15585. bool usesAnySymbols() const;
  15586. /** Returns a list of all symbols that may be needed to resolve this expression in the given scope. */
  15587. void findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const;
  15588. /** An exception that can be thrown by Expression::parse(). */
  15589. class ParseError : public std::exception
  15590. {
  15591. public:
  15592. ParseError (const String& message);
  15593. String description;
  15594. };
  15595. /** Expression type.
  15596. @see Expression::getType()
  15597. */
  15598. enum Type
  15599. {
  15600. constantType,
  15601. functionType,
  15602. operatorType,
  15603. symbolType
  15604. };
  15605. /** Returns the type of this expression. */
  15606. Type getType() const throw();
  15607. /** If this expression is a symbol, function or operator, this returns its identifier. */
  15608. const String getSymbolOrFunction() const;
  15609. /** Returns the number of inputs to this expression.
  15610. @see getInput
  15611. */
  15612. int getNumInputs() const;
  15613. /** Retrieves one of the inputs to this expression.
  15614. @see getNumInputs
  15615. */
  15616. const Expression getInput (int index) const;
  15617. private:
  15618. class Term;
  15619. class Helpers;
  15620. friend class Term;
  15621. friend class Helpers;
  15622. friend class ScopedPointer<Term>;
  15623. friend class ReferenceCountedObjectPtr<Term>;
  15624. ReferenceCountedObjectPtr<Term> term;
  15625. explicit Expression (Term* term);
  15626. };
  15627. #endif // __JUCE_EXPRESSION_JUCEHEADER__
  15628. /*** End of inlined file: juce_Expression.h ***/
  15629. #endif
  15630. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  15631. #endif
  15632. #ifndef __JUCE_RANDOM_JUCEHEADER__
  15633. /*** Start of inlined file: juce_Random.h ***/
  15634. #ifndef __JUCE_RANDOM_JUCEHEADER__
  15635. #define __JUCE_RANDOM_JUCEHEADER__
  15636. /**
  15637. A simple pseudo-random number generator.
  15638. */
  15639. class JUCE_API Random
  15640. {
  15641. public:
  15642. /** Creates a Random object based on a seed value.
  15643. For a given seed value, the subsequent numbers generated by this object
  15644. will be predictable, so a good idea is to set this value based
  15645. on the time, e.g.
  15646. new Random (Time::currentTimeMillis())
  15647. */
  15648. explicit Random (int64 seedValue) throw();
  15649. /** Destructor. */
  15650. ~Random() throw();
  15651. /** Returns the next random 32 bit integer.
  15652. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  15653. */
  15654. int nextInt() throw();
  15655. /** Returns the next random number, limited to a given range.
  15656. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  15657. */
  15658. int nextInt (int maxValue) throw();
  15659. /** Returns the next 64-bit random number.
  15660. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  15661. */
  15662. int64 nextInt64() throw();
  15663. /** Returns the next random floating-point number.
  15664. @returns a random value in the range 0 to 1.0
  15665. */
  15666. float nextFloat() throw();
  15667. /** Returns the next random floating-point number.
  15668. @returns a random value in the range 0 to 1.0
  15669. */
  15670. double nextDouble() throw();
  15671. /** Returns the next random boolean value.
  15672. */
  15673. bool nextBool() throw();
  15674. /** Returns a BigInteger containing a random number.
  15675. @returns a random value in the range 0 to (maximumValue - 1).
  15676. */
  15677. const BigInteger nextLargeNumber (const BigInteger& maximumValue);
  15678. /** Sets a range of bits in a BigInteger to random values. */
  15679. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  15680. /** To avoid the overhead of having to create a new Random object whenever
  15681. you need a number, this is a shared application-wide object that
  15682. can be used.
  15683. It's not thread-safe though, so threads should use their own Random object.
  15684. */
  15685. static Random& getSystemRandom() throw();
  15686. /** Resets this Random object to a given seed value. */
  15687. void setSeed (int64 newSeed) throw();
  15688. /** Merges this object's seed with another value.
  15689. This sets the seed to be a value created by combining the current seed and this
  15690. new value.
  15691. */
  15692. void combineSeed (int64 seedValue) throw();
  15693. /** Reseeds this generator using a value generated from various semi-random system
  15694. properties like the current time, etc.
  15695. Because this function convolves the time with the last seed value, calling
  15696. it repeatedly will increase the randomness of the final result.
  15697. */
  15698. void setSeedRandomly();
  15699. private:
  15700. int64 seed;
  15701. JUCE_LEAK_DETECTOR (Random);
  15702. };
  15703. #endif // __JUCE_RANDOM_JUCEHEADER__
  15704. /*** End of inlined file: juce_Random.h ***/
  15705. #endif
  15706. #ifndef __JUCE_RANGE_JUCEHEADER__
  15707. #endif
  15708. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  15709. #endif
  15710. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  15711. #endif
  15712. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  15713. #endif
  15714. #ifndef __JUCE_LEAKEDOBJECTDETECTOR_JUCEHEADER__
  15715. #endif
  15716. #ifndef __JUCE_MEMORY_JUCEHEADER__
  15717. #endif
  15718. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  15719. #endif
  15720. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  15721. #endif
  15722. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  15723. #endif
  15724. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  15725. /*** Start of inlined file: juce_WeakReference.h ***/
  15726. #ifndef __JUCE_WEAKREFERENCE_JUCEHEADER__
  15727. #define __JUCE_WEAKREFERENCE_JUCEHEADER__
  15728. /**
  15729. This class acts as a pointer which will automatically become null if the object
  15730. to which it points is deleted.
  15731. To accomplish this, the source object needs to cooperate by performing a couple of simple tasks.
  15732. It must provide a getWeakReference() method and embed a WeakReference::Master object, which stores
  15733. a shared pointer object. It must also clear this master pointer when it's getting deleted.
  15734. E.g.
  15735. @code
  15736. class MyObject
  15737. {
  15738. public:
  15739. MyObject()
  15740. {
  15741. // If you're planning on using your WeakReferences in a multi-threaded situation, you may choose
  15742. // to call getWeakReference() here in the constructor, which will pre-initialise it, avoiding an
  15743. // (extremely unlikely) race condition that could occur if multiple threads overlap while making
  15744. // the first call to getWeakReference().
  15745. }
  15746. ~MyObject()
  15747. {
  15748. // This will zero all the references - you need to call this in your destructor.
  15749. masterReference.clear();
  15750. }
  15751. // Your object must provide a method that looks pretty much identical to this (except
  15752. // for the templated class name, of course).
  15753. const WeakReference<MyObject>::SharedRef& getWeakReference()
  15754. {
  15755. return masterReference (this);
  15756. }
  15757. private:
  15758. // You need to embed one of these inside your object. It can be private.
  15759. WeakReference<MyObject>::Master masterReference;
  15760. };
  15761. // Here's an example of using a pointer..
  15762. MyObject* n = new MyObject();
  15763. WeakReference<MyObject> myObjectRef = n;
  15764. MyObject* pointer1 = myObjectRef; // returns a valid pointer to 'n'
  15765. delete n;
  15766. MyObject* pointer2 = myObjectRef; // returns a null pointer
  15767. @endcode
  15768. @see WeakReference::Master
  15769. */
  15770. template <class ObjectType>
  15771. class WeakReference
  15772. {
  15773. public:
  15774. /** Creates a null SafePointer. */
  15775. WeakReference() throw() {}
  15776. /** Creates a WeakReference that points at the given object. */
  15777. WeakReference (ObjectType* const object) : holder (object != 0 ? object->getWeakReference() : 0) {}
  15778. /** Creates a copy of another WeakReference. */
  15779. WeakReference (const WeakReference& other) throw() : holder (other.holder) {}
  15780. /** Copies another pointer to this one. */
  15781. WeakReference& operator= (const WeakReference& other) { holder = other.holder; return *this; }
  15782. /** Copies another pointer to this one. */
  15783. WeakReference& operator= (ObjectType* const newObject) { holder = newObject != 0 ? newObject->getWeakReference() : 0; return *this; }
  15784. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  15785. ObjectType* get() const throw() { return holder != 0 ? holder->get() : 0; }
  15786. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  15787. operator ObjectType*() const throw() { return get(); }
  15788. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  15789. ObjectType* operator->() throw() { return get(); }
  15790. /** Returns the object that this pointer refers to, or null if the object no longer exists. */
  15791. const ObjectType* operator->() const throw() { return get(); }
  15792. /** This returns true if this reference has been pointing at an object, but that object has
  15793. since been deleted.
  15794. If this reference was only ever pointing at a null pointer, this will return false. Using
  15795. operator=() to make this refer to a different object will reset this flag to match the status
  15796. of the reference from which you're copying.
  15797. */
  15798. bool wasObjectDeleted() const throw() { return holder != 0 && holder->get() == 0; }
  15799. bool operator== (ObjectType* const object) const throw() { return get() == object; }
  15800. bool operator!= (ObjectType* const object) const throw() { return get() != object; }
  15801. /** This class is used internally by the WeakReference class - don't use it directly
  15802. in your code!
  15803. @see WeakReference
  15804. */
  15805. class SharedPointer : public ReferenceCountedObject
  15806. {
  15807. public:
  15808. explicit SharedPointer (ObjectType* const owner_) throw() : owner (owner_) {}
  15809. inline ObjectType* get() const throw() { return owner; }
  15810. void clearPointer() throw() { owner = 0; }
  15811. private:
  15812. ObjectType* volatile owner;
  15813. JUCE_DECLARE_NON_COPYABLE (SharedPointer);
  15814. };
  15815. typedef ReferenceCountedObjectPtr<SharedPointer> SharedRef;
  15816. /**
  15817. This class is embedded inside an object to which you want to attach WeakReference pointers.
  15818. See the WeakReference class notes for an example of how to use this class.
  15819. @see WeakReference
  15820. */
  15821. class Master
  15822. {
  15823. public:
  15824. Master() throw() {}
  15825. ~Master()
  15826. {
  15827. // You must remember to call clear() in your source object's destructor! See the notes
  15828. // for the WeakReference class for an example of how to do this.
  15829. jassert (sharedPointer == 0 || sharedPointer->get() == 0);
  15830. }
  15831. /** The first call to this method will create an internal object that is shared by all weak
  15832. references to the object.
  15833. You need to call this from your main object's getWeakReference() method - see the WeakReference
  15834. class notes for an example.
  15835. */
  15836. const SharedRef& operator() (ObjectType* const object)
  15837. {
  15838. if (sharedPointer == 0)
  15839. {
  15840. sharedPointer = new SharedPointer (object);
  15841. }
  15842. else
  15843. {
  15844. // You're trying to create a weak reference to an object that has already been deleted!!
  15845. jassert (sharedPointer->get() != 0);
  15846. }
  15847. return sharedPointer;
  15848. }
  15849. /** The object that owns this master pointer should call this before it gets destroyed,
  15850. to zero all the references to this object that may be out there. See the WeakReference
  15851. class notes for an example of how to do this.
  15852. */
  15853. void clear()
  15854. {
  15855. if (sharedPointer != 0)
  15856. sharedPointer->clearPointer();
  15857. }
  15858. private:
  15859. SharedRef sharedPointer;
  15860. JUCE_DECLARE_NON_COPYABLE (Master);
  15861. };
  15862. private:
  15863. SharedRef holder;
  15864. };
  15865. #endif // __JUCE_WEAKREFERENCE_JUCEHEADER__
  15866. /*** End of inlined file: juce_WeakReference.h ***/
  15867. #endif
  15868. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  15869. #endif
  15870. #ifndef __JUCE_CHARPOINTER_ASCII_JUCEHEADER__
  15871. #endif
  15872. #ifndef __JUCE_CHARPOINTER_UTF16_JUCEHEADER__
  15873. #endif
  15874. #ifndef __JUCE_CHARPOINTER_UTF32_JUCEHEADER__
  15875. #endif
  15876. #ifndef __JUCE_CHARPOINTER_UTF8_JUCEHEADER__
  15877. #endif
  15878. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  15879. #endif
  15880. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  15881. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  15882. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  15883. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  15884. /** Used in the same way as the T(text) macro, this will attempt to translate a
  15885. string into a localised version using the LocalisedStrings class.
  15886. @see LocalisedStrings
  15887. */
  15888. #define TRANS(stringLiteral) \
  15889. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  15890. /**
  15891. Used to convert strings to localised foreign-language versions.
  15892. This is basically a look-up table of strings and their translated equivalents.
  15893. It can be loaded from a text file, so that you can supply a set of localised
  15894. versions of strings that you use in your app.
  15895. To use it in your code, simply call the translate() method on each string that
  15896. might have foreign versions, and if none is found, the method will just return
  15897. the original string.
  15898. The translation file should start with some lines specifying a description of
  15899. the language it contains, and also a list of ISO country codes where it might
  15900. be appropriate to use the file. After that, each line of the file should contain
  15901. a pair of quoted strings with an '=' sign.
  15902. E.g. for a french translation, the file might be:
  15903. @code
  15904. language: French
  15905. countries: fr be mc ch lu
  15906. "hello" = "bonjour"
  15907. "goodbye" = "au revoir"
  15908. @endcode
  15909. If the strings need to contain a quote character, they can use '\"' instead, and
  15910. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  15911. (you can use this to add comments).
  15912. Note that this is a singleton class, so don't create or destroy the object directly.
  15913. There's also a TRANS(text) macro defined to make it easy to use the this.
  15914. E.g. @code
  15915. printSomething (TRANS("hello"));
  15916. @endcode
  15917. This macro is used in the Juce classes themselves, so your application has a chance to
  15918. intercept and translate any internal Juce text strings that might be shown. (You can easily
  15919. get a list of all the messages by searching for the TRANS() macro in the Juce source
  15920. code).
  15921. */
  15922. class JUCE_API LocalisedStrings
  15923. {
  15924. public:
  15925. /** Creates a set of translations from the text of a translation file.
  15926. When you create one of these, you can call setCurrentMappings() to make it
  15927. the set of mappings that the system's using.
  15928. */
  15929. LocalisedStrings (const String& fileContents);
  15930. /** Creates a set of translations from a file.
  15931. When you create one of these, you can call setCurrentMappings() to make it
  15932. the set of mappings that the system's using.
  15933. */
  15934. LocalisedStrings (const File& fileToLoad);
  15935. /** Destructor. */
  15936. ~LocalisedStrings();
  15937. /** Selects the current set of mappings to be used by the system.
  15938. The object you pass in will be automatically deleted when no longer needed, so
  15939. don't keep a pointer to it. You can also pass in zero to remove the current
  15940. mappings.
  15941. See also the TRANS() macro, which uses the current set to do its translation.
  15942. @see translateWithCurrentMappings
  15943. */
  15944. static void setCurrentMappings (LocalisedStrings* newTranslations);
  15945. /** Returns the currently selected set of mappings.
  15946. This is the object that was last passed to setCurrentMappings(). It may
  15947. be 0 if none has been created.
  15948. */
  15949. static LocalisedStrings* getCurrentMappings();
  15950. /** Tries to translate a string using the currently selected set of mappings.
  15951. If no mapping has been set, or if the mapping doesn't contain a translation
  15952. for the string, this will just return the original string.
  15953. See also the TRANS() macro, which uses this method to do its translation.
  15954. @see setCurrentMappings, getCurrentMappings
  15955. */
  15956. static const String translateWithCurrentMappings (const String& text);
  15957. /** Tries to translate a string using the currently selected set of mappings.
  15958. If no mapping has been set, or if the mapping doesn't contain a translation
  15959. for the string, this will just return the original string.
  15960. See also the TRANS() macro, which uses this method to do its translation.
  15961. @see setCurrentMappings, getCurrentMappings
  15962. */
  15963. static const String translateWithCurrentMappings (const char* text);
  15964. /** Attempts to look up a string and return its localised version.
  15965. If the string isn't found in the list, the original string will be returned.
  15966. */
  15967. const String translate (const String& text) const;
  15968. /** Returns the name of the language specified in the translation file.
  15969. This is specified in the file using a line starting with "language:", e.g.
  15970. @code
  15971. language: german
  15972. @endcode
  15973. */
  15974. const String getLanguageName() const { return languageName; }
  15975. /** Returns the list of suitable country codes listed in the translation file.
  15976. These is specified in the file using a line starting with "countries:", e.g.
  15977. @code
  15978. countries: fr be mc ch lu
  15979. @endcode
  15980. The country codes are supposed to be 2-character ISO complient codes.
  15981. */
  15982. const StringArray getCountryCodes() const { return countryCodes; }
  15983. /** Indicates whether to use a case-insensitive search when looking up a string.
  15984. This defaults to true.
  15985. */
  15986. void setIgnoresCase (bool shouldIgnoreCase);
  15987. private:
  15988. String languageName;
  15989. StringArray countryCodes;
  15990. StringPairArray translations;
  15991. void loadFromText (const String& fileContents);
  15992. JUCE_LEAK_DETECTOR (LocalisedStrings);
  15993. };
  15994. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  15995. /*** End of inlined file: juce_LocalisedStrings.h ***/
  15996. #endif
  15997. #ifndef __JUCE_NEWLINE_JUCEHEADER__
  15998. #endif
  15999. #ifndef __JUCE_STRING_JUCEHEADER__
  16000. #endif
  16001. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  16002. #endif
  16003. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  16004. #endif
  16005. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  16006. #endif
  16007. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  16008. /*** Start of inlined file: juce_XmlDocument.h ***/
  16009. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  16010. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  16011. /**
  16012. Parses a text-based XML document and creates an XmlElement object from it.
  16013. The parser will parse DTDs to load external entities but won't
  16014. check the document for validity against the DTD.
  16015. e.g.
  16016. @code
  16017. XmlDocument myDocument (File ("myfile.xml"));
  16018. XmlElement* mainElement = myDocument.getDocumentElement();
  16019. if (mainElement == 0)
  16020. {
  16021. String error = myDocument.getLastParseError();
  16022. }
  16023. else
  16024. {
  16025. ..use the element
  16026. }
  16027. @endcode
  16028. Or you can use the static helper methods for quick parsing..
  16029. @code
  16030. XmlElement* xml = XmlDocument::parse (myXmlFile);
  16031. if (xml != 0 && xml->hasTagName ("foobar"))
  16032. {
  16033. ...etc
  16034. @endcode
  16035. @see XmlElement
  16036. */
  16037. class JUCE_API XmlDocument
  16038. {
  16039. public:
  16040. /** Creates an XmlDocument from the xml text.
  16041. The text doesn't actually get parsed until the getDocumentElement() method is called.
  16042. */
  16043. XmlDocument (const String& documentText);
  16044. /** Creates an XmlDocument from a file.
  16045. The text doesn't actually get parsed until the getDocumentElement() method is called.
  16046. */
  16047. XmlDocument (const File& file);
  16048. /** Destructor. */
  16049. ~XmlDocument();
  16050. /** Creates an XmlElement object to represent the main document node.
  16051. This method will do the actual parsing of the text, and if there's a
  16052. parse error, it may returns 0 (and you can find out the error using
  16053. the getLastParseError() method).
  16054. See also the parse() methods, which provide a shorthand way to quickly
  16055. parse a file or string.
  16056. @param onlyReadOuterDocumentElement if true, the parser will only read the
  16057. first section of the file, and will only
  16058. return the outer document element - this
  16059. allows quick checking of large files to
  16060. see if they contain the correct type of
  16061. tag, without having to parse the entire file
  16062. @returns a new XmlElement which the caller will need to delete, or null if
  16063. there was an error.
  16064. @see getLastParseError
  16065. */
  16066. XmlElement* getDocumentElement (bool onlyReadOuterDocumentElement = false);
  16067. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  16068. @returns the error, or an empty string if there was no error.
  16069. */
  16070. const String& getLastParseError() const throw();
  16071. /** Sets an input source object to use for parsing documents that reference external entities.
  16072. If the document has been created from a file, this probably won't be needed, but
  16073. if you're parsing some text and there might be a DTD that references external
  16074. files, you may need to create a custom input source that can retrieve the
  16075. other files it needs.
  16076. The object that is passed-in will be deleted automatically when no longer needed.
  16077. @see InputSource
  16078. */
  16079. void setInputSource (InputSource* newSource) throw();
  16080. /** Sets a flag to change the treatment of empty text elements.
  16081. If this is true (the default state), then any text elements that contain only
  16082. whitespace characters will be ingored during parsing. If you need to catch
  16083. whitespace-only text, then you should set this to false before calling the
  16084. getDocumentElement() method.
  16085. */
  16086. void setEmptyTextElementsIgnored (bool shouldBeIgnored) throw();
  16087. /** A handy static method that parses a file.
  16088. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  16089. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  16090. */
  16091. static XmlElement* parse (const File& file);
  16092. /** A handy static method that parses some XML data.
  16093. This is a shortcut for creating an XmlDocument object and calling getDocumentElement() on it.
  16094. @returns a new XmlElement which the caller will need to delete, or null if there was an error.
  16095. */
  16096. static XmlElement* parse (const String& xmlData);
  16097. private:
  16098. String originalText;
  16099. String::CharPointerType input;
  16100. bool outOfData, errorOccurred;
  16101. String lastError, dtdText;
  16102. StringArray tokenisedDTD;
  16103. bool needToLoadDTD, ignoreEmptyTextElements;
  16104. ScopedPointer <InputSource> inputSource;
  16105. void setLastError (const String& desc, bool carryOn);
  16106. void skipHeader();
  16107. void skipNextWhiteSpace();
  16108. juce_wchar readNextChar() throw();
  16109. XmlElement* readNextElement (bool alsoParseSubElements);
  16110. void readChildElements (XmlElement* parent);
  16111. int findNextTokenLength() throw();
  16112. void readQuotedString (String& result);
  16113. void readEntity (String& result);
  16114. const String getFileContents (const String& filename) const;
  16115. const String expandEntity (const String& entity);
  16116. const String expandExternalEntity (const String& entity);
  16117. const String getParameterEntity (const String& entity);
  16118. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XmlDocument);
  16119. };
  16120. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  16121. /*** End of inlined file: juce_XmlDocument.h ***/
  16122. #endif
  16123. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  16124. #endif
  16125. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  16126. #endif
  16127. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16128. /*** Start of inlined file: juce_InterProcessLock.h ***/
  16129. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16130. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16131. /**
  16132. Acts as a critical section which processes can use to block each other.
  16133. @see CriticalSection
  16134. */
  16135. class JUCE_API InterProcessLock
  16136. {
  16137. public:
  16138. /** Creates a lock object.
  16139. @param name a name that processes will use to identify this lock object
  16140. */
  16141. explicit InterProcessLock (const String& name);
  16142. /** Destructor.
  16143. This will also release the lock if it's currently held by this process.
  16144. */
  16145. ~InterProcessLock();
  16146. /** Attempts to lock the critical section.
  16147. @param timeOutMillisecs how many milliseconds to wait if the lock
  16148. is already held by another process - a value of
  16149. 0 will return immediately, negative values will wait
  16150. forever
  16151. @returns true if the lock could be gained within the timeout period, or
  16152. false if the timeout expired.
  16153. */
  16154. bool enter (int timeOutMillisecs = -1);
  16155. /** Releases the lock if it's currently held by this process.
  16156. */
  16157. void exit();
  16158. /**
  16159. Automatically locks and unlocks an InterProcessLock object.
  16160. This works like a ScopedLock, but using an InterprocessLock rather than
  16161. a CriticalSection.
  16162. @see ScopedLock
  16163. */
  16164. class ScopedLockType
  16165. {
  16166. public:
  16167. /** Creates a scoped lock.
  16168. As soon as it is created, this will lock the InterProcessLock, and
  16169. when the ScopedLockType object is deleted, the InterProcessLock will
  16170. be unlocked.
  16171. Note that since an InterprocessLock can fail due to errors, you should check
  16172. isLocked() to make sure that the lock was successful before using it.
  16173. Make sure this object is created and deleted by the same thread,
  16174. otherwise there are no guarantees what will happen! Best just to use it
  16175. as a local stack object, rather than creating one with the new() operator.
  16176. */
  16177. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  16178. /** Destructor.
  16179. The InterProcessLock will be unlocked when the destructor is called.
  16180. Make sure this object is created and deleted by the same thread,
  16181. otherwise there are no guarantees what will happen!
  16182. */
  16183. inline ~ScopedLockType() { lock_.exit(); }
  16184. /** Returns true if the InterProcessLock was successfully locked. */
  16185. bool isLocked() const throw() { return lockWasSuccessful; }
  16186. private:
  16187. InterProcessLock& lock_;
  16188. bool lockWasSuccessful;
  16189. JUCE_DECLARE_NON_COPYABLE (ScopedLockType);
  16190. };
  16191. private:
  16192. class Pimpl;
  16193. friend class ScopedPointer <Pimpl>;
  16194. ScopedPointer <Pimpl> pimpl;
  16195. CriticalSection lock;
  16196. String name;
  16197. JUCE_DECLARE_NON_COPYABLE (InterProcessLock);
  16198. };
  16199. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  16200. /*** End of inlined file: juce_InterProcessLock.h ***/
  16201. #endif
  16202. #ifndef __JUCE_PROCESS_JUCEHEADER__
  16203. /*** Start of inlined file: juce_Process.h ***/
  16204. #ifndef __JUCE_PROCESS_JUCEHEADER__
  16205. #define __JUCE_PROCESS_JUCEHEADER__
  16206. /** Represents the current executable's process.
  16207. This contains methods for controlling the current application at the
  16208. process-level.
  16209. @see Thread, JUCEApplication
  16210. */
  16211. class JUCE_API Process
  16212. {
  16213. public:
  16214. enum ProcessPriority
  16215. {
  16216. LowPriority = 0,
  16217. NormalPriority = 1,
  16218. HighPriority = 2,
  16219. RealtimePriority = 3
  16220. };
  16221. /** Changes the current process's priority.
  16222. @param priority the process priority, where
  16223. 0=low, 1=normal, 2=high, 3=realtime
  16224. */
  16225. static void setPriority (const ProcessPriority priority);
  16226. /** Kills the current process immediately.
  16227. This is an emergency process terminator that kills the application
  16228. immediately - it's intended only for use only when something goes
  16229. horribly wrong.
  16230. @see JUCEApplication::quit
  16231. */
  16232. static void terminate();
  16233. /** Returns true if this application process is the one that the user is
  16234. currently using.
  16235. */
  16236. static bool isForegroundProcess();
  16237. /** Raises the current process's privilege level.
  16238. Does nothing if this isn't supported by the current OS, or if process
  16239. privilege level is fixed.
  16240. */
  16241. static void raisePrivilege();
  16242. /** Lowers the current process's privilege level.
  16243. Does nothing if this isn't supported by the current OS, or if process
  16244. privilege level is fixed.
  16245. */
  16246. static void lowerPrivilege();
  16247. /** Returns true if this process is being hosted by a debugger.
  16248. */
  16249. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  16250. private:
  16251. Process();
  16252. JUCE_DECLARE_NON_COPYABLE (Process);
  16253. };
  16254. #endif // __JUCE_PROCESS_JUCEHEADER__
  16255. /*** End of inlined file: juce_Process.h ***/
  16256. #endif
  16257. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  16258. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  16259. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  16260. #define __JUCE_READWRITELOCK_JUCEHEADER__
  16261. /*** Start of inlined file: juce_WaitableEvent.h ***/
  16262. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  16263. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  16264. /**
  16265. Allows threads to wait for events triggered by other threads.
  16266. A thread can call wait() on a WaitableObject, and this will suspend the
  16267. calling thread until another thread wakes it up by calling the signal()
  16268. method.
  16269. */
  16270. class JUCE_API WaitableEvent
  16271. {
  16272. public:
  16273. /** Creates a WaitableEvent object.
  16274. @param manualReset If this is false, the event will be reset automatically when the wait()
  16275. method is called. If manualReset is true, then once the event is signalled,
  16276. the only way to reset it will be by calling the reset() method.
  16277. */
  16278. WaitableEvent (bool manualReset = false) throw();
  16279. /** Destructor.
  16280. If other threads are waiting on this object when it gets deleted, this
  16281. can cause nasty errors, so be careful!
  16282. */
  16283. ~WaitableEvent() throw();
  16284. /** Suspends the calling thread until the event has been signalled.
  16285. This will wait until the object's signal() method is called by another thread,
  16286. or until the timeout expires.
  16287. After the event has been signalled, this method will return true and if manualReset
  16288. was set to false in the WaitableEvent's constructor, then the event will be reset.
  16289. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  16290. value will cause it to wait forever.
  16291. @returns true if the object has been signalled, false if the timeout expires first.
  16292. @see signal, reset
  16293. */
  16294. bool wait (int timeOutMilliseconds = -1) const throw();
  16295. /** Wakes up any threads that are currently waiting on this object.
  16296. If signal() is called when nothing is waiting, the next thread to call wait()
  16297. will return immediately and reset the signal.
  16298. @see wait, reset
  16299. */
  16300. void signal() const throw();
  16301. /** Resets the event to an unsignalled state.
  16302. If it's not already signalled, this does nothing.
  16303. */
  16304. void reset() const throw();
  16305. private:
  16306. void* internal;
  16307. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WaitableEvent);
  16308. };
  16309. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  16310. /*** End of inlined file: juce_WaitableEvent.h ***/
  16311. /*** Start of inlined file: juce_Thread.h ***/
  16312. #ifndef __JUCE_THREAD_JUCEHEADER__
  16313. #define __JUCE_THREAD_JUCEHEADER__
  16314. /**
  16315. Encapsulates a thread.
  16316. Subclasses derive from Thread and implement the run() method, in which they
  16317. do their business. The thread can then be started with the startThread() method
  16318. and controlled with various other methods.
  16319. This class also contains some thread-related static methods, such
  16320. as sleep(), yield(), getCurrentThreadId() etc.
  16321. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  16322. MessageManagerLock
  16323. */
  16324. class JUCE_API Thread
  16325. {
  16326. public:
  16327. /**
  16328. Creates a thread.
  16329. When first created, the thread is not running. Use the startThread()
  16330. method to start it.
  16331. */
  16332. explicit Thread (const String& threadName);
  16333. /** Destructor.
  16334. Deleting a Thread object that is running will only give the thread a
  16335. brief opportunity to stop itself cleanly, so it's recommended that you
  16336. should always call stopThread() with a decent timeout before deleting,
  16337. to avoid the thread being forcibly killed (which is a Bad Thing).
  16338. */
  16339. virtual ~Thread();
  16340. /** Must be implemented to perform the thread's actual code.
  16341. Remember that the thread must regularly check the threadShouldExit()
  16342. method whilst running, and if this returns true it should return from
  16343. the run() method as soon as possible to avoid being forcibly killed.
  16344. @see threadShouldExit, startThread
  16345. */
  16346. virtual void run() = 0;
  16347. // Thread control functions..
  16348. /** Starts the thread running.
  16349. This will start the thread's run() method.
  16350. (if it's already started, startThread() won't do anything).
  16351. @see stopThread
  16352. */
  16353. void startThread();
  16354. /** Starts the thread with a given priority.
  16355. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  16356. If the thread is already running, its priority will be changed.
  16357. @see startThread, setPriority
  16358. */
  16359. void startThread (int priority);
  16360. /** Attempts to stop the thread running.
  16361. This method will cause the threadShouldExit() method to return true
  16362. and call notify() in case the thread is currently waiting.
  16363. Hopefully the thread will then respond to this by exiting cleanly, and
  16364. the stopThread method will wait for a given time-period for this to
  16365. happen.
  16366. If the thread is stuck and fails to respond after the time-out, it gets
  16367. forcibly killed, which is a very bad thing to happen, as it could still
  16368. be holding locks, etc. which are needed by other parts of your program.
  16369. @param timeOutMilliseconds The number of milliseconds to wait for the
  16370. thread to finish before killing it by force. A negative
  16371. value in here will wait forever.
  16372. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  16373. */
  16374. void stopThread (int timeOutMilliseconds);
  16375. /** Returns true if the thread is currently active */
  16376. bool isThreadRunning() const;
  16377. /** Sets a flag to tell the thread it should stop.
  16378. Calling this means that the threadShouldExit() method will then return true.
  16379. The thread should be regularly checking this to see whether it should exit.
  16380. If your thread makes use of wait(), you might want to call notify() after calling
  16381. this method, to interrupt any waits that might be in progress, and allow it
  16382. to reach a point where it can exit.
  16383. @see threadShouldExit
  16384. @see waitForThreadToExit
  16385. */
  16386. void signalThreadShouldExit();
  16387. /** Checks whether the thread has been told to stop running.
  16388. Threads need to check this regularly, and if it returns true, they should
  16389. return from their run() method at the first possible opportunity.
  16390. @see signalThreadShouldExit
  16391. */
  16392. inline bool threadShouldExit() const { return threadShouldExit_; }
  16393. /** Waits for the thread to stop.
  16394. This will waits until isThreadRunning() is false or until a timeout expires.
  16395. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  16396. is less than zero, it will wait forever.
  16397. @returns true if the thread exits, or false if the timeout expires first.
  16398. */
  16399. bool waitForThreadToExit (int timeOutMilliseconds) const;
  16400. /** Changes the thread's priority.
  16401. May return false if for some reason the priority can't be changed.
  16402. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  16403. of 5 is normal.
  16404. */
  16405. bool setPriority (int priority);
  16406. /** Changes the priority of the caller thread.
  16407. Similar to setPriority(), but this static method acts on the caller thread.
  16408. May return false if for some reason the priority can't be changed.
  16409. @see setPriority
  16410. */
  16411. static bool setCurrentThreadPriority (int priority);
  16412. /** Sets the affinity mask for the thread.
  16413. This will only have an effect next time the thread is started - i.e. if the
  16414. thread is already running when called, it'll have no effect.
  16415. @see setCurrentThreadAffinityMask
  16416. */
  16417. void setAffinityMask (uint32 affinityMask);
  16418. /** Changes the affinity mask for the caller thread.
  16419. This will change the affinity mask for the thread that calls this static method.
  16420. @see setAffinityMask
  16421. */
  16422. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  16423. // this can be called from any thread that needs to pause..
  16424. static void JUCE_CALLTYPE sleep (int milliseconds);
  16425. /** Yields the calling thread's current time-slot. */
  16426. static void JUCE_CALLTYPE yield();
  16427. /** Makes the thread wait for a notification.
  16428. This puts the thread to sleep until either the timeout period expires, or
  16429. another thread calls the notify() method to wake it up.
  16430. A negative time-out value means that the method will wait indefinitely.
  16431. @returns true if the event has been signalled, false if the timeout expires.
  16432. */
  16433. bool wait (int timeOutMilliseconds) const;
  16434. /** Wakes up the thread.
  16435. If the thread has called the wait() method, this will wake it up.
  16436. @see wait
  16437. */
  16438. void notify() const;
  16439. /** A value type used for thread IDs.
  16440. @see getCurrentThreadId(), getThreadId()
  16441. */
  16442. typedef void* ThreadID;
  16443. /** Returns an id that identifies the caller thread.
  16444. To find the ID of a particular thread object, use getThreadId().
  16445. @returns a unique identifier that identifies the calling thread.
  16446. @see getThreadId
  16447. */
  16448. static ThreadID getCurrentThreadId();
  16449. /** Finds the thread object that is currently running.
  16450. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  16451. object associated with them, so this will return 0.
  16452. */
  16453. static Thread* getCurrentThread();
  16454. /** Returns the ID of this thread.
  16455. That means the ID of this thread object - not of the thread that's calling the method.
  16456. This can change when the thread is started and stopped, and will be invalid if the
  16457. thread's not actually running.
  16458. @see getCurrentThreadId
  16459. */
  16460. ThreadID getThreadId() const throw() { return threadId_; }
  16461. /** Returns the name of the thread.
  16462. This is the name that gets set in the constructor.
  16463. */
  16464. const String getThreadName() const { return threadName_; }
  16465. /** Returns the number of currently-running threads.
  16466. @returns the number of Thread objects known to be currently running.
  16467. @see stopAllThreads
  16468. */
  16469. static int getNumRunningThreads();
  16470. /** Tries to stop all currently-running threads.
  16471. This will attempt to stop all the threads known to be running at the moment.
  16472. */
  16473. static void stopAllThreads (int timeoutInMillisecs);
  16474. private:
  16475. const String threadName_;
  16476. void* volatile threadHandle_;
  16477. ThreadID threadId_;
  16478. CriticalSection startStopLock;
  16479. WaitableEvent startSuspensionEvent_, defaultEvent_;
  16480. int threadPriority_;
  16481. uint32 affinityMask_;
  16482. bool volatile threadShouldExit_;
  16483. #ifndef DOXYGEN
  16484. friend class MessageManager;
  16485. friend void JUCE_API juce_threadEntryPoint (void*);
  16486. #endif
  16487. void launchThread();
  16488. void closeThreadHandle();
  16489. void killThread();
  16490. void threadEntryPoint();
  16491. static void setCurrentThreadName (const String& name);
  16492. static bool setThreadPriority (void* handle, int priority);
  16493. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Thread);
  16494. };
  16495. #endif // __JUCE_THREAD_JUCEHEADER__
  16496. /*** End of inlined file: juce_Thread.h ***/
  16497. /**
  16498. A critical section that allows multiple simultaneous readers.
  16499. Features of this type of lock are:
  16500. - Multiple readers can hold the lock at the same time, but only one writer
  16501. can hold it at once.
  16502. - Writers trying to gain the lock will be blocked until all readers and writers
  16503. have released it
  16504. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  16505. blocked until the writer has obtained and released it
  16506. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  16507. there are no other readers
  16508. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  16509. - Recursive locking is supported.
  16510. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  16511. */
  16512. class JUCE_API ReadWriteLock
  16513. {
  16514. public:
  16515. /**
  16516. Creates a ReadWriteLock object.
  16517. */
  16518. ReadWriteLock() throw();
  16519. /** Destructor.
  16520. If the object is deleted whilst locked, any subsequent behaviour
  16521. is unpredictable.
  16522. */
  16523. ~ReadWriteLock() throw();
  16524. /** Locks this object for reading.
  16525. Multiple threads can simulaneously lock the object for reading, but if another
  16526. thread has it locked for writing, then this will block until it releases the
  16527. lock.
  16528. @see exitRead, ScopedReadLock
  16529. */
  16530. void enterRead() const throw();
  16531. /** Releases the read-lock.
  16532. If the caller thread hasn't got the lock, this can have unpredictable results.
  16533. If the enterRead() method has been called multiple times by the thread, each
  16534. call must be matched by a call to exitRead() before other threads will be allowed
  16535. to take over the lock.
  16536. @see enterRead, ScopedReadLock
  16537. */
  16538. void exitRead() const throw();
  16539. /** Locks this object for writing.
  16540. This will block until any other threads that have it locked for reading or
  16541. writing have released their lock.
  16542. @see exitWrite, ScopedWriteLock
  16543. */
  16544. void enterWrite() const throw();
  16545. /** Tries to lock this object for writing.
  16546. This is like enterWrite(), but doesn't block - it returns true if it manages
  16547. to obtain the lock.
  16548. @see enterWrite
  16549. */
  16550. bool tryEnterWrite() const throw();
  16551. /** Releases the write-lock.
  16552. If the caller thread hasn't got the lock, this can have unpredictable results.
  16553. If the enterWrite() method has been called multiple times by the thread, each
  16554. call must be matched by a call to exit() before other threads will be allowed
  16555. to take over the lock.
  16556. @see enterWrite, ScopedWriteLock
  16557. */
  16558. void exitWrite() const throw();
  16559. private:
  16560. CriticalSection accessLock;
  16561. WaitableEvent waitEvent;
  16562. mutable int numWaitingWriters, numWriters;
  16563. mutable Thread::ThreadID writerThreadId;
  16564. mutable Array <Thread::ThreadID> readerThreads;
  16565. JUCE_DECLARE_NON_COPYABLE (ReadWriteLock);
  16566. };
  16567. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  16568. /*** End of inlined file: juce_ReadWriteLock.h ***/
  16569. #endif
  16570. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  16571. #endif
  16572. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  16573. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  16574. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  16575. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  16576. /**
  16577. Automatically locks and unlocks a ReadWriteLock object.
  16578. Use one of these as a local variable to control access to a ReadWriteLock.
  16579. e.g. @code
  16580. ReadWriteLock myLock;
  16581. for (;;)
  16582. {
  16583. const ScopedReadLock myScopedLock (myLock);
  16584. // myLock is now locked
  16585. ...do some stuff...
  16586. // myLock gets unlocked here.
  16587. }
  16588. @endcode
  16589. @see ReadWriteLock, ScopedWriteLock
  16590. */
  16591. class JUCE_API ScopedReadLock
  16592. {
  16593. public:
  16594. /** Creates a ScopedReadLock.
  16595. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  16596. when the ScopedReadLock object is deleted, the ReadWriteLock will
  16597. be unlocked.
  16598. Make sure this object is created and deleted by the same thread,
  16599. otherwise there are no guarantees what will happen! Best just to use it
  16600. as a local stack object, rather than creating one with the new() operator.
  16601. */
  16602. inline explicit ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  16603. /** Destructor.
  16604. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  16605. Make sure this object is created and deleted by the same thread,
  16606. otherwise there are no guarantees what will happen!
  16607. */
  16608. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  16609. private:
  16610. const ReadWriteLock& lock_;
  16611. JUCE_DECLARE_NON_COPYABLE (ScopedReadLock);
  16612. };
  16613. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  16614. /*** End of inlined file: juce_ScopedReadLock.h ***/
  16615. #endif
  16616. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  16617. /*** Start of inlined file: juce_ScopedTryLock.h ***/
  16618. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  16619. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  16620. /**
  16621. Automatically tries to lock and unlock a CriticalSection object.
  16622. Use one of these as a local variable to control access to a CriticalSection.
  16623. e.g. @code
  16624. CriticalSection myCriticalSection;
  16625. for (;;)
  16626. {
  16627. const ScopedTryLock myScopedTryLock (myCriticalSection);
  16628. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  16629. // should test this with the isLocked() method before doing your thread-unsafe
  16630. // action..
  16631. if (myScopedTryLock.isLocked())
  16632. {
  16633. ...do some stuff...
  16634. }
  16635. else
  16636. {
  16637. ..our attempt at locking failed because another thread had already locked it..
  16638. }
  16639. // myCriticalSection gets unlocked here (if it was locked)
  16640. }
  16641. @endcode
  16642. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  16643. */
  16644. class JUCE_API ScopedTryLock
  16645. {
  16646. public:
  16647. /** Creates a ScopedTryLock.
  16648. As soon as it is created, this will try to lock the CriticalSection, and
  16649. when the ScopedTryLock object is deleted, the CriticalSection will
  16650. be unlocked if the lock was successful.
  16651. Make sure this object is created and deleted by the same thread,
  16652. otherwise there are no guarantees what will happen! Best just to use it
  16653. as a local stack object, rather than creating one with the new() operator.
  16654. */
  16655. inline explicit ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  16656. /** Destructor.
  16657. The CriticalSection will be unlocked (if locked) when the destructor is called.
  16658. Make sure this object is created and deleted by the same thread,
  16659. otherwise there are no guarantees what will happen!
  16660. */
  16661. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  16662. /** Returns true if the CriticalSection was successfully locked. */
  16663. bool isLocked() const throw() { return lockWasSuccessful; }
  16664. private:
  16665. const CriticalSection& lock_;
  16666. const bool lockWasSuccessful;
  16667. JUCE_DECLARE_NON_COPYABLE (ScopedTryLock);
  16668. };
  16669. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  16670. /*** End of inlined file: juce_ScopedTryLock.h ***/
  16671. #endif
  16672. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  16673. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  16674. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  16675. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  16676. /**
  16677. Automatically locks and unlocks a ReadWriteLock object.
  16678. Use one of these as a local variable to control access to a ReadWriteLock.
  16679. e.g. @code
  16680. ReadWriteLock myLock;
  16681. for (;;)
  16682. {
  16683. const ScopedWriteLock myScopedLock (myLock);
  16684. // myLock is now locked
  16685. ...do some stuff...
  16686. // myLock gets unlocked here.
  16687. }
  16688. @endcode
  16689. @see ReadWriteLock, ScopedReadLock
  16690. */
  16691. class JUCE_API ScopedWriteLock
  16692. {
  16693. public:
  16694. /** Creates a ScopedWriteLock.
  16695. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  16696. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  16697. be unlocked.
  16698. Make sure this object is created and deleted by the same thread,
  16699. otherwise there are no guarantees what will happen! Best just to use it
  16700. as a local stack object, rather than creating one with the new() operator.
  16701. */
  16702. inline explicit ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  16703. /** Destructor.
  16704. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  16705. Make sure this object is created and deleted by the same thread,
  16706. otherwise there are no guarantees what will happen!
  16707. */
  16708. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  16709. private:
  16710. const ReadWriteLock& lock_;
  16711. JUCE_DECLARE_NON_COPYABLE (ScopedWriteLock);
  16712. };
  16713. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  16714. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  16715. #endif
  16716. #ifndef __JUCE_THREAD_JUCEHEADER__
  16717. #endif
  16718. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  16719. /*** Start of inlined file: juce_ThreadPool.h ***/
  16720. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  16721. #define __JUCE_THREADPOOL_JUCEHEADER__
  16722. class ThreadPool;
  16723. class ThreadPoolThread;
  16724. /**
  16725. A task that is executed by a ThreadPool object.
  16726. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  16727. its threads.
  16728. The runJob() method needs to be implemented to do the task, and if the code that
  16729. does the work takes a significant time to run, it must keep checking the shouldExit()
  16730. method to see if something is trying to interrupt the job. If shouldExit() returns
  16731. true, the runJob() method must return immediately.
  16732. @see ThreadPool, Thread
  16733. */
  16734. class JUCE_API ThreadPoolJob
  16735. {
  16736. public:
  16737. /** Creates a thread pool job object.
  16738. After creating your job, add it to a thread pool with ThreadPool::addJob().
  16739. */
  16740. explicit ThreadPoolJob (const String& name);
  16741. /** Destructor. */
  16742. virtual ~ThreadPoolJob();
  16743. /** Returns the name of this job.
  16744. @see setJobName
  16745. */
  16746. const String getJobName() const;
  16747. /** Changes the job's name.
  16748. @see getJobName
  16749. */
  16750. void setJobName (const String& newName);
  16751. /** These are the values that can be returned by the runJob() method.
  16752. */
  16753. enum JobStatus
  16754. {
  16755. jobHasFinished = 0, /**< indicates that the job has finished and can be
  16756. removed from the pool. */
  16757. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  16758. should be automatically deleted by the pool. */
  16759. jobNeedsRunningAgain /**< indicates that the job would like to be called
  16760. again when a thread is free. */
  16761. };
  16762. /** Peforms the actual work that this job needs to do.
  16763. Your subclass must implement this method, in which is does its work.
  16764. If the code in this method takes a significant time to run, it must repeatedly check
  16765. the shouldExit() method to see if something is trying to interrupt the job.
  16766. If shouldExit() ever returns true, the runJob() method must return immediately.
  16767. If this method returns jobHasFinished, then the job will be removed from the pool
  16768. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  16769. pool and will get a chance to run again as soon as a thread is free.
  16770. @see shouldExit()
  16771. */
  16772. virtual JobStatus runJob() = 0;
  16773. /** Returns true if this job is currently running its runJob() method. */
  16774. bool isRunning() const { return isActive; }
  16775. /** Returns true if something is trying to interrupt this job and make it stop.
  16776. Your runJob() method must call this whenever it gets a chance, and if it ever
  16777. returns true, the runJob() method must return immediately.
  16778. @see signalJobShouldExit()
  16779. */
  16780. bool shouldExit() const { return shouldStop; }
  16781. /** Calling this will cause the shouldExit() method to return true, and the job
  16782. should (if it's been implemented correctly) stop as soon as possible.
  16783. @see shouldExit()
  16784. */
  16785. void signalJobShouldExit();
  16786. private:
  16787. friend class ThreadPool;
  16788. friend class ThreadPoolThread;
  16789. String jobName;
  16790. ThreadPool* pool;
  16791. bool shouldStop, isActive, shouldBeDeleted;
  16792. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolJob);
  16793. };
  16794. /**
  16795. A set of threads that will run a list of jobs.
  16796. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  16797. will be called by the next pooled thread that becomes free.
  16798. @see ThreadPoolJob, Thread
  16799. */
  16800. class JUCE_API ThreadPool
  16801. {
  16802. public:
  16803. /** Creates a thread pool.
  16804. Once you've created a pool, you can give it some things to do with the addJob()
  16805. method.
  16806. @param numberOfThreads the maximum number of actual threads to run.
  16807. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  16808. until there are some jobs to run. If false, then
  16809. all the threads will be fired-up immediately so that
  16810. they're ready for action
  16811. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  16812. inactive for this length of time, they will automatically
  16813. be stopped until more jobs come along and they're needed
  16814. */
  16815. ThreadPool (int numberOfThreads,
  16816. bool startThreadsOnlyWhenNeeded = true,
  16817. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  16818. /** Destructor.
  16819. This will attempt to remove all the jobs before deleting, but if you want to
  16820. specify a timeout, you should call removeAllJobs() explicitly before deleting
  16821. the pool.
  16822. */
  16823. ~ThreadPool();
  16824. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  16825. for some kind of operation.
  16826. @see ThreadPool::removeAllJobs
  16827. */
  16828. class JUCE_API JobSelector
  16829. {
  16830. public:
  16831. virtual ~JobSelector() {}
  16832. /** Should return true if the specified thread matches your criteria for whatever
  16833. operation that this object is being used for.
  16834. Any implementation of this method must be extremely fast and thread-safe!
  16835. */
  16836. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  16837. };
  16838. /** Adds a job to the queue.
  16839. Once a job has been added, then the next time a thread is free, it will run
  16840. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  16841. runJob() method, the pool will either remove the job from the pool or add it to
  16842. the back of the queue to be run again.
  16843. */
  16844. void addJob (ThreadPoolJob* job);
  16845. /** Tries to remove a job from the pool.
  16846. If the job isn't yet running, this will simply remove it. If it is running, it
  16847. will wait for it to finish.
  16848. If the timeout period expires before the job finishes running, then the job will be
  16849. left in the pool and this will return false. It returns true if the job is sucessfully
  16850. stopped and removed.
  16851. @param job the job to remove
  16852. @param interruptIfRunning if true, then if the job is currently busy, its
  16853. ThreadPoolJob::signalJobShouldExit() method will be called to try
  16854. to interrupt it. If false, then if the job will be allowed to run
  16855. until it stops normally (or the timeout expires)
  16856. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  16857. before giving up and returning false
  16858. */
  16859. bool removeJob (ThreadPoolJob* job,
  16860. bool interruptIfRunning,
  16861. int timeOutMilliseconds);
  16862. /** Tries to remove all jobs from the pool.
  16863. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  16864. methods called to try to interrupt them
  16865. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  16866. before giving up and returning false
  16867. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  16868. they will simply be removed from the pool. Jobs that are already running when
  16869. this method is called can choose whether they should be deleted by
  16870. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  16871. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  16872. jobs should be removed. If it is zero, all jobs are removed
  16873. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  16874. expires while waiting for one or more jobs to stop
  16875. */
  16876. bool removeAllJobs (bool interruptRunningJobs,
  16877. int timeOutMilliseconds,
  16878. bool deleteInactiveJobs = false,
  16879. JobSelector* selectedJobsToRemove = 0);
  16880. /** Returns the number of jobs currently running or queued.
  16881. */
  16882. int getNumJobs() const;
  16883. /** Returns one of the jobs in the queue.
  16884. Note that this can be a very volatile list as jobs might be continuously getting shifted
  16885. around in the list, and this method may return 0 if the index is currently out-of-range.
  16886. */
  16887. ThreadPoolJob* getJob (int index) const;
  16888. /** Returns true if the given job is currently queued or running.
  16889. @see isJobRunning()
  16890. */
  16891. bool contains (const ThreadPoolJob* job) const;
  16892. /** Returns true if the given job is currently being run by a thread.
  16893. */
  16894. bool isJobRunning (const ThreadPoolJob* job) const;
  16895. /** Waits until a job has finished running and has been removed from the pool.
  16896. This will wait until the job is no longer in the pool - i.e. until its
  16897. runJob() method returns ThreadPoolJob::jobHasFinished.
  16898. If the timeout period expires before the job finishes, this will return false;
  16899. it returns true if the job has finished successfully.
  16900. */
  16901. bool waitForJobToFinish (const ThreadPoolJob* job,
  16902. int timeOutMilliseconds) const;
  16903. /** Returns a list of the names of all the jobs currently running or queued.
  16904. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  16905. */
  16906. const StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  16907. /** Changes the priority of all the threads.
  16908. This will call Thread::setPriority() for each thread in the pool.
  16909. May return false if for some reason the priority can't be changed.
  16910. */
  16911. bool setThreadPriorities (int newPriority);
  16912. private:
  16913. const int threadStopTimeout;
  16914. int priority;
  16915. class ThreadPoolThread;
  16916. friend class OwnedArray <ThreadPoolThread>;
  16917. OwnedArray <ThreadPoolThread> threads;
  16918. Array <ThreadPoolJob*> jobs;
  16919. CriticalSection lock;
  16920. uint32 lastJobEndTime;
  16921. WaitableEvent jobFinishedSignal;
  16922. friend class ThreadPoolThread;
  16923. bool runNextJob();
  16924. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPool);
  16925. };
  16926. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  16927. /*** End of inlined file: juce_ThreadPool.h ***/
  16928. #endif
  16929. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  16930. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  16931. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  16932. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  16933. class TimeSliceThread;
  16934. /**
  16935. Used by the TimeSliceThread class.
  16936. To register your class with a TimeSliceThread, derive from this class and
  16937. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  16938. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  16939. deleting your client!
  16940. @see TimeSliceThread
  16941. */
  16942. class JUCE_API TimeSliceClient
  16943. {
  16944. public:
  16945. /** Destructor. */
  16946. virtual ~TimeSliceClient() {}
  16947. /** Called back by a TimeSliceThread.
  16948. When you register this class with it, a TimeSliceThread will repeatedly call
  16949. this method.
  16950. The implementation of this method should use its time-slice to do something that's
  16951. quick - never block for longer than absolutely necessary.
  16952. @returns Your method should return the number of milliseconds which it would like to wait before being called
  16953. again. Returning 0 will make the thread call again as soon as possible (after possibly servicing
  16954. other busy clients). If you return a value below zero, your client will be removed from the list of clients,
  16955. and won't be called again. The value you specify isn't a guaranteee, and is only used as a hint by the
  16956. thread - the actual time before the next callback may be more or less than specified.
  16957. You can force the TimeSliceThread to wake up and poll again immediately by calling its notify() method.
  16958. */
  16959. virtual int useTimeSlice() = 0;
  16960. private:
  16961. friend class TimeSliceThread;
  16962. Time nextCallTime;
  16963. };
  16964. /**
  16965. A thread that keeps a list of clients, and calls each one in turn, giving them
  16966. all a chance to run some sort of short task.
  16967. @see TimeSliceClient, Thread
  16968. */
  16969. class JUCE_API TimeSliceThread : public Thread
  16970. {
  16971. public:
  16972. /**
  16973. Creates a TimeSliceThread.
  16974. When first created, the thread is not running. Use the startThread()
  16975. method to start it.
  16976. */
  16977. explicit TimeSliceThread (const String& threadName);
  16978. /** Destructor.
  16979. Deleting a Thread object that is running will only give the thread a
  16980. brief opportunity to stop itself cleanly, so it's recommended that you
  16981. should always call stopThread() with a decent timeout before deleting,
  16982. to avoid the thread being forcibly killed (which is a Bad Thing).
  16983. */
  16984. ~TimeSliceThread();
  16985. /** Adds a client to the list.
  16986. The client's callbacks will start after the number of milliseconds specified
  16987. by millisecondsBeforeStarting (and this may happen before this method has returned).
  16988. */
  16989. void addTimeSliceClient (TimeSliceClient* client, int millisecondsBeforeStarting = 0);
  16990. /** Removes a client from the list.
  16991. This method will make sure that all callbacks to the client have completely
  16992. finished before the method returns.
  16993. */
  16994. void removeTimeSliceClient (TimeSliceClient* client);
  16995. /** Returns the number of registered clients. */
  16996. int getNumClients() const;
  16997. /** Returns one of the registered clients. */
  16998. TimeSliceClient* getClient (int index) const;
  16999. /** @internal */
  17000. void run();
  17001. private:
  17002. CriticalSection callbackLock, listLock;
  17003. Array <TimeSliceClient*> clients;
  17004. TimeSliceClient* clientBeingCalled;
  17005. TimeSliceClient* getNextClient (int index) const;
  17006. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimeSliceThread);
  17007. };
  17008. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  17009. /*** End of inlined file: juce_TimeSliceThread.h ***/
  17010. #endif
  17011. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  17012. #endif
  17013. #endif
  17014. /*** End of inlined file: juce_core_includes.h ***/
  17015. // if you're compiling a command-line app, you might want to just include the core headers,
  17016. // so you can set this macro before including juce.h
  17017. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  17018. /*** Start of inlined file: juce_app_includes.h ***/
  17019. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  17020. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  17021. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  17022. /*** Start of inlined file: juce_Application.h ***/
  17023. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  17024. #define __JUCE_APPLICATION_JUCEHEADER__
  17025. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  17026. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17027. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17028. /*** Start of inlined file: juce_Component.h ***/
  17029. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  17030. #define __JUCE_COMPONENT_JUCEHEADER__
  17031. /*** Start of inlined file: juce_MouseCursor.h ***/
  17032. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  17033. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  17034. class Image;
  17035. class ComponentPeer;
  17036. class Component;
  17037. /**
  17038. Represents a mouse cursor image.
  17039. This object can either be used to represent one of the standard mouse
  17040. cursor shapes, or a custom one generated from an image.
  17041. */
  17042. class JUCE_API MouseCursor
  17043. {
  17044. public:
  17045. /** The set of available standard mouse cursors. */
  17046. enum StandardCursorType
  17047. {
  17048. NoCursor = 0, /**< An invisible cursor. */
  17049. NormalCursor, /**< The stardard arrow cursor. */
  17050. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  17051. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  17052. CrosshairCursor, /**< A pair of crosshairs. */
  17053. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  17054. that you're dragging a copy of something. */
  17055. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  17056. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  17057. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  17058. UpDownResizeCursor, /**< an arrow pointing up and down. */
  17059. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  17060. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  17061. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  17062. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  17063. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  17064. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  17065. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  17066. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  17067. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  17068. };
  17069. /** Creates the standard arrow cursor. */
  17070. MouseCursor();
  17071. /** Creates one of the standard mouse cursor */
  17072. MouseCursor (StandardCursorType type);
  17073. /** Creates a custom cursor from an image.
  17074. @param image the image to use for the cursor - if this is bigger than the
  17075. system can manage, it might get scaled down first, and might
  17076. also have to be turned to black-and-white if it can't do colour
  17077. cursors.
  17078. @param hotSpotX the x position of the cursor's hotspot within the image
  17079. @param hotSpotY the y position of the cursor's hotspot within the image
  17080. */
  17081. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  17082. /** Creates a copy of another cursor object. */
  17083. MouseCursor (const MouseCursor& other);
  17084. /** Copies this cursor from another object. */
  17085. MouseCursor& operator= (const MouseCursor& other);
  17086. /** Destructor. */
  17087. ~MouseCursor();
  17088. /** Checks whether two mouse cursors are the same.
  17089. For custom cursors, two cursors created from the same image won't be
  17090. recognised as the same, only MouseCursor objects that have been
  17091. copied from the same object.
  17092. */
  17093. bool operator== (const MouseCursor& other) const throw();
  17094. /** Checks whether two mouse cursors are the same.
  17095. For custom cursors, two cursors created from the same image won't be
  17096. recognised as the same, only MouseCursor objects that have been
  17097. copied from the same object.
  17098. */
  17099. bool operator!= (const MouseCursor& other) const throw();
  17100. /** Makes the system show its default 'busy' cursor.
  17101. This will turn the system cursor to an hourglass or spinning beachball
  17102. until the next time the mouse is moved, or hideWaitCursor() is called.
  17103. This is handy if the message loop is about to block for a couple of
  17104. seconds while busy and you want to give the user feedback about this.
  17105. @see MessageManager::setTimeBeforeShowingWaitCursor
  17106. */
  17107. static void showWaitCursor();
  17108. /** If showWaitCursor has been called, this will return the mouse to its
  17109. normal state.
  17110. This will look at what component is under the mouse, and update the
  17111. cursor to be the correct one for that component.
  17112. @see showWaitCursor
  17113. */
  17114. static void hideWaitCursor();
  17115. private:
  17116. class SharedCursorHandle;
  17117. friend class SharedCursorHandle;
  17118. SharedCursorHandle* cursorHandle;
  17119. friend class MouseInputSourceInternal;
  17120. void showInWindow (ComponentPeer* window) const;
  17121. void showInAllWindows() const;
  17122. void* getHandle() const throw();
  17123. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  17124. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  17125. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  17126. JUCE_LEAK_DETECTOR (MouseCursor);
  17127. };
  17128. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  17129. /*** End of inlined file: juce_MouseCursor.h ***/
  17130. /*** Start of inlined file: juce_MouseListener.h ***/
  17131. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  17132. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  17133. class MouseEvent;
  17134. /**
  17135. A MouseListener can be registered with a component to receive callbacks
  17136. about mouse events that happen to that component.
  17137. @see Component::addMouseListener, Component::removeMouseListener
  17138. */
  17139. class JUCE_API MouseListener
  17140. {
  17141. public:
  17142. /** Destructor. */
  17143. virtual ~MouseListener() {}
  17144. /** Called when the mouse moves inside a component.
  17145. If the mouse button isn't pressed and the mouse moves over a component,
  17146. this will be called to let the component react to this.
  17147. A component will always get a mouseEnter callback before a mouseMove.
  17148. @param e details about the position and status of the mouse event, including
  17149. the source component in which it occurred
  17150. @see mouseEnter, mouseExit, mouseDrag, contains
  17151. */
  17152. virtual void mouseMove (const MouseEvent& e);
  17153. /** Called when the mouse first enters a component.
  17154. If the mouse button isn't pressed and the mouse moves into a component,
  17155. this will be called to let the component react to this.
  17156. When the mouse button is pressed and held down while being moved in
  17157. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  17158. mouseDrag messages are sent to the component that the mouse was originally
  17159. clicked on, until the button is released.
  17160. @param e details about the position and status of the mouse event, including
  17161. the source component in which it occurred
  17162. @see mouseExit, mouseDrag, mouseMove, contains
  17163. */
  17164. virtual void mouseEnter (const MouseEvent& e);
  17165. /** Called when the mouse moves out of a component.
  17166. This will be called when the mouse moves off the edge of this
  17167. component.
  17168. If the mouse button was pressed, and it was then dragged off the
  17169. edge of the component and released, then this callback will happen
  17170. when the button is released, after the mouseUp callback.
  17171. @param e details about the position and status of the mouse event, including
  17172. the source component in which it occurred
  17173. @see mouseEnter, mouseDrag, mouseMove, contains
  17174. */
  17175. virtual void mouseExit (const MouseEvent& e);
  17176. /** Called when a mouse button is pressed.
  17177. The MouseEvent object passed in contains lots of methods for finding out
  17178. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  17179. were held down at the time.
  17180. Once a button is held down, the mouseDrag method will be called when the
  17181. mouse moves, until the button is released.
  17182. @param e details about the position and status of the mouse event, including
  17183. the source component in which it occurred
  17184. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  17185. */
  17186. virtual void mouseDown (const MouseEvent& e);
  17187. /** Called when the mouse is moved while a button is held down.
  17188. When a mouse button is pressed inside a component, that component
  17189. receives mouseDrag callbacks each time the mouse moves, even if the
  17190. mouse strays outside the component's bounds.
  17191. @param e details about the position and status of the mouse event, including
  17192. the source component in which it occurred
  17193. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  17194. */
  17195. virtual void mouseDrag (const MouseEvent& e);
  17196. /** Called when a mouse button is released.
  17197. A mouseUp callback is sent to the component in which a button was pressed
  17198. even if the mouse is actually over a different component when the
  17199. button is released.
  17200. The MouseEvent object passed in contains lots of methods for finding out
  17201. which buttons were down just before they were released.
  17202. @param e details about the position and status of the mouse event, including
  17203. the source component in which it occurred
  17204. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  17205. */
  17206. virtual void mouseUp (const MouseEvent& e);
  17207. /** Called when a mouse button has been double-clicked on a component.
  17208. The MouseEvent object passed in contains lots of methods for finding out
  17209. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  17210. were held down at the time.
  17211. @param e details about the position and status of the mouse event, including
  17212. the source component in which it occurred
  17213. @see mouseDown, mouseUp
  17214. */
  17215. virtual void mouseDoubleClick (const MouseEvent& e);
  17216. /** Called when the mouse-wheel is moved.
  17217. This callback is sent to the component that the mouse is over when the
  17218. wheel is moved.
  17219. If not overridden, the component will forward this message to its parent, so
  17220. that parent components can collect mouse-wheel messages that happen to
  17221. child components which aren't interested in them.
  17222. @param e details about the position and status of the mouse event, including
  17223. the source component in which it occurred
  17224. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  17225. value means the wheel has been pushed to the right, negative means it
  17226. was pushed to the left
  17227. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  17228. value means the wheel has been pushed upwards, negative means it
  17229. was pushed downwards
  17230. */
  17231. virtual void mouseWheelMove (const MouseEvent& e,
  17232. float wheelIncrementX,
  17233. float wheelIncrementY);
  17234. };
  17235. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  17236. /*** End of inlined file: juce_MouseListener.h ***/
  17237. /*** Start of inlined file: juce_MouseEvent.h ***/
  17238. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  17239. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  17240. class Component;
  17241. class MouseInputSource;
  17242. /*** Start of inlined file: juce_ModifierKeys.h ***/
  17243. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  17244. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  17245. /**
  17246. Represents the state of the mouse buttons and modifier keys.
  17247. This is used both by mouse events and by KeyPress objects to describe
  17248. the state of keys such as shift, control, alt, etc.
  17249. @see KeyPress, MouseEvent::mods
  17250. */
  17251. class JUCE_API ModifierKeys
  17252. {
  17253. public:
  17254. /** Creates a ModifierKeys object from a raw set of flags.
  17255. @param flags to represent the keys that are down
  17256. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  17257. rightButtonModifier, commandModifier, popupMenuClickModifier
  17258. */
  17259. ModifierKeys (int flags = 0) throw();
  17260. /** Creates a copy of another object. */
  17261. ModifierKeys (const ModifierKeys& other) throw();
  17262. /** Copies this object from another one. */
  17263. ModifierKeys& operator= (const ModifierKeys& other) throw();
  17264. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  17265. This is a platform-agnostic way of checking for the operating system's
  17266. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  17267. Windows/Linux, it's actually checking for the CTRL key.
  17268. */
  17269. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  17270. /** Checks whether the user is trying to launch a pop-up menu.
  17271. This checks for platform-specific modifiers that might indicate that the user
  17272. is following the operating system's normal method of showing a pop-up menu.
  17273. So on Windows/Linux, this method is really testing for a right-click.
  17274. On the Mac, it tests for either the CTRL key being down, or a right-click.
  17275. */
  17276. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  17277. /** Checks whether the flag is set for the left mouse-button. */
  17278. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  17279. /** Checks whether the flag is set for the right mouse-button.
  17280. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  17281. this is platform-independent (and makes your code more explanatory too).
  17282. */
  17283. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  17284. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  17285. /** Tests for any of the mouse-button flags. */
  17286. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  17287. /** Tests for any of the modifier key flags. */
  17288. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  17289. /** Checks whether the shift key's flag is set. */
  17290. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  17291. /** Checks whether the CTRL key's flag is set.
  17292. Remember that it's better to use the platform-agnostic routines to test for command-key and
  17293. popup-menu modifiers.
  17294. @see isCommandDown, isPopupMenu
  17295. */
  17296. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  17297. /** Checks whether the shift key's flag is set. */
  17298. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  17299. /** Flags that represent the different keys. */
  17300. enum Flags
  17301. {
  17302. /** Shift key flag. */
  17303. shiftModifier = 1,
  17304. /** CTRL key flag. */
  17305. ctrlModifier = 2,
  17306. /** ALT key flag. */
  17307. altModifier = 4,
  17308. /** Left mouse button flag. */
  17309. leftButtonModifier = 16,
  17310. /** Right mouse button flag. */
  17311. rightButtonModifier = 32,
  17312. /** Middle mouse button flag. */
  17313. middleButtonModifier = 64,
  17314. #if JUCE_MAC
  17315. /** Command key flag - on windows this is the same as the CTRL key flag. */
  17316. commandModifier = 8,
  17317. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  17318. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  17319. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  17320. #else
  17321. /** Command key flag - on windows this is the same as the CTRL key flag. */
  17322. commandModifier = ctrlModifier,
  17323. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  17324. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  17325. popupMenuClickModifier = rightButtonModifier,
  17326. #endif
  17327. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  17328. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  17329. /** Represents a combination of all the mouse buttons at once. */
  17330. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  17331. };
  17332. /** Returns a copy of only the mouse-button flags */
  17333. const ModifierKeys withOnlyMouseButtons() const throw() { return ModifierKeys (flags & allMouseButtonModifiers); }
  17334. /** Returns a copy of only the non-mouse flags */
  17335. const ModifierKeys withoutMouseButtons() const throw() { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  17336. bool operator== (const ModifierKeys& other) const throw() { return flags == other.flags; }
  17337. bool operator!= (const ModifierKeys& other) const throw() { return flags != other.flags; }
  17338. /** Returns the raw flags for direct testing. */
  17339. inline int getRawFlags() const throw() { return flags; }
  17340. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const throw() { return ModifierKeys (flags & ~rawFlagsToClear); }
  17341. inline const ModifierKeys withFlags (int rawFlagsToSet) const throw() { return ModifierKeys (flags | rawFlagsToSet); }
  17342. /** Tests a combination of flags and returns true if any of them are set. */
  17343. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  17344. /** Returns the total number of mouse buttons that are down. */
  17345. int getNumMouseButtonsDown() const throw();
  17346. /** Creates a ModifierKeys object to represent the last-known state of the
  17347. keyboard and mouse buttons.
  17348. @see getCurrentModifiersRealtime
  17349. */
  17350. static const ModifierKeys getCurrentModifiers() throw();
  17351. /** Creates a ModifierKeys object to represent the current state of the
  17352. keyboard and mouse buttons.
  17353. This isn't often needed and isn't recommended, but will actively check all the
  17354. mouse and key states rather than just returning their last-known state like
  17355. getCurrentModifiers() does.
  17356. This is only needed in special circumstances for up-to-date modifier information
  17357. at times when the app's event loop isn't running normally.
  17358. Another reason to avoid this method is that it's not stateless, and calling it may
  17359. update the value returned by getCurrentModifiers(), which could cause subtle changes
  17360. in the behaviour of some components.
  17361. */
  17362. static const ModifierKeys getCurrentModifiersRealtime() throw();
  17363. private:
  17364. int flags;
  17365. static ModifierKeys currentModifiers;
  17366. friend class ComponentPeer;
  17367. friend class MouseInputSource;
  17368. friend class MouseInputSourceInternal;
  17369. static void updateCurrentModifiers() throw();
  17370. };
  17371. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  17372. /*** End of inlined file: juce_ModifierKeys.h ***/
  17373. /*** Start of inlined file: juce_Point.h ***/
  17374. #ifndef __JUCE_POINT_JUCEHEADER__
  17375. #define __JUCE_POINT_JUCEHEADER__
  17376. /*** Start of inlined file: juce_AffineTransform.h ***/
  17377. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  17378. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  17379. /**
  17380. Represents a 2D affine-transformation matrix.
  17381. An affine transformation is a transformation such as a rotation, scale, shear,
  17382. resize or translation.
  17383. These are used for various 2D transformation tasks, e.g. with Path objects.
  17384. @see Path, Point, Line
  17385. */
  17386. class JUCE_API AffineTransform
  17387. {
  17388. public:
  17389. /** Creates an identity transform. */
  17390. AffineTransform() throw();
  17391. /** Creates a copy of another transform. */
  17392. AffineTransform (const AffineTransform& other) throw();
  17393. /** Creates a transform from a set of raw matrix values.
  17394. The resulting matrix is:
  17395. (mat00 mat01 mat02)
  17396. (mat10 mat11 mat12)
  17397. ( 0 0 1 )
  17398. */
  17399. AffineTransform (float mat00, float mat01, float mat02,
  17400. float mat10, float mat11, float mat12) throw();
  17401. /** Copies from another AffineTransform object */
  17402. AffineTransform& operator= (const AffineTransform& other) throw();
  17403. /** Compares two transforms. */
  17404. bool operator== (const AffineTransform& other) const throw();
  17405. /** Compares two transforms. */
  17406. bool operator!= (const AffineTransform& other) const throw();
  17407. /** A ready-to-use identity transform, which you can use to append other
  17408. transformations to.
  17409. e.g. @code
  17410. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  17411. .scaled (2.0f);
  17412. @endcode
  17413. */
  17414. static const AffineTransform identity;
  17415. /** Transforms a 2D co-ordinate using this matrix. */
  17416. template <typename ValueType>
  17417. void transformPoint (ValueType& x, ValueType& y) const throw()
  17418. {
  17419. const ValueType oldX = x;
  17420. x = static_cast <ValueType> (mat00 * oldX + mat01 * y + mat02);
  17421. y = static_cast <ValueType> (mat10 * oldX + mat11 * y + mat12);
  17422. }
  17423. /** Transforms two 2D co-ordinates using this matrix.
  17424. This is just a shortcut for calling transformPoint() on each of these pairs of
  17425. coordinates in turn. (And putting all the calculations into one function hopefully
  17426. also gives the compiler a bit more scope for pipelining it).
  17427. */
  17428. template <typename ValueType>
  17429. void transformPoints (ValueType& x1, ValueType& y1,
  17430. ValueType& x2, ValueType& y2) const throw()
  17431. {
  17432. const ValueType oldX1 = x1, oldX2 = x2;
  17433. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  17434. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  17435. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  17436. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  17437. }
  17438. /** Transforms three 2D co-ordinates using this matrix.
  17439. This is just a shortcut for calling transformPoint() on each of these pairs of
  17440. coordinates in turn. (And putting all the calculations into one function hopefully
  17441. also gives the compiler a bit more scope for pipelining it).
  17442. */
  17443. template <typename ValueType>
  17444. void transformPoints (ValueType& x1, ValueType& y1,
  17445. ValueType& x2, ValueType& y2,
  17446. ValueType& x3, ValueType& y3) const throw()
  17447. {
  17448. const ValueType oldX1 = x1, oldX2 = x2, oldX3 = x3;
  17449. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  17450. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  17451. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  17452. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  17453. x3 = static_cast <ValueType> (mat00 * oldX3 + mat01 * y3 + mat02);
  17454. y3 = static_cast <ValueType> (mat10 * oldX3 + mat11 * y3 + mat12);
  17455. }
  17456. /** Returns a new transform which is the same as this one followed by a translation. */
  17457. const AffineTransform translated (float deltaX,
  17458. float deltaY) const throw();
  17459. /** Returns a new transform which is a translation. */
  17460. static const AffineTransform translation (float deltaX,
  17461. float deltaY) throw();
  17462. /** Returns a transform which is the same as this one followed by a rotation.
  17463. The rotation is specified by a number of radians to rotate clockwise, centred around
  17464. the origin (0, 0).
  17465. */
  17466. const AffineTransform rotated (float angleInRadians) const throw();
  17467. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  17468. The rotation is specified by a number of radians to rotate clockwise, centred around
  17469. the co-ordinates passed in.
  17470. */
  17471. const AffineTransform rotated (float angleInRadians,
  17472. float pivotX,
  17473. float pivotY) const throw();
  17474. /** Returns a new transform which is a rotation about (0, 0). */
  17475. static const AffineTransform rotation (float angleInRadians) throw();
  17476. /** Returns a new transform which is a rotation about a given point. */
  17477. static const AffineTransform rotation (float angleInRadians,
  17478. float pivotX,
  17479. float pivotY) throw();
  17480. /** Returns a transform which is the same as this one followed by a re-scaling.
  17481. The scaling is centred around the origin (0, 0).
  17482. */
  17483. const AffineTransform scaled (float factorX,
  17484. float factorY) const throw();
  17485. /** Returns a transform which is the same as this one followed by a re-scaling.
  17486. The scaling is centred around the origin provided.
  17487. */
  17488. const AffineTransform scaled (float factorX, float factorY,
  17489. float pivotX, float pivotY) const throw();
  17490. /** Returns a new transform which is a re-scale about the origin. */
  17491. static const AffineTransform scale (float factorX,
  17492. float factorY) throw();
  17493. /** Returns a new transform which is a re-scale centred around the point provided. */
  17494. static const AffineTransform scale (float factorX, float factorY,
  17495. float pivotX, float pivotY) throw();
  17496. /** Returns a transform which is the same as this one followed by a shear.
  17497. The shear is centred around the origin (0, 0).
  17498. */
  17499. const AffineTransform sheared (float shearX, float shearY) const throw();
  17500. /** Returns a shear transform, centred around the origin (0, 0). */
  17501. static const AffineTransform shear (float shearX, float shearY) throw();
  17502. /** Returns a matrix which is the inverse operation of this one.
  17503. Some matrices don't have an inverse - in this case, the method will just return
  17504. an identity transform.
  17505. */
  17506. const AffineTransform inverted() const throw();
  17507. /** Returns the transform that will map three known points onto three coordinates
  17508. that are supplied.
  17509. This returns the transform that will transform (0, 0) into (x00, y00),
  17510. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  17511. */
  17512. static const AffineTransform fromTargetPoints (float x00, float y00,
  17513. float x10, float y10,
  17514. float x01, float y01) throw();
  17515. /** Returns the transform that will map three specified points onto three target points.
  17516. */
  17517. static const AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
  17518. float sourceX2, float sourceY2, float targetX2, float targetY2,
  17519. float sourceX3, float sourceY3, float targetX3, float targetY3) throw();
  17520. /** Returns the result of concatenating another transformation after this one. */
  17521. const AffineTransform followedBy (const AffineTransform& other) const throw();
  17522. /** Returns true if this transform has no effect on points. */
  17523. bool isIdentity() const throw();
  17524. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  17525. bool isSingularity() const throw();
  17526. /** Returns true if the transform only translates, and doesn't scale or rotate the
  17527. points. */
  17528. bool isOnlyTranslation() const throw();
  17529. /** If this transform is only a translation, this returns the X offset.
  17530. @see isOnlyTranslation
  17531. */
  17532. float getTranslationX() const throw() { return mat02; }
  17533. /** If this transform is only a translation, this returns the X offset.
  17534. @see isOnlyTranslation
  17535. */
  17536. float getTranslationY() const throw() { return mat12; }
  17537. /** Returns the approximate scale factor by which lengths will be transformed.
  17538. Obviously a length may be scaled by entirely different amounts depending on its
  17539. direction, so this is only appropriate as a rough guide.
  17540. */
  17541. float getScaleFactor() const throw();
  17542. /* The transform matrix is:
  17543. (mat00 mat01 mat02)
  17544. (mat10 mat11 mat12)
  17545. ( 0 0 1 )
  17546. */
  17547. float mat00, mat01, mat02;
  17548. float mat10, mat11, mat12;
  17549. private:
  17550. JUCE_LEAK_DETECTOR (AffineTransform);
  17551. };
  17552. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  17553. /*** End of inlined file: juce_AffineTransform.h ***/
  17554. /**
  17555. A pair of (x, y) co-ordinates.
  17556. The ValueType template should be a primitive type such as int, float, double,
  17557. rather than a class.
  17558. @see Line, Path, AffineTransform
  17559. */
  17560. template <typename ValueType>
  17561. class Point
  17562. {
  17563. public:
  17564. /** Creates a point with co-ordinates (0, 0). */
  17565. Point() throw() : x(), y() {}
  17566. /** Creates a copy of another point. */
  17567. Point (const Point& other) throw() : x (other.x), y (other.y) {}
  17568. /** Creates a point from an (x, y) position. */
  17569. Point (const ValueType initialX, const ValueType initialY) throw() : x (initialX), y (initialY) {}
  17570. /** Destructor. */
  17571. ~Point() throw() {}
  17572. /** Copies this point from another one. */
  17573. Point& operator= (const Point& other) throw() { x = other.x; y = other.y; return *this; }
  17574. inline bool operator== (const Point& other) const throw() { return x == other.x && y == other.y; }
  17575. inline bool operator!= (const Point& other) const throw() { return x != other.x || y != other.y; }
  17576. /** Returns true if the point is (0, 0). */
  17577. bool isOrigin() const throw() { return x == ValueType() && y == ValueType(); }
  17578. /** Returns the point's x co-ordinate. */
  17579. inline ValueType getX() const throw() { return x; }
  17580. /** Returns the point's y co-ordinate. */
  17581. inline ValueType getY() const throw() { return y; }
  17582. /** Sets the point's x co-ordinate. */
  17583. inline void setX (const ValueType newX) throw() { x = newX; }
  17584. /** Sets the point's y co-ordinate. */
  17585. inline void setY (const ValueType newY) throw() { y = newY; }
  17586. /** Returns a point which has the same Y position as this one, but a new X. */
  17587. const Point withX (const ValueType newX) const throw() { return Point (newX, y); }
  17588. /** Returns a point which has the same X position as this one, but a new Y. */
  17589. const Point withY (const ValueType newY) const throw() { return Point (x, newY); }
  17590. /** Changes the point's x and y co-ordinates. */
  17591. void setXY (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  17592. /** Adds a pair of co-ordinates to this value. */
  17593. void addXY (const ValueType xToAdd, const ValueType yToAdd) throw() { x += xToAdd; y += yToAdd; }
  17594. /** Returns a point with a given offset from this one. */
  17595. const Point translated (const ValueType xDelta, const ValueType yDelta) const throw() { return Point (x + xDelta, y + yDelta); }
  17596. /** Adds two points together. */
  17597. const Point operator+ (const Point& other) const throw() { return Point (x + other.x, y + other.y); }
  17598. /** Adds another point's co-ordinates to this one. */
  17599. Point& operator+= (const Point& other) throw() { x += other.x; y += other.y; return *this; }
  17600. /** Subtracts one points from another. */
  17601. const Point operator- (const Point& other) const throw() { return Point (x - other.x, y - other.y); }
  17602. /** Subtracts another point's co-ordinates to this one. */
  17603. Point& operator-= (const Point& other) throw() { x -= other.x; y -= other.y; return *this; }
  17604. /** Returns a point whose coordinates are multiplied by a given value. */
  17605. const Point operator* (const ValueType multiplier) const throw() { return Point (x * multiplier, y * multiplier); }
  17606. /** Multiplies the point's co-ordinates by a value. */
  17607. Point& operator*= (const ValueType multiplier) throw() { x *= multiplier; y *= multiplier; return *this; }
  17608. /** Returns a point whose coordinates are divided by a given value. */
  17609. const Point operator/ (const ValueType divisor) const throw() { return Point (x / divisor, y / divisor); }
  17610. /** Divides the point's co-ordinates by a value. */
  17611. Point& operator/= (const ValueType divisor) throw() { x /= divisor; y /= divisor; return *this; }
  17612. /** Returns the inverse of this point. */
  17613. const Point operator-() const throw() { return Point (-x, -y); }
  17614. /** Returns the straight-line distance between this point and another one. */
  17615. ValueType getDistanceFromOrigin() const throw() { return juce_hypot (x, y); }
  17616. /** Returns the straight-line distance between this point and another one. */
  17617. ValueType getDistanceFrom (const Point& other) const throw() { return juce_hypot (x - other.x, y - other.y); }
  17618. /** Returns the angle from this point to another one.
  17619. The return value is the number of radians clockwise from the 3 o'clock direction,
  17620. where this point is the centre and the other point is on the circumference.
  17621. */
  17622. ValueType getAngleToPoint (const Point& other) const throw() { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  17623. /** Taking this point to be the centre of a circle, this returns a point on its circumference.
  17624. @param radius the radius of the circle.
  17625. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  17626. */
  17627. const Point getPointOnCircumference (const float radius, const float angle) const throw() { return Point<float> (x + radius * std::sin (angle),
  17628. y - radius * std::cos (angle)); }
  17629. /** Taking this point to be the centre of an ellipse, this returns a point on its circumference.
  17630. @param radiusX the horizontal radius of the circle.
  17631. @param radiusY the vertical radius of the circle.
  17632. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  17633. */
  17634. const Point getPointOnCircumference (const float radiusX, const float radiusY, const float angle) const throw() { return Point<float> (x + radiusX * std::sin (angle),
  17635. y - radiusY * std::cos (angle)); }
  17636. /** Uses a transform to change the point's co-ordinates.
  17637. This will only compile if ValueType = float!
  17638. @see AffineTransform::transformPoint
  17639. */
  17640. void applyTransform (const AffineTransform& transform) throw() { transform.transformPoint (x, y); }
  17641. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  17642. const Point transformedBy (const AffineTransform& transform) const throw() { return Point (transform.mat00 * x + transform.mat01 * y + transform.mat02,
  17643. transform.mat10 * x + transform.mat11 * y + transform.mat12); }
  17644. /** Casts this point to a Point<int> object. */
  17645. const Point<int> toInt() const throw() { return Point<int> (static_cast <int> (x), static_cast<int> (y)); }
  17646. /** Casts this point to a Point<float> object. */
  17647. const Point<float> toFloat() const throw() { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  17648. /** Casts this point to a Point<double> object. */
  17649. const Point<double> toDouble() const throw() { return Point<double> (static_cast <double> (x), static_cast<double> (y)); }
  17650. /** Returns the point as a string in the form "x, y". */
  17651. const String toString() const { return String (x) + ", " + String (y); }
  17652. private:
  17653. ValueType x, y;
  17654. };
  17655. #endif // __JUCE_POINT_JUCEHEADER__
  17656. /*** End of inlined file: juce_Point.h ***/
  17657. /**
  17658. Contains position and status information about a mouse event.
  17659. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  17660. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  17661. */
  17662. class JUCE_API MouseEvent
  17663. {
  17664. public:
  17665. /** Creates a MouseEvent.
  17666. Normally an application will never need to use this.
  17667. @param source the source that's invoking the event
  17668. @param position the position of the mouse, relative to the component that is passed-in
  17669. @param modifiers the key modifiers at the time of the event
  17670. @param eventComponent the component that the mouse event applies to
  17671. @param originator the component that originally received the event
  17672. @param eventTime the time the event happened
  17673. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  17674. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  17675. the same as the current mouse-x position.
  17676. @param mouseDownTime the time at which the corresponding mouse-down event happened
  17677. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  17678. the same as the current mouse-event time.
  17679. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  17680. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  17681. */
  17682. MouseEvent (MouseInputSource& source,
  17683. const Point<int>& position,
  17684. const ModifierKeys& modifiers,
  17685. Component* eventComponent,
  17686. Component* originator,
  17687. const Time& eventTime,
  17688. const Point<int> mouseDownPos,
  17689. const Time& mouseDownTime,
  17690. int numberOfClicks,
  17691. bool mouseWasDragged) throw();
  17692. /** Destructor. */
  17693. ~MouseEvent() throw();
  17694. /** The x-position of the mouse when the event occurred.
  17695. This value is relative to the top-left of the component to which the
  17696. event applies (as indicated by the MouseEvent::eventComponent field).
  17697. */
  17698. const int x;
  17699. /** The y-position of the mouse when the event occurred.
  17700. This value is relative to the top-left of the component to which the
  17701. event applies (as indicated by the MouseEvent::eventComponent field).
  17702. */
  17703. const int y;
  17704. /** The key modifiers associated with the event.
  17705. This will let you find out which mouse buttons were down, as well as which
  17706. modifier keys were held down.
  17707. When used for mouse-up events, this will indicate the state of the mouse buttons
  17708. just before they were released, so that you can tell which button they let go of.
  17709. */
  17710. const ModifierKeys mods;
  17711. /** The component that this event applies to.
  17712. This is usually the component that the mouse was over at the time, but for mouse-drag
  17713. events the mouse could actually be over a different component and the events are
  17714. still sent to the component that the button was originally pressed on.
  17715. The x and y member variables are relative to this component's position.
  17716. If you use getEventRelativeTo() to retarget this object to be relative to a different
  17717. component, this pointer will be updated, but originalComponent remains unchanged.
  17718. @see originalComponent
  17719. */
  17720. Component* const eventComponent;
  17721. /** The component that the event first occurred on.
  17722. If you use getEventRelativeTo() to retarget this object to be relative to a different
  17723. component, this value remains unchanged to indicate the first component that received it.
  17724. @see eventComponent
  17725. */
  17726. Component* const originalComponent;
  17727. /** The time that this mouse-event occurred.
  17728. */
  17729. const Time eventTime;
  17730. /** The source device that generated this event.
  17731. */
  17732. MouseInputSource& source;
  17733. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  17734. The co-ordinate is relative to the component specified in MouseEvent::component.
  17735. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  17736. */
  17737. int getMouseDownX() const throw();
  17738. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  17739. The co-ordinate is relative to the component specified in MouseEvent::component.
  17740. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  17741. */
  17742. int getMouseDownY() const throw();
  17743. /** Returns the co-ordinates of the last place that a mouse was pressed.
  17744. The co-ordinates are relative to the component specified in MouseEvent::component.
  17745. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  17746. */
  17747. const Point<int> getMouseDownPosition() const throw();
  17748. /** Returns the straight-line distance between where the mouse is now and where it
  17749. was the last time the button was pressed.
  17750. This is quite handy for things like deciding whether the user has moved far enough
  17751. for it to be considered a drag operation.
  17752. @see getDistanceFromDragStartX
  17753. */
  17754. int getDistanceFromDragStart() const throw();
  17755. /** Returns the difference between the mouse's current x postion and where it was
  17756. when the button was last pressed.
  17757. @see getDistanceFromDragStart
  17758. */
  17759. int getDistanceFromDragStartX() const throw();
  17760. /** Returns the difference between the mouse's current y postion and where it was
  17761. when the button was last pressed.
  17762. @see getDistanceFromDragStart
  17763. */
  17764. int getDistanceFromDragStartY() const throw();
  17765. /** Returns the difference between the mouse's current postion and where it was
  17766. when the button was last pressed.
  17767. @see getDistanceFromDragStart
  17768. */
  17769. const Point<int> getOffsetFromDragStart() const throw();
  17770. /** Returns true if the mouse has just been clicked.
  17771. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  17772. the user has dragged the mouse more than a few pixels from the place where the
  17773. mouse-down occurred.
  17774. Once they have dragged it far enough for this method to return false, it will continue
  17775. to return false until the mouse-up, even if they move the mouse back to the same
  17776. position where they originally pressed it. This means that it's very handy for
  17777. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  17778. callback to ignore any small movements they might make while clicking.
  17779. @returns true if the mouse wasn't dragged by more than a few pixels between
  17780. the last time the button was pressed and released.
  17781. */
  17782. bool mouseWasClicked() const throw();
  17783. /** For a click event, the number of times the mouse was clicked in succession.
  17784. So for example a double-click event will return 2, a triple-click 3, etc.
  17785. */
  17786. int getNumberOfClicks() const throw() { return numberOfClicks; }
  17787. /** Returns the time that the mouse button has been held down for.
  17788. If called from a mouseDrag or mouseUp callback, this will return the
  17789. number of milliseconds since the corresponding mouseDown event occurred.
  17790. If called in other contexts, e.g. a mouseMove, then the returned value
  17791. may be 0 or an undefined value.
  17792. */
  17793. int getLengthOfMousePress() const throw();
  17794. /** The position of the mouse when the event occurred.
  17795. This position is relative to the top-left of the component to which the
  17796. event applies (as indicated by the MouseEvent::eventComponent field).
  17797. */
  17798. const Point<int> getPosition() const throw();
  17799. /** Returns the mouse x position of this event, in global screen co-ordinates.
  17800. The co-ordinates are relative to the top-left of the main monitor.
  17801. @see getScreenPosition
  17802. */
  17803. int getScreenX() const;
  17804. /** Returns the mouse y position of this event, in global screen co-ordinates.
  17805. The co-ordinates are relative to the top-left of the main monitor.
  17806. @see getScreenPosition
  17807. */
  17808. int getScreenY() const;
  17809. /** Returns the mouse position of this event, in global screen co-ordinates.
  17810. The co-ordinates are relative to the top-left of the main monitor.
  17811. @see getMouseDownScreenPosition
  17812. */
  17813. const Point<int> getScreenPosition() const;
  17814. /** Returns the x co-ordinate at which the mouse button was last pressed.
  17815. The co-ordinates are relative to the top-left of the main monitor.
  17816. @see getMouseDownScreenPosition
  17817. */
  17818. int getMouseDownScreenX() const;
  17819. /** Returns the y co-ordinate at which the mouse button was last pressed.
  17820. The co-ordinates are relative to the top-left of the main monitor.
  17821. @see getMouseDownScreenPosition
  17822. */
  17823. int getMouseDownScreenY() const;
  17824. /** Returns the co-ordinates at which the mouse button was last pressed.
  17825. The co-ordinates are relative to the top-left of the main monitor.
  17826. @see getScreenPosition
  17827. */
  17828. const Point<int> getMouseDownScreenPosition() const;
  17829. /** Creates a version of this event that is relative to a different component.
  17830. The x and y positions of the event that is returned will have been
  17831. adjusted to be relative to the new component.
  17832. */
  17833. const MouseEvent getEventRelativeTo (Component* otherComponent) const throw();
  17834. /** Creates a copy of this event with a different position.
  17835. All other members of the event object are the same, but the x and y are
  17836. replaced with these new values.
  17837. */
  17838. const MouseEvent withNewPosition (const Point<int>& newPosition) const throw();
  17839. /** Changes the application-wide setting for the double-click time limit.
  17840. This is the maximum length of time between mouse-clicks for it to be
  17841. considered a double-click. It's used by the Component class.
  17842. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  17843. */
  17844. static void setDoubleClickTimeout (int timeOutMilliseconds) throw();
  17845. /** Returns the application-wide setting for the double-click time limit.
  17846. This is the maximum length of time between mouse-clicks for it to be
  17847. considered a double-click. It's used by the Component class.
  17848. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  17849. */
  17850. static int getDoubleClickTimeout() throw();
  17851. private:
  17852. const Point<int> mouseDownPos;
  17853. const Time mouseDownTime;
  17854. const int numberOfClicks;
  17855. const bool wasMovedSinceMouseDown;
  17856. static int doubleClickTimeOutMs;
  17857. MouseEvent& operator= (const MouseEvent&);
  17858. };
  17859. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  17860. /*** End of inlined file: juce_MouseEvent.h ***/
  17861. /*** Start of inlined file: juce_ComponentListener.h ***/
  17862. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  17863. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  17864. class Component;
  17865. /**
  17866. Gets informed about changes to a component's hierarchy or position.
  17867. To monitor a component for changes, register a subclass of ComponentListener
  17868. with the component using Component::addComponentListener().
  17869. Be sure to deregister listeners before you delete them!
  17870. @see Component::addComponentListener, Component::removeComponentListener
  17871. */
  17872. class JUCE_API ComponentListener
  17873. {
  17874. public:
  17875. /** Destructor. */
  17876. virtual ~ComponentListener() {}
  17877. /** Called when the component's position or size changes.
  17878. @param component the component that was moved or resized
  17879. @param wasMoved true if the component's top-left corner has just moved
  17880. @param wasResized true if the component's width or height has just changed
  17881. @see Component::setBounds, Component::resized, Component::moved
  17882. */
  17883. virtual void componentMovedOrResized (Component& component,
  17884. bool wasMoved,
  17885. bool wasResized);
  17886. /** Called when the component is brought to the top of the z-order.
  17887. @param component the component that was moved
  17888. @see Component::toFront, Component::broughtToFront
  17889. */
  17890. virtual void componentBroughtToFront (Component& component);
  17891. /** Called when the component is made visible or invisible.
  17892. @param component the component that changed
  17893. @see Component::setVisible
  17894. */
  17895. virtual void componentVisibilityChanged (Component& component);
  17896. /** Called when the component has children added or removed.
  17897. @param component the component whose children were changed
  17898. @see Component::childrenChanged, Component::addChildComponent,
  17899. Component::removeChildComponent
  17900. */
  17901. virtual void componentChildrenChanged (Component& component);
  17902. /** Called to indicate that the component's parents have changed.
  17903. When a component is added or removed from its parent, all of its children
  17904. will produce this notification (recursively - so all children of its
  17905. children will also be called as well).
  17906. @param component the component that this listener is registered with
  17907. @see Component::parentHierarchyChanged
  17908. */
  17909. virtual void componentParentHierarchyChanged (Component& component);
  17910. /** Called when the component's name is changed.
  17911. @see Component::setName, Component::getName
  17912. */
  17913. virtual void componentNameChanged (Component& component);
  17914. /** Called when the component is in the process of being deleted.
  17915. This callback is made from inside the destructor, so be very, very cautious
  17916. about what you do in here.
  17917. In particular, bear in mind that it's the Component base class's destructor that calls
  17918. this - so if the object that's being deleted is a subclass of Component, then the
  17919. subclass layers of the object will already have been destructed when it gets to this
  17920. point!
  17921. */
  17922. virtual void componentBeingDeleted (Component& component);
  17923. };
  17924. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  17925. /*** End of inlined file: juce_ComponentListener.h ***/
  17926. /*** Start of inlined file: juce_KeyListener.h ***/
  17927. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  17928. #define __JUCE_KEYLISTENER_JUCEHEADER__
  17929. /*** Start of inlined file: juce_KeyPress.h ***/
  17930. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  17931. #define __JUCE_KEYPRESS_JUCEHEADER__
  17932. /**
  17933. Represents a key press, including any modifier keys that are needed.
  17934. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  17935. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  17936. */
  17937. class JUCE_API KeyPress
  17938. {
  17939. public:
  17940. /** Creates an (invalid) KeyPress.
  17941. @see isValid
  17942. */
  17943. KeyPress() throw();
  17944. /** Creates a KeyPress for a key and some modifiers.
  17945. e.g.
  17946. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  17947. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  17948. @param keyCode a code that represents the key - this value must be
  17949. one of special constants listed in this class, or an
  17950. 8-bit character code such as a letter (case is ignored),
  17951. digit or a simple key like "," or ".". Note that this
  17952. isn't the same as the textCharacter parameter, so for example
  17953. a keyCode of 'a' and a shift-key modifier should have a
  17954. textCharacter value of 'A'.
  17955. @param modifiers the modifiers to associate with the keystroke
  17956. @param textCharacter the character that would be printed if someone typed
  17957. this keypress into a text editor. This value may be
  17958. null if the keypress is a non-printing character
  17959. @see getKeyCode, isKeyCode, getModifiers
  17960. */
  17961. KeyPress (int keyCode,
  17962. const ModifierKeys& modifiers,
  17963. juce_wchar textCharacter) throw();
  17964. /** Creates a keypress with a keyCode but no modifiers or text character.
  17965. */
  17966. KeyPress (int keyCode) throw();
  17967. /** Creates a copy of another KeyPress. */
  17968. KeyPress (const KeyPress& other) throw();
  17969. /** Copies this KeyPress from another one. */
  17970. KeyPress& operator= (const KeyPress& other) throw();
  17971. /** Compares two KeyPress objects. */
  17972. bool operator== (const KeyPress& other) const throw();
  17973. /** Compares two KeyPress objects. */
  17974. bool operator!= (const KeyPress& other) const throw();
  17975. /** Returns true if this is a valid KeyPress.
  17976. A null keypress can be created by the default constructor, in case it's
  17977. needed.
  17978. */
  17979. bool isValid() const throw() { return keyCode != 0; }
  17980. /** Returns the key code itself.
  17981. This will either be one of the special constants defined in this class,
  17982. or an 8-bit character code.
  17983. */
  17984. int getKeyCode() const throw() { return keyCode; }
  17985. /** Returns the key modifiers.
  17986. @see ModifierKeys
  17987. */
  17988. const ModifierKeys getModifiers() const throw() { return mods; }
  17989. /** Returns the character that is associated with this keypress.
  17990. This is the character that you'd expect to see printed if you press this
  17991. keypress in a text editor or similar component.
  17992. */
  17993. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  17994. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  17995. the modifiers.
  17996. The values for key codes can either be one of the special constants defined in
  17997. this class, or an 8-bit character code.
  17998. @see getKeyCode
  17999. */
  18000. bool isKeyCode (int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  18001. /** Converts a textual key description to a KeyPress.
  18002. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  18003. This isn't designed to cope with any kind of input, but should be given the
  18004. strings that are created by the getTextDescription() method.
  18005. If the string can't be parsed, the object returned will be invalid.
  18006. @see getTextDescription
  18007. */
  18008. static const KeyPress createFromDescription (const String& textVersion);
  18009. /** Creates a textual description of the key combination.
  18010. e.g. "CTRL + C" or "DELETE".
  18011. To store a keypress in a file, use this method, along with createFromDescription()
  18012. to retrieve it later.
  18013. */
  18014. const String getTextDescription() const;
  18015. /** Checks whether the user is currently holding down the keys that make up this
  18016. KeyPress.
  18017. Note that this will return false if any extra modifier keys are
  18018. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  18019. then it will be false.
  18020. */
  18021. bool isCurrentlyDown() const;
  18022. /** Checks whether a particular key is held down, irrespective of modifiers.
  18023. The values for key codes can either be one of the special constants defined in
  18024. this class, or an 8-bit character code.
  18025. */
  18026. static bool isKeyCurrentlyDown (int keyCode);
  18027. // Key codes
  18028. //
  18029. // Note that the actual values of these are platform-specific and may change
  18030. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  18031. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  18032. //
  18033. static const int spaceKey; /**< key-code for the space bar */
  18034. static const int escapeKey; /**< key-code for the escape key */
  18035. static const int returnKey; /**< key-code for the return key*/
  18036. static const int tabKey; /**< key-code for the tab key*/
  18037. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  18038. static const int backspaceKey; /**< key-code for the backspace key */
  18039. static const int insertKey; /**< key-code for the insert key */
  18040. static const int upKey; /**< key-code for the cursor-up key */
  18041. static const int downKey; /**< key-code for the cursor-down key */
  18042. static const int leftKey; /**< key-code for the cursor-left key */
  18043. static const int rightKey; /**< key-code for the cursor-right key */
  18044. static const int pageUpKey; /**< key-code for the page-up key */
  18045. static const int pageDownKey; /**< key-code for the page-down key */
  18046. static const int homeKey; /**< key-code for the home key */
  18047. static const int endKey; /**< key-code for the end key */
  18048. static const int F1Key; /**< key-code for the F1 key */
  18049. static const int F2Key; /**< key-code for the F2 key */
  18050. static const int F3Key; /**< key-code for the F3 key */
  18051. static const int F4Key; /**< key-code for the F4 key */
  18052. static const int F5Key; /**< key-code for the F5 key */
  18053. static const int F6Key; /**< key-code for the F6 key */
  18054. static const int F7Key; /**< key-code for the F7 key */
  18055. static const int F8Key; /**< key-code for the F8 key */
  18056. static const int F9Key; /**< key-code for the F9 key */
  18057. static const int F10Key; /**< key-code for the F10 key */
  18058. static const int F11Key; /**< key-code for the F11 key */
  18059. static const int F12Key; /**< key-code for the F12 key */
  18060. static const int F13Key; /**< key-code for the F13 key */
  18061. static const int F14Key; /**< key-code for the F14 key */
  18062. static const int F15Key; /**< key-code for the F15 key */
  18063. static const int F16Key; /**< key-code for the F16 key */
  18064. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  18065. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  18066. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  18067. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  18068. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  18069. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  18070. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  18071. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  18072. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  18073. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  18074. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  18075. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  18076. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  18077. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  18078. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  18079. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  18080. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  18081. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  18082. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  18083. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  18084. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  18085. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  18086. private:
  18087. int keyCode;
  18088. ModifierKeys mods;
  18089. juce_wchar textCharacter;
  18090. JUCE_LEAK_DETECTOR (KeyPress);
  18091. };
  18092. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  18093. /*** End of inlined file: juce_KeyPress.h ***/
  18094. class Component;
  18095. /**
  18096. Receives callbacks when keys are pressed.
  18097. You can add a key listener to a component to be informed when that component
  18098. gets key events. See the Component::addListener method for more details.
  18099. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  18100. */
  18101. class JUCE_API KeyListener
  18102. {
  18103. public:
  18104. /** Destructor. */
  18105. virtual ~KeyListener() {}
  18106. /** Called to indicate that a key has been pressed.
  18107. If your implementation returns true, then the key event is considered to have
  18108. been consumed, and will not be passed on to any other components. If it returns
  18109. false, then the key will be passed to other components that might want to use it.
  18110. @param key the keystroke, including modifier keys
  18111. @param originatingComponent the component that received the key event
  18112. @see keyStateChanged, Component::keyPressed
  18113. */
  18114. virtual bool keyPressed (const KeyPress& key,
  18115. Component* originatingComponent) = 0;
  18116. /** Called when any key is pressed or released.
  18117. When this is called, classes that might be interested in
  18118. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  18119. check whether their key has changed.
  18120. If your implementation returns true, then the key event is considered to have
  18121. been consumed, and will not be passed on to any other components. If it returns
  18122. false, then the key will be passed to other components that might want to use it.
  18123. @param originatingComponent the component that received the key event
  18124. @param isKeyDown true if a key is being pressed, false if one is being released
  18125. @see KeyPress, Component::keyStateChanged
  18126. */
  18127. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  18128. };
  18129. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  18130. /*** End of inlined file: juce_KeyListener.h ***/
  18131. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  18132. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  18133. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  18134. class Component;
  18135. /**
  18136. Controls the order in which focus moves between components.
  18137. The default algorithm used by this class to work out the order of traversal
  18138. is as follows:
  18139. - if two components both have an explicit focus order specified, then the
  18140. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  18141. method).
  18142. - any component with an explicit focus order greater than 0 comes before ones
  18143. that don't have an order specified.
  18144. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  18145. order.
  18146. If you need traversal in a more customised way, you can create a subclass
  18147. of KeyboardFocusTraverser that uses your own algorithm, and use
  18148. Component::createFocusTraverser() to create it.
  18149. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  18150. */
  18151. class JUCE_API KeyboardFocusTraverser
  18152. {
  18153. public:
  18154. KeyboardFocusTraverser();
  18155. /** Destructor. */
  18156. virtual ~KeyboardFocusTraverser();
  18157. /** Returns the component that should be given focus after the specified one
  18158. when moving "forwards".
  18159. The default implementation will return the next component which is to the
  18160. right of or below this one.
  18161. This may return 0 if there's no suitable candidate.
  18162. */
  18163. virtual Component* getNextComponent (Component* current);
  18164. /** Returns the component that should be given focus after the specified one
  18165. when moving "backwards".
  18166. The default implementation will return the next component which is to the
  18167. left of or above this one.
  18168. This may return 0 if there's no suitable candidate.
  18169. */
  18170. virtual Component* getPreviousComponent (Component* current);
  18171. /** Returns the component that should receive focus be default within the given
  18172. parent component.
  18173. The default implementation will just return the foremost child component that
  18174. wants focus.
  18175. This may return 0 if there's no suitable candidate.
  18176. */
  18177. virtual Component* getDefaultComponent (Component* parentComponent);
  18178. };
  18179. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  18180. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  18181. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  18182. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  18183. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  18184. /*** Start of inlined file: juce_Graphics.h ***/
  18185. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  18186. #define __JUCE_GRAPHICS_JUCEHEADER__
  18187. /*** Start of inlined file: juce_Font.h ***/
  18188. #ifndef __JUCE_FONT_JUCEHEADER__
  18189. #define __JUCE_FONT_JUCEHEADER__
  18190. /*** Start of inlined file: juce_Typeface.h ***/
  18191. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  18192. #define __JUCE_TYPEFACE_JUCEHEADER__
  18193. /*** Start of inlined file: juce_Path.h ***/
  18194. #ifndef __JUCE_PATH_JUCEHEADER__
  18195. #define __JUCE_PATH_JUCEHEADER__
  18196. /*** Start of inlined file: juce_Line.h ***/
  18197. #ifndef __JUCE_LINE_JUCEHEADER__
  18198. #define __JUCE_LINE_JUCEHEADER__
  18199. /**
  18200. Represents a line.
  18201. This class contains a bunch of useful methods for various geometric
  18202. tasks.
  18203. The ValueType template parameter should be a primitive type - float or double
  18204. are what it's designed for. Integer types will work in a basic way, but some methods
  18205. that perform mathematical operations may not compile, or they may not produce
  18206. sensible results.
  18207. @see Point, Rectangle, Path, Graphics::drawLine
  18208. */
  18209. template <typename ValueType>
  18210. class Line
  18211. {
  18212. public:
  18213. /** Creates a line, using (0, 0) as its start and end points. */
  18214. Line() throw() {}
  18215. /** Creates a copy of another line. */
  18216. Line (const Line& other) throw()
  18217. : start (other.start),
  18218. end (other.end)
  18219. {
  18220. }
  18221. /** Creates a line based on the co-ordinates of its start and end points. */
  18222. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) throw()
  18223. : start (startX, startY),
  18224. end (endX, endY)
  18225. {
  18226. }
  18227. /** Creates a line from its start and end points. */
  18228. Line (const Point<ValueType>& startPoint,
  18229. const Point<ValueType>& endPoint) throw()
  18230. : start (startPoint),
  18231. end (endPoint)
  18232. {
  18233. }
  18234. /** Copies a line from another one. */
  18235. Line& operator= (const Line& other) throw()
  18236. {
  18237. start = other.start;
  18238. end = other.end;
  18239. return *this;
  18240. }
  18241. /** Destructor. */
  18242. ~Line() throw() {}
  18243. /** Returns the x co-ordinate of the line's start point. */
  18244. inline ValueType getStartX() const throw() { return start.getX(); }
  18245. /** Returns the y co-ordinate of the line's start point. */
  18246. inline ValueType getStartY() const throw() { return start.getY(); }
  18247. /** Returns the x co-ordinate of the line's end point. */
  18248. inline ValueType getEndX() const throw() { return end.getX(); }
  18249. /** Returns the y co-ordinate of the line's end point. */
  18250. inline ValueType getEndY() const throw() { return end.getY(); }
  18251. /** Returns the line's start point. */
  18252. inline const Point<ValueType>& getStart() const throw() { return start; }
  18253. /** Returns the line's end point. */
  18254. inline const Point<ValueType>& getEnd() const throw() { return end; }
  18255. /** Changes this line's start point */
  18256. void setStart (ValueType newStartX, ValueType newStartY) throw() { start.setXY (newStartX, newStartY); }
  18257. /** Changes this line's end point */
  18258. void setEnd (ValueType newEndX, ValueType newEndY) throw() { end.setXY (newEndX, newEndY); }
  18259. /** Changes this line's start point */
  18260. void setStart (const Point<ValueType>& newStart) throw() { start = newStart; }
  18261. /** Changes this line's end point */
  18262. void setEnd (const Point<ValueType>& newEnd) throw() { end = newEnd; }
  18263. /** Returns a line that is the same as this one, but with the start and end reversed, */
  18264. const Line reversed() const throw() { return Line (end, start); }
  18265. /** Applies an affine transform to the line's start and end points. */
  18266. void applyTransform (const AffineTransform& transform) throw()
  18267. {
  18268. start.applyTransform (transform);
  18269. end.applyTransform (transform);
  18270. }
  18271. /** Returns the length of the line. */
  18272. ValueType getLength() const throw() { return start.getDistanceFrom (end); }
  18273. /** Returns true if the line's start and end x co-ordinates are the same. */
  18274. bool isVertical() const throw() { return start.getX() == end.getX(); }
  18275. /** Returns true if the line's start and end y co-ordinates are the same. */
  18276. bool isHorizontal() const throw() { return start.getY() == end.getY(); }
  18277. /** Returns the line's angle.
  18278. This value is the number of radians clockwise from the 3 o'clock direction,
  18279. where the line's start point is considered to be at the centre.
  18280. */
  18281. ValueType getAngle() const throw() { return start.getAngleToPoint (end); }
  18282. /** Compares two lines. */
  18283. bool operator== (const Line& other) const throw() { return start == other.start && end == other.end; }
  18284. /** Compares two lines. */
  18285. bool operator!= (const Line& other) const throw() { return start != other.start || end != other.end; }
  18286. /** Finds the intersection between two lines.
  18287. @param line the other line
  18288. @param intersection the position of the point where the lines meet (or
  18289. where they would meet if they were infinitely long)
  18290. the intersection (if the lines intersect). If the lines
  18291. are parallel, this will just be set to the position
  18292. of one of the line's endpoints.
  18293. @returns true if the line segments intersect; false if they dont. Even if they
  18294. don't intersect, the intersection co-ordinates returned will still
  18295. be valid
  18296. */
  18297. bool intersects (const Line& line, Point<ValueType>& intersection) const throw()
  18298. {
  18299. return findIntersection (start, end, line.start, line.end, intersection);
  18300. }
  18301. /** Finds the intersection between two lines.
  18302. @param line the line to intersect with
  18303. @returns the point at which the lines intersect, even if this lies beyond the end of the lines
  18304. */
  18305. const Point<ValueType> getIntersection (const Line& line) const throw()
  18306. {
  18307. Point<ValueType> p;
  18308. findIntersection (start, end, line.start, line.end, p);
  18309. return p;
  18310. }
  18311. /** Returns the location of the point which is a given distance along this line.
  18312. @param distanceFromStart the distance to move along the line from its
  18313. start point. This value can be negative or longer
  18314. than the line itself
  18315. @see getPointAlongLineProportionally
  18316. */
  18317. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const throw()
  18318. {
  18319. return start + (end - start) * (distanceFromStart / getLength());
  18320. }
  18321. /** Returns a point which is a certain distance along and to the side of this line.
  18322. This effectively moves a given distance along the line, then another distance
  18323. perpendicularly to this, and returns the resulting position.
  18324. @param distanceFromStart the distance to move along the line from its
  18325. start point. This value can be negative or longer
  18326. than the line itself
  18327. @param perpendicularDistance how far to move sideways from the line. If you're
  18328. looking along the line from its start towards its
  18329. end, then a positive value here will move to the
  18330. right, negative value move to the left.
  18331. */
  18332. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  18333. ValueType perpendicularDistance) const throw()
  18334. {
  18335. const Point<ValueType> delta (end - start);
  18336. const double length = juce_hypot ((double) delta.getX(),
  18337. (double) delta.getY());
  18338. if (length == 0)
  18339. return start;
  18340. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  18341. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  18342. }
  18343. /** Returns the location of the point which is a given distance along this line
  18344. proportional to the line's length.
  18345. @param proportionOfLength the distance to move along the line from its
  18346. start point, in multiples of the line's length.
  18347. So a value of 0.0 will return the line's start point
  18348. and a value of 1.0 will return its end point. (This value
  18349. can be negative or greater than 1.0).
  18350. @see getPointAlongLine
  18351. */
  18352. const Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const throw()
  18353. {
  18354. return start + (end - start) * proportionOfLength;
  18355. }
  18356. /** Returns the smallest distance between this line segment and a given point.
  18357. So if the point is close to the line, this will return the perpendicular
  18358. distance from the line; if the point is a long way beyond one of the line's
  18359. end-point's, it'll return the straight-line distance to the nearest end-point.
  18360. pointOnLine receives the position of the point that is found.
  18361. @returns the point's distance from the line
  18362. @see getPositionAlongLineOfNearestPoint
  18363. */
  18364. ValueType getDistanceFromPoint (const Point<ValueType>& targetPoint,
  18365. Point<ValueType>& pointOnLine) const throw()
  18366. {
  18367. const Point<ValueType> delta (end - start);
  18368. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  18369. if (length > 0)
  18370. {
  18371. const double prop = ((targetPoint.getX() - start.getX()) * delta.getX()
  18372. + (targetPoint.getY() - start.getY()) * delta.getY()) / length;
  18373. if (prop >= 0 && prop <= 1.0)
  18374. {
  18375. pointOnLine = start + delta * (ValueType) prop;
  18376. return targetPoint.getDistanceFrom (pointOnLine);
  18377. }
  18378. }
  18379. const float fromStart = targetPoint.getDistanceFrom (start);
  18380. const float fromEnd = targetPoint.getDistanceFrom (end);
  18381. if (fromStart < fromEnd)
  18382. {
  18383. pointOnLine = start;
  18384. return fromStart;
  18385. }
  18386. else
  18387. {
  18388. pointOnLine = end;
  18389. return fromEnd;
  18390. }
  18391. }
  18392. /** Finds the point on this line which is nearest to a given point, and
  18393. returns its position as a proportional position along the line.
  18394. @returns a value 0 to 1.0 which is the distance along this line from the
  18395. line's start to the point which is nearest to the point passed-in. To
  18396. turn this number into a position, use getPointAlongLineProportionally().
  18397. @see getDistanceFromPoint, getPointAlongLineProportionally
  18398. */
  18399. ValueType findNearestProportionalPositionTo (const Point<ValueType>& point) const throw()
  18400. {
  18401. const Point<ValueType> delta (end - start);
  18402. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  18403. return length <= 0 ? 0
  18404. : jlimit ((ValueType) 0, (ValueType) 1,
  18405. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  18406. + (point.getY() - start.getY()) * delta.getY()) / length));
  18407. }
  18408. /** Finds the point on this line which is nearest to a given point.
  18409. @see getDistanceFromPoint, findNearestProportionalPositionTo
  18410. */
  18411. const Point<ValueType> findNearestPointTo (const Point<ValueType>& point) const throw()
  18412. {
  18413. return getPointAlongLineProportionally (findNearestProportionalPositionTo (point));
  18414. }
  18415. /** Returns true if the given point lies above this line.
  18416. The return value is true if the point's y coordinate is less than the y
  18417. coordinate of this line at the given x (assuming the line extends infinitely
  18418. in both directions).
  18419. */
  18420. bool isPointAbove (const Point<ValueType>& point) const throw()
  18421. {
  18422. return start.getX() != end.getX()
  18423. && point.getY() < ((end.getY() - start.getY())
  18424. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  18425. }
  18426. /** Returns a shortened copy of this line.
  18427. This will chop off part of the start of this line by a certain amount, (leaving the
  18428. end-point the same), and return the new line.
  18429. */
  18430. const Line withShortenedStart (ValueType distanceToShortenBy) const throw()
  18431. {
  18432. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  18433. }
  18434. /** Returns a shortened copy of this line.
  18435. This will chop off part of the end of this line by a certain amount, (leaving the
  18436. start-point the same), and return the new line.
  18437. */
  18438. const Line withShortenedEnd (ValueType distanceToShortenBy) const throw()
  18439. {
  18440. const ValueType length = getLength();
  18441. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  18442. }
  18443. private:
  18444. Point<ValueType> start, end;
  18445. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  18446. const Point<ValueType>& p3, const Point<ValueType>& p4,
  18447. Point<ValueType>& intersection) throw()
  18448. {
  18449. if (p2 == p3)
  18450. {
  18451. intersection = p2;
  18452. return true;
  18453. }
  18454. const Point<ValueType> d1 (p2 - p1);
  18455. const Point<ValueType> d2 (p4 - p3);
  18456. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  18457. if (divisor == 0)
  18458. {
  18459. if (! (d1.isOrigin() || d2.isOrigin()))
  18460. {
  18461. if (d1.getY() == 0 && d2.getY() != 0)
  18462. {
  18463. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  18464. intersection = p1.withX (p3.getX() + along * d2.getX());
  18465. return along >= 0 && along <= (ValueType) 1;
  18466. }
  18467. else if (d2.getY() == 0 && d1.getY() != 0)
  18468. {
  18469. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  18470. intersection = p3.withX (p1.getX() + along * d1.getX());
  18471. return along >= 0 && along <= (ValueType) 1;
  18472. }
  18473. else if (d1.getX() == 0 && d2.getX() != 0)
  18474. {
  18475. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  18476. intersection = p1.withY (p3.getY() + along * d2.getY());
  18477. return along >= 0 && along <= (ValueType) 1;
  18478. }
  18479. else if (d2.getX() == 0 && d1.getX() != 0)
  18480. {
  18481. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  18482. intersection = p3.withY (p1.getY() + along * d1.getY());
  18483. return along >= 0 && along <= (ValueType) 1;
  18484. }
  18485. }
  18486. intersection = (p2 + p3) / (ValueType) 2;
  18487. return false;
  18488. }
  18489. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  18490. intersection = p1 + d1 * along1;
  18491. if (along1 < 0 || along1 > (ValueType) 1)
  18492. return false;
  18493. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  18494. return along2 >= 0 && along2 <= (ValueType) 1;
  18495. }
  18496. };
  18497. #endif // __JUCE_LINE_JUCEHEADER__
  18498. /*** End of inlined file: juce_Line.h ***/
  18499. /*** Start of inlined file: juce_Rectangle.h ***/
  18500. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  18501. #define __JUCE_RECTANGLE_JUCEHEADER__
  18502. class RectangleList;
  18503. /**
  18504. Manages a rectangle and allows geometric operations to be performed on it.
  18505. @see RectangleList, Path, Line, Point
  18506. */
  18507. template <typename ValueType>
  18508. class Rectangle
  18509. {
  18510. public:
  18511. /** Creates a rectangle of zero size.
  18512. The default co-ordinates will be (0, 0, 0, 0).
  18513. */
  18514. Rectangle() throw()
  18515. : x(), y(), w(), h()
  18516. {
  18517. }
  18518. /** Creates a copy of another rectangle. */
  18519. Rectangle (const Rectangle& other) throw()
  18520. : x (other.x), y (other.y),
  18521. w (other.w), h (other.h)
  18522. {
  18523. }
  18524. /** Creates a rectangle with a given position and size. */
  18525. Rectangle (const ValueType initialX, const ValueType initialY,
  18526. const ValueType width, const ValueType height) throw()
  18527. : x (initialX), y (initialY),
  18528. w (width), h (height)
  18529. {
  18530. }
  18531. /** Creates a rectangle with a given size, and a position of (0, 0). */
  18532. Rectangle (const ValueType width, const ValueType height) throw()
  18533. : x(), y(), w (width), h (height)
  18534. {
  18535. }
  18536. /** Creates a Rectangle from the positions of two opposite corners. */
  18537. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) throw()
  18538. : x (jmin (corner1.getX(), corner2.getX())),
  18539. y (jmin (corner1.getY(), corner2.getY())),
  18540. w (corner1.getX() - corner2.getX()),
  18541. h (corner1.getY() - corner2.getY())
  18542. {
  18543. if (w < ValueType()) w = -w;
  18544. if (h < ValueType()) h = -h;
  18545. }
  18546. /** Creates a Rectangle from a set of left, right, top, bottom coordinates.
  18547. The right and bottom values must be larger than the left and top ones, or the resulting
  18548. rectangle will have a negative size.
  18549. */
  18550. static const Rectangle leftTopRightBottom (const ValueType left, const ValueType top,
  18551. const ValueType right, const ValueType bottom) throw()
  18552. {
  18553. return Rectangle (left, top, right - left, bottom - top);
  18554. }
  18555. Rectangle& operator= (const Rectangle& other) throw()
  18556. {
  18557. x = other.x; y = other.y;
  18558. w = other.w; h = other.h;
  18559. return *this;
  18560. }
  18561. /** Destructor. */
  18562. ~Rectangle() throw() {}
  18563. /** Returns true if the rectangle's width and height are both zero or less */
  18564. bool isEmpty() const throw() { return w <= ValueType() || h <= ValueType(); }
  18565. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  18566. inline ValueType getX() const throw() { return x; }
  18567. /** Returns the y co-ordinate of the rectangle's top edge. */
  18568. inline ValueType getY() const throw() { return y; }
  18569. /** Returns the width of the rectangle. */
  18570. inline ValueType getWidth() const throw() { return w; }
  18571. /** Returns the height of the rectangle. */
  18572. inline ValueType getHeight() const throw() { return h; }
  18573. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  18574. inline ValueType getRight() const throw() { return x + w; }
  18575. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  18576. inline ValueType getBottom() const throw() { return y + h; }
  18577. /** Returns the x co-ordinate of the rectangle's centre. */
  18578. ValueType getCentreX() const throw() { return x + w / (ValueType) 2; }
  18579. /** Returns the y co-ordinate of the rectangle's centre. */
  18580. ValueType getCentreY() const throw() { return y + h / (ValueType) 2; }
  18581. /** Returns the centre point of the rectangle. */
  18582. const Point<ValueType> getCentre() const throw() { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  18583. /** Returns the aspect ratio of the rectangle's width / height.
  18584. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  18585. it returns height / width. */
  18586. ValueType getAspectRatio (const bool widthOverHeight = true) const throw() { return widthOverHeight ? w / h : h / w; }
  18587. /** Returns the rectangle's top-left position as a Point. */
  18588. const Point<ValueType> getPosition() const throw() { return Point<ValueType> (x, y); }
  18589. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  18590. void setPosition (const Point<ValueType>& newPos) throw() { x = newPos.getX(); y = newPos.getY(); }
  18591. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  18592. void setPosition (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  18593. /** Returns a rectangle with the same size as this one, but a new position. */
  18594. const Rectangle withPosition (const ValueType newX, const ValueType newY) const throw() { return Rectangle (newX, newY, w, h); }
  18595. /** Returns a rectangle with the same size as this one, but a new position. */
  18596. const Rectangle withPosition (const Point<ValueType>& newPos) const throw() { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  18597. /** Returns the rectangle's top-left position as a Point. */
  18598. const Point<ValueType> getTopLeft() const throw() { return getPosition(); }
  18599. /** Returns the rectangle's top-right position as a Point. */
  18600. const Point<ValueType> getTopRight() const throw() { return Point<ValueType> (x + w, y); }
  18601. /** Returns the rectangle's bottom-left position as a Point. */
  18602. const Point<ValueType> getBottomLeft() const throw() { return Point<ValueType> (x, y + h); }
  18603. /** Returns the rectangle's bottom-right position as a Point. */
  18604. const Point<ValueType> getBottomRight() const throw() { return Point<ValueType> (x + w, y + h); }
  18605. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  18606. void setSize (const ValueType newWidth, const ValueType newHeight) throw() { w = newWidth; h = newHeight; }
  18607. /** Returns a rectangle with the same position as this one, but a new size. */
  18608. const Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const throw() { return Rectangle (x, y, newWidth, newHeight); }
  18609. /** Changes all the rectangle's co-ordinates. */
  18610. void setBounds (const ValueType newX, const ValueType newY,
  18611. const ValueType newWidth, const ValueType newHeight) throw()
  18612. {
  18613. x = newX; y = newY; w = newWidth; h = newHeight;
  18614. }
  18615. /** Changes the rectangle's X coordinate */
  18616. void setX (const ValueType newX) throw() { x = newX; }
  18617. /** Changes the rectangle's Y coordinate */
  18618. void setY (const ValueType newY) throw() { y = newY; }
  18619. /** Changes the rectangle's width */
  18620. void setWidth (const ValueType newWidth) throw() { w = newWidth; }
  18621. /** Changes the rectangle's height */
  18622. void setHeight (const ValueType newHeight) throw() { h = newHeight; }
  18623. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  18624. const Rectangle withX (const ValueType newX) const throw() { return Rectangle (newX, y, w, h); }
  18625. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  18626. const Rectangle withY (const ValueType newY) const throw() { return Rectangle (x, newY, w, h); }
  18627. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  18628. const Rectangle withWidth (const ValueType newWidth) const throw() { return Rectangle (x, y, newWidth, h); }
  18629. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  18630. const Rectangle withHeight (const ValueType newHeight) const throw() { return Rectangle (x, y, w, newHeight); }
  18631. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  18632. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  18633. @see withLeft
  18634. */
  18635. void setLeft (const ValueType newLeft) throw()
  18636. {
  18637. w = jmax (ValueType(), x + w - newLeft);
  18638. x = newLeft;
  18639. }
  18640. /** Returns a new rectangle with a different x position, but the same right-hand edge as this one.
  18641. If the new x is beyond the right of the current right-hand edge, the width will be set to zero.
  18642. @see setLeft
  18643. */
  18644. const Rectangle withLeft (const ValueType newLeft) const throw() { return Rectangle (newLeft, y, jmax (ValueType(), x + w - newLeft), h); }
  18645. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  18646. If the y is moved to be below the current bottom edge, the height will be set to zero.
  18647. @see withTop
  18648. */
  18649. void setTop (const ValueType newTop) throw()
  18650. {
  18651. h = jmax (ValueType(), y + h - newTop);
  18652. y = newTop;
  18653. }
  18654. /** Returns a new rectangle with a different y position, but the same bottom edge as this one.
  18655. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  18656. @see setTop
  18657. */
  18658. const Rectangle withTop (const ValueType newTop) const throw() { return Rectangle (x, newTop, w, jmax (ValueType(), y + h - newTop)); }
  18659. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  18660. If the new right is below the current X value, the X will be pushed down to match it.
  18661. @see getRight, withRight
  18662. */
  18663. void setRight (const ValueType newRight) throw()
  18664. {
  18665. x = jmin (x, newRight);
  18666. w = newRight - x;
  18667. }
  18668. /** Returns a new rectangle with a different right-hand edge position, but the same left-hand edge as this one.
  18669. If the new right edge is below the current left-hand edge, the width will be set to zero.
  18670. @see setRight
  18671. */
  18672. const Rectangle withRight (const ValueType newRight) const throw() { return Rectangle (jmin (x, newRight), y, jmax (ValueType(), newRight - x), h); }
  18673. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  18674. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  18675. @see getBottom, withBottom
  18676. */
  18677. void setBottom (const ValueType newBottom) throw()
  18678. {
  18679. y = jmin (y, newBottom);
  18680. h = newBottom - y;
  18681. }
  18682. /** Returns a new rectangle with a different bottom edge position, but the same top edge as this one.
  18683. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  18684. @see setBottom
  18685. */
  18686. const Rectangle withBottom (const ValueType newBottom) const throw() { return Rectangle (x, jmin (y, newBottom), w, jmax (ValueType(), newBottom - y)); }
  18687. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  18688. void translate (const ValueType deltaX,
  18689. const ValueType deltaY) throw()
  18690. {
  18691. x += deltaX;
  18692. y += deltaY;
  18693. }
  18694. /** Returns a rectangle which is the same as this one moved by a given amount. */
  18695. const Rectangle translated (const ValueType deltaX,
  18696. const ValueType deltaY) const throw()
  18697. {
  18698. return Rectangle (x + deltaX, y + deltaY, w, h);
  18699. }
  18700. /** Returns a rectangle which is the same as this one moved by a given amount. */
  18701. const Rectangle operator+ (const Point<ValueType>& deltaPosition) const throw()
  18702. {
  18703. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  18704. }
  18705. /** Moves this rectangle by a given amount. */
  18706. Rectangle& operator+= (const Point<ValueType>& deltaPosition) throw()
  18707. {
  18708. x += deltaPosition.getX(); y += deltaPosition.getY();
  18709. return *this;
  18710. }
  18711. /** Returns a rectangle which is the same as this one moved by a given amount. */
  18712. const Rectangle operator- (const Point<ValueType>& deltaPosition) const throw()
  18713. {
  18714. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  18715. }
  18716. /** Moves this rectangle by a given amount. */
  18717. Rectangle& operator-= (const Point<ValueType>& deltaPosition) throw()
  18718. {
  18719. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  18720. return *this;
  18721. }
  18722. /** Expands the rectangle by a given amount.
  18723. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  18724. @see expanded, reduce, reduced
  18725. */
  18726. void expand (const ValueType deltaX,
  18727. const ValueType deltaY) throw()
  18728. {
  18729. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  18730. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  18731. setBounds (x - deltaX, y - deltaY, nw, nh);
  18732. }
  18733. /** Returns a rectangle that is larger than this one by a given amount.
  18734. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  18735. @see expand, reduce, reduced
  18736. */
  18737. const Rectangle expanded (const ValueType deltaX,
  18738. const ValueType deltaY) const throw()
  18739. {
  18740. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  18741. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  18742. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  18743. }
  18744. /** Shrinks the rectangle by a given amount.
  18745. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  18746. @see reduced, expand, expanded
  18747. */
  18748. void reduce (const ValueType deltaX,
  18749. const ValueType deltaY) throw()
  18750. {
  18751. expand (-deltaX, -deltaY);
  18752. }
  18753. /** Returns a rectangle that is smaller than this one by a given amount.
  18754. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  18755. @see reduce, expand, expanded
  18756. */
  18757. const Rectangle reduced (const ValueType deltaX,
  18758. const ValueType deltaY) const throw()
  18759. {
  18760. return expanded (-deltaX, -deltaY);
  18761. }
  18762. /** Removes a strip from the top of this rectangle, reducing this rectangle
  18763. by the specified amount and returning the section that was removed.
  18764. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  18765. return (100, 100, 300, 50) and leave this rectangle as (100, 150, 300, 250).
  18766. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  18767. that value.
  18768. */
  18769. const Rectangle removeFromTop (const ValueType amountToRemove) throw()
  18770. {
  18771. const Rectangle r (x, y, w, jmin (amountToRemove, h));
  18772. y += r.h; h -= r.h;
  18773. return r;
  18774. }
  18775. /** Removes a strip from the left-hand edge of this rectangle, reducing this rectangle
  18776. by the specified amount and returning the section that was removed.
  18777. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  18778. return (100, 100, 50, 300) and leave this rectangle as (150, 100, 250, 300).
  18779. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  18780. that value.
  18781. */
  18782. const Rectangle removeFromLeft (const ValueType amountToRemove) throw()
  18783. {
  18784. const Rectangle r (x, y, jmin (amountToRemove, w), h);
  18785. x += r.w; w -= r.w;
  18786. return r;
  18787. }
  18788. /** Removes a strip from the right-hand edge of this rectangle, reducing this rectangle
  18789. by the specified amount and returning the section that was removed.
  18790. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  18791. return (250, 100, 50, 300) and leave this rectangle as (100, 100, 250, 300).
  18792. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  18793. that value.
  18794. */
  18795. const Rectangle removeFromRight (ValueType amountToRemove) throw()
  18796. {
  18797. amountToRemove = jmin (amountToRemove, w);
  18798. const Rectangle r (x + w - amountToRemove, y, amountToRemove, h);
  18799. w -= amountToRemove;
  18800. return r;
  18801. }
  18802. /** Removes a strip from the bottom of this rectangle, reducing this rectangle
  18803. by the specified amount and returning the section that was removed.
  18804. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  18805. return (100, 250, 300, 50) and leave this rectangle as (100, 100, 300, 250).
  18806. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  18807. that value.
  18808. */
  18809. const Rectangle removeFromBottom (ValueType amountToRemove) throw()
  18810. {
  18811. amountToRemove = jmin (amountToRemove, h);
  18812. const Rectangle r (x, y + h - amountToRemove, w, amountToRemove);
  18813. h -= amountToRemove;
  18814. return r;
  18815. }
  18816. /** Returns true if the two rectangles are identical. */
  18817. bool operator== (const Rectangle& other) const throw()
  18818. {
  18819. return x == other.x && y == other.y
  18820. && w == other.w && h == other.h;
  18821. }
  18822. /** Returns true if the two rectangles are not identical. */
  18823. bool operator!= (const Rectangle& other) const throw()
  18824. {
  18825. return x != other.x || y != other.y
  18826. || w != other.w || h != other.h;
  18827. }
  18828. /** Returns true if this co-ordinate is inside the rectangle. */
  18829. bool contains (const ValueType xCoord, const ValueType yCoord) const throw()
  18830. {
  18831. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  18832. }
  18833. /** Returns true if this co-ordinate is inside the rectangle. */
  18834. bool contains (const Point<ValueType>& point) const throw()
  18835. {
  18836. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  18837. }
  18838. /** Returns true if this other rectangle is completely inside this one. */
  18839. bool contains (const Rectangle& other) const throw()
  18840. {
  18841. return x <= other.x && y <= other.y
  18842. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  18843. }
  18844. /** Returns the nearest point to the specified point that lies within this rectangle. */
  18845. const Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const throw()
  18846. {
  18847. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  18848. jlimit (y, y + h, point.getY()));
  18849. }
  18850. /** Returns true if any part of another rectangle overlaps this one. */
  18851. bool intersects (const Rectangle& other) const throw()
  18852. {
  18853. return x + w > other.x
  18854. && y + h > other.y
  18855. && x < other.x + other.w
  18856. && y < other.y + other.h
  18857. && w > ValueType() && h > ValueType();
  18858. }
  18859. /** Returns the region that is the overlap between this and another rectangle.
  18860. If the two rectangles don't overlap, the rectangle returned will be empty.
  18861. */
  18862. const Rectangle getIntersection (const Rectangle& other) const throw()
  18863. {
  18864. const ValueType nx = jmax (x, other.x);
  18865. const ValueType ny = jmax (y, other.y);
  18866. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  18867. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  18868. if (nw >= ValueType() && nh >= ValueType())
  18869. return Rectangle (nx, ny, nw, nh);
  18870. return Rectangle();
  18871. }
  18872. /** Clips a rectangle so that it lies only within this one.
  18873. This is a non-static version of intersectRectangles().
  18874. Returns false if the two regions didn't overlap.
  18875. */
  18876. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const throw()
  18877. {
  18878. const int maxX = jmax (otherX, x);
  18879. otherW = jmin (otherX + otherW, x + w) - maxX;
  18880. if (otherW > ValueType())
  18881. {
  18882. const int maxY = jmax (otherY, y);
  18883. otherH = jmin (otherY + otherH, y + h) - maxY;
  18884. if (otherH > ValueType())
  18885. {
  18886. otherX = maxX; otherY = maxY;
  18887. return true;
  18888. }
  18889. }
  18890. return false;
  18891. }
  18892. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  18893. If either this or the other rectangle are empty, they will not be counted as
  18894. part of the resulting region.
  18895. */
  18896. const Rectangle getUnion (const Rectangle& other) const throw()
  18897. {
  18898. if (other.isEmpty()) return *this;
  18899. if (isEmpty()) return other;
  18900. const ValueType newX = jmin (x, other.x);
  18901. const ValueType newY = jmin (y, other.y);
  18902. return Rectangle (newX, newY,
  18903. jmax (x + w, other.x + other.w) - newX,
  18904. jmax (y + h, other.y + other.h) - newY);
  18905. }
  18906. /** If this rectangle merged with another one results in a simple rectangle, this
  18907. will set this rectangle to the result, and return true.
  18908. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  18909. or if they form a complex region.
  18910. */
  18911. bool enlargeIfAdjacent (const Rectangle& other) throw()
  18912. {
  18913. if (x == other.x && getRight() == other.getRight()
  18914. && (other.getBottom() >= y && other.y <= getBottom()))
  18915. {
  18916. const ValueType newY = jmin (y, other.y);
  18917. h = jmax (getBottom(), other.getBottom()) - newY;
  18918. y = newY;
  18919. return true;
  18920. }
  18921. else if (y == other.y && getBottom() == other.getBottom()
  18922. && (other.getRight() >= x && other.x <= getRight()))
  18923. {
  18924. const ValueType newX = jmin (x, other.x);
  18925. w = jmax (getRight(), other.getRight()) - newX;
  18926. x = newX;
  18927. return true;
  18928. }
  18929. return false;
  18930. }
  18931. /** If after removing another rectangle from this one the result is a simple rectangle,
  18932. this will set this object's bounds to be the result, and return true.
  18933. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  18934. or if removing the other one would form a complex region.
  18935. */
  18936. bool reduceIfPartlyContainedIn (const Rectangle& other) throw()
  18937. {
  18938. int inside = 0;
  18939. const int otherR = other.getRight();
  18940. if (x >= other.x && x < otherR) inside = 1;
  18941. const int otherB = other.getBottom();
  18942. if (y >= other.y && y < otherB) inside |= 2;
  18943. const int r = x + w;
  18944. if (r >= other.x && r < otherR) inside |= 4;
  18945. const int b = y + h;
  18946. if (b >= other.y && b < otherB) inside |= 8;
  18947. switch (inside)
  18948. {
  18949. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  18950. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  18951. case 2 + 4 + 8: w = other.x - x; return true;
  18952. case 1 + 4 + 8: h = other.y - y; return true;
  18953. }
  18954. return false;
  18955. }
  18956. /** Returns the smallest rectangle that can contain the shape created by applying
  18957. a transform to this rectangle.
  18958. This should only be used on floating point rectangles.
  18959. */
  18960. const Rectangle transformed (const AffineTransform& transform) const throw()
  18961. {
  18962. float x1 = x, y1 = y;
  18963. float x2 = x + w, y2 = y;
  18964. float x3 = x, y3 = y + h;
  18965. float x4 = x2, y4 = y3;
  18966. transform.transformPoints (x1, y1, x2, y2);
  18967. transform.transformPoints (x3, y3, x4, y4);
  18968. const float rx = jmin (x1, x2, x3, x4);
  18969. const float ry = jmin (y1, y2, y3, y4);
  18970. return Rectangle (rx, ry,
  18971. jmax (x1, x2, x3, x4) - rx,
  18972. jmax (y1, y2, y3, y4) - ry);
  18973. }
  18974. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  18975. This is only relevent for floating-point rectangles, of course.
  18976. @see toFloat()
  18977. */
  18978. const Rectangle<int> getSmallestIntegerContainer() const throw()
  18979. {
  18980. const int x1 = (int) std::floor (static_cast<float> (x));
  18981. const int y1 = (int) std::floor (static_cast<float> (y));
  18982. const int x2 = (int) std::ceil (static_cast<float> (x + w));
  18983. const int y2 = (int) std::ceil (static_cast<float> (y + h));
  18984. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  18985. }
  18986. /** Returns the smallest Rectangle that can contain a set of points. */
  18987. static const Rectangle findAreaContainingPoints (const Point<ValueType>* const points, const int numPoints) throw()
  18988. {
  18989. if (numPoints == 0)
  18990. return Rectangle();
  18991. ValueType minX (points[0].getX());
  18992. ValueType maxX (minX);
  18993. ValueType minY (points[0].getY());
  18994. ValueType maxY (minY);
  18995. for (int i = 1; i < numPoints; ++i)
  18996. {
  18997. minX = jmin (minX, points[i].getX());
  18998. maxX = jmax (maxX, points[i].getX());
  18999. minY = jmin (minY, points[i].getY());
  19000. maxY = jmax (maxY, points[i].getY());
  19001. }
  19002. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  19003. }
  19004. /** Casts this rectangle to a Rectangle<float>.
  19005. Obviously this is mainly useful for rectangles that use integer types.
  19006. @see getSmallestIntegerContainer
  19007. */
  19008. const Rectangle<float> toFloat() const throw()
  19009. {
  19010. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  19011. static_cast<float> (w), static_cast<float> (h));
  19012. }
  19013. /** Static utility to intersect two sets of rectangular co-ordinates.
  19014. Returns false if the two regions didn't overlap.
  19015. @see intersectRectangle
  19016. */
  19017. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  19018. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) throw()
  19019. {
  19020. const ValueType x = jmax (x1, x2);
  19021. w1 = jmin (x1 + w1, x2 + w2) - x;
  19022. if (w1 > ValueType())
  19023. {
  19024. const ValueType y = jmax (y1, y2);
  19025. h1 = jmin (y1 + h1, y2 + h2) - y;
  19026. if (h1 > ValueType())
  19027. {
  19028. x1 = x; y1 = y;
  19029. return true;
  19030. }
  19031. }
  19032. return false;
  19033. }
  19034. /** Creates a string describing this rectangle.
  19035. The string will be of the form "x y width height", e.g. "100 100 400 200".
  19036. Coupled with the fromString() method, this is very handy for things like
  19037. storing rectangles (particularly component positions) in XML attributes.
  19038. @see fromString
  19039. */
  19040. const String toString() const
  19041. {
  19042. String s;
  19043. s.preallocateStorage (16);
  19044. s << x << ' ' << y << ' ' << w << ' ' << h;
  19045. return s;
  19046. }
  19047. /** Parses a string containing a rectangle's details.
  19048. The string should contain 4 integer tokens, in the form "x y width height". They
  19049. can be comma or whitespace separated.
  19050. This method is intended to go with the toString() method, to form an easy way
  19051. of saving/loading rectangles as strings.
  19052. @see toString
  19053. */
  19054. static const Rectangle fromString (const String& stringVersion)
  19055. {
  19056. StringArray toks;
  19057. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  19058. return Rectangle (toks[0].trim().getIntValue(),
  19059. toks[1].trim().getIntValue(),
  19060. toks[2].trim().getIntValue(),
  19061. toks[3].trim().getIntValue());
  19062. }
  19063. private:
  19064. friend class RectangleList;
  19065. ValueType x, y, w, h;
  19066. };
  19067. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  19068. /*** End of inlined file: juce_Rectangle.h ***/
  19069. /*** Start of inlined file: juce_Justification.h ***/
  19070. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  19071. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  19072. /**
  19073. Represents a type of justification to be used when positioning graphical items.
  19074. e.g. it indicates whether something should be placed top-left, top-right,
  19075. centred, etc.
  19076. It is used in various places wherever this kind of information is needed.
  19077. */
  19078. class JUCE_API Justification
  19079. {
  19080. public:
  19081. /** Creates a Justification object using a combination of flags. */
  19082. inline Justification (int flags_) throw() : flags (flags_) {}
  19083. /** Creates a copy of another Justification object. */
  19084. Justification (const Justification& other) throw();
  19085. /** Copies another Justification object. */
  19086. Justification& operator= (const Justification& other) throw();
  19087. bool operator== (const Justification& other) const throw() { return flags == other.flags; }
  19088. bool operator!= (const Justification& other) const throw() { return flags != other.flags; }
  19089. /** Returns the raw flags that are set for this Justification object. */
  19090. inline int getFlags() const throw() { return flags; }
  19091. /** Tests a set of flags for this object.
  19092. @returns true if any of the flags passed in are set on this object.
  19093. */
  19094. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  19095. /** Returns just the flags from this object that deal with vertical layout. */
  19096. int getOnlyVerticalFlags() const throw();
  19097. /** Returns just the flags from this object that deal with horizontal layout. */
  19098. int getOnlyHorizontalFlags() const throw();
  19099. /** Adjusts the position of a rectangle to fit it into a space.
  19100. The (x, y) position of the rectangle will be updated to position it inside the
  19101. given space according to the justification flags.
  19102. */
  19103. template <typename ValueType>
  19104. void applyToRectangle (ValueType& x, ValueType& y, ValueType w, ValueType h,
  19105. ValueType spaceX, ValueType spaceY, ValueType spaceW, ValueType spaceH) const throw()
  19106. {
  19107. x = spaceX;
  19108. if ((flags & horizontallyCentred) != 0) x += (spaceW - w) / (ValueType) 2;
  19109. else if ((flags & right) != 0) x += spaceW - w;
  19110. y = spaceY;
  19111. if ((flags & verticallyCentred) != 0) y += (spaceH - h) / (ValueType) 2;
  19112. else if ((flags & bottom) != 0) y += spaceH - h;
  19113. }
  19114. /** Returns the new position of a rectangle that has been justified to fit within a given space.
  19115. */
  19116. template <typename ValueType>
  19117. const Rectangle<ValueType> appliedToRectangle (const Rectangle<ValueType>& areaToAdjust,
  19118. const Rectangle<ValueType>& targetSpace) const throw()
  19119. {
  19120. ValueType x = areaToAdjust.getX(), y = areaToAdjust.getY();
  19121. applyToRectangle (x, y, areaToAdjust.getWidth(), areaToAdjust.getHeight(),
  19122. targetSpace.getX(), targetSpace.getY(), targetSpace.getWidth(), targetSpace.getHeight());
  19123. return areaToAdjust.withPosition (x, y);
  19124. }
  19125. /** Flag values that can be combined and used in the constructor. */
  19126. enum
  19127. {
  19128. /** Indicates that the item should be aligned against the left edge of the available space. */
  19129. left = 1,
  19130. /** Indicates that the item should be aligned against the right edge of the available space. */
  19131. right = 2,
  19132. /** Indicates that the item should be placed in the centre between the left and right
  19133. sides of the available space. */
  19134. horizontallyCentred = 4,
  19135. /** Indicates that the item should be aligned against the top edge of the available space. */
  19136. top = 8,
  19137. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  19138. bottom = 16,
  19139. /** Indicates that the item should be placed in the centre between the top and bottom
  19140. sides of the available space. */
  19141. verticallyCentred = 32,
  19142. /** Indicates that lines of text should be spread out to fill the maximum width
  19143. available, so that both margins are aligned vertically.
  19144. */
  19145. horizontallyJustified = 64,
  19146. /** Indicates that the item should be centred vertically and horizontally.
  19147. This is equivalent to (horizontallyCentred | verticallyCentred)
  19148. */
  19149. centred = 36,
  19150. /** Indicates that the item should be centred vertically but placed on the left hand side.
  19151. This is equivalent to (left | verticallyCentred)
  19152. */
  19153. centredLeft = 33,
  19154. /** Indicates that the item should be centred vertically but placed on the right hand side.
  19155. This is equivalent to (right | verticallyCentred)
  19156. */
  19157. centredRight = 34,
  19158. /** Indicates that the item should be centred horizontally and placed at the top.
  19159. This is equivalent to (horizontallyCentred | top)
  19160. */
  19161. centredTop = 12,
  19162. /** Indicates that the item should be centred horizontally and placed at the bottom.
  19163. This is equivalent to (horizontallyCentred | bottom)
  19164. */
  19165. centredBottom = 20,
  19166. /** Indicates that the item should be placed in the top-left corner.
  19167. This is equivalent to (left | top)
  19168. */
  19169. topLeft = 9,
  19170. /** Indicates that the item should be placed in the top-right corner.
  19171. This is equivalent to (right | top)
  19172. */
  19173. topRight = 10,
  19174. /** Indicates that the item should be placed in the bottom-left corner.
  19175. This is equivalent to (left | bottom)
  19176. */
  19177. bottomLeft = 17,
  19178. /** Indicates that the item should be placed in the bottom-left corner.
  19179. This is equivalent to (right | bottom)
  19180. */
  19181. bottomRight = 18
  19182. };
  19183. private:
  19184. int flags;
  19185. };
  19186. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  19187. /*** End of inlined file: juce_Justification.h ***/
  19188. class Image;
  19189. /**
  19190. A path is a sequence of lines and curves that may either form a closed shape
  19191. or be open-ended.
  19192. To use a path, you can create an empty one, then add lines and curves to it
  19193. to create shapes, then it can be rendered by a Graphics context or used
  19194. for geometric operations.
  19195. e.g. @code
  19196. Path myPath;
  19197. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  19198. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  19199. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  19200. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  19201. // add an ellipse as well, which will form a second sub-path within the path..
  19202. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  19203. // double the width of the whole thing..
  19204. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  19205. // and draw it to a graphics context with a 5-pixel thick outline.
  19206. g.strokePath (myPath, PathStrokeType (5.0f));
  19207. @endcode
  19208. A path object can actually contain multiple sub-paths, which may themselves
  19209. be open or closed.
  19210. @see PathFlatteningIterator, PathStrokeType, Graphics
  19211. */
  19212. class JUCE_API Path
  19213. {
  19214. public:
  19215. /** Creates an empty path. */
  19216. Path();
  19217. /** Creates a copy of another path. */
  19218. Path (const Path& other);
  19219. /** Destructor. */
  19220. ~Path();
  19221. /** Copies this path from another one. */
  19222. Path& operator= (const Path& other);
  19223. bool operator== (const Path& other) const throw();
  19224. bool operator!= (const Path& other) const throw();
  19225. /** Returns true if the path doesn't contain any lines or curves. */
  19226. bool isEmpty() const throw();
  19227. /** Returns the smallest rectangle that contains all points within the path.
  19228. */
  19229. const Rectangle<float> getBounds() const throw();
  19230. /** Returns the smallest rectangle that contains all points within the path
  19231. after it's been transformed with the given tranasform matrix.
  19232. */
  19233. const Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const throw();
  19234. /** Checks whether a point lies within the path.
  19235. This is only relevent for closed paths (see closeSubPath()), and
  19236. may produce false results if used on a path which has open sub-paths.
  19237. The path's winding rule is taken into account by this method.
  19238. The tolerance parameter is the maximum error allowed when flattening the path,
  19239. so this method could return a false positive when your point is up to this distance
  19240. outside the path's boundary.
  19241. @see closeSubPath, setUsingNonZeroWinding
  19242. */
  19243. bool contains (float x, float y,
  19244. float tolerance = 1.0f) const;
  19245. /** Checks whether a point lies within the path.
  19246. This is only relevent for closed paths (see closeSubPath()), and
  19247. may produce false results if used on a path which has open sub-paths.
  19248. The path's winding rule is taken into account by this method.
  19249. The tolerance parameter is the maximum error allowed when flattening the path,
  19250. so this method could return a false positive when your point is up to this distance
  19251. outside the path's boundary.
  19252. @see closeSubPath, setUsingNonZeroWinding
  19253. */
  19254. bool contains (const Point<float>& point,
  19255. float tolerance = 1.0f) const;
  19256. /** Checks whether a line crosses the path.
  19257. This will return positive if the line crosses any of the paths constituent
  19258. lines or curves. It doesn't take into account whether the line is inside
  19259. or outside the path, or whether the path is open or closed.
  19260. The tolerance parameter is the maximum error allowed when flattening the path,
  19261. so this method could return a false positive when your point is up to this distance
  19262. outside the path's boundary.
  19263. */
  19264. bool intersectsLine (const Line<float>& line,
  19265. float tolerance = 1.0f);
  19266. /** Cuts off parts of a line to keep the parts that are either inside or
  19267. outside this path.
  19268. Note that this isn't smart enough to cope with situations where the
  19269. line would need to be cut into multiple pieces to correctly clip against
  19270. a re-entrant shape.
  19271. @param line the line to clip
  19272. @param keepSectionOutsidePath if true, it's the section outside the path
  19273. that will be kept; if false its the section inside
  19274. the path
  19275. */
  19276. const Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  19277. /** Returns the length of the path.
  19278. @see getPointAlongPath
  19279. */
  19280. float getLength (const AffineTransform& transform = AffineTransform::identity) const;
  19281. /** Returns a point that is the specified distance along the path.
  19282. If the distance is greater than the total length of the path, this will return the
  19283. end point.
  19284. @see getLength
  19285. */
  19286. const Point<float> getPointAlongPath (float distanceFromStart,
  19287. const AffineTransform& transform = AffineTransform::identity) const;
  19288. /** Finds the point along the path which is nearest to a given position.
  19289. This sets pointOnPath to the nearest point, and returns the distance of this point from the start
  19290. of the path.
  19291. */
  19292. float getNearestPoint (const Point<float>& targetPoint,
  19293. Point<float>& pointOnPath,
  19294. const AffineTransform& transform = AffineTransform::identity) const;
  19295. /** Removes all lines and curves, resetting the path completely. */
  19296. void clear() throw();
  19297. /** Begins a new subpath with a given starting position.
  19298. This will move the path's current position to the co-ordinates passed in and
  19299. make it ready to draw lines or curves starting from this position.
  19300. After adding whatever lines and curves are needed, you can either
  19301. close the current sub-path using closeSubPath() or call startNewSubPath()
  19302. to move to a new sub-path, leaving the old one open-ended.
  19303. @see lineTo, quadraticTo, cubicTo, closeSubPath
  19304. */
  19305. void startNewSubPath (float startX, float startY);
  19306. /** Begins a new subpath with a given starting position.
  19307. This will move the path's current position to the co-ordinates passed in and
  19308. make it ready to draw lines or curves starting from this position.
  19309. After adding whatever lines and curves are needed, you can either
  19310. close the current sub-path using closeSubPath() or call startNewSubPath()
  19311. to move to a new sub-path, leaving the old one open-ended.
  19312. @see lineTo, quadraticTo, cubicTo, closeSubPath
  19313. */
  19314. void startNewSubPath (const Point<float>& start);
  19315. /** Closes a the current sub-path with a line back to its start-point.
  19316. When creating a closed shape such as a triangle, don't use 3 lineTo()
  19317. calls - instead use two lineTo() calls, followed by a closeSubPath()
  19318. to join the final point back to the start.
  19319. This ensures that closes shapes are recognised as such, and this is
  19320. important for tasks like drawing strokes, which needs to know whether to
  19321. draw end-caps or not.
  19322. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  19323. */
  19324. void closeSubPath();
  19325. /** Adds a line from the shape's last position to a new end-point.
  19326. This will connect the end-point of the last line or curve that was added
  19327. to a new point, using a straight line.
  19328. See the class description for an example of how to add lines and curves to a path.
  19329. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  19330. */
  19331. void lineTo (float endX, float endY);
  19332. /** Adds a line from the shape's last position to a new end-point.
  19333. This will connect the end-point of the last line or curve that was added
  19334. to a new point, using a straight line.
  19335. See the class description for an example of how to add lines and curves to a path.
  19336. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  19337. */
  19338. void lineTo (const Point<float>& end);
  19339. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  19340. This will connect the end-point of the last line or curve that was added
  19341. to a new point, using a quadratic spline with one control-point.
  19342. See the class description for an example of how to add lines and curves to a path.
  19343. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  19344. */
  19345. void quadraticTo (float controlPointX,
  19346. float controlPointY,
  19347. float endPointX,
  19348. float endPointY);
  19349. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  19350. This will connect the end-point of the last line or curve that was added
  19351. to a new point, using a quadratic spline with one control-point.
  19352. See the class description for an example of how to add lines and curves to a path.
  19353. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  19354. */
  19355. void quadraticTo (const Point<float>& controlPoint,
  19356. const Point<float>& endPoint);
  19357. /** Adds a cubic bezier curve from the shape's last position to a new position.
  19358. This will connect the end-point of the last line or curve that was added
  19359. to a new point, using a cubic spline with two control-points.
  19360. See the class description for an example of how to add lines and curves to a path.
  19361. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  19362. */
  19363. void cubicTo (float controlPoint1X,
  19364. float controlPoint1Y,
  19365. float controlPoint2X,
  19366. float controlPoint2Y,
  19367. float endPointX,
  19368. float endPointY);
  19369. /** Adds a cubic bezier curve from the shape's last position to a new position.
  19370. This will connect the end-point of the last line or curve that was added
  19371. to a new point, using a cubic spline with two control-points.
  19372. See the class description for an example of how to add lines and curves to a path.
  19373. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  19374. */
  19375. void cubicTo (const Point<float>& controlPoint1,
  19376. const Point<float>& controlPoint2,
  19377. const Point<float>& endPoint);
  19378. /** Returns the last point that was added to the path by one of the drawing methods.
  19379. */
  19380. const Point<float> getCurrentPosition() const;
  19381. /** Adds a rectangle to the path.
  19382. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19383. @see addRoundedRectangle, addTriangle
  19384. */
  19385. void addRectangle (float x, float y, float width, float height);
  19386. /** Adds a rectangle to the path.
  19387. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19388. @see addRoundedRectangle, addTriangle
  19389. */
  19390. template <typename ValueType>
  19391. void addRectangle (const Rectangle<ValueType>& rectangle)
  19392. {
  19393. addRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  19394. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()));
  19395. }
  19396. /** Adds a rectangle with rounded corners to the path.
  19397. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19398. @see addRectangle, addTriangle
  19399. */
  19400. void addRoundedRectangle (float x, float y, float width, float height,
  19401. float cornerSize);
  19402. /** Adds a rectangle with rounded corners to the path.
  19403. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19404. @see addRectangle, addTriangle
  19405. */
  19406. void addRoundedRectangle (float x, float y, float width, float height,
  19407. float cornerSizeX,
  19408. float cornerSizeY);
  19409. /** Adds a rectangle with rounded corners to the path.
  19410. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19411. @see addRectangle, addTriangle
  19412. */
  19413. template <typename ValueType>
  19414. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSizeX, float cornerSizeY)
  19415. {
  19416. addRoundedRectangle (static_cast <float> (rectangle.getX()), static_cast <float> (rectangle.getY()),
  19417. static_cast <float> (rectangle.getWidth()), static_cast <float> (rectangle.getHeight()),
  19418. cornerSizeX, cornerSizeY);
  19419. }
  19420. /** Adds a rectangle with rounded corners to the path.
  19421. The rectangle is added as a new sub-path. (Any currently open paths will be left open).
  19422. @see addRectangle, addTriangle
  19423. */
  19424. template <typename ValueType>
  19425. void addRoundedRectangle (const Rectangle<ValueType>& rectangle, float cornerSize)
  19426. {
  19427. addRoundedRectangle (rectangle, cornerSize, cornerSize);
  19428. }
  19429. /** Adds a triangle to the path.
  19430. The triangle is added as a new closed sub-path. (Any currently open paths will be left open).
  19431. Note that whether the vertices are specified in clockwise or anticlockwise
  19432. order will affect how the triangle is filled when it overlaps other
  19433. shapes (the winding order setting will affect this of course).
  19434. */
  19435. void addTriangle (float x1, float y1,
  19436. float x2, float y2,
  19437. float x3, float y3);
  19438. /** Adds a quadrilateral to the path.
  19439. The quad is added as a new closed sub-path. (Any currently open paths will be left open).
  19440. Note that whether the vertices are specified in clockwise or anticlockwise
  19441. order will affect how the quad is filled when it overlaps other
  19442. shapes (the winding order setting will affect this of course).
  19443. */
  19444. void addQuadrilateral (float x1, float y1,
  19445. float x2, float y2,
  19446. float x3, float y3,
  19447. float x4, float y4);
  19448. /** Adds an ellipse to the path.
  19449. The shape is added as a new sub-path. (Any currently open paths will be left open).
  19450. @see addArc
  19451. */
  19452. void addEllipse (float x, float y, float width, float height);
  19453. /** Adds an elliptical arc to the current path.
  19454. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  19455. or anti-clockwise according to whether the end angle is greater than the start. This means
  19456. that sometimes you may need to use values greater than 2*Pi for the end angle.
  19457. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  19458. @param y the top edge of the rectangle in which the elliptical outline fits
  19459. @param width the width of the rectangle in which the elliptical outline fits
  19460. @param height the height of the rectangle in which the elliptical outline fits
  19461. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  19462. top-centre of the ellipse)
  19463. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  19464. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  19465. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  19466. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  19467. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  19468. it will be added to the current sub-path, continuing from the current postition
  19469. @see addCentredArc, arcTo, addPieSegment, addEllipse
  19470. */
  19471. void addArc (float x, float y, float width, float height,
  19472. float fromRadians,
  19473. float toRadians,
  19474. bool startAsNewSubPath = false);
  19475. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  19476. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  19477. or anti-clockwise according to whether the end angle is greater than the start. This means
  19478. that sometimes you may need to use values greater than 2*Pi for the end angle.
  19479. @param centreX the centre x of the ellipse
  19480. @param centreY the centre y of the ellipse
  19481. @param radiusX the horizontal radius of the ellipse
  19482. @param radiusY the vertical radius of the ellipse
  19483. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  19484. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  19485. top-centre of the ellipse)
  19486. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  19487. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  19488. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  19489. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  19490. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  19491. it will be added to the current sub-path, continuing from the current postition
  19492. @see addArc, arcTo
  19493. */
  19494. void addCentredArc (float centreX, float centreY,
  19495. float radiusX, float radiusY,
  19496. float rotationOfEllipse,
  19497. float fromRadians,
  19498. float toRadians,
  19499. bool startAsNewSubPath = false);
  19500. /** Adds a "pie-chart" shape to the path.
  19501. The shape is added as a new sub-path. (Any currently open paths will be
  19502. left open).
  19503. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  19504. or anti-clockwise according to whether the end angle is greater than the start. This means
  19505. that sometimes you may need to use values greater than 2*Pi for the end angle.
  19506. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  19507. @param y the top edge of the rectangle in which the elliptical outline fits
  19508. @param width the width of the rectangle in which the elliptical outline fits
  19509. @param height the height of the rectangle in which the elliptical outline fits
  19510. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  19511. top-centre of the ellipse)
  19512. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  19513. top-centre of the ellipse)
  19514. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  19515. ellipse at its centre, where this value indicates the inner ellipse's size with
  19516. respect to the outer one.
  19517. @see addArc
  19518. */
  19519. void addPieSegment (float x, float y,
  19520. float width, float height,
  19521. float fromRadians,
  19522. float toRadians,
  19523. float innerCircleProportionalSize);
  19524. /** Adds a line with a specified thickness.
  19525. The line is added as a new closed sub-path. (Any currently open paths will be
  19526. left open).
  19527. @see addArrow
  19528. */
  19529. void addLineSegment (const Line<float>& line, float lineThickness);
  19530. /** Adds a line with an arrowhead on the end.
  19531. The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
  19532. @see PathStrokeType::createStrokeWithArrowheads
  19533. */
  19534. void addArrow (const Line<float>& line,
  19535. float lineThickness,
  19536. float arrowheadWidth,
  19537. float arrowheadLength);
  19538. /** Adds a polygon shape to the path.
  19539. @see addStar
  19540. */
  19541. void addPolygon (const Point<float>& centre,
  19542. int numberOfSides,
  19543. float radius,
  19544. float startAngle = 0.0f);
  19545. /** Adds a star shape to the path.
  19546. @see addPolygon
  19547. */
  19548. void addStar (const Point<float>& centre,
  19549. int numberOfPoints,
  19550. float innerRadius,
  19551. float outerRadius,
  19552. float startAngle = 0.0f);
  19553. /** Adds a speech-bubble shape to the path.
  19554. @param bodyX the left of the main body area of the bubble
  19555. @param bodyY the top of the main body area of the bubble
  19556. @param bodyW the width of the main body area of the bubble
  19557. @param bodyH the height of the main body area of the bubble
  19558. @param cornerSize the amount by which to round off the corners of the main body rectangle
  19559. @param arrowTipX the x position that the tip of the arrow should connect to
  19560. @param arrowTipY the y position that the tip of the arrow should connect to
  19561. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  19562. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  19563. arrow's base should be - this is a proportional distance between 0 and 1.0
  19564. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  19565. */
  19566. void addBubble (float bodyX, float bodyY,
  19567. float bodyW, float bodyH,
  19568. float cornerSize,
  19569. float arrowTipX,
  19570. float arrowTipY,
  19571. int whichSide,
  19572. float arrowPositionAlongEdgeProportional,
  19573. float arrowWidth);
  19574. /** Adds another path to this one.
  19575. The new path is added as a new sub-path. (Any currently open paths in this
  19576. path will be left open).
  19577. @param pathToAppend the path to add
  19578. */
  19579. void addPath (const Path& pathToAppend);
  19580. /** Adds another path to this one, transforming it on the way in.
  19581. The new path is added as a new sub-path, its points being transformed by the given
  19582. matrix before being added.
  19583. @param pathToAppend the path to add
  19584. @param transformToApply an optional transform to apply to the incoming vertices
  19585. */
  19586. void addPath (const Path& pathToAppend,
  19587. const AffineTransform& transformToApply);
  19588. /** Swaps the contents of this path with another one.
  19589. The internal data of the two paths is swapped over, so this is much faster than
  19590. copying it to a temp variable and back.
  19591. */
  19592. void swapWithPath (Path& other) throw();
  19593. /** Applies a 2D transform to all the vertices in the path.
  19594. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  19595. */
  19596. void applyTransform (const AffineTransform& transform) throw();
  19597. /** Rescales this path to make it fit neatly into a given space.
  19598. This is effectively a quick way of calling
  19599. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  19600. @param x the x position of the rectangle to fit the path inside
  19601. @param y the y position of the rectangle to fit the path inside
  19602. @param width the width of the rectangle to fit the path inside
  19603. @param height the height of the rectangle to fit the path inside
  19604. @param preserveProportions if true, it will fit the path into the space without altering its
  19605. horizontal/vertical scale ratio; if false, it will distort the
  19606. path to fill the specified ratio both horizontally and vertically
  19607. @see applyTransform, getTransformToScaleToFit
  19608. */
  19609. void scaleToFit (float x, float y, float width, float height,
  19610. bool preserveProportions) throw();
  19611. /** Returns a transform that can be used to rescale the path to fit into a given space.
  19612. @param x the x position of the rectangle to fit the path inside
  19613. @param y the y position of the rectangle to fit the path inside
  19614. @param width the width of the rectangle to fit the path inside
  19615. @param height the height of the rectangle to fit the path inside
  19616. @param preserveProportions if true, it will fit the path into the space without altering its
  19617. horizontal/vertical scale ratio; if false, it will distort the
  19618. path to fill the specified ratio both horizontally and vertically
  19619. @param justificationType if the proportions are preseved, the resultant path may be smaller
  19620. than the available rectangle, so this describes how it should be
  19621. positioned within the space.
  19622. @returns an appropriate transformation
  19623. @see applyTransform, scaleToFit
  19624. */
  19625. const AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  19626. bool preserveProportions,
  19627. const Justification& justificationType = Justification::centred) const;
  19628. /** Creates a version of this path where all sharp corners have been replaced by curves.
  19629. Wherever two lines meet at an angle, this will replace the corner with a curve
  19630. of the given radius.
  19631. */
  19632. const Path createPathWithRoundedCorners (float cornerRadius) const;
  19633. /** Changes the winding-rule to be used when filling the path.
  19634. If set to true (which is the default), then the path uses a non-zero-winding rule
  19635. to determine which points are inside the path. If set to false, it uses an
  19636. alternate-winding rule.
  19637. The winding-rule comes into play when areas of the shape overlap other
  19638. areas, and determines whether the overlapping regions are considered to be
  19639. inside or outside.
  19640. Changing this value just sets a flag - it doesn't affect the contents of the
  19641. path.
  19642. @see isUsingNonZeroWinding
  19643. */
  19644. void setUsingNonZeroWinding (bool isNonZeroWinding) throw();
  19645. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  19646. The default for a new path is true.
  19647. @see setUsingNonZeroWinding
  19648. */
  19649. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  19650. /** Iterates the lines and curves that a path contains.
  19651. @see Path, PathFlatteningIterator
  19652. */
  19653. class JUCE_API Iterator
  19654. {
  19655. public:
  19656. Iterator (const Path& path);
  19657. ~Iterator();
  19658. /** Moves onto the next element in the path.
  19659. If this returns false, there are no more elements. If it returns true,
  19660. the elementType variable will be set to the type of the current element,
  19661. and some of the x and y variables will be filled in with values.
  19662. */
  19663. bool next();
  19664. enum PathElementType
  19665. {
  19666. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  19667. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  19668. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  19669. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  19670. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  19671. };
  19672. PathElementType elementType;
  19673. float x1, y1, x2, y2, x3, y3;
  19674. private:
  19675. const Path& path;
  19676. size_t index;
  19677. JUCE_DECLARE_NON_COPYABLE (Iterator);
  19678. };
  19679. /** Loads a stored path from a data stream.
  19680. The data in the stream must have been written using writePathToStream().
  19681. Note that this will append the stored path to whatever is currently in
  19682. this path, so you might need to call clear() beforehand.
  19683. @see loadPathFromData, writePathToStream
  19684. */
  19685. void loadPathFromStream (InputStream& source);
  19686. /** Loads a stored path from a block of data.
  19687. This is similar to loadPathFromStream(), but just reads from a block
  19688. of data. Useful if you're including stored shapes in your code as a
  19689. block of static data.
  19690. @see loadPathFromStream, writePathToStream
  19691. */
  19692. void loadPathFromData (const void* data, int numberOfBytes);
  19693. /** Stores the path by writing it out to a stream.
  19694. After writing out a path, you can reload it using loadPathFromStream().
  19695. @see loadPathFromStream, loadPathFromData
  19696. */
  19697. void writePathToStream (OutputStream& destination) const;
  19698. /** Creates a string containing a textual representation of this path.
  19699. @see restoreFromString
  19700. */
  19701. const String toString() const;
  19702. /** Restores this path from a string that was created with the toString() method.
  19703. @see toString()
  19704. */
  19705. void restoreFromString (const String& stringVersion);
  19706. private:
  19707. friend class PathFlatteningIterator;
  19708. friend class Path::Iterator;
  19709. ArrayAllocationBase <float, DummyCriticalSection> data;
  19710. size_t numElements;
  19711. float pathXMin, pathXMax, pathYMin, pathYMax;
  19712. bool useNonZeroWinding;
  19713. static const float lineMarker;
  19714. static const float moveMarker;
  19715. static const float quadMarker;
  19716. static const float cubicMarker;
  19717. static const float closeSubPathMarker;
  19718. JUCE_LEAK_DETECTOR (Path);
  19719. };
  19720. #endif // __JUCE_PATH_JUCEHEADER__
  19721. /*** End of inlined file: juce_Path.h ***/
  19722. class Font;
  19723. /** A typeface represents a size-independent font.
  19724. This base class is abstract, but calling createSystemTypefaceFor() will return
  19725. a platform-specific subclass that can be used.
  19726. The CustomTypeface subclass allow you to build your own typeface, and to
  19727. load and save it in the Juce typeface format.
  19728. Normally you should never need to deal directly with Typeface objects - the Font
  19729. class does everything you typically need for rendering text.
  19730. @see CustomTypeface, Font
  19731. */
  19732. class JUCE_API Typeface : public ReferenceCountedObject
  19733. {
  19734. public:
  19735. /** A handy typedef for a pointer to a typeface. */
  19736. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  19737. /** Returns the name of the typeface.
  19738. @see Font::getTypefaceName
  19739. */
  19740. const String getName() const throw() { return name; }
  19741. /** Creates a new system typeface. */
  19742. static const Ptr createSystemTypefaceFor (const Font& font);
  19743. /** Destructor. */
  19744. virtual ~Typeface();
  19745. /** Returns true if this typeface can be used to render the specified font.
  19746. When called, the font will already have been checked to make sure that its name and
  19747. style flags match the typeface.
  19748. */
  19749. virtual bool isSuitableForFont (const Font&) const { return true; }
  19750. /** Returns the ascent of the font, as a proportion of its height.
  19751. The height is considered to always be normalised as 1.0, so this will be a
  19752. value less that 1.0, indicating the proportion of the font that lies above
  19753. its baseline.
  19754. */
  19755. virtual float getAscent() const = 0;
  19756. /** Returns the descent of the font, as a proportion of its height.
  19757. The height is considered to always be normalised as 1.0, so this will be a
  19758. value less that 1.0, indicating the proportion of the font that lies below
  19759. its baseline.
  19760. */
  19761. virtual float getDescent() const = 0;
  19762. /** Measures the width of a line of text.
  19763. The distance returned is based on the font having an normalised height of 1.0.
  19764. You should never need to call this directly! Use Font::getStringWidth() instead!
  19765. */
  19766. virtual float getStringWidth (const String& text) = 0;
  19767. /** Converts a line of text into its glyph numbers and their positions.
  19768. The distances returned are based on the font having an normalised height of 1.0.
  19769. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  19770. */
  19771. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  19772. /** Returns the outline for a glyph.
  19773. The path returned will be normalised to a font height of 1.0.
  19774. */
  19775. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  19776. /** Returns true if the typeface uses hinting. */
  19777. virtual bool isHinted() const { return false; }
  19778. /** Changes the number of fonts that are cached in memory. */
  19779. static void setTypefaceCacheSize (int numFontsToCache);
  19780. protected:
  19781. String name;
  19782. bool isFallbackFont;
  19783. explicit Typeface (const String& name) throw();
  19784. static const Ptr getFallbackTypeface();
  19785. private:
  19786. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Typeface);
  19787. };
  19788. /** A typeface that can be populated with custom glyphs.
  19789. You can create a CustomTypeface if you need one that contains your own glyphs,
  19790. or if you need to load a typeface from a Juce-formatted binary stream.
  19791. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  19792. to copy glyphs into this face.
  19793. @see Typeface, Font
  19794. */
  19795. class JUCE_API CustomTypeface : public Typeface
  19796. {
  19797. public:
  19798. /** Creates a new, empty typeface. */
  19799. CustomTypeface();
  19800. /** Loads a typeface from a previously saved stream.
  19801. The stream must have been created by writeToStream().
  19802. @see writeToStream
  19803. */
  19804. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  19805. /** Destructor. */
  19806. ~CustomTypeface();
  19807. /** Resets this typeface, deleting all its glyphs and settings. */
  19808. void clear();
  19809. /** Sets the vital statistics for the typeface.
  19810. @param name the typeface's name
  19811. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  19812. the value that will be returned by Typeface::getAscent(). The
  19813. descent is assumed to be (1.0 - ascent)
  19814. @param isBold should be true if the typeface is bold
  19815. @param isItalic should be true if the typeface is italic
  19816. @param defaultCharacter the character to be used as a replacement if there's
  19817. no glyph available for the character that's being drawn
  19818. */
  19819. void setCharacteristics (const String& name, float ascent,
  19820. bool isBold, bool isItalic,
  19821. juce_wchar defaultCharacter) throw();
  19822. /** Adds a glyph to the typeface.
  19823. The path that is passed in is normalised so that the font height is 1.0, and its
  19824. origin is the anchor point of the character on its baseline.
  19825. The width is the nominal width of the character, and any extra kerning values that
  19826. are specified will be added to this width.
  19827. */
  19828. void addGlyph (juce_wchar character, const Path& path, float width) throw();
  19829. /** Specifies an extra kerning amount to be used between a pair of characters.
  19830. The amount will be added to the nominal width of the first character when laying out a string.
  19831. */
  19832. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) throw();
  19833. /** Adds a range of glyphs from another typeface.
  19834. This will attempt to pull in the paths and kerning information from another typeface and
  19835. add it to this one.
  19836. */
  19837. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw();
  19838. /** Saves this typeface as a Juce-formatted font file.
  19839. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  19840. constructor.
  19841. */
  19842. bool writeToStream (OutputStream& outputStream);
  19843. // The following methods implement the basic Typeface behaviour.
  19844. float getAscent() const;
  19845. float getDescent() const;
  19846. float getStringWidth (const String& text);
  19847. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  19848. bool getOutlineForGlyph (int glyphNumber, Path& path);
  19849. int getGlyphForCharacter (juce_wchar character);
  19850. protected:
  19851. juce_wchar defaultCharacter;
  19852. float ascent;
  19853. bool isBold, isItalic;
  19854. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  19855. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  19856. particular character and there's no corresponding glyph, they'll call this
  19857. method so that a subclass can try to add that glyph, returning true if it
  19858. manages to do so.
  19859. */
  19860. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  19861. private:
  19862. class GlyphInfo;
  19863. friend class OwnedArray<GlyphInfo>;
  19864. OwnedArray <GlyphInfo> glyphs;
  19865. short lookupTable [128];
  19866. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) throw();
  19867. GlyphInfo* findGlyphSubstituting (juce_wchar character) throw();
  19868. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomTypeface);
  19869. };
  19870. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  19871. /*** End of inlined file: juce_Typeface.h ***/
  19872. class LowLevelGraphicsContext;
  19873. /**
  19874. Represents a particular font, including its size, style, etc.
  19875. Apart from the typeface to be used, a Font object also dictates whether
  19876. the font is bold, italic, underlined, how big it is, and its kerning and
  19877. horizontal scale factor.
  19878. @see Typeface
  19879. */
  19880. class JUCE_API Font
  19881. {
  19882. public:
  19883. /** A combination of these values is used by the constructor to specify the
  19884. style of font to use.
  19885. */
  19886. enum FontStyleFlags
  19887. {
  19888. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  19889. bold = 1, /**< boldens the font. @see setStyleFlags */
  19890. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  19891. underlined = 4 /**< underlines the font. @see setStyleFlags */
  19892. };
  19893. /** Creates a sans-serif font in a given size.
  19894. @param fontHeight the height in pixels (can be fractional)
  19895. @param styleFlags the style to use - this can be a combination of the
  19896. Font::bold, Font::italic and Font::underlined, or
  19897. just Font::plain for the normal style.
  19898. @see FontStyleFlags, getDefaultSansSerifFontName
  19899. */
  19900. Font (float fontHeight, int styleFlags = plain);
  19901. /** Creates a font with a given typeface and parameters.
  19902. @param typefaceName the name of the typeface to use
  19903. @param fontHeight the height in pixels (can be fractional)
  19904. @param styleFlags the style to use - this can be a combination of the
  19905. Font::bold, Font::italic and Font::underlined, or
  19906. just Font::plain for the normal style.
  19907. @see FontStyleFlags, getDefaultSansSerifFontName
  19908. */
  19909. Font (const String& typefaceName, float fontHeight, int styleFlags);
  19910. /** Creates a copy of another Font object. */
  19911. Font (const Font& other) throw();
  19912. /** Creates a font for a typeface. */
  19913. Font (const Typeface::Ptr& typeface);
  19914. /** Creates a basic sans-serif font at a default height.
  19915. You should use one of the other constructors for creating a font that you're planning
  19916. on drawing with - this constructor is here to help initialise objects before changing
  19917. the font's settings later.
  19918. */
  19919. Font();
  19920. /** Copies this font from another one. */
  19921. Font& operator= (const Font& other) throw();
  19922. bool operator== (const Font& other) const throw();
  19923. bool operator!= (const Font& other) const throw();
  19924. /** Destructor. */
  19925. ~Font() throw();
  19926. /** Changes the name of the typeface family.
  19927. e.g. "Arial", "Courier", etc.
  19928. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  19929. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  19930. but are generic names that are used to represent the various default fonts.
  19931. If you need to know the exact typeface name being used, you can call
  19932. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  19933. If a suitable font isn't found on the machine, it'll just use a default instead.
  19934. */
  19935. void setTypefaceName (const String& faceName);
  19936. /** Returns the name of the typeface family that this font uses.
  19937. e.g. "Arial", "Courier", etc.
  19938. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  19939. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  19940. but are generic names that are used to represent the various default fonts.
  19941. If you need to know the exact typeface name being used, you can call
  19942. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  19943. */
  19944. const String& getTypefaceName() const throw() { return font->typefaceName; }
  19945. /** Returns a typeface name that represents the default sans-serif font.
  19946. This is also the typeface that will be used when a font is created without
  19947. specifying any typeface details.
  19948. Note that this method just returns a generic placeholder string that means "the default
  19949. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  19950. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  19951. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  19952. */
  19953. static const String getDefaultSansSerifFontName();
  19954. /** Returns a typeface name that represents the default sans-serif font.
  19955. Note that this method just returns a generic placeholder string that means "the default
  19956. serif font" - it's not the actual name of this font. To get the actual name, use
  19957. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  19958. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  19959. */
  19960. static const String getDefaultSerifFontName();
  19961. /** Returns a typeface name that represents the default sans-serif font.
  19962. Note that this method just returns a generic placeholder string that means "the default
  19963. monospaced font" - it's not the actual name of this font. To get the actual name, use
  19964. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  19965. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  19966. */
  19967. static const String getDefaultMonospacedFontName();
  19968. /** Returns the typeface names of the default fonts on the current platform. */
  19969. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback);
  19970. /** Returns the total height of this font.
  19971. This is the maximum height, from the top of the ascent to the bottom of the
  19972. descenders.
  19973. @see setHeight, setHeightWithoutChangingWidth, getAscent
  19974. */
  19975. float getHeight() const throw() { return font->height; }
  19976. /** Changes the font's height.
  19977. @see getHeight, setHeightWithoutChangingWidth
  19978. */
  19979. void setHeight (float newHeight);
  19980. /** Changes the font's height without changing its width.
  19981. This alters the horizontal scale to compensate for the change in height.
  19982. */
  19983. void setHeightWithoutChangingWidth (float newHeight);
  19984. /** Returns the height of the font above its baseline.
  19985. This is the maximum height from the baseline to the top.
  19986. @see getHeight, getDescent
  19987. */
  19988. float getAscent() const;
  19989. /** Returns the amount that the font descends below its baseline.
  19990. This is calculated as (getHeight() - getAscent()).
  19991. @see getAscent, getHeight
  19992. */
  19993. float getDescent() const;
  19994. /** Returns the font's style flags.
  19995. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  19996. enum, to describe whether the font is bold, italic, etc.
  19997. @see FontStyleFlags
  19998. */
  19999. int getStyleFlags() const throw() { return font->styleFlags; }
  20000. /** Changes the font's style.
  20001. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  20002. enum, to set the font's properties
  20003. @see FontStyleFlags
  20004. */
  20005. void setStyleFlags (int newFlags);
  20006. /** Makes the font bold or non-bold. */
  20007. void setBold (bool shouldBeBold);
  20008. /** Returns a copy of this font with the bold attribute set. */
  20009. const Font boldened() const;
  20010. /** Returns true if the font is bold. */
  20011. bool isBold() const throw();
  20012. /** Makes the font italic or non-italic. */
  20013. void setItalic (bool shouldBeItalic);
  20014. /** Returns a copy of this font with the italic attribute set. */
  20015. const Font italicised() const;
  20016. /** Returns true if the font is italic. */
  20017. bool isItalic() const throw();
  20018. /** Makes the font underlined or non-underlined. */
  20019. void setUnderline (bool shouldBeUnderlined);
  20020. /** Returns true if the font is underlined. */
  20021. bool isUnderlined() const throw();
  20022. /** Changes the font's horizontal scale factor.
  20023. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  20024. narrower, greater than 1.0 will be stretched out.
  20025. */
  20026. void setHorizontalScale (float scaleFactor);
  20027. /** Returns the font's horizontal scale.
  20028. A value of 1.0 is the normal scale, less than this will be narrower, greater
  20029. than 1.0 will be stretched out.
  20030. @see setHorizontalScale
  20031. */
  20032. float getHorizontalScale() const throw() { return font->horizontalScale; }
  20033. /** Changes the font's kerning.
  20034. @param extraKerning a multiple of the font's height that will be added
  20035. to space between the characters. So a value of zero is
  20036. normal spacing, positive values spread the letters out,
  20037. negative values make them closer together.
  20038. */
  20039. void setExtraKerningFactor (float extraKerning);
  20040. /** Returns the font's kerning.
  20041. This is the extra space added between adjacent characters, as a proportion
  20042. of the font's height.
  20043. A value of zero is normal spacing, positive values will spread the letters
  20044. out more, and negative values make them closer together.
  20045. */
  20046. float getExtraKerningFactor() const throw() { return font->kerning; }
  20047. /** Changes all the font's characteristics with one call. */
  20048. void setSizeAndStyle (float newHeight,
  20049. int newStyleFlags,
  20050. float newHorizontalScale,
  20051. float newKerningAmount);
  20052. /** Returns the total width of a string as it would be drawn using this font.
  20053. For a more accurate floating-point result, use getStringWidthFloat().
  20054. */
  20055. int getStringWidth (const String& text) const;
  20056. /** Returns the total width of a string as it would be drawn using this font.
  20057. @see getStringWidth
  20058. */
  20059. float getStringWidthFloat (const String& text) const;
  20060. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  20061. An extra x offset is added at the end of the run, to indicate where the right hand
  20062. edge of the last character is.
  20063. */
  20064. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const;
  20065. /** Returns the typeface used by this font.
  20066. Note that the object returned may go out of scope if this font is deleted
  20067. or has its style changed.
  20068. */
  20069. Typeface* getTypeface() const;
  20070. /** Creates an array of Font objects to represent all the fonts on the system.
  20071. If you just need the names of the typefaces, you can also use
  20072. findAllTypefaceNames() instead.
  20073. @param results the array to which new Font objects will be added.
  20074. */
  20075. static void findFonts (Array<Font>& results);
  20076. /** Returns a list of all the available typeface names.
  20077. The names returned can be passed into setTypefaceName().
  20078. You can use this instead of findFonts() if you only need their names, and not
  20079. font objects.
  20080. */
  20081. static const StringArray findAllTypefaceNames();
  20082. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  20083. in the requested typeface.
  20084. */
  20085. static const String getFallbackFontName();
  20086. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  20087. available in whatever font you're trying to use.
  20088. */
  20089. static void setFallbackFontName (const String& name);
  20090. /** Creates a string to describe this font.
  20091. The string will contain information to describe the font's typeface, size, and
  20092. style. To recreate the font from this string, use fromString().
  20093. */
  20094. const String toString() const;
  20095. /** Recreates a font from its stringified encoding.
  20096. This method takes a string that was created by toString(), and recreates the
  20097. original font.
  20098. */
  20099. static const Font fromString (const String& fontDescription);
  20100. private:
  20101. friend class FontGlyphAlphaMap;
  20102. friend class TypefaceCache;
  20103. class SharedFontInternal : public ReferenceCountedObject
  20104. {
  20105. public:
  20106. SharedFontInternal (float height, int styleFlags) throw();
  20107. SharedFontInternal (const String& typefaceName, float height, int styleFlags) throw();
  20108. SharedFontInternal (const Typeface::Ptr& typeface) throw();
  20109. SharedFontInternal (const SharedFontInternal& other) throw();
  20110. bool operator== (const SharedFontInternal&) const throw();
  20111. String typefaceName;
  20112. float height, horizontalScale, kerning, ascent;
  20113. int styleFlags;
  20114. Typeface::Ptr typeface;
  20115. };
  20116. ReferenceCountedObjectPtr <SharedFontInternal> font;
  20117. void dupeInternalIfShared();
  20118. JUCE_LEAK_DETECTOR (Font);
  20119. };
  20120. #endif // __JUCE_FONT_JUCEHEADER__
  20121. /*** End of inlined file: juce_Font.h ***/
  20122. /*** Start of inlined file: juce_PathStrokeType.h ***/
  20123. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20124. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20125. /**
  20126. Describes a type of stroke used to render a solid outline along a path.
  20127. A PathStrokeType object can be used directly to create the shape of an outline
  20128. around a path, and is used by Graphics::strokePath to specify the type of
  20129. stroke to draw.
  20130. @see Path, Graphics::strokePath
  20131. */
  20132. class JUCE_API PathStrokeType
  20133. {
  20134. public:
  20135. /** The type of shape to use for the corners between two adjacent line segments. */
  20136. enum JointStyle
  20137. {
  20138. mitered, /**< Indicates that corners should be drawn with sharp joints.
  20139. Note that for angles that curve back on themselves, drawing a
  20140. mitre could require extending the point too far away from the
  20141. path, so a mitre limit is imposed and any corners that exceed it
  20142. are drawn as bevelled instead. */
  20143. curved, /**< Indicates that corners should be drawn as rounded-off. */
  20144. beveled /**< Indicates that corners should be drawn with a line flattening their
  20145. outside edge. */
  20146. };
  20147. /** The type shape to use for the ends of lines. */
  20148. enum EndCapStyle
  20149. {
  20150. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  20151. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  20152. the thickness of the stroke. */
  20153. rounded /**< Ends of lines are rounded-off with a circular shape. */
  20154. };
  20155. /** Creates a stroke type.
  20156. @param strokeThickness the width of the line to use
  20157. @param jointStyle the type of joints to use for corners
  20158. @param endStyle the type of end-caps to use for the ends of open paths.
  20159. */
  20160. PathStrokeType (float strokeThickness,
  20161. JointStyle jointStyle = mitered,
  20162. EndCapStyle endStyle = butt) throw();
  20163. /** Createes a copy of another stroke type. */
  20164. PathStrokeType (const PathStrokeType& other) throw();
  20165. /** Copies another stroke onto this one. */
  20166. PathStrokeType& operator= (const PathStrokeType& other) throw();
  20167. /** Destructor. */
  20168. ~PathStrokeType() throw();
  20169. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  20170. @param destPath the resultant stroked outline shape will be copied into this path.
  20171. Note that it's ok for the source and destination Paths to be
  20172. the same object, so you can easily turn a path into a stroked version
  20173. of itself.
  20174. @param sourcePath the path to use as the source
  20175. @param transform an optional transform to apply to the points from the source path
  20176. as they are being used
  20177. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  20178. a higher resolution, which improves the quality if you'll later want
  20179. to enlarge the stroked path. So for example, if you're planning on drawing
  20180. the stroke at 3x the size that you're creating it, you should set this to 3.
  20181. @see createDashedStroke
  20182. */
  20183. void createStrokedPath (Path& destPath,
  20184. const Path& sourcePath,
  20185. const AffineTransform& transform = AffineTransform::identity,
  20186. float extraAccuracy = 1.0f) const;
  20187. /** Applies this stroke type to a path, creating a dashed line.
  20188. This is similar to createStrokedPath, but uses the array passed in to
  20189. break the stroke up into a series of dashes.
  20190. @param destPath the resultant stroked outline shape will be copied into this path.
  20191. Note that it's ok for the source and destination Paths to be
  20192. the same object, so you can easily turn a path into a stroked version
  20193. of itself.
  20194. @param sourcePath the path to use as the source
  20195. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  20196. a line of length 2, then skip a length of 3, then add a line of length 4,
  20197. skip 5, and keep repeating this pattern.
  20198. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  20199. an even number, otherwise the pattern will get out of step as it
  20200. repeats.
  20201. @param transform an optional transform to apply to the points from the source path
  20202. as they are being used
  20203. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  20204. a higher resolution, which improves the quality if you'll later want
  20205. to enlarge the stroked path. So for example, if you're planning on drawing
  20206. the stroke at 3x the size that you're creating it, you should set this to 3.
  20207. */
  20208. void createDashedStroke (Path& destPath,
  20209. const Path& sourcePath,
  20210. const float* dashLengths,
  20211. int numDashLengths,
  20212. const AffineTransform& transform = AffineTransform::identity,
  20213. float extraAccuracy = 1.0f) const;
  20214. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  20215. @param destPath the resultant stroked outline shape will be copied into this path.
  20216. Note that it's ok for the source and destination Paths to be
  20217. the same object, so you can easily turn a path into a stroked version
  20218. of itself.
  20219. @param sourcePath the path to use as the source
  20220. @param arrowheadStartWidth the width of the arrowhead at the start of the path
  20221. @param arrowheadStartLength the length of the arrowhead at the start of the path
  20222. @param arrowheadEndWidth the width of the arrowhead at the end of the path
  20223. @param arrowheadEndLength the length of the arrowhead at the end of the path
  20224. @param transform an optional transform to apply to the points from the source path
  20225. as they are being used
  20226. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  20227. a higher resolution, which improves the quality if you'll later want
  20228. to enlarge the stroked path. So for example, if you're planning on drawing
  20229. the stroke at 3x the size that you're creating it, you should set this to 3.
  20230. @see createDashedStroke
  20231. */
  20232. void createStrokeWithArrowheads (Path& destPath,
  20233. const Path& sourcePath,
  20234. float arrowheadStartWidth, float arrowheadStartLength,
  20235. float arrowheadEndWidth, float arrowheadEndLength,
  20236. const AffineTransform& transform = AffineTransform::identity,
  20237. float extraAccuracy = 1.0f) const;
  20238. /** Returns the stroke thickness. */
  20239. float getStrokeThickness() const throw() { return thickness; }
  20240. /** Sets the stroke thickness. */
  20241. void setStrokeThickness (float newThickness) throw() { thickness = newThickness; }
  20242. /** Returns the joint style. */
  20243. JointStyle getJointStyle() const throw() { return jointStyle; }
  20244. /** Sets the joint style. */
  20245. void setJointStyle (JointStyle newStyle) throw() { jointStyle = newStyle; }
  20246. /** Returns the end-cap style. */
  20247. EndCapStyle getEndStyle() const throw() { return endStyle; }
  20248. /** Sets the end-cap style. */
  20249. void setEndStyle (EndCapStyle newStyle) throw() { endStyle = newStyle; }
  20250. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  20251. bool operator== (const PathStrokeType& other) const throw();
  20252. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  20253. bool operator!= (const PathStrokeType& other) const throw();
  20254. private:
  20255. float thickness;
  20256. JointStyle jointStyle;
  20257. EndCapStyle endStyle;
  20258. JUCE_LEAK_DETECTOR (PathStrokeType);
  20259. };
  20260. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  20261. /*** End of inlined file: juce_PathStrokeType.h ***/
  20262. /*** Start of inlined file: juce_Colours.h ***/
  20263. #ifndef __JUCE_COLOURS_JUCEHEADER__
  20264. #define __JUCE_COLOURS_JUCEHEADER__
  20265. /*** Start of inlined file: juce_Colour.h ***/
  20266. #ifndef __JUCE_COLOUR_JUCEHEADER__
  20267. #define __JUCE_COLOUR_JUCEHEADER__
  20268. /*** Start of inlined file: juce_PixelFormats.h ***/
  20269. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  20270. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  20271. #ifndef DOXYGEN
  20272. #if JUCE_MSVC
  20273. #pragma pack (push, 1)
  20274. #define PACKED
  20275. #elif JUCE_GCC
  20276. #define PACKED __attribute__((packed))
  20277. #else
  20278. #define PACKED
  20279. #endif
  20280. #endif
  20281. class PixelRGB;
  20282. class PixelAlpha;
  20283. /**
  20284. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  20285. operations with it.
  20286. This is used internally by the imaging classes.
  20287. @see PixelRGB
  20288. */
  20289. class JUCE_API PixelARGB
  20290. {
  20291. public:
  20292. /** Creates a pixel without defining its colour. */
  20293. PixelARGB() throw() {}
  20294. ~PixelARGB() throw() {}
  20295. /** Creates a pixel from a 32-bit argb value.
  20296. */
  20297. PixelARGB (const uint32 argb_) throw()
  20298. : argb (argb_)
  20299. {
  20300. }
  20301. forcedinline uint32 getARGB() const throw() { return argb; }
  20302. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  20303. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  20304. forcedinline uint8 getAlpha() const throw() { return components.a; }
  20305. forcedinline uint8 getRed() const throw() { return components.r; }
  20306. forcedinline uint8 getGreen() const throw() { return components.g; }
  20307. forcedinline uint8 getBlue() const throw() { return components.b; }
  20308. /** Blends another pixel onto this one.
  20309. This takes into account the opacity of the pixel being overlaid, and blends
  20310. it accordingly.
  20311. */
  20312. forcedinline void blend (const PixelARGB& src) throw()
  20313. {
  20314. uint32 sargb = src.getARGB();
  20315. const uint32 alpha = 0x100 - (sargb >> 24);
  20316. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  20317. sargb += 0xff00ff00 & (getAG() * alpha);
  20318. argb = sargb;
  20319. }
  20320. /** Blends another pixel onto this one.
  20321. This takes into account the opacity of the pixel being overlaid, and blends
  20322. it accordingly.
  20323. */
  20324. forcedinline void blend (const PixelAlpha& src) throw();
  20325. /** Blends another pixel onto this one.
  20326. This takes into account the opacity of the pixel being overlaid, and blends
  20327. it accordingly.
  20328. */
  20329. forcedinline void blend (const PixelRGB& src) throw();
  20330. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  20331. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  20332. being used, so this can blend semi-transparently from a PixelRGB argument.
  20333. */
  20334. template <class Pixel>
  20335. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  20336. {
  20337. ++extraAlpha;
  20338. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  20339. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  20340. const uint32 alpha = 0x100 - (sargb >> 24);
  20341. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  20342. sargb += 0xff00ff00 & (getAG() * alpha);
  20343. argb = sargb;
  20344. }
  20345. /** Blends another pixel with this one, creating a colour that is somewhere
  20346. between the two, as specified by the amount.
  20347. */
  20348. template <class Pixel>
  20349. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  20350. {
  20351. uint32 drb = getRB();
  20352. drb += (((src.getRB() - drb) * amount) >> 8);
  20353. drb &= 0x00ff00ff;
  20354. uint32 dag = getAG();
  20355. dag += (((src.getAG() - dag) * amount) >> 8);
  20356. dag &= 0x00ff00ff;
  20357. dag <<= 8;
  20358. dag |= drb;
  20359. argb = dag;
  20360. }
  20361. /** Copies another pixel colour over this one.
  20362. This doesn't blend it - this colour is simply replaced by the other one.
  20363. */
  20364. template <class Pixel>
  20365. forcedinline void set (const Pixel& src) throw()
  20366. {
  20367. argb = src.getARGB();
  20368. }
  20369. /** Replaces the colour's alpha value with another one. */
  20370. forcedinline void setAlpha (const uint8 newAlpha) throw()
  20371. {
  20372. components.a = newAlpha;
  20373. }
  20374. /** Multiplies the colour's alpha value with another one. */
  20375. forcedinline void multiplyAlpha (int multiplier) throw()
  20376. {
  20377. ++multiplier;
  20378. argb = ((multiplier * getAG()) & 0xff00ff00)
  20379. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  20380. }
  20381. forcedinline void multiplyAlpha (const float multiplier) throw()
  20382. {
  20383. multiplyAlpha ((int) (multiplier * 256.0f));
  20384. }
  20385. /** Sets the pixel's colour from individual components. */
  20386. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  20387. {
  20388. components.b = b;
  20389. components.g = g;
  20390. components.r = r;
  20391. components.a = a;
  20392. }
  20393. /** Premultiplies the pixel's RGB values by its alpha. */
  20394. forcedinline void premultiply() throw()
  20395. {
  20396. const uint32 alpha = components.a;
  20397. if (alpha < 0xff)
  20398. {
  20399. if (alpha == 0)
  20400. {
  20401. components.b = 0;
  20402. components.g = 0;
  20403. components.r = 0;
  20404. }
  20405. else
  20406. {
  20407. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  20408. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  20409. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  20410. }
  20411. }
  20412. }
  20413. /** Unpremultiplies the pixel's RGB values. */
  20414. forcedinline void unpremultiply() throw()
  20415. {
  20416. const uint32 alpha = components.a;
  20417. if (alpha < 0xff)
  20418. {
  20419. if (alpha == 0)
  20420. {
  20421. components.b = 0;
  20422. components.g = 0;
  20423. components.r = 0;
  20424. }
  20425. else
  20426. {
  20427. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  20428. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  20429. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  20430. }
  20431. }
  20432. }
  20433. forcedinline void desaturate() throw()
  20434. {
  20435. if (components.a < 0xff && components.a > 0)
  20436. {
  20437. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  20438. components.r = components.g = components.b
  20439. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  20440. }
  20441. else
  20442. {
  20443. components.r = components.g = components.b
  20444. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  20445. }
  20446. }
  20447. /** The indexes of the different components in the byte layout of this type of colour. */
  20448. #if JUCE_BIG_ENDIAN
  20449. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  20450. #else
  20451. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  20452. #endif
  20453. private:
  20454. union
  20455. {
  20456. uint32 argb;
  20457. struct
  20458. {
  20459. #if JUCE_BIG_ENDIAN
  20460. uint8 a : 8, r : 8, g : 8, b : 8;
  20461. #else
  20462. uint8 b, g, r, a;
  20463. #endif
  20464. } PACKED components;
  20465. };
  20466. }
  20467. #ifndef DOXYGEN
  20468. PACKED
  20469. #endif
  20470. ;
  20471. /**
  20472. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  20473. This is used internally by the imaging classes.
  20474. @see PixelARGB
  20475. */
  20476. class JUCE_API PixelRGB
  20477. {
  20478. public:
  20479. /** Creates a pixel without defining its colour. */
  20480. PixelRGB() throw() {}
  20481. ~PixelRGB() throw() {}
  20482. /** Creates a pixel from a 32-bit argb value.
  20483. (The argb format is that used by PixelARGB)
  20484. */
  20485. PixelRGB (const uint32 argb) throw()
  20486. {
  20487. r = (uint8) (argb >> 16);
  20488. g = (uint8) (argb >> 8);
  20489. b = (uint8) (argb);
  20490. }
  20491. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  20492. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  20493. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  20494. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  20495. forcedinline uint8 getRed() const throw() { return r; }
  20496. forcedinline uint8 getGreen() const throw() { return g; }
  20497. forcedinline uint8 getBlue() const throw() { return b; }
  20498. /** Blends another pixel onto this one.
  20499. This takes into account the opacity of the pixel being overlaid, and blends
  20500. it accordingly.
  20501. */
  20502. forcedinline void blend (const PixelARGB& src) throw()
  20503. {
  20504. uint32 sargb = src.getARGB();
  20505. const uint32 alpha = 0x100 - (sargb >> 24);
  20506. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  20507. sargb += 0x0000ff00 & (g * alpha);
  20508. r = (uint8) (sargb >> 16);
  20509. g = (uint8) (sargb >> 8);
  20510. b = (uint8) sargb;
  20511. }
  20512. forcedinline void blend (const PixelRGB& src) throw()
  20513. {
  20514. set (src);
  20515. }
  20516. forcedinline void blend (const PixelAlpha& src) throw();
  20517. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  20518. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  20519. being used, so this can blend semi-transparently from a PixelRGB argument.
  20520. */
  20521. template <class Pixel>
  20522. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  20523. {
  20524. ++extraAlpha;
  20525. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  20526. const uint32 sag = extraAlpha * src.getAG();
  20527. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  20528. const uint32 alpha = 0x100 - (sargb >> 24);
  20529. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  20530. sargb += 0x0000ff00 & (g * alpha);
  20531. b = (uint8) sargb;
  20532. g = (uint8) (sargb >> 8);
  20533. r = (uint8) (sargb >> 16);
  20534. }
  20535. /** Blends another pixel with this one, creating a colour that is somewhere
  20536. between the two, as specified by the amount.
  20537. */
  20538. template <class Pixel>
  20539. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  20540. {
  20541. uint32 drb = getRB();
  20542. drb += (((src.getRB() - drb) * amount) >> 8);
  20543. uint32 dag = getAG();
  20544. dag += (((src.getAG() - dag) * amount) >> 8);
  20545. b = (uint8) drb;
  20546. g = (uint8) dag;
  20547. r = (uint8) (drb >> 16);
  20548. }
  20549. /** Copies another pixel colour over this one.
  20550. This doesn't blend it - this colour is simply replaced by the other one.
  20551. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  20552. is thrown away.
  20553. */
  20554. template <class Pixel>
  20555. forcedinline void set (const Pixel& src) throw()
  20556. {
  20557. b = src.getBlue();
  20558. g = src.getGreen();
  20559. r = src.getRed();
  20560. }
  20561. /** This method is included for compatibility with the PixelARGB class. */
  20562. forcedinline void setAlpha (const uint8) throw() {}
  20563. /** Multiplies the colour's alpha value with another one. */
  20564. forcedinline void multiplyAlpha (int) throw() {}
  20565. /** Sets the pixel's colour from individual components. */
  20566. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  20567. {
  20568. r = r_;
  20569. g = g_;
  20570. b = b_;
  20571. }
  20572. /** Premultiplies the pixel's RGB values by its alpha. */
  20573. forcedinline void premultiply() throw() {}
  20574. /** Unpremultiplies the pixel's RGB values. */
  20575. forcedinline void unpremultiply() throw() {}
  20576. forcedinline void desaturate() throw()
  20577. {
  20578. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  20579. }
  20580. /** The indexes of the different components in the byte layout of this type of colour. */
  20581. #if JUCE_MAC
  20582. enum { indexR = 0, indexG = 1, indexB = 2 };
  20583. #else
  20584. enum { indexR = 2, indexG = 1, indexB = 0 };
  20585. #endif
  20586. private:
  20587. #if JUCE_MAC
  20588. uint8 r, g, b;
  20589. #else
  20590. uint8 b, g, r;
  20591. #endif
  20592. }
  20593. #ifndef DOXYGEN
  20594. PACKED
  20595. #endif
  20596. ;
  20597. forcedinline void PixelARGB::blend (const PixelRGB& src) throw()
  20598. {
  20599. set (src);
  20600. }
  20601. /**
  20602. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  20603. This is used internally by the imaging classes.
  20604. @see PixelARGB, PixelRGB
  20605. */
  20606. class JUCE_API PixelAlpha
  20607. {
  20608. public:
  20609. /** Creates a pixel without defining its colour. */
  20610. PixelAlpha() throw() {}
  20611. ~PixelAlpha() throw() {}
  20612. /** Creates a pixel from a 32-bit argb value.
  20613. (The argb format is that used by PixelARGB)
  20614. */
  20615. PixelAlpha (const uint32 argb) throw()
  20616. {
  20617. a = (uint8) (argb >> 24);
  20618. }
  20619. forcedinline uint32 getARGB() const throw() { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  20620. forcedinline uint32 getRB() const throw() { return (((uint32) a) << 16) | a; }
  20621. forcedinline uint32 getAG() const throw() { return (((uint32) a) << 16) | a; }
  20622. forcedinline uint8 getAlpha() const throw() { return a; }
  20623. forcedinline uint8 getRed() const throw() { return 0; }
  20624. forcedinline uint8 getGreen() const throw() { return 0; }
  20625. forcedinline uint8 getBlue() const throw() { return 0; }
  20626. /** Blends another pixel onto this one.
  20627. This takes into account the opacity of the pixel being overlaid, and blends
  20628. it accordingly.
  20629. */
  20630. template <class Pixel>
  20631. forcedinline void blend (const Pixel& src) throw()
  20632. {
  20633. const int srcA = src.getAlpha();
  20634. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  20635. }
  20636. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  20637. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  20638. being used, so this can blend semi-transparently from a PixelRGB argument.
  20639. */
  20640. template <class Pixel>
  20641. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  20642. {
  20643. ++extraAlpha;
  20644. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  20645. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  20646. }
  20647. /** Blends another pixel with this one, creating a colour that is somewhere
  20648. between the two, as specified by the amount.
  20649. */
  20650. template <class Pixel>
  20651. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  20652. {
  20653. a += ((src,getAlpha() - a) * amount) >> 8;
  20654. }
  20655. /** Copies another pixel colour over this one.
  20656. This doesn't blend it - this colour is simply replaced by the other one.
  20657. */
  20658. template <class Pixel>
  20659. forcedinline void set (const Pixel& src) throw()
  20660. {
  20661. a = src.getAlpha();
  20662. }
  20663. /** Replaces the colour's alpha value with another one. */
  20664. forcedinline void setAlpha (const uint8 newAlpha) throw()
  20665. {
  20666. a = newAlpha;
  20667. }
  20668. /** Multiplies the colour's alpha value with another one. */
  20669. forcedinline void multiplyAlpha (int multiplier) throw()
  20670. {
  20671. ++multiplier;
  20672. a = (uint8) ((a * multiplier) >> 8);
  20673. }
  20674. forcedinline void multiplyAlpha (const float multiplier) throw()
  20675. {
  20676. a = (uint8) (a * multiplier);
  20677. }
  20678. /** Sets the pixel's colour from individual components. */
  20679. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) throw()
  20680. {
  20681. a = a_;
  20682. }
  20683. /** Premultiplies the pixel's RGB values by its alpha. */
  20684. forcedinline void premultiply() throw()
  20685. {
  20686. }
  20687. /** Unpremultiplies the pixel's RGB values. */
  20688. forcedinline void unpremultiply() throw()
  20689. {
  20690. }
  20691. forcedinline void desaturate() throw()
  20692. {
  20693. }
  20694. /** The indexes of the different components in the byte layout of this type of colour. */
  20695. enum { indexA = 0 };
  20696. private:
  20697. uint8 a : 8;
  20698. }
  20699. #ifndef DOXYGEN
  20700. PACKED
  20701. #endif
  20702. ;
  20703. forcedinline void PixelRGB::blend (const PixelAlpha& src) throw()
  20704. {
  20705. blend (PixelARGB (src.getARGB()));
  20706. }
  20707. forcedinline void PixelARGB::blend (const PixelAlpha& src) throw()
  20708. {
  20709. uint32 sargb = src.getARGB();
  20710. const uint32 alpha = 0x100 - (sargb >> 24);
  20711. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  20712. sargb += 0xff00ff00 & (getAG() * alpha);
  20713. argb = sargb;
  20714. }
  20715. #if JUCE_MSVC
  20716. #pragma pack (pop)
  20717. #endif
  20718. #undef PACKED
  20719. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  20720. /*** End of inlined file: juce_PixelFormats.h ***/
  20721. /**
  20722. Represents a colour, also including a transparency value.
  20723. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  20724. */
  20725. class JUCE_API Colour
  20726. {
  20727. public:
  20728. /** Creates a transparent black colour. */
  20729. Colour() throw();
  20730. /** Creates a copy of another Colour object. */
  20731. Colour (const Colour& other) throw();
  20732. /** Creates a colour from a 32-bit ARGB value.
  20733. The format of this number is:
  20734. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  20735. All components in the range 0x00 to 0xff.
  20736. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  20737. @see getPixelARGB
  20738. */
  20739. explicit Colour (uint32 argb) throw();
  20740. /** Creates an opaque colour using 8-bit red, green and blue values */
  20741. Colour (uint8 red,
  20742. uint8 green,
  20743. uint8 blue) throw();
  20744. /** Creates an opaque colour using 8-bit red, green and blue values */
  20745. static const Colour fromRGB (uint8 red,
  20746. uint8 green,
  20747. uint8 blue) throw();
  20748. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  20749. Colour (uint8 red,
  20750. uint8 green,
  20751. uint8 blue,
  20752. uint8 alpha) throw();
  20753. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  20754. static const Colour fromRGBA (uint8 red,
  20755. uint8 green,
  20756. uint8 blue,
  20757. uint8 alpha) throw();
  20758. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  20759. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  20760. Values outside the valid range will be clipped.
  20761. */
  20762. Colour (uint8 red,
  20763. uint8 green,
  20764. uint8 blue,
  20765. float alpha) throw();
  20766. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  20767. static const Colour fromRGBAFloat (uint8 red,
  20768. uint8 green,
  20769. uint8 blue,
  20770. float alpha) throw();
  20771. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  20772. The floating point values must be between 0.0 and 1.0.
  20773. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  20774. Values outside the valid range will be clipped.
  20775. */
  20776. Colour (float hue,
  20777. float saturation,
  20778. float brightness,
  20779. uint8 alpha) throw();
  20780. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  20781. All values must be between 0.0 and 1.0.
  20782. Numbers outside the valid range will be clipped.
  20783. */
  20784. Colour (float hue,
  20785. float saturation,
  20786. float brightness,
  20787. float alpha) throw();
  20788. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  20789. The floating point values must be between 0.0 and 1.0.
  20790. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  20791. Values outside the valid range will be clipped.
  20792. */
  20793. static const Colour fromHSV (float hue,
  20794. float saturation,
  20795. float brightness,
  20796. float alpha) throw();
  20797. /** Destructor. */
  20798. ~Colour() throw();
  20799. /** Copies another Colour object. */
  20800. Colour& operator= (const Colour& other) throw();
  20801. /** Compares two colours. */
  20802. bool operator== (const Colour& other) const throw();
  20803. /** Compares two colours. */
  20804. bool operator!= (const Colour& other) const throw();
  20805. /** Returns the red component of this colour.
  20806. @returns a value between 0x00 and 0xff.
  20807. */
  20808. uint8 getRed() const throw() { return argb.getRed(); }
  20809. /** Returns the green component of this colour.
  20810. @returns a value between 0x00 and 0xff.
  20811. */
  20812. uint8 getGreen() const throw() { return argb.getGreen(); }
  20813. /** Returns the blue component of this colour.
  20814. @returns a value between 0x00 and 0xff.
  20815. */
  20816. uint8 getBlue() const throw() { return argb.getBlue(); }
  20817. /** Returns the red component of this colour as a floating point value.
  20818. @returns a value between 0.0 and 1.0
  20819. */
  20820. float getFloatRed() const throw();
  20821. /** Returns the green component of this colour as a floating point value.
  20822. @returns a value between 0.0 and 1.0
  20823. */
  20824. float getFloatGreen() const throw();
  20825. /** Returns the blue component of this colour as a floating point value.
  20826. @returns a value between 0.0 and 1.0
  20827. */
  20828. float getFloatBlue() const throw();
  20829. /** Returns a premultiplied ARGB pixel object that represents this colour.
  20830. */
  20831. const PixelARGB getPixelARGB() const throw();
  20832. /** Returns a 32-bit integer that represents this colour.
  20833. The format of this number is:
  20834. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  20835. */
  20836. uint32 getARGB() const throw();
  20837. /** Returns the colour's alpha (opacity).
  20838. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  20839. */
  20840. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  20841. /** Returns the colour's alpha (opacity) as a floating point value.
  20842. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  20843. */
  20844. float getFloatAlpha() const throw();
  20845. /** Returns true if this colour is completely opaque.
  20846. Equivalent to (getAlpha() == 0xff).
  20847. */
  20848. bool isOpaque() const throw();
  20849. /** Returns true if this colour is completely transparent.
  20850. Equivalent to (getAlpha() == 0x00).
  20851. */
  20852. bool isTransparent() const throw();
  20853. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  20854. const Colour withAlpha (uint8 newAlpha) const throw();
  20855. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  20856. const Colour withAlpha (float newAlpha) const throw();
  20857. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  20858. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  20859. */
  20860. const Colour withMultipliedAlpha (float alphaMultiplier) const throw();
  20861. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  20862. If the foreground colour is semi-transparent, it is blended onto this colour
  20863. accordingly.
  20864. */
  20865. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  20866. /** Returns a colour that lies somewhere between this one and another.
  20867. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  20868. is 1.0, the result is 100% of the other colour.
  20869. */
  20870. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const throw();
  20871. /** Returns the colour's hue component.
  20872. The value returned is in the range 0.0 to 1.0
  20873. */
  20874. float getHue() const throw();
  20875. /** Returns the colour's saturation component.
  20876. The value returned is in the range 0.0 to 1.0
  20877. */
  20878. float getSaturation() const throw();
  20879. /** Returns the colour's brightness component.
  20880. The value returned is in the range 0.0 to 1.0
  20881. */
  20882. float getBrightness() const throw();
  20883. /** Returns the colour's hue, saturation and brightness components all at once.
  20884. The values returned are in the range 0.0 to 1.0
  20885. */
  20886. void getHSB (float& hue,
  20887. float& saturation,
  20888. float& brightness) const throw();
  20889. /** Returns a copy of this colour with a different hue. */
  20890. const Colour withHue (float newHue) const throw();
  20891. /** Returns a copy of this colour with a different saturation. */
  20892. const Colour withSaturation (float newSaturation) const throw();
  20893. /** Returns a copy of this colour with a different brightness.
  20894. @see brighter, darker, withMultipliedBrightness
  20895. */
  20896. const Colour withBrightness (float newBrightness) const throw();
  20897. /** Returns a copy of this colour with it hue rotated.
  20898. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  20899. @see brighter, darker, withMultipliedBrightness
  20900. */
  20901. const Colour withRotatedHue (float amountToRotate) const throw();
  20902. /** Returns a copy of this colour with its saturation multiplied by the given value.
  20903. The new colour's saturation is (this->getSaturation() * multiplier)
  20904. (the result is clipped to legal limits).
  20905. */
  20906. const Colour withMultipliedSaturation (float multiplier) const throw();
  20907. /** Returns a copy of this colour with its brightness multiplied by the given value.
  20908. The new colour's saturation is (this->getBrightness() * multiplier)
  20909. (the result is clipped to legal limits).
  20910. */
  20911. const Colour withMultipliedBrightness (float amount) const throw();
  20912. /** Returns a brighter version of this colour.
  20913. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  20914. unchanged, and higher values make it brighter
  20915. @see withMultipliedBrightness
  20916. */
  20917. const Colour brighter (float amountBrighter = 0.4f) const throw();
  20918. /** Returns a darker version of this colour.
  20919. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  20920. unchanged, and higher values make it darker
  20921. @see withMultipliedBrightness
  20922. */
  20923. const Colour darker (float amountDarker = 0.4f) const throw();
  20924. /** Returns a colour that will be clearly visible against this colour.
  20925. The amount parameter indicates how contrasting the new colour should
  20926. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  20927. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  20928. return white; Colours::white.contrasting (1.0f) will return black, etc.
  20929. */
  20930. const Colour contrasting (float amount = 1.0f) const throw();
  20931. /** Returns a colour that contrasts against two colours.
  20932. Looks for a colour that contrasts with both of the colours passed-in.
  20933. Handy for things like choosing a highlight colour in text editors, etc.
  20934. */
  20935. static const Colour contrasting (const Colour& colour1,
  20936. const Colour& colour2) throw();
  20937. /** Returns an opaque shade of grey.
  20938. @param brightness the level of grey to return - 0 is black, 1.0 is white
  20939. */
  20940. static const Colour greyLevel (float brightness) throw();
  20941. /** Returns a stringified version of this colour.
  20942. The string can be turned back into a colour using the fromString() method.
  20943. */
  20944. const String toString() const;
  20945. /** Reads the colour from a string that was created with toString().
  20946. */
  20947. static const Colour fromString (const String& encodedColourString);
  20948. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  20949. const String toDisplayString (bool includeAlphaValue) const;
  20950. private:
  20951. PixelARGB argb;
  20952. };
  20953. #endif // __JUCE_COLOUR_JUCEHEADER__
  20954. /*** End of inlined file: juce_Colour.h ***/
  20955. /**
  20956. Contains a set of predefined named colours (mostly standard HTML colours)
  20957. @see Colour, Colours::greyLevel
  20958. */
  20959. class Colours
  20960. {
  20961. public:
  20962. static JUCE_API const Colour
  20963. transparentBlack, /**< ARGB = 0x00000000 */
  20964. transparentWhite, /**< ARGB = 0x00ffffff */
  20965. black, /**< ARGB = 0xff000000 */
  20966. white, /**< ARGB = 0xffffffff */
  20967. blue, /**< ARGB = 0xff0000ff */
  20968. grey, /**< ARGB = 0xff808080 */
  20969. green, /**< ARGB = 0xff008000 */
  20970. red, /**< ARGB = 0xffff0000 */
  20971. yellow, /**< ARGB = 0xffffff00 */
  20972. aliceblue, antiquewhite, aqua, aquamarine,
  20973. azure, beige, bisque, blanchedalmond,
  20974. blueviolet, brown, burlywood, cadetblue,
  20975. chartreuse, chocolate, coral, cornflowerblue,
  20976. cornsilk, crimson, cyan, darkblue,
  20977. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  20978. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  20979. darkorchid, darkred, darksalmon, darkseagreen,
  20980. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  20981. deeppink, deepskyblue, dimgrey, dodgerblue,
  20982. firebrick, floralwhite, forestgreen, fuchsia,
  20983. gainsboro, gold, goldenrod, greenyellow,
  20984. honeydew, hotpink, indianred, indigo,
  20985. ivory, khaki, lavender, lavenderblush,
  20986. lemonchiffon, lightblue, lightcoral, lightcyan,
  20987. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  20988. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  20989. lightsteelblue, lightyellow, lime, limegreen,
  20990. linen, magenta, maroon, mediumaquamarine,
  20991. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  20992. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  20993. midnightblue, mintcream, mistyrose, navajowhite,
  20994. navy, oldlace, olive, olivedrab,
  20995. orange, orangered, orchid, palegoldenrod,
  20996. palegreen, paleturquoise, palevioletred, papayawhip,
  20997. peachpuff, peru, pink, plum,
  20998. powderblue, purple, rosybrown, royalblue,
  20999. saddlebrown, salmon, sandybrown, seagreen,
  21000. seashell, sienna, silver, skyblue,
  21001. slateblue, slategrey, snow, springgreen,
  21002. steelblue, tan, teal, thistle,
  21003. tomato, turquoise, violet, wheat,
  21004. whitesmoke, yellowgreen;
  21005. /** Attempts to look up a string in the list of known colour names, and return
  21006. the appropriate colour.
  21007. A non-case-sensitive search is made of the list of predefined colours, and
  21008. if a match is found, that colour is returned. If no match is found, the
  21009. colour passed in as the defaultColour parameter is returned.
  21010. */
  21011. static JUCE_API const Colour findColourForName (const String& colourName,
  21012. const Colour& defaultColour);
  21013. private:
  21014. // this isn't a class you should ever instantiate - it's just here for the
  21015. // static values in it.
  21016. Colours();
  21017. JUCE_DECLARE_NON_COPYABLE (Colours);
  21018. };
  21019. #endif // __JUCE_COLOURS_JUCEHEADER__
  21020. /*** End of inlined file: juce_Colours.h ***/
  21021. /*** Start of inlined file: juce_ColourGradient.h ***/
  21022. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  21023. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  21024. /**
  21025. Describes the layout and colours that should be used to paint a colour gradient.
  21026. @see Graphics::setGradientFill
  21027. */
  21028. class JUCE_API ColourGradient
  21029. {
  21030. public:
  21031. /** Creates a gradient object.
  21032. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  21033. colour2 should be. In between them there's a gradient.
  21034. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  21035. its centre.
  21036. The alpha transparencies of the colours are used, so note that
  21037. if you blend from transparent to a solid colour, the RGB of the transparent
  21038. colour will become visible in parts of the gradient. e.g. blending
  21039. from Colour::transparentBlack to Colours::white will produce a
  21040. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  21041. will be white all the way across.
  21042. @see ColourGradient
  21043. */
  21044. ColourGradient (const Colour& colour1, float x1, float y1,
  21045. const Colour& colour2, float x2, float y2,
  21046. bool isRadial);
  21047. /** Creates an uninitialised gradient.
  21048. If you use this constructor instead of the other one, be sure to set all the
  21049. object's public member variables before using it!
  21050. */
  21051. ColourGradient() throw();
  21052. /** Destructor */
  21053. ~ColourGradient();
  21054. /** Removes any colours that have been added.
  21055. This will also remove any start and end colours, so the gradient won't work. You'll
  21056. need to add more colours with addColour().
  21057. */
  21058. void clearColours();
  21059. /** Adds a colour at a point along the length of the gradient.
  21060. This allows the gradient to go through a spectrum of colours, instead of just a
  21061. start and end colour.
  21062. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  21063. of the distance along the line between the two points
  21064. at which the colour should occur.
  21065. @param colour the colour that should be used at this point
  21066. @returns the index at which the new point was added
  21067. */
  21068. int addColour (double proportionAlongGradient,
  21069. const Colour& colour);
  21070. /** Removes one of the colours from the gradient. */
  21071. void removeColour (int index);
  21072. /** Multiplies the alpha value of all the colours by the given scale factor */
  21073. void multiplyOpacity (float multiplier) throw();
  21074. /** Returns the number of colour-stops that have been added. */
  21075. int getNumColours() const throw();
  21076. /** Returns the position along the length of the gradient of the colour with this index.
  21077. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  21078. */
  21079. double getColourPosition (int index) const throw();
  21080. /** Returns the colour that was added with a given index.
  21081. The index is from 0 to getNumColours() - 1.
  21082. */
  21083. const Colour getColour (int index) const throw();
  21084. /** Changes the colour at a given index.
  21085. The index is from 0 to getNumColours() - 1.
  21086. */
  21087. void setColour (int index, const Colour& newColour) throw();
  21088. /** Returns the an interpolated colour at any position along the gradient.
  21089. @param position the position along the gradient, between 0 and 1
  21090. */
  21091. const Colour getColourAtPosition (double position) const throw();
  21092. /** Creates a set of interpolated premultiplied ARGB values.
  21093. This will resize the HeapBlock, fill it with the colours, and will return the number of
  21094. colours that it added.
  21095. */
  21096. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  21097. /** Returns true if all colours are opaque. */
  21098. bool isOpaque() const throw();
  21099. /** Returns true if all colours are completely transparent. */
  21100. bool isInvisible() const throw();
  21101. Point<float> point1, point2;
  21102. /** If true, the gradient should be filled circularly, centred around
  21103. point1, with point2 defining a point on the circumference.
  21104. If false, the gradient is linear between the two points.
  21105. */
  21106. bool isRadial;
  21107. bool operator== (const ColourGradient& other) const throw();
  21108. bool operator!= (const ColourGradient& other) const throw();
  21109. private:
  21110. struct ColourPoint
  21111. {
  21112. ColourPoint() throw() {}
  21113. ColourPoint (const double position_, const Colour& colour_) throw()
  21114. : position (position_), colour (colour_)
  21115. {}
  21116. bool operator== (const ColourPoint& other) const throw() { return position == other.position && colour == other.colour; }
  21117. bool operator!= (const ColourPoint& other) const throw() { return position != other.position || colour != other.colour; }
  21118. double position;
  21119. Colour colour;
  21120. };
  21121. Array <ColourPoint> colours;
  21122. JUCE_LEAK_DETECTOR (ColourGradient);
  21123. };
  21124. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  21125. /*** End of inlined file: juce_ColourGradient.h ***/
  21126. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  21127. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  21128. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  21129. /**
  21130. Defines the method used to postion some kind of rectangular object within
  21131. a rectangular viewport.
  21132. Although similar to Justification, this is more specific, and has some extra
  21133. options.
  21134. */
  21135. class JUCE_API RectanglePlacement
  21136. {
  21137. public:
  21138. /** Creates a RectanglePlacement object using a combination of flags. */
  21139. inline RectanglePlacement (int flags_) throw() : flags (flags_) {}
  21140. /** Creates a copy of another RectanglePlacement object. */
  21141. RectanglePlacement (const RectanglePlacement& other) throw();
  21142. /** Copies another RectanglePlacement object. */
  21143. RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  21144. /** Flag values that can be combined and used in the constructor. */
  21145. enum
  21146. {
  21147. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  21148. xLeft = 1,
  21149. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  21150. xRight = 2,
  21151. /** Indicates that the source should be placed in the centre between the left and right
  21152. sides of the available space. */
  21153. xMid = 4,
  21154. /** Indicates that the source's top edge should be aligned with the top edge of the
  21155. destination rectangle. */
  21156. yTop = 8,
  21157. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  21158. destination rectangle. */
  21159. yBottom = 16,
  21160. /** Indicates that the source should be placed in the centre between the top and bottom
  21161. sides of the available space. */
  21162. yMid = 32,
  21163. /** If this flag is set, then the source rectangle will be resized to completely fill
  21164. the destination rectangle, and all other flags are ignored.
  21165. */
  21166. stretchToFit = 64,
  21167. /** If this flag is set, then the source rectangle will be resized so that it is the
  21168. minimum size to completely fill the destination rectangle, without changing its
  21169. aspect ratio. This means that some of the source rectangle may fall outside
  21170. the destination.
  21171. If this flag is not set, the source will be given the maximum size at which none
  21172. of it falls outside the destination rectangle.
  21173. */
  21174. fillDestination = 128,
  21175. /** Indicates that the source rectangle can be reduced in size if required, but should
  21176. never be made larger than its original size.
  21177. */
  21178. onlyReduceInSize = 256,
  21179. /** Indicates that the source rectangle can be enlarged if required, but should
  21180. never be made smaller than its original size.
  21181. */
  21182. onlyIncreaseInSize = 512,
  21183. /** Indicates that the source rectangle's size should be left unchanged.
  21184. */
  21185. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  21186. /** A shorthand value that is equivalent to (xMid | yMid). */
  21187. centred = 4 + 32
  21188. };
  21189. /** Returns the raw flags that are set for this object. */
  21190. inline int getFlags() const throw() { return flags; }
  21191. /** Tests a set of flags for this object.
  21192. @returns true if any of the flags passed in are set on this object.
  21193. */
  21194. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  21195. /** Adjusts the position and size of a rectangle to fit it into a space.
  21196. The source rectangle co-ordinates will be adjusted so that they fit into
  21197. the destination rectangle based on this object's flags.
  21198. */
  21199. void applyTo (double& sourceX,
  21200. double& sourceY,
  21201. double& sourceW,
  21202. double& sourceH,
  21203. double destinationX,
  21204. double destinationY,
  21205. double destinationW,
  21206. double destinationH) const throw();
  21207. /** Returns the transform that should be applied to these source co-ordinates to fit them
  21208. into the destination rectangle using the current flags.
  21209. */
  21210. template <typename ValueType>
  21211. const Rectangle<ValueType> appliedTo (const Rectangle<ValueType>& source,
  21212. const Rectangle<ValueType>& destination) const throw()
  21213. {
  21214. double x = source.getX(), y = source.getY(), w = source.getWidth(), h = source.getHeight();
  21215. applyTo (x, y, w, h, static_cast <double> (destination.getX()), static_cast <double> (destination.getY()),
  21216. static_cast <double> (destination.getWidth()), static_cast <double> (destination.getHeight()));
  21217. return Rectangle<ValueType> (static_cast <ValueType> (x), static_cast <ValueType> (y),
  21218. static_cast <ValueType> (w), static_cast <ValueType> (h));
  21219. }
  21220. /** Returns the transform that should be applied to these source co-ordinates to fit them
  21221. into the destination rectangle using the current flags.
  21222. */
  21223. const AffineTransform getTransformToFit (const Rectangle<float>& source,
  21224. const Rectangle<float>& destination) const throw();
  21225. private:
  21226. int flags;
  21227. };
  21228. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  21229. /*** End of inlined file: juce_RectanglePlacement.h ***/
  21230. class LowLevelGraphicsContext;
  21231. class Image;
  21232. class FillType;
  21233. class RectangleList;
  21234. /**
  21235. A graphics context, used for drawing a component or image.
  21236. When a Component needs painting, a Graphics context is passed to its
  21237. Component::paint() method, and this you then call methods within this
  21238. object to actually draw the component's content.
  21239. A Graphics can also be created from an image, to allow drawing directly onto
  21240. that image.
  21241. @see Component::paint
  21242. */
  21243. class JUCE_API Graphics
  21244. {
  21245. public:
  21246. /** Creates a Graphics object to draw directly onto the given image.
  21247. The graphics object that is created will be set up to draw onto the image,
  21248. with the context's clipping area being the entire size of the image, and its
  21249. origin being the image's origin. To draw into a subsection of an image, use the
  21250. reduceClipRegion() and setOrigin() methods.
  21251. Obviously you shouldn't delete the image before this context is deleted.
  21252. */
  21253. explicit Graphics (const Image& imageToDrawOnto);
  21254. /** Destructor. */
  21255. ~Graphics();
  21256. /** Changes the current drawing colour.
  21257. This sets the colour that will now be used for drawing operations - it also
  21258. sets the opacity to that of the colour passed-in.
  21259. If a brush is being used when this method is called, the brush will be deselected,
  21260. and any subsequent drawing will be done with a solid colour brush instead.
  21261. @see setOpacity
  21262. */
  21263. void setColour (const Colour& newColour);
  21264. /** Changes the opacity to use with the current colour.
  21265. If a solid colour is being used for drawing, this changes its opacity
  21266. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  21267. If a gradient is being used, this will have no effect on it.
  21268. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  21269. */
  21270. void setOpacity (float newOpacity);
  21271. /** Sets the context to use a gradient for its fill pattern.
  21272. */
  21273. void setGradientFill (const ColourGradient& gradient);
  21274. /** Sets the context to use a tiled image pattern for filling.
  21275. Make sure that you don't delete this image while it's still being used by
  21276. this context!
  21277. */
  21278. void setTiledImageFill (const Image& imageToUse,
  21279. int anchorX, int anchorY,
  21280. float opacity);
  21281. /** Changes the current fill settings.
  21282. @see setColour, setGradientFill, setTiledImageFill
  21283. */
  21284. void setFillType (const FillType& newFill);
  21285. /** Changes the font to use for subsequent text-drawing functions.
  21286. Note there's also a setFont (float, int) method to quickly change the size and
  21287. style of the current font.
  21288. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  21289. */
  21290. void setFont (const Font& newFont);
  21291. /** Changes the size and style of the currently-selected font.
  21292. This is a convenient shortcut that changes the context's current font to a
  21293. different size or style. The typeface won't be changed.
  21294. @see Font
  21295. */
  21296. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  21297. /** Returns the currently selected font. */
  21298. const Font getCurrentFont() const;
  21299. /** Draws a one-line text string.
  21300. This will use the current colour (or brush) to fill the text. The font is the last
  21301. one specified by setFont().
  21302. @param text the string to draw
  21303. @param startX the position to draw the left-hand edge of the text
  21304. @param baselineY the position of the text's baseline
  21305. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  21306. */
  21307. void drawSingleLineText (const String& text,
  21308. int startX, int baselineY) const;
  21309. /** Draws text across multiple lines.
  21310. This will break the text onto a new line where there's a new-line or
  21311. carriage-return character, or at a word-boundary when the text becomes wider
  21312. than the size specified by the maximumLineWidth parameter.
  21313. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  21314. */
  21315. void drawMultiLineText (const String& text,
  21316. int startX, int baselineY,
  21317. int maximumLineWidth) const;
  21318. /** Renders a string of text as a vector path.
  21319. This allows a string to be transformed with an arbitrary AffineTransform and
  21320. rendered using the current colour/brush. It's much slower than the normal text methods
  21321. but more accurate.
  21322. @see setFont
  21323. */
  21324. void drawTextAsPath (const String& text,
  21325. const AffineTransform& transform) const;
  21326. /** Draws a line of text within a specified rectangle.
  21327. The text will be positioned within the rectangle based on the justification
  21328. flags passed-in. If the string is too long to fit inside the rectangle, it will
  21329. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  21330. flag is true).
  21331. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  21332. */
  21333. void drawText (const String& text,
  21334. int x, int y, int width, int height,
  21335. const Justification& justificationType,
  21336. bool useEllipsesIfTooBig) const;
  21337. /** Tries to draw a text string inside a given space.
  21338. This does its best to make the given text readable within the specified rectangle,
  21339. so it useful for labelling things.
  21340. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  21341. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  21342. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  21343. it's been truncated.
  21344. A Justification parameter lets you specify how the text is laid out within the rectangle,
  21345. both horizontally and vertically.
  21346. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  21347. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  21348. can set this value to 1.0f.
  21349. @see GlyphArrangement::addFittedText
  21350. */
  21351. void drawFittedText (const String& text,
  21352. int x, int y, int width, int height,
  21353. const Justification& justificationFlags,
  21354. int maximumNumberOfLines,
  21355. float minimumHorizontalScale = 0.7f) const;
  21356. /** Fills the context's entire clip region with the current colour or brush.
  21357. (See also the fillAll (const Colour&) method which is a quick way of filling
  21358. it with a given colour).
  21359. */
  21360. void fillAll() const;
  21361. /** Fills the context's entire clip region with a given colour.
  21362. This leaves the context's current colour and brush unchanged, it just
  21363. uses the specified colour temporarily.
  21364. */
  21365. void fillAll (const Colour& colourToUse) const;
  21366. /** Fills a rectangle with the current colour or brush.
  21367. @see drawRect, fillRoundedRectangle
  21368. */
  21369. void fillRect (int x, int y, int width, int height) const;
  21370. /** Fills a rectangle with the current colour or brush. */
  21371. void fillRect (const Rectangle<int>& rectangle) const;
  21372. /** Fills a rectangle with the current colour or brush.
  21373. This uses sub-pixel positioning so is slower than the fillRect method which
  21374. takes integer co-ordinates.
  21375. */
  21376. void fillRect (float x, float y, float width, float height) const;
  21377. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  21378. @see drawRoundedRectangle, Path::addRoundedRectangle
  21379. */
  21380. void fillRoundedRectangle (float x, float y, float width, float height,
  21381. float cornerSize) const;
  21382. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  21383. @see drawRoundedRectangle, Path::addRoundedRectangle
  21384. */
  21385. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  21386. float cornerSize) const;
  21387. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  21388. */
  21389. void fillCheckerBoard (const Rectangle<int>& area,
  21390. int checkWidth, int checkHeight,
  21391. const Colour& colour1, const Colour& colour2) const;
  21392. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  21393. The lines are drawn inside the given rectangle, and greater line thicknesses
  21394. extend inwards.
  21395. @see fillRect
  21396. */
  21397. void drawRect (int x, int y, int width, int height,
  21398. int lineThickness = 1) const;
  21399. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  21400. The lines are drawn inside the given rectangle, and greater line thicknesses
  21401. extend inwards.
  21402. @see fillRect
  21403. */
  21404. void drawRect (float x, float y, float width, float height,
  21405. float lineThickness = 1.0f) const;
  21406. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  21407. The lines are drawn inside the given rectangle, and greater line thicknesses
  21408. extend inwards.
  21409. @see fillRect
  21410. */
  21411. void drawRect (const Rectangle<int>& rectangle,
  21412. int lineThickness = 1) const;
  21413. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  21414. @see fillRoundedRectangle, Path::addRoundedRectangle
  21415. */
  21416. void drawRoundedRectangle (float x, float y, float width, float height,
  21417. float cornerSize, float lineThickness) const;
  21418. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  21419. @see fillRoundedRectangle, Path::addRoundedRectangle
  21420. */
  21421. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  21422. float cornerSize, float lineThickness) const;
  21423. /** Draws a 3D raised (or indented) bevel using two colours.
  21424. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  21425. extend inwards.
  21426. The top-left colour is used for the top- and left-hand edges of the
  21427. bevel; the bottom-right colour is used for the bottom- and right-hand
  21428. edges.
  21429. If useGradient is true, then the bevel fades out to make it look more curved
  21430. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  21431. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  21432. the centre edges are sharp and it fades towards the outside.
  21433. */
  21434. void drawBevel (int x, int y, int width, int height,
  21435. int bevelThickness,
  21436. const Colour& topLeftColour = Colours::white,
  21437. const Colour& bottomRightColour = Colours::black,
  21438. bool useGradient = true,
  21439. bool sharpEdgeOnOutside = true) const;
  21440. /** Draws a pixel using the current colour or brush.
  21441. */
  21442. void setPixel (int x, int y) const;
  21443. /** Fills an ellipse with the current colour or brush.
  21444. The ellipse is drawn to fit inside the given rectangle.
  21445. @see drawEllipse, Path::addEllipse
  21446. */
  21447. void fillEllipse (float x, float y, float width, float height) const;
  21448. /** Draws an elliptical stroke using the current colour or brush.
  21449. @see fillEllipse, Path::addEllipse
  21450. */
  21451. void drawEllipse (float x, float y, float width, float height,
  21452. float lineThickness) const;
  21453. /** Draws a line between two points.
  21454. The line is 1 pixel wide and drawn with the current colour or brush.
  21455. */
  21456. void drawLine (float startX, float startY, float endX, float endY) const;
  21457. /** Draws a line between two points with a given thickness.
  21458. @see Path::addLineSegment
  21459. */
  21460. void drawLine (float startX, float startY, float endX, float endY,
  21461. float lineThickness) const;
  21462. /** Draws a line between two points.
  21463. The line is 1 pixel wide and drawn with the current colour or brush.
  21464. */
  21465. void drawLine (const Line<float>& line) const;
  21466. /** Draws a line between two points with a given thickness.
  21467. @see Path::addLineSegment
  21468. */
  21469. void drawLine (const Line<float>& line, float lineThickness) const;
  21470. /** Draws a dashed line using a custom set of dash-lengths.
  21471. @param line the line to draw
  21472. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  21473. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  21474. draw 6 pixels, skip 7 pixels, and then repeat.
  21475. @param numDashLengths the number of elements in the array (this must be an even number).
  21476. @param lineThickness the thickness of the line to draw
  21477. @param dashIndexToStartFrom the index in the dash-length array to use for the first segment
  21478. @see PathStrokeType::createDashedStroke
  21479. */
  21480. void drawDashedLine (const Line<float>& line,
  21481. const float* dashLengths, int numDashLengths,
  21482. float lineThickness = 1.0f,
  21483. int dashIndexToStartFrom = 0) const;
  21484. /** Draws a vertical line of pixels at a given x position.
  21485. The x position is an integer, but the top and bottom of the line can be sub-pixel
  21486. positions, and these will be anti-aliased if necessary.
  21487. */
  21488. void drawVerticalLine (int x, float top, float bottom) const;
  21489. /** Draws a horizontal line of pixels at a given y position.
  21490. The y position is an integer, but the left and right ends of the line can be sub-pixel
  21491. positions, and these will be anti-aliased if necessary.
  21492. */
  21493. void drawHorizontalLine (int y, float left, float right) const;
  21494. /** Fills a path using the currently selected colour or brush.
  21495. */
  21496. void fillPath (const Path& path,
  21497. const AffineTransform& transform = AffineTransform::identity) const;
  21498. /** Draws a path's outline using the currently selected colour or brush.
  21499. */
  21500. void strokePath (const Path& path,
  21501. const PathStrokeType& strokeType,
  21502. const AffineTransform& transform = AffineTransform::identity) const;
  21503. /** Draws a line with an arrowhead at its end.
  21504. @param line the line to draw
  21505. @param lineThickness the thickness of the line
  21506. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  21507. @param arrowheadLength the length of the arrow head (along the length of the line)
  21508. */
  21509. void drawArrow (const Line<float>& line,
  21510. float lineThickness,
  21511. float arrowheadWidth,
  21512. float arrowheadLength) const;
  21513. /** Types of rendering quality that can be specified when drawing images.
  21514. @see blendImage, Graphics::setImageResamplingQuality
  21515. */
  21516. enum ResamplingQuality
  21517. {
  21518. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  21519. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  21520. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  21521. };
  21522. /** Changes the quality that will be used when resampling images.
  21523. By default a Graphics object will be set to mediumRenderingQuality.
  21524. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  21525. */
  21526. void setImageResamplingQuality (const ResamplingQuality newQuality);
  21527. /** Draws an image.
  21528. This will draw the whole of an image, positioning its top-left corner at the
  21529. given co-ordinates, and keeping its size the same. This is the simplest image
  21530. drawing method - the others give more control over the scaling and clipping
  21531. of the images.
  21532. Images are composited using the context's current opacity, so if you
  21533. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  21534. (or setColour() with an opaque colour) before drawing images.
  21535. */
  21536. void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
  21537. bool fillAlphaChannelWithCurrentBrush = false) const;
  21538. /** Draws part of an image, rescaling it to fit in a given target region.
  21539. The specified area of the source image is rescaled and drawn to fill the
  21540. specifed destination rectangle.
  21541. Images are composited using the context's current opacity, so if you
  21542. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  21543. (or setColour() with an opaque colour) before drawing images.
  21544. @param imageToDraw the image to overlay
  21545. @param destX the left of the destination rectangle
  21546. @param destY the top of the destination rectangle
  21547. @param destWidth the width of the destination rectangle
  21548. @param destHeight the height of the destination rectangle
  21549. @param sourceX the left of the rectangle to copy from the source image
  21550. @param sourceY the top of the rectangle to copy from the source image
  21551. @param sourceWidth the width of the rectangle to copy from the source image
  21552. @param sourceHeight the height of the rectangle to copy from the source image
  21553. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  21554. the source image's alpha channel is used as a mask with
  21555. which to fill the destination using the current colour
  21556. or brush. (If the source is has no alpha channel, then
  21557. it will just fill the target with a solid rectangle)
  21558. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  21559. */
  21560. void drawImage (const Image& imageToDraw,
  21561. int destX, int destY, int destWidth, int destHeight,
  21562. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  21563. bool fillAlphaChannelWithCurrentBrush = false) const;
  21564. /** Draws an image, having applied an affine transform to it.
  21565. This lets you throw the image around in some wacky ways, rotate it, shear,
  21566. scale it, etc.
  21567. Images are composited using the context's current opacity, so if you
  21568. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  21569. (or setColour() with an opaque colour) before drawing images.
  21570. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  21571. are ignored and it is filled with the current brush, masked by its alpha channel.
  21572. If you want to render only a subsection of an image, use Image::getClippedImage() to
  21573. create the section that you need.
  21574. @see setImageResamplingQuality, drawImage
  21575. */
  21576. void drawImageTransformed (const Image& imageToDraw,
  21577. const AffineTransform& transform,
  21578. bool fillAlphaChannelWithCurrentBrush = false) const;
  21579. /** Draws an image to fit within a designated rectangle.
  21580. If the image is too big or too small for the space, it will be rescaled
  21581. to fit as nicely as it can do without affecting its aspect ratio. It will
  21582. then be placed within the target rectangle according to the justification flags
  21583. specified.
  21584. @param imageToDraw the source image to draw
  21585. @param destX top-left of the target rectangle to fit it into
  21586. @param destY top-left of the target rectangle to fit it into
  21587. @param destWidth size of the target rectangle to fit the image into
  21588. @param destHeight size of the target rectangle to fit the image into
  21589. @param placementWithinTarget this specifies how the image should be positioned
  21590. within the target rectangle - see the RectanglePlacement
  21591. class for more details about this.
  21592. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  21593. alpha channel will be used as a mask with which to
  21594. draw with the current brush or colour. This is
  21595. similar to fillAlphaMap(), and see also drawImage()
  21596. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  21597. */
  21598. void drawImageWithin (const Image& imageToDraw,
  21599. int destX, int destY, int destWidth, int destHeight,
  21600. const RectanglePlacement& placementWithinTarget,
  21601. bool fillAlphaChannelWithCurrentBrush = false) const;
  21602. /** Returns the position of the bounding box for the current clipping region.
  21603. @see getClipRegion, clipRegionIntersects
  21604. */
  21605. const Rectangle<int> getClipBounds() const;
  21606. /** Checks whether a rectangle overlaps the context's clipping region.
  21607. If this returns false, no part of the given area can be drawn onto, so this
  21608. method can be used to optimise a component's paint() method, by letting it
  21609. avoid drawing complex objects that aren't within the region being repainted.
  21610. */
  21611. bool clipRegionIntersects (const Rectangle<int>& area) const;
  21612. /** Intersects the current clipping region with another region.
  21613. @returns true if the resulting clipping region is non-zero in size
  21614. @see setOrigin, clipRegionIntersects
  21615. */
  21616. bool reduceClipRegion (int x, int y, int width, int height);
  21617. /** Intersects the current clipping region with another region.
  21618. @returns true if the resulting clipping region is non-zero in size
  21619. @see setOrigin, clipRegionIntersects
  21620. */
  21621. bool reduceClipRegion (const Rectangle<int>& area);
  21622. /** Intersects the current clipping region with a rectangle list region.
  21623. @returns true if the resulting clipping region is non-zero in size
  21624. @see setOrigin, clipRegionIntersects
  21625. */
  21626. bool reduceClipRegion (const RectangleList& clipRegion);
  21627. /** Intersects the current clipping region with a path.
  21628. @returns true if the resulting clipping region is non-zero in size
  21629. @see reduceClipRegion
  21630. */
  21631. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  21632. /** Intersects the current clipping region with an image's alpha-channel.
  21633. The current clipping path is intersected with the area covered by this image's
  21634. alpha-channel, after the image has been transformed by the specified matrix.
  21635. @param image the image whose alpha-channel should be used. If the image doesn't
  21636. have an alpha-channel, it is treated as entirely opaque.
  21637. @param transform a matrix to apply to the image
  21638. @returns true if the resulting clipping region is non-zero in size
  21639. @see reduceClipRegion
  21640. */
  21641. bool reduceClipRegion (const Image& image, const AffineTransform& transform);
  21642. /** Excludes a rectangle to stop it being drawn into. */
  21643. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  21644. /** Returns true if no drawing can be done because the clip region is zero. */
  21645. bool isClipEmpty() const;
  21646. /** Saves the current graphics state on an internal stack.
  21647. To restore the state, use restoreState().
  21648. @see ScopedSaveState
  21649. */
  21650. void saveState();
  21651. /** Restores a graphics state that was previously saved with saveState().
  21652. @see ScopedSaveState
  21653. */
  21654. void restoreState();
  21655. /** Uses RAII to save and restore the state of a graphics context.
  21656. On construction, this calls Graphics::saveState(), and on destruction it calls
  21657. Graphics::restoreState() on the Graphics object that you supply.
  21658. */
  21659. class ScopedSaveState
  21660. {
  21661. public:
  21662. ScopedSaveState (Graphics& g);
  21663. ~ScopedSaveState();
  21664. private:
  21665. Graphics& context;
  21666. JUCE_DECLARE_NON_COPYABLE (ScopedSaveState);
  21667. };
  21668. /** Begins rendering to an off-screen bitmap which will later be flattened onto the current
  21669. context with the given opacity.
  21670. The context uses an internal stack of temporary image layers to do this. When you've
  21671. finished drawing to the layer, call endTransparencyLayer() to complete the operation and
  21672. composite the finished layer. Every call to beginTransparencyLayer() MUST be matched
  21673. by a corresponding call to endTransparencyLayer()!
  21674. This call also saves the current state, and endTransparencyLayer() restores it.
  21675. */
  21676. void beginTransparencyLayer (float layerOpacity);
  21677. /** Completes a drawing operation to a temporary semi-transparent buffer.
  21678. See beginTransparencyLayer() for more details.
  21679. */
  21680. void endTransparencyLayer();
  21681. /** Moves the position of the context's origin.
  21682. This changes the position that the context considers to be (0, 0) to
  21683. the specified position.
  21684. So if you call setOrigin (100, 100), then the position that was previously
  21685. referred to as (100, 100) will subsequently be considered to be (0, 0).
  21686. @see reduceClipRegion, addTransform
  21687. */
  21688. void setOrigin (int newOriginX, int newOriginY);
  21689. /** Adds a transformation which will be performed on all the graphics operations that
  21690. the context subsequently performs.
  21691. After calling this, all the coordinates that are passed into the context will be
  21692. transformed by this matrix.
  21693. @see setOrigin
  21694. */
  21695. void addTransform (const AffineTransform& transform);
  21696. /** Resets the current colour, brush, and font to default settings. */
  21697. void resetToDefaultState();
  21698. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  21699. bool isVectorDevice() const;
  21700. /** Create a graphics that uses a given low-level renderer.
  21701. For internal use only.
  21702. NB. The context will NOT be deleted by this object when it is deleted.
  21703. */
  21704. Graphics (LowLevelGraphicsContext* internalContext) throw();
  21705. /** @internal */
  21706. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  21707. private:
  21708. LowLevelGraphicsContext* const context;
  21709. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  21710. bool saveStatePending;
  21711. void saveStateIfPending();
  21712. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Graphics);
  21713. };
  21714. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  21715. /*** End of inlined file: juce_Graphics.h ***/
  21716. /**
  21717. A graphical effect filter that can be applied to components.
  21718. An ImageEffectFilter can be applied to the image that a component
  21719. paints before it hits the screen.
  21720. This is used for adding effects like shadows, blurs, etc.
  21721. @see Component::setComponentEffect
  21722. */
  21723. class JUCE_API ImageEffectFilter
  21724. {
  21725. public:
  21726. /** Overridden to render the effect.
  21727. The implementation of this method must use the image that is passed in
  21728. as its source, and should render its output to the graphics context passed in.
  21729. @param sourceImage the image that the source component has just rendered with
  21730. its paint() method. The image may or may not have an alpha
  21731. channel, depending on whether the component is opaque.
  21732. @param destContext the graphics context to use to draw the resultant image.
  21733. @param alpha the alpha with which to draw the resultant image to the
  21734. target context
  21735. */
  21736. virtual void applyEffect (Image& sourceImage,
  21737. Graphics& destContext,
  21738. float alpha) = 0;
  21739. /** Destructor. */
  21740. virtual ~ImageEffectFilter() {}
  21741. };
  21742. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  21743. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  21744. /*** Start of inlined file: juce_Image.h ***/
  21745. #ifndef __JUCE_IMAGE_JUCEHEADER__
  21746. #define __JUCE_IMAGE_JUCEHEADER__
  21747. /**
  21748. Holds a fixed-size bitmap.
  21749. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  21750. To draw into an image, create a Graphics object for it.
  21751. e.g. @code
  21752. // create a transparent 500x500 image..
  21753. Image myImage (Image::RGB, 500, 500, true);
  21754. Graphics g (myImage);
  21755. g.setColour (Colours::red);
  21756. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  21757. @endcode
  21758. Other useful ways to create an image are with the ImageCache class, or the
  21759. ImageFileFormat, which provides a way to load common image files.
  21760. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  21761. */
  21762. class JUCE_API Image
  21763. {
  21764. public:
  21765. /**
  21766. */
  21767. enum PixelFormat
  21768. {
  21769. UnknownFormat,
  21770. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  21771. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  21772. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  21773. };
  21774. /**
  21775. */
  21776. enum ImageType
  21777. {
  21778. SoftwareImage = 0,
  21779. NativeImage
  21780. };
  21781. /** Creates a null image. */
  21782. Image();
  21783. /** Creates an image with a specified size and format.
  21784. @param format the number of colour channels in the image
  21785. @param imageWidth the desired width of the image, in pixels - this value must be
  21786. greater than zero (otherwise a width of 1 will be used)
  21787. @param imageHeight the desired width of the image, in pixels - this value must be
  21788. greater than zero (otherwise a height of 1 will be used)
  21789. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  21790. or transparent black (if it's ARGB). If false, the image may contain
  21791. junk initially, so you need to make sure you overwrite it thoroughly.
  21792. @param type the type of image - this lets you specify whether you want a purely
  21793. memory-based image, or one that may be managed by the OS if possible.
  21794. */
  21795. Image (PixelFormat format,
  21796. int imageWidth,
  21797. int imageHeight,
  21798. bool clearImage,
  21799. ImageType type = NativeImage);
  21800. /** Creates a shared reference to another image.
  21801. This won't create a duplicate of the image - when Image objects are copied, they simply
  21802. point to the same shared image data. To make sure that an Image object has its own unique,
  21803. unshared internal data, call duplicateIfShared().
  21804. */
  21805. Image (const Image& other);
  21806. /** Makes this image refer to the same underlying image as another object.
  21807. This won't create a duplicate of the image - when Image objects are copied, they simply
  21808. point to the same shared image data. To make sure that an Image object has its own unique,
  21809. unshared internal data, call duplicateIfShared().
  21810. */
  21811. Image& operator= (const Image&);
  21812. /** Destructor. */
  21813. ~Image();
  21814. /** Returns true if the two images are referring to the same internal, shared image. */
  21815. bool operator== (const Image& other) const throw() { return image == other.image; }
  21816. /** Returns true if the two images are not referring to the same internal, shared image. */
  21817. bool operator!= (const Image& other) const throw() { return image != other.image; }
  21818. /** Returns true if this image isn't null.
  21819. If you create an Image with the default constructor, it has no size or content, and is null
  21820. until you reassign it to an Image which contains some actual data.
  21821. The isNull() method is the opposite of isValid().
  21822. @see isNull
  21823. */
  21824. inline bool isValid() const throw() { return image != 0; }
  21825. /** Returns true if this image is not valid.
  21826. If you create an Image with the default constructor, it has no size or content, and is null
  21827. until you reassign it to an Image which contains some actual data.
  21828. The isNull() method is the opposite of isValid().
  21829. @see isValid
  21830. */
  21831. inline bool isNull() const throw() { return image == 0; }
  21832. /** A null Image object that can be used when you need to return an invalid image.
  21833. This object is the equivalient to an Image created with the default constructor.
  21834. */
  21835. static const Image null;
  21836. /** Returns the image's width (in pixels). */
  21837. int getWidth() const throw() { return image == 0 ? 0 : image->width; }
  21838. /** Returns the image's height (in pixels). */
  21839. int getHeight() const throw() { return image == 0 ? 0 : image->height; }
  21840. /** Returns a rectangle with the same size as this image.
  21841. The rectangle's origin is always (0, 0).
  21842. */
  21843. const Rectangle<int> getBounds() const throw() { return image == 0 ? Rectangle<int>() : Rectangle<int> (image->width, image->height); }
  21844. /** Returns the image's pixel format. */
  21845. PixelFormat getFormat() const throw() { return image == 0 ? UnknownFormat : image->format; }
  21846. /** True if the image's format is ARGB. */
  21847. bool isARGB() const throw() { return getFormat() == ARGB; }
  21848. /** True if the image's format is RGB. */
  21849. bool isRGB() const throw() { return getFormat() == RGB; }
  21850. /** True if the image's format is a single-channel alpha map. */
  21851. bool isSingleChannel() const throw() { return getFormat() == SingleChannel; }
  21852. /** True if the image contains an alpha-channel. */
  21853. bool hasAlphaChannel() const throw() { return getFormat() != RGB; }
  21854. /** Clears a section of the image with a given colour.
  21855. This won't do any alpha-blending - it just sets all pixels in the image to
  21856. the given colour (which may be non-opaque if the image has an alpha channel).
  21857. */
  21858. void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  21859. /** Returns a rescaled version of this image.
  21860. A new image is returned which is a copy of this one, rescaled to the given size.
  21861. Note that if the new size is identical to the existing image, this will just return
  21862. a reference to the original image, and won't actually create a duplicate.
  21863. */
  21864. const Image rescaled (int newWidth, int newHeight,
  21865. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  21866. /** Returns a version of this image with a different image format.
  21867. A new image is returned which has been converted to the specified format.
  21868. Note that if the new format is no different to the current one, this will just return
  21869. a reference to the original image, and won't actually create a copy.
  21870. */
  21871. const Image convertedToFormat (PixelFormat newFormat) const;
  21872. /** Makes sure that no other Image objects share the same underlying data as this one.
  21873. If no other Image objects refer to the same shared data as this one, this method has no
  21874. effect. But if there are other references to the data, this will create a new copy of
  21875. the data internally.
  21876. Call this if you want to draw onto the image, but want to make sure that this doesn't
  21877. affect any other code that may be sharing the same data.
  21878. @see getReferenceCount
  21879. */
  21880. void duplicateIfShared();
  21881. /** Returns an image which refers to a subsection of this image.
  21882. This will not make a copy of the original - the new image will keep a reference to it, so that
  21883. if the original image is changed, the contents of the subsection will also change. Likewise if you
  21884. draw into the subimage, you'll also be drawing onto that area of the original image. Note that if
  21885. you use operator= to make the original Image object refer to something else, the subsection image
  21886. won't pick up this change, it'll remain pointing at the original.
  21887. The area passed-in will be clipped to the bounds of this image, so this may return a smaller
  21888. image than the area you asked for, or even a null image if the area was out-of-bounds.
  21889. */
  21890. const Image getClippedImage (const Rectangle<int>& area) const;
  21891. /** Returns the colour of one of the pixels in the image.
  21892. If the co-ordinates given are beyond the image's boundaries, this will
  21893. return Colours::transparentBlack.
  21894. @see setPixelAt, Image::BitmapData::getPixelColour
  21895. */
  21896. const Colour getPixelAt (int x, int y) const;
  21897. /** Sets the colour of one of the image's pixels.
  21898. If the co-ordinates are beyond the image's boundaries, then nothing will happen.
  21899. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  21900. with the given one. The colour's opacity will be ignored if this image doesn't have
  21901. an alpha-channel.
  21902. @see getPixelAt, Image::BitmapData::setPixelColour
  21903. */
  21904. void setPixelAt (int x, int y, const Colour& colour);
  21905. /** Changes the opacity of a pixel.
  21906. This only has an effect if the image has an alpha channel and if the
  21907. given co-ordinates are inside the image's boundary.
  21908. The multiplier must be in the range 0 to 1.0, and the current alpha
  21909. at the given co-ordinates will be multiplied by this value.
  21910. @see setPixelAt
  21911. */
  21912. void multiplyAlphaAt (int x, int y, float multiplier);
  21913. /** Changes the overall opacity of the image.
  21914. This will multiply the alpha value of each pixel in the image by the given
  21915. amount (limiting the resulting alpha values between 0 and 255). This allows
  21916. you to make an image more or less transparent.
  21917. If the image doesn't have an alpha channel, this won't have any effect.
  21918. */
  21919. void multiplyAllAlphas (float amountToMultiplyBy);
  21920. /** Changes all the colours to be shades of grey, based on their current luminosity.
  21921. */
  21922. void desaturate();
  21923. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  21924. You should only use this class as a last resort - messing about with the internals of
  21925. an image is only recommended for people who really know what they're doing!
  21926. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  21927. hanging around while the image is being used elsewhere.
  21928. Depending on the way the image class is implemented, this may create a temporary buffer
  21929. which is copied back to the image when the object is deleted, or it may just get a pointer
  21930. directly into the image's raw data.
  21931. You can use the stride and data values in this class directly, but don't alter them!
  21932. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  21933. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  21934. */
  21935. class BitmapData
  21936. {
  21937. public:
  21938. BitmapData (Image& image, int x, int y, int w, int h, bool needsToBeWritable);
  21939. BitmapData (const Image& image, int x, int y, int w, int h);
  21940. BitmapData (const Image& image, bool needsToBeWritable);
  21941. ~BitmapData();
  21942. /** Returns a pointer to the start of a line in the image.
  21943. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  21944. sure it's not out-of-range.
  21945. */
  21946. inline uint8* getLinePointer (int y) const throw() { return data + y * lineStride; }
  21947. /** Returns a pointer to a pixel in the image.
  21948. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  21949. not out-of-range.
  21950. */
  21951. inline uint8* getPixelPointer (int x, int y) const throw() { return data + y * lineStride + x * pixelStride; }
  21952. /** Returns the colour of a given pixel.
  21953. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  21954. repsonsibility to make sure they're within the image's size.
  21955. */
  21956. const Colour getPixelColour (int x, int y) const throw();
  21957. /** Sets the colour of a given pixel.
  21958. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  21959. repsonsibility to make sure they're within the image's size.
  21960. */
  21961. void setPixelColour (int x, int y, const Colour& colour) const throw();
  21962. uint8* data;
  21963. const PixelFormat pixelFormat;
  21964. int lineStride, pixelStride, width, height;
  21965. private:
  21966. JUCE_DECLARE_NON_COPYABLE (BitmapData);
  21967. };
  21968. /** Copies some pixel values to a rectangle of the image.
  21969. The format of the pixel data must match that of the image itself, and the
  21970. rectangle supplied must be within the image's bounds.
  21971. */
  21972. void setPixelData (int destX, int destY, int destW, int destH,
  21973. const uint8* sourcePixelData, int sourceLineStride);
  21974. /** Copies a section of the image to somewhere else within itself. */
  21975. void moveImageSection (int destX, int destY,
  21976. int sourceX, int sourceY,
  21977. int width, int height);
  21978. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  21979. of the image.
  21980. @param result the list that will have the area added to it
  21981. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  21982. above this level will be considered opaque
  21983. */
  21984. void createSolidAreaMask (RectangleList& result,
  21985. float alphaThreshold = 0.5f) const;
  21986. /** Returns a NamedValueSet that is attached to the image and which can be used for
  21987. associating custom values with it.
  21988. If this is a null image, this will return a null pointer.
  21989. */
  21990. NamedValueSet* getProperties() const;
  21991. /** Creates a context suitable for drawing onto this image.
  21992. Don't call this method directly! It's used internally by the Graphics class.
  21993. */
  21994. LowLevelGraphicsContext* createLowLevelContext() const;
  21995. /** Returns the number of Image objects which are currently referring to the same internal
  21996. shared image data.
  21997. @see duplicateIfShared
  21998. */
  21999. int getReferenceCount() const throw() { return image == 0 ? 0 : image->getReferenceCount(); }
  22000. /** This is a base class for task-specific types of image.
  22001. Don't use this class directly! It's used internally by the Image class.
  22002. */
  22003. class SharedImage : public ReferenceCountedObject
  22004. {
  22005. public:
  22006. SharedImage (PixelFormat format, int width, int height);
  22007. ~SharedImage();
  22008. virtual LowLevelGraphicsContext* createLowLevelContext() = 0;
  22009. virtual SharedImage* clone() = 0;
  22010. virtual ImageType getType() const = 0;
  22011. static SharedImage* createNativeImage (PixelFormat format, int width, int height, bool clearImage);
  22012. static SharedImage* createSoftwareImage (PixelFormat format, int width, int height, bool clearImage);
  22013. const PixelFormat getPixelFormat() const throw() { return format; }
  22014. int getWidth() const throw() { return width; }
  22015. int getHeight() const throw() { return height; }
  22016. int getPixelStride() const throw() { return pixelStride; }
  22017. int getLineStride() const throw() { return lineStride; }
  22018. uint8* getPixelData (int x, int y) const throw();
  22019. protected:
  22020. friend class Image;
  22021. friend class BitmapData;
  22022. const PixelFormat format;
  22023. const int width, height;
  22024. int pixelStride, lineStride;
  22025. uint8* imageData;
  22026. NamedValueSet userData;
  22027. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedImage);
  22028. };
  22029. /** @internal */
  22030. SharedImage* getSharedImage() const throw() { return image; }
  22031. /** @internal */
  22032. explicit Image (SharedImage* instance);
  22033. private:
  22034. friend class SharedImage;
  22035. friend class BitmapData;
  22036. ReferenceCountedObjectPtr<SharedImage> image;
  22037. JUCE_LEAK_DETECTOR (Image);
  22038. };
  22039. #endif // __JUCE_IMAGE_JUCEHEADER__
  22040. /*** End of inlined file: juce_Image.h ***/
  22041. /*** Start of inlined file: juce_RectangleList.h ***/
  22042. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  22043. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  22044. /**
  22045. Maintains a set of rectangles as a complex region.
  22046. This class allows a set of rectangles to be treated as a solid shape, and can
  22047. add and remove rectangular sections of it, and simplify overlapping or
  22048. adjacent rectangles.
  22049. @see Rectangle
  22050. */
  22051. class JUCE_API RectangleList
  22052. {
  22053. public:
  22054. /** Creates an empty RectangleList */
  22055. RectangleList() throw();
  22056. /** Creates a copy of another list */
  22057. RectangleList (const RectangleList& other);
  22058. /** Creates a list containing just one rectangle. */
  22059. RectangleList (const Rectangle<int>& rect);
  22060. /** Copies this list from another one. */
  22061. RectangleList& operator= (const RectangleList& other);
  22062. /** Destructor. */
  22063. ~RectangleList();
  22064. /** Returns true if the region is empty. */
  22065. bool isEmpty() const throw();
  22066. /** Returns the number of rectangles in the list. */
  22067. int getNumRectangles() const throw() { return rects.size(); }
  22068. /** Returns one of the rectangles at a particular index.
  22069. @returns the rectangle at the index, or an empty rectangle if the
  22070. index is out-of-range.
  22071. */
  22072. const Rectangle<int> getRectangle (int index) const throw();
  22073. /** Removes all rectangles to leave an empty region. */
  22074. void clear();
  22075. /** Merges a new rectangle into the list.
  22076. The rectangle being added will first be clipped to remove any parts of it
  22077. that overlap existing rectangles in the list.
  22078. */
  22079. void add (int x, int y, int width, int height);
  22080. /** Merges a new rectangle into the list.
  22081. The rectangle being added will first be clipped to remove any parts of it
  22082. that overlap existing rectangles in the list, and adjacent rectangles will be
  22083. merged into it.
  22084. */
  22085. void add (const Rectangle<int>& rect);
  22086. /** Dumbly adds a rectangle to the list without checking for overlaps.
  22087. This simply adds the rectangle to the end, it doesn't merge it or remove
  22088. any overlapping bits.
  22089. */
  22090. void addWithoutMerging (const Rectangle<int>& rect);
  22091. /** Merges another rectangle list into this one.
  22092. Any overlaps between the two lists will be clipped, so that the result is
  22093. the union of both lists.
  22094. */
  22095. void add (const RectangleList& other);
  22096. /** Removes a rectangular region from the list.
  22097. Any rectangles in the list which overlap this will be clipped and subdivided
  22098. if necessary.
  22099. */
  22100. void subtract (const Rectangle<int>& rect);
  22101. /** Removes all areas in another RectangleList from this one.
  22102. Any rectangles in the list which overlap this will be clipped and subdivided
  22103. if necessary.
  22104. @returns true if the resulting list is non-empty.
  22105. */
  22106. bool subtract (const RectangleList& otherList);
  22107. /** Removes any areas of the region that lie outside a given rectangle.
  22108. Any rectangles in the list which overlap this will be clipped and subdivided
  22109. if necessary.
  22110. Returns true if the resulting region is not empty, false if it is empty.
  22111. @see getIntersectionWith
  22112. */
  22113. bool clipTo (const Rectangle<int>& rect);
  22114. /** Removes any areas of the region that lie outside a given rectangle list.
  22115. Any rectangles in this object which overlap the specified list will be clipped
  22116. and subdivided if necessary.
  22117. Returns true if the resulting region is not empty, false if it is empty.
  22118. @see getIntersectionWith
  22119. */
  22120. bool clipTo (const RectangleList& other);
  22121. /** Creates a region which is the result of clipping this one to a given rectangle.
  22122. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  22123. resulting region into the list whose reference is passed-in.
  22124. Returns true if the resulting region is not empty, false if it is empty.
  22125. @see clipTo
  22126. */
  22127. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  22128. /** Swaps the contents of this and another list.
  22129. This swaps their internal pointers, so is hugely faster than using copy-by-value
  22130. to swap them.
  22131. */
  22132. void swapWith (RectangleList& otherList) throw();
  22133. /** Checks whether the region contains a given point.
  22134. @returns true if the point lies within one of the rectangles in the list
  22135. */
  22136. bool containsPoint (int x, int y) const throw();
  22137. /** Checks whether the region contains the whole of a given rectangle.
  22138. @returns true all parts of the rectangle passed in lie within the region
  22139. defined by this object
  22140. @see intersectsRectangle, containsPoint
  22141. */
  22142. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  22143. /** Checks whether the region contains any part of a given rectangle.
  22144. @returns true if any part of the rectangle passed in lies within the region
  22145. defined by this object
  22146. @see containsRectangle
  22147. */
  22148. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw();
  22149. /** Checks whether this region intersects any part of another one.
  22150. @see intersectsRectangle
  22151. */
  22152. bool intersects (const RectangleList& other) const throw();
  22153. /** Returns the smallest rectangle that can enclose the whole of this region. */
  22154. const Rectangle<int> getBounds() const throw();
  22155. /** Optimises the list into a minimum number of constituent rectangles.
  22156. This will try to combine any adjacent rectangles into larger ones where
  22157. possible, to simplify lists that might have been fragmented by repeated
  22158. add/subtract calls.
  22159. */
  22160. void consolidate();
  22161. /** Adds an x and y value to all the co-ordinates. */
  22162. void offsetAll (int dx, int dy) throw();
  22163. /** Creates a Path object to represent this region. */
  22164. const Path toPath() const;
  22165. /** An iterator for accessing all the rectangles in a RectangleList. */
  22166. class Iterator
  22167. {
  22168. public:
  22169. Iterator (const RectangleList& list) throw();
  22170. ~Iterator();
  22171. /** Advances to the next rectangle, and returns true if it's not finished.
  22172. Call this before using getRectangle() to find the rectangle that was returned.
  22173. */
  22174. bool next() throw();
  22175. /** Returns the current rectangle. */
  22176. const Rectangle<int>* getRectangle() const throw() { return current; }
  22177. private:
  22178. const Rectangle<int>* current;
  22179. const RectangleList& owner;
  22180. int index;
  22181. JUCE_DECLARE_NON_COPYABLE (Iterator);
  22182. };
  22183. private:
  22184. friend class Iterator;
  22185. Array <Rectangle<int> > rects;
  22186. JUCE_LEAK_DETECTOR (RectangleList);
  22187. };
  22188. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  22189. /*** End of inlined file: juce_RectangleList.h ***/
  22190. /*** Start of inlined file: juce_BorderSize.h ***/
  22191. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  22192. #define __JUCE_BORDERSIZE_JUCEHEADER__
  22193. /**
  22194. Specifies a set of gaps to be left around the sides of a rectangle.
  22195. This is basically the size of the spaces at the top, bottom, left and right of
  22196. a rectangle. It's used by various component classes to specify borders.
  22197. @see Rectangle
  22198. */
  22199. template <typename ValueType>
  22200. class BorderSize
  22201. {
  22202. public:
  22203. /** Creates a null border.
  22204. All sizes are left as 0.
  22205. */
  22206. BorderSize() throw()
  22207. : top(), left(), bottom(), right()
  22208. {
  22209. }
  22210. /** Creates a copy of another border. */
  22211. BorderSize (const BorderSize& other) throw()
  22212. : top (other.top), left (other.left), bottom (other.bottom), right (other.right)
  22213. {
  22214. }
  22215. /** Creates a border with the given gaps. */
  22216. BorderSize (ValueType topGap, ValueType leftGap, ValueType bottomGap, ValueType rightGap) throw()
  22217. : top (topGap), left (leftGap), bottom (bottomGap), right (rightGap)
  22218. {
  22219. }
  22220. /** Creates a border with the given gap on all sides. */
  22221. explicit BorderSize (ValueType allGaps) throw()
  22222. : top (allGaps), left (allGaps), bottom (allGaps), right (allGaps)
  22223. {
  22224. }
  22225. /** Returns the gap that should be left at the top of the region. */
  22226. ValueType getTop() const throw() { return top; }
  22227. /** Returns the gap that should be left at the top of the region. */
  22228. ValueType getLeft() const throw() { return left; }
  22229. /** Returns the gap that should be left at the top of the region. */
  22230. ValueType getBottom() const throw() { return bottom; }
  22231. /** Returns the gap that should be left at the top of the region. */
  22232. ValueType getRight() const throw() { return right; }
  22233. /** Returns the sum of the top and bottom gaps. */
  22234. ValueType getTopAndBottom() const throw() { return top + bottom; }
  22235. /** Returns the sum of the left and right gaps. */
  22236. ValueType getLeftAndRight() const throw() { return left + right; }
  22237. /** Returns true if this border has no thickness along any edge. */
  22238. bool isEmpty() const throw() { return left + right + top + bottom == ValueType(); }
  22239. /** Changes the top gap. */
  22240. void setTop (ValueType newTopGap) throw() { top = newTopGap; }
  22241. /** Changes the left gap. */
  22242. void setLeft (ValueType newLeftGap) throw() { left = newLeftGap; }
  22243. /** Changes the bottom gap. */
  22244. void setBottom (ValueType newBottomGap) throw() { bottom = newBottomGap; }
  22245. /** Changes the right gap. */
  22246. void setRight (ValueType newRightGap) throw() { right = newRightGap; }
  22247. /** Returns a rectangle with these borders removed from it. */
  22248. const Rectangle<ValueType> subtractedFrom (const Rectangle<ValueType>& original) const throw()
  22249. {
  22250. return Rectangle<ValueType> (original.getX() + left,
  22251. original.getY() + top,
  22252. original.getWidth() - (left + right),
  22253. original.getHeight() - (top + bottom));
  22254. }
  22255. /** Removes this border from a given rectangle. */
  22256. void subtractFrom (Rectangle<ValueType>& rectangle) const throw()
  22257. {
  22258. rectangle = subtractedFrom (rectangle);
  22259. }
  22260. /** Returns a rectangle with these borders added around it. */
  22261. const Rectangle<ValueType> addedTo (const Rectangle<ValueType>& original) const throw()
  22262. {
  22263. return Rectangle<ValueType> (original.getX() - left,
  22264. original.getY() - top,
  22265. original.getWidth() + (left + right),
  22266. original.getHeight() + (top + bottom));
  22267. }
  22268. /** Adds this border around a given rectangle. */
  22269. void addTo (Rectangle<ValueType>& rectangle) const throw()
  22270. {
  22271. rectangle = addedTo (rectangle);
  22272. }
  22273. bool operator== (const BorderSize& other) const throw()
  22274. {
  22275. return top == other.top && left == other.left && bottom == other.bottom && right == other.right;
  22276. }
  22277. bool operator!= (const BorderSize& other) const throw()
  22278. {
  22279. return ! operator== (other);
  22280. }
  22281. private:
  22282. ValueType top, left, bottom, right;
  22283. JUCE_LEAK_DETECTOR (BorderSize);
  22284. };
  22285. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  22286. /*** End of inlined file: juce_BorderSize.h ***/
  22287. /*** Start of inlined file: juce_ModalComponentManager.h ***/
  22288. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  22289. #define __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  22290. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  22291. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  22292. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  22293. /**
  22294. Classes derived from this will be automatically deleted when the application exits.
  22295. After JUCEApplication::shutdown() has been called, any objects derived from
  22296. DeletedAtShutdown which are still in existence will be deleted in the reverse
  22297. order to that in which they were created.
  22298. So if you've got a singleton and don't want to have to explicitly delete it, just
  22299. inherit from this and it'll be taken care of.
  22300. */
  22301. class JUCE_API DeletedAtShutdown
  22302. {
  22303. protected:
  22304. /** Creates a DeletedAtShutdown object. */
  22305. DeletedAtShutdown();
  22306. /** Destructor.
  22307. It's ok to delete these objects explicitly - it's only the ones left
  22308. dangling at the end that will be deleted automatically.
  22309. */
  22310. virtual ~DeletedAtShutdown();
  22311. public:
  22312. /** Deletes all extant objects.
  22313. This shouldn't be used by applications, as it's called automatically
  22314. in the shutdown code of the JUCEApplication class.
  22315. */
  22316. static void deleteAll();
  22317. private:
  22318. static CriticalSection& getLock();
  22319. static Array <DeletedAtShutdown*>& getObjects();
  22320. JUCE_DECLARE_NON_COPYABLE (DeletedAtShutdown);
  22321. };
  22322. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  22323. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  22324. /**
  22325. Manages the system's stack of modal components.
  22326. Normally you'll just use the Component methods to invoke modal states in components,
  22327. and won't have to deal with this class directly, but this is the singleton object that's
  22328. used internally to manage the stack.
  22329. @see Component::enterModalState, Component::exitModalState, Component::isCurrentlyModal,
  22330. Component::getCurrentlyModalComponent, Component::isCurrentlyBlockedByAnotherModalComponent
  22331. */
  22332. class JUCE_API ModalComponentManager : public AsyncUpdater,
  22333. public DeletedAtShutdown
  22334. {
  22335. public:
  22336. /** Receives callbacks when a modal component is dismissed.
  22337. You can register a callback using Component::enterModalState() or
  22338. ModalComponentManager::attachCallback().
  22339. */
  22340. class Callback
  22341. {
  22342. public:
  22343. /** */
  22344. Callback() {}
  22345. /** Destructor. */
  22346. virtual ~Callback() {}
  22347. /** Called to indicate that a modal component has been dismissed.
  22348. You can register a callback using Component::enterModalState() or
  22349. ModalComponentManager::attachCallback().
  22350. The returnValue parameter is the value that was passed to Component::exitModalState()
  22351. when the component was dismissed.
  22352. The callback object will be deleted shortly after this method is called.
  22353. */
  22354. virtual void modalStateFinished (int returnValue) = 0;
  22355. };
  22356. /** Returns the number of components currently being shown modally.
  22357. @see getModalComponent
  22358. */
  22359. int getNumModalComponents() const;
  22360. /** Returns one of the components being shown modally.
  22361. An index of 0 is the most recently-shown, topmost component.
  22362. */
  22363. Component* getModalComponent (int index) const;
  22364. /** Returns true if the specified component is in a modal state. */
  22365. bool isModal (Component* component) const;
  22366. /** Returns true if the specified component is currently the topmost modal component. */
  22367. bool isFrontModalComponent (Component* component) const;
  22368. /** Adds a new callback that will be called when the specified modal component is dismissed.
  22369. If the component is modal, then when it is dismissed, either by being hidden, or by calling
  22370. Component::exitModalState(), then the Callback::modalStateFinished() method will be
  22371. called.
  22372. Each component can have any number of callbacks associated with it, and this one is added
  22373. to that list.
  22374. The object that is passed in will be deleted by the manager when it's no longer needed. If
  22375. the given component is not currently modal, the callback object is deleted immediately and
  22376. no action is taken.
  22377. */
  22378. void attachCallback (Component* component, Callback* callback);
  22379. /** Brings any modal components to the front. */
  22380. void bringModalComponentsToFront();
  22381. /** Runs the event loop until the currently topmost modal component is dismissed, and
  22382. returns the exit code for that component.
  22383. */
  22384. int runEventLoopForCurrentComponent();
  22385. juce_DeclareSingleton_SingleThreaded_Minimal (ModalComponentManager);
  22386. protected:
  22387. /** Creates a ModalComponentManager.
  22388. You shouldn't ever call the constructor - it's a singleton, so use ModalComponentManager::getInstance()
  22389. */
  22390. ModalComponentManager();
  22391. /** Destructor. */
  22392. ~ModalComponentManager();
  22393. /** @internal */
  22394. void handleAsyncUpdate();
  22395. private:
  22396. class ModalItem;
  22397. class ReturnValueRetriever;
  22398. friend class Component;
  22399. friend class OwnedArray <ModalItem>;
  22400. OwnedArray <ModalItem> stack;
  22401. void startModal (Component* component, Callback* callback);
  22402. void endModal (Component* component, int returnValue);
  22403. void endModal (Component* component);
  22404. JUCE_DECLARE_NON_COPYABLE (ModalComponentManager);
  22405. };
  22406. #endif // __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  22407. /*** End of inlined file: juce_ModalComponentManager.h ***/
  22408. class LookAndFeel;
  22409. class MouseInputSource;
  22410. class MouseInputSourceInternal;
  22411. class ComponentPeer;
  22412. class MarkerList;
  22413. class RelativeRectangle;
  22414. /**
  22415. The base class for all JUCE user-interface objects.
  22416. */
  22417. class JUCE_API Component : public MouseListener
  22418. {
  22419. public:
  22420. /** Creates a component.
  22421. To get it to actually appear, you'll also need to:
  22422. - Either add it to a parent component or use the addToDesktop() method to
  22423. make it a desktop window
  22424. - Set its size and position to something sensible
  22425. - Use setVisible() to make it visible
  22426. And for it to serve any useful purpose, you'll need to write a
  22427. subclass of Component or use one of the other types of component from
  22428. the library.
  22429. */
  22430. Component();
  22431. /** Destructor.
  22432. Note that when a component is deleted, any child components it contains are NOT
  22433. automatically deleted. It's your responsibilty to manage their lifespan - you
  22434. may want to use helper methods like deleteAllChildren(), or less haphazard
  22435. approaches like using ScopedPointers or normal object aggregation to manage them.
  22436. If the component being deleted is currently the child of another one, then during
  22437. deletion, it will be removed from its parent, and the parent will receive a childrenChanged()
  22438. callback. Any ComponentListener objects that have registered with it will also have their
  22439. ComponentListener::componentBeingDeleted() methods called.
  22440. */
  22441. virtual ~Component();
  22442. /** Creates a component, setting its name at the same time.
  22443. @see getName, setName
  22444. */
  22445. explicit Component (const String& componentName);
  22446. /** Returns the name of this component.
  22447. @see setName
  22448. */
  22449. const String& getName() const throw() { return componentName; }
  22450. /** Sets the name of this component.
  22451. When the name changes, all registered ComponentListeners will receive a
  22452. ComponentListener::componentNameChanged() callback.
  22453. @see getName
  22454. */
  22455. virtual void setName (const String& newName);
  22456. /** Returns the ID string that was set by setComponentID().
  22457. @see setComponentID
  22458. */
  22459. const String& getComponentID() const throw() { return componentID; }
  22460. /** Sets the component's ID string.
  22461. You can retrieve the ID using getComponentID().
  22462. @see getComponentID
  22463. */
  22464. void setComponentID (const String& newID);
  22465. /** Makes the component visible or invisible.
  22466. This method will show or hide the component.
  22467. Note that components default to being non-visible when first created.
  22468. Also note that visible components won't be seen unless all their parent components
  22469. are also visible.
  22470. This method will call visibilityChanged() and also componentVisibilityChanged()
  22471. for any component listeners that are interested in this component.
  22472. @param shouldBeVisible whether to show or hide the component
  22473. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  22474. */
  22475. virtual void setVisible (bool shouldBeVisible);
  22476. /** Tests whether the component is visible or not.
  22477. this doesn't necessarily tell you whether this comp is actually on the screen
  22478. because this depends on whether all the parent components are also visible - use
  22479. isShowing() to find this out.
  22480. @see isShowing, setVisible
  22481. */
  22482. bool isVisible() const throw() { return flags.visibleFlag; }
  22483. /** Called when this component's visiblility changes.
  22484. @see setVisible, isVisible
  22485. */
  22486. virtual void visibilityChanged();
  22487. /** Tests whether this component and all its parents are visible.
  22488. @returns true only if this component and all its parents are visible.
  22489. @see isVisible
  22490. */
  22491. bool isShowing() const;
  22492. /** Makes this component appear as a window on the desktop.
  22493. Note that before calling this, you should make sure that the component's opacity is
  22494. set correctly using setOpaque(). If the component is non-opaque, the windowing
  22495. system will try to create a special transparent window for it, which will generally take
  22496. a lot more CPU to operate (and might not even be possible on some platforms).
  22497. If the component is inside a parent component at the time this method is called, it
  22498. will be first be removed from that parent. Likewise if a component on the desktop
  22499. is subsequently added to another component, it'll be removed from the desktop.
  22500. @param windowStyleFlags a combination of the flags specified in the
  22501. ComponentPeer::StyleFlags enum, which define the
  22502. window's characteristics.
  22503. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  22504. in which the juce component should place itself. On Windows,
  22505. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  22506. supported on all platforms, and best left as 0 unless you know
  22507. what you're doing
  22508. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  22509. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  22510. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  22511. */
  22512. virtual void addToDesktop (int windowStyleFlags,
  22513. void* nativeWindowToAttachTo = 0);
  22514. /** If the component is currently showing on the desktop, this will hide it.
  22515. You can also use setVisible() to hide a desktop window temporarily, but
  22516. removeFromDesktop() will free any system resources that are being used up.
  22517. @see addToDesktop, isOnDesktop
  22518. */
  22519. void removeFromDesktop();
  22520. /** Returns true if this component is currently showing on the desktop.
  22521. @see addToDesktop, removeFromDesktop
  22522. */
  22523. bool isOnDesktop() const throw();
  22524. /** Returns the heavyweight window that contains this component.
  22525. If this component is itself on the desktop, this will return the window
  22526. object that it is using. Otherwise, it will return the window of
  22527. its top-level parent component.
  22528. This may return 0 if there isn't a desktop component.
  22529. @see addToDesktop, isOnDesktop
  22530. */
  22531. ComponentPeer* getPeer() const;
  22532. /** For components on the desktop, this is called if the system wants to close the window.
  22533. This is a signal that either the user or the system wants the window to close. The
  22534. default implementation of this method will trigger an assertion to warn you that your
  22535. component should do something about it, but you can override this to ignore the event
  22536. if you want.
  22537. */
  22538. virtual void userTriedToCloseWindow();
  22539. /** Called for a desktop component which has just been minimised or un-minimised.
  22540. This will only be called for components on the desktop.
  22541. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  22542. */
  22543. virtual void minimisationStateChanged (bool isNowMinimised);
  22544. /** Brings the component to the front of its siblings.
  22545. If some of the component's siblings have had their 'always-on-top' flag set,
  22546. then they will still be kept in front of this one (unless of course this
  22547. one is also 'always-on-top').
  22548. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  22549. to the component (see grabKeyboardFocus() for more details)
  22550. @see toBack, toBehind, setAlwaysOnTop
  22551. */
  22552. void toFront (bool shouldAlsoGainFocus);
  22553. /** Changes this component's z-order to be at the back of all its siblings.
  22554. If the component is set to be 'always-on-top', it will only be moved to the
  22555. back of the other other 'always-on-top' components.
  22556. @see toFront, toBehind, setAlwaysOnTop
  22557. */
  22558. void toBack();
  22559. /** Changes this component's z-order so that it's just behind another component.
  22560. @see toFront, toBack
  22561. */
  22562. void toBehind (Component* other);
  22563. /** Sets whether the component should always be kept at the front of its siblings.
  22564. @see isAlwaysOnTop
  22565. */
  22566. void setAlwaysOnTop (bool shouldStayOnTop);
  22567. /** Returns true if this component is set to always stay in front of its siblings.
  22568. @see setAlwaysOnTop
  22569. */
  22570. bool isAlwaysOnTop() const throw();
  22571. /** Returns the x coordinate of the component's left edge.
  22572. This is a distance in pixels from the left edge of the component's parent.
  22573. Note that if you've used setTransform() to apply a transform, then the component's
  22574. bounds will no longer be a direct reflection of the position at which it appears within
  22575. its parent, as the transform will be applied to its bounding box.
  22576. */
  22577. inline int getX() const throw() { return bounds.getX(); }
  22578. /** Returns the y coordinate of the top of this component.
  22579. This is a distance in pixels from the top edge of the component's parent.
  22580. Note that if you've used setTransform() to apply a transform, then the component's
  22581. bounds will no longer be a direct reflection of the position at which it appears within
  22582. its parent, as the transform will be applied to its bounding box.
  22583. */
  22584. inline int getY() const throw() { return bounds.getY(); }
  22585. /** Returns the component's width in pixels. */
  22586. inline int getWidth() const throw() { return bounds.getWidth(); }
  22587. /** Returns the component's height in pixels. */
  22588. inline int getHeight() const throw() { return bounds.getHeight(); }
  22589. /** Returns the x coordinate of the component's right-hand edge.
  22590. This is a distance in pixels from the left edge of the component's parent.
  22591. Note that if you've used setTransform() to apply a transform, then the component's
  22592. bounds will no longer be a direct reflection of the position at which it appears within
  22593. its parent, as the transform will be applied to its bounding box.
  22594. */
  22595. int getRight() const throw() { return bounds.getRight(); }
  22596. /** Returns the component's top-left position as a Point. */
  22597. const Point<int> getPosition() const throw() { return bounds.getPosition(); }
  22598. /** Returns the y coordinate of the bottom edge of this component.
  22599. This is a distance in pixels from the top edge of the component's parent.
  22600. Note that if you've used setTransform() to apply a transform, then the component's
  22601. bounds will no longer be a direct reflection of the position at which it appears within
  22602. its parent, as the transform will be applied to its bounding box.
  22603. */
  22604. int getBottom() const throw() { return bounds.getBottom(); }
  22605. /** Returns this component's bounding box.
  22606. The rectangle returned is relative to the top-left of the component's parent.
  22607. Note that if you've used setTransform() to apply a transform, then the component's
  22608. bounds will no longer be a direct reflection of the position at which it appears within
  22609. its parent, as the transform will be applied to its bounding box.
  22610. */
  22611. const Rectangle<int>& getBounds() const throw() { return bounds; }
  22612. /** Returns the component's bounds, relative to its own origin.
  22613. This is like getBounds(), but returns the rectangle in local coordinates, In practice, it'll
  22614. return a rectangle with position (0, 0), and the same size as this component.
  22615. */
  22616. const Rectangle<int> getLocalBounds() const throw();
  22617. /** Returns the area of this component's parent which this component covers.
  22618. The returned area is relative to the parent's coordinate space.
  22619. If the component has an affine transform specified, then the resulting area will be
  22620. the smallest rectangle that fully covers the component's transformed bounding box.
  22621. If this component has no parent, the return value will simply be the same as getBounds().
  22622. */
  22623. const Rectangle<int> getBoundsInParent() const throw();
  22624. /** Returns the region of this component that's not obscured by other, opaque components.
  22625. The RectangleList that is returned represents the area of this component
  22626. which isn't covered by opaque child components.
  22627. If includeSiblings is true, it will also take into account any siblings
  22628. that may be overlapping the component.
  22629. */
  22630. void getVisibleArea (RectangleList& result,
  22631. bool includeSiblings) const;
  22632. /** Returns this component's x coordinate relative the the screen's top-left origin.
  22633. @see getX, localPointToGlobal
  22634. */
  22635. int getScreenX() const;
  22636. /** Returns this component's y coordinate relative the the screen's top-left origin.
  22637. @see getY, localPointToGlobal
  22638. */
  22639. int getScreenY() const;
  22640. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  22641. @see getScreenBounds
  22642. */
  22643. const Point<int> getScreenPosition() const;
  22644. /** Returns the bounds of this component, relative to the screen's top-left.
  22645. @see getScreenPosition
  22646. */
  22647. const Rectangle<int> getScreenBounds() const;
  22648. /** Converts a point to be relative to this component's coordinate space.
  22649. This takes a point relative to a different component, and returns its position relative to this
  22650. component. If the sourceComponent parameter is null, the source point is assumed to be a global
  22651. screen coordinate.
  22652. */
  22653. const Point<int> getLocalPoint (const Component* sourceComponent,
  22654. const Point<int>& pointRelativeToSourceComponent) const;
  22655. /** Converts a rectangle to be relative to this component's coordinate space.
  22656. This takes a rectangle that is relative to a different component, and returns its position relative
  22657. to this component. If the sourceComponent parameter is null, the source rectangle is assumed to be
  22658. a screen coordinate.
  22659. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  22660. may not actually be rectanglular when converted to the target space, so in that situation this will return
  22661. the smallest rectangle that fully contains the transformed area.
  22662. */
  22663. const Rectangle<int> getLocalArea (const Component* sourceComponent,
  22664. const Rectangle<int>& areaRelativeToSourceComponent) const;
  22665. /** Converts a point relative to this component's top-left into a screen coordinate.
  22666. @see getLocalPoint, localAreaToGlobal
  22667. */
  22668. const Point<int> localPointToGlobal (const Point<int>& localPoint) const;
  22669. /** Converts a rectangle from this component's coordinate space to a screen coordinate.
  22670. If you've used setTransform() to apply one or more transforms to components, then the source rectangle
  22671. may not actually be rectanglular when converted to the target space, so in that situation this will return
  22672. the smallest rectangle that fully contains the transformed area.
  22673. @see getLocalPoint, localPointToGlobal
  22674. */
  22675. const Rectangle<int> localAreaToGlobal (const Rectangle<int>& localArea) const;
  22676. /** Moves the component to a new position.
  22677. Changes the component's top-left position (without changing its size).
  22678. The position is relative to the top-left of the component's parent.
  22679. If the component actually moves, this method will make a synchronous call to moved().
  22680. Note that if you've used setTransform() to apply a transform, then the component's
  22681. bounds will no longer be a direct reflection of the position at which it appears within
  22682. its parent, as the transform will be applied to whatever bounds you set for it.
  22683. @see setBounds, ComponentListener::componentMovedOrResized
  22684. */
  22685. void setTopLeftPosition (int x, int y);
  22686. /** Moves the component to a new position.
  22687. Changes the position of the component's top-right corner (keeping it the same size).
  22688. The position is relative to the top-left of the component's parent.
  22689. If the component actually moves, this method will make a synchronous call to moved().
  22690. Note that if you've used setTransform() to apply a transform, then the component's
  22691. bounds will no longer be a direct reflection of the position at which it appears within
  22692. its parent, as the transform will be applied to whatever bounds you set for it.
  22693. */
  22694. void setTopRightPosition (int x, int y);
  22695. /** Changes the size of the component.
  22696. A synchronous call to resized() will be occur if the size actually changes.
  22697. Note that if you've used setTransform() to apply a transform, then the component's
  22698. bounds will no longer be a direct reflection of the position at which it appears within
  22699. its parent, as the transform will be applied to whatever bounds you set for it.
  22700. */
  22701. void setSize (int newWidth, int newHeight);
  22702. /** Changes the component's position and size.
  22703. The coordinates are relative to the top-left of the component's parent, or relative
  22704. to the origin of the screen is the component is on the desktop.
  22705. If this method changes the component's top-left position, it will make a synchronous
  22706. call to moved(). If it changes the size, it will also make a call to resized().
  22707. Note that if you've used setTransform() to apply a transform, then the component's
  22708. bounds will no longer be a direct reflection of the position at which it appears within
  22709. its parent, as the transform will be applied to whatever bounds you set for it.
  22710. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  22711. */
  22712. void setBounds (int x, int y, int width, int height);
  22713. /** Changes the component's position and size.
  22714. The coordinates are relative to the top-left of the component's parent, or relative
  22715. to the origin of the screen is the component is on the desktop.
  22716. If this method changes the component's top-left position, it will make a synchronous
  22717. call to moved(). If it changes the size, it will also make a call to resized().
  22718. Note that if you've used setTransform() to apply a transform, then the component's
  22719. bounds will no longer be a direct reflection of the position at which it appears within
  22720. its parent, as the transform will be applied to whatever bounds you set for it.
  22721. @see setBounds
  22722. */
  22723. void setBounds (const Rectangle<int>& newBounds);
  22724. /** Changes the component's position and size.
  22725. This is similar to the other setBounds() methods, but uses RelativeRectangle::applyToComponent()
  22726. to set the position, This uses a Component::Positioner to make sure that any dynamic
  22727. expressions are used in the RelativeRectangle will be automatically re-applied to the
  22728. component's bounds when the source values change. See RelativeRectangle::applyToComponent()
  22729. for more details.
  22730. When using relative expressions, the following symbols are available:
  22731. - "left", "right", "top", "bottom" refer to the position of those edges in this component, so
  22732. e.g. for a component whose width is always 100, you might set the right edge to the "left + 100".
  22733. - "[id].left", "[id].right", "[id].top", "[id].bottom", "[id].width", "[id].height", where [id] is
  22734. the identifier of one of this component's siblings. A component's identifier is set with
  22735. Component::setComponentID(). So for example if you want your component to always be 50 pixels to the
  22736. right of the one called "xyz", you could set your left edge to be "xyz.right + 50".
  22737. - Instead of an [id], you can use the name "parent" to refer to this component's parent. Like
  22738. any other component, these values are relative to their component's parent, so "parent.right" won't be
  22739. very useful for positioning a component because it refers to a position with the parent's parent.. but
  22740. "parent.width" can be used for setting positions relative to the parent's size. E.g. to make a 10x10
  22741. component which remains 1 pixel away from its parent's bottom-right, you could use
  22742. "right - 10, bottom - 10, parent.width - 1, parent.height - 1".
  22743. - The name of one of the parent component's markers can also be used as a symbol. For markers to be
  22744. used, the parent component must implement its Component::getMarkers() method, and return at least one
  22745. valid MarkerList. So if you want your component's top edge to be 10 pixels below the
  22746. marker called "foobar", you'd set it to "foobar + 10".
  22747. See the Expression class for details about the operators that are supported, but for example
  22748. if you wanted to make your component remain centred within its parent with a size of 100, 100,
  22749. you could express it as:
  22750. @code myComp.setBounds (RelativeBounds ("parent.width / 2 - 50, parent.height / 2 - 50, left + 100, top + 100"));
  22751. @endcode
  22752. ..or an alternative way to achieve the same thing:
  22753. @code myComp.setBounds (RelativeBounds ("right - 100, bottom - 100, parent.width / 2 + 50, parent.height / 2 + 50"));
  22754. @endcode
  22755. Or if you wanted a 100x100 component whose top edge is lined up to a marker called "topMarker" and
  22756. which is positioned 50 pixels to the right of another component called "otherComp", you could write:
  22757. @code myComp.setBounds (RelativeBounds ("otherComp.right + 50, topMarker, left + 100, top + 100"));
  22758. @endcode
  22759. Be careful not to make your coordinate expressions recursive, though, or exceptions and assertions will
  22760. be thrown!
  22761. @see setBounds, RelativeRectangle::applyToComponent(), Expression
  22762. */
  22763. void setBounds (const RelativeRectangle& newBounds);
  22764. /** Changes the component's position and size in terms of fractions of its parent's size.
  22765. The values are factors of the parent's size, so for example
  22766. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  22767. width and height of the parent, with its top-left position 20% of
  22768. the way across and down the parent.
  22769. @see setBounds
  22770. */
  22771. void setBoundsRelative (float proportionalX, float proportionalY,
  22772. float proportionalWidth, float proportionalHeight);
  22773. /** Changes the component's position and size based on the amount of space to leave around it.
  22774. This will position the component within its parent, leaving the specified number of
  22775. pixels around each edge.
  22776. @see setBounds
  22777. */
  22778. void setBoundsInset (const BorderSize<int>& borders);
  22779. /** Positions the component within a given rectangle, keeping its proportions
  22780. unchanged.
  22781. If onlyReduceInSize is false, the component will be resized to fill as much of the
  22782. rectangle as possible without changing its aspect ratio (the component's
  22783. current size is used to determine its aspect ratio, so a zero-size component
  22784. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  22785. too big to fit inside the rectangle.
  22786. It will then be positioned within the rectangle according to the justification flags
  22787. specified.
  22788. @see setBounds
  22789. */
  22790. void setBoundsToFit (int x, int y, int width, int height,
  22791. const Justification& justification,
  22792. bool onlyReduceInSize);
  22793. /** Changes the position of the component's centre.
  22794. Leaves the component's size unchanged, but sets the position of its centre
  22795. relative to its parent's top-left.
  22796. @see setBounds
  22797. */
  22798. void setCentrePosition (int x, int y);
  22799. /** Changes the position of the component's centre.
  22800. Leaves the position unchanged, but positions its centre relative to its
  22801. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  22802. its parent.
  22803. */
  22804. void setCentreRelative (float x, float y);
  22805. /** Changes the component's size and centres it within its parent.
  22806. After changing the size, the component will be moved so that it's
  22807. centred within its parent. If the component is on the desktop (or has no
  22808. parent component), then it'll be centred within the main monitor area.
  22809. */
  22810. void centreWithSize (int width, int height);
  22811. /** Sets a transform matrix to be applied to this component.
  22812. If you set a transform for a component, the component's position will be warped by it, relative to
  22813. the component's parent's top-left origin. This means that the values you pass into setBounds() will no
  22814. longer reflect the actual area within the parent that the component covers, as the bounds will be
  22815. transformed and the component will probably end up actually appearing somewhere else within its parent.
  22816. When using transforms you need to be extremely careful when converting coordinates between the
  22817. coordinate spaces of different components or the screen - you should always use getLocalPoint(),
  22818. getLocalArea(), etc to do this, and never just manually add a component's position to a point in order to
  22819. convert it between different components (but I'm sure you would never have done that anyway...).
  22820. Currently, transforms are not supported for desktop windows, so the transform will be ignored if you
  22821. put a component on the desktop.
  22822. To remove a component's transform, simply pass AffineTransform::identity as the parameter to this method.
  22823. */
  22824. void setTransform (const AffineTransform& transform);
  22825. /** Returns the transform that is currently being applied to this component.
  22826. For more details about transforms, see setTransform().
  22827. @see setTransform
  22828. */
  22829. const AffineTransform getTransform() const;
  22830. /** Returns true if a non-identity transform is being applied to this component.
  22831. For more details about transforms, see setTransform().
  22832. @see setTransform
  22833. */
  22834. bool isTransformed() const throw();
  22835. /** Returns a proportion of the component's width.
  22836. This is a handy equivalent of (getWidth() * proportion).
  22837. */
  22838. int proportionOfWidth (float proportion) const throw();
  22839. /** Returns a proportion of the component's height.
  22840. This is a handy equivalent of (getHeight() * proportion).
  22841. */
  22842. int proportionOfHeight (float proportion) const throw();
  22843. /** Returns the width of the component's parent.
  22844. If the component has no parent (i.e. if it's on the desktop), this will return
  22845. the width of the screen.
  22846. */
  22847. int getParentWidth() const throw();
  22848. /** Returns the height of the component's parent.
  22849. If the component has no parent (i.e. if it's on the desktop), this will return
  22850. the height of the screen.
  22851. */
  22852. int getParentHeight() const throw();
  22853. /** Returns the screen coordinates of the monitor that contains this component.
  22854. If there's only one monitor, this will return its size - if there are multiple
  22855. monitors, it will return the area of the monitor that contains the component's
  22856. centre.
  22857. */
  22858. const Rectangle<int> getParentMonitorArea() const;
  22859. /** Returns the number of child components that this component contains.
  22860. @see getChildComponent, getIndexOfChildComponent
  22861. */
  22862. int getNumChildComponents() const throw();
  22863. /** Returns one of this component's child components, by it index.
  22864. The component with index 0 is at the back of the z-order, the one at the
  22865. front will have index (getNumChildComponents() - 1).
  22866. If the index is out-of-range, this will return a null pointer.
  22867. @see getNumChildComponents, getIndexOfChildComponent
  22868. */
  22869. Component* getChildComponent (int index) const throw();
  22870. /** Returns the index of this component in the list of child components.
  22871. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  22872. values are further towards the front.
  22873. Returns -1 if the component passed-in is not a child of this component.
  22874. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  22875. */
  22876. int getIndexOfChildComponent (const Component* child) const throw();
  22877. /** Adds a child component to this one.
  22878. Adding a child component does not mean that the component will own or delete the child - it's
  22879. your responsibility to delete the component. Note that it's safe to delete a component
  22880. without first removing it from its parent - doing so will automatically remove it and
  22881. send out the appropriate notifications before the deletion completes.
  22882. If the child is already a child of this component, then no action will be taken, and its
  22883. z-order will be left unchanged.
  22884. @param child the new component to add. If the component passed-in is already
  22885. the child of another component, it'll first be removed from it current parent.
  22886. @param zOrder The index in the child-list at which this component should be inserted.
  22887. A value of -1 will insert it in front of the others, 0 is the back.
  22888. @see removeChildComponent, addAndMakeVisible, getChild, ComponentListener::componentChildrenChanged
  22889. */
  22890. void addChildComponent (Component* child, int zOrder = -1);
  22891. /** Adds a child component to this one, and also makes the child visible if it isn't.
  22892. Quite a useful function, this is just the same as calling setVisible (true) on the child
  22893. and then addChildComponent(). See addChildComponent() for more details.
  22894. */
  22895. void addAndMakeVisible (Component* child, int zOrder = -1);
  22896. /** Removes one of this component's child-components.
  22897. If the child passed-in isn't actually a child of this component (either because
  22898. it's invalid or is the child of a different parent), then no action is taken.
  22899. Note that removing a child will not delete it! But it's ok to delete a component
  22900. without first removing it - doing so will automatically remove it and send out the
  22901. appropriate notifications before the deletion completes.
  22902. @see addChildComponent, ComponentListener::componentChildrenChanged
  22903. */
  22904. void removeChildComponent (Component* childToRemove);
  22905. /** Removes one of this component's child-components by index.
  22906. This will return a pointer to the component that was removed, or null if
  22907. the index was out-of-range.
  22908. Note that removing a child will not delete it! But it's ok to delete a component
  22909. without first removing it - doing so will automatically remove it and send out the
  22910. appropriate notifications before the deletion completes.
  22911. @see addChildComponent, ComponentListener::componentChildrenChanged
  22912. */
  22913. Component* removeChildComponent (int childIndexToRemove);
  22914. /** Removes all this component's children.
  22915. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  22916. */
  22917. void removeAllChildren();
  22918. /** Removes all this component's children, and deletes them.
  22919. @see removeAllChildren
  22920. */
  22921. void deleteAllChildren();
  22922. /** Returns the component which this component is inside.
  22923. If this is the highest-level component or hasn't yet been added to
  22924. a parent, this will return null.
  22925. */
  22926. Component* getParentComponent() const throw() { return parentComponent; }
  22927. /** Searches the parent components for a component of a specified class.
  22928. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  22929. component that can be dynamically cast to a MyComp, or will return 0 if none
  22930. of the parents are suitable.
  22931. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  22932. */
  22933. template <class TargetClass>
  22934. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  22935. {
  22936. (void) dummyParameter;
  22937. Component* p = parentComponent;
  22938. while (p != 0)
  22939. {
  22940. TargetClass* target = dynamic_cast <TargetClass*> (p);
  22941. if (target != 0)
  22942. return target;
  22943. p = p->parentComponent;
  22944. }
  22945. return 0;
  22946. }
  22947. /** Returns the highest-level component which contains this one or its parents.
  22948. This will search upwards in the parent-hierarchy from this component, until it
  22949. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  22950. not yet added to a parent), and will return that.
  22951. */
  22952. Component* getTopLevelComponent() const throw();
  22953. /** Checks whether a component is anywhere inside this component or its children.
  22954. This will recursively check through this component's children to see if the
  22955. given component is anywhere inside.
  22956. */
  22957. bool isParentOf (const Component* possibleChild) const throw();
  22958. /** Called to indicate that the component's parents have changed.
  22959. When a component is added or removed from its parent, this method will
  22960. be called on all of its children (recursively - so all children of its
  22961. children will also be called as well).
  22962. Subclasses can override this if they need to react to this in some way.
  22963. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  22964. */
  22965. virtual void parentHierarchyChanged();
  22966. /** Subclasses can use this callback to be told when children are added or removed.
  22967. @see parentHierarchyChanged
  22968. */
  22969. virtual void childrenChanged();
  22970. /** Tests whether a given point inside the component.
  22971. Overriding this method allows you to create components which only intercept
  22972. mouse-clicks within a user-defined area.
  22973. This is called to find out whether a particular x, y coordinate is
  22974. considered to be inside the component or not, and is used by methods such
  22975. as contains() and getComponentAt() to work out which component
  22976. the mouse is clicked on.
  22977. Components with custom shapes will probably want to override it to perform
  22978. some more complex hit-testing.
  22979. The default implementation of this method returns either true or false,
  22980. depending on the value that was set by calling setInterceptsMouseClicks() (true
  22981. is the default return value).
  22982. Note that the hit-test region is not related to the opacity with which
  22983. areas of a component are painted.
  22984. Applications should never call hitTest() directly - instead use the
  22985. contains() method, because this will also test for occlusion by the
  22986. component's parent.
  22987. Note that for components on the desktop, this method will be ignored, because it's
  22988. not always possible to implement this behaviour on all platforms.
  22989. @param x the x coordinate to test, relative to the left hand edge of this
  22990. component. This value is guaranteed to be greater than or equal to
  22991. zero, and less than the component's width
  22992. @param y the y coordinate to test, relative to the top edge of this
  22993. component. This value is guaranteed to be greater than or equal to
  22994. zero, and less than the component's height
  22995. @returns true if the click is considered to be inside the component
  22996. @see setInterceptsMouseClicks, contains
  22997. */
  22998. virtual bool hitTest (int x, int y);
  22999. /** Changes the default return value for the hitTest() method.
  23000. Setting this to false is an easy way to make a component pass its mouse-clicks
  23001. through to the components behind it.
  23002. When a component is created, the default setting for this is true.
  23003. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  23004. return false (or true for child components if allowClicksOnChildComponents
  23005. is true)
  23006. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  23007. components can be clicked on as normal but clicks on this component pass
  23008. straight through; if this is false and allowClicksOnThisComponent
  23009. is false, then neither this component nor any child components can
  23010. be clicked on
  23011. @see hitTest, getInterceptsMouseClicks
  23012. */
  23013. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  23014. bool allowClicksOnChildComponents) throw();
  23015. /** Retrieves the current state of the mouse-click interception flags.
  23016. On return, the two parameters are set to the state used in the last call to
  23017. setInterceptsMouseClicks().
  23018. @see setInterceptsMouseClicks
  23019. */
  23020. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  23021. bool& allowsClicksOnChildComponents) const throw();
  23022. /** Returns true if a given point lies within this component or one of its children.
  23023. Never override this method! Use hitTest to create custom hit regions.
  23024. @param localPoint the coordinate to test, relative to this component's top-left.
  23025. @returns true if the point is within the component's hit-test area, but only if
  23026. that part of the component isn't clipped by its parent component. Note
  23027. that this won't take into account any overlapping sibling components
  23028. which might be in the way - for that, see reallyContains()
  23029. @see hitTest, reallyContains, getComponentAt
  23030. */
  23031. bool contains (const Point<int>& localPoint);
  23032. /** Returns true if a given point lies in this component, taking any overlapping
  23033. siblings into account.
  23034. @param localPoint the coordinate to test, relative to this component's top-left.
  23035. @param returnTrueIfWithinAChild if the point actually lies within a child of this component,
  23036. this determines whether that is counted as a hit.
  23037. @see contains, getComponentAt
  23038. */
  23039. bool reallyContains (const Point<int>& localPoint, bool returnTrueIfWithinAChild);
  23040. /** Returns the component at a certain point within this one.
  23041. @param x the x coordinate to test, relative to this component's left edge.
  23042. @param y the y coordinate to test, relative to this component's top edge.
  23043. @returns the component that is at this position - which may be 0, this component,
  23044. or one of its children. Note that overlapping siblings that might actually
  23045. be in the way are not taken into account by this method - to account for these,
  23046. instead call getComponentAt on the top-level parent of this component.
  23047. @see hitTest, contains, reallyContains
  23048. */
  23049. Component* getComponentAt (int x, int y);
  23050. /** Returns the component at a certain point within this one.
  23051. @param position the coordinate to test, relative to this component's top-left.
  23052. @returns the component that is at this position - which may be 0, this component,
  23053. or one of its children. Note that overlapping siblings that might actually
  23054. be in the way are not taken into account by this method - to account for these,
  23055. instead call getComponentAt on the top-level parent of this component.
  23056. @see hitTest, contains, reallyContains
  23057. */
  23058. Component* getComponentAt (const Point<int>& position);
  23059. /** Marks the whole component as needing to be redrawn.
  23060. Calling this will not do any repainting immediately, but will mark the component
  23061. as 'dirty'. At some point in the near future the operating system will send a paint
  23062. message, which will redraw all the dirty regions of all components.
  23063. There's no guarantee about how soon after calling repaint() the redraw will actually
  23064. happen, and other queued events may be delivered before a redraw is done.
  23065. If the setBufferedToImage() method has been used to cause this component
  23066. to use a buffer, the repaint() call will invalidate the component's buffer.
  23067. To redraw just a subsection of the component rather than the whole thing,
  23068. use the repaint (int, int, int, int) method.
  23069. @see paint
  23070. */
  23071. void repaint();
  23072. /** Marks a subsection of this component as needing to be redrawn.
  23073. Calling this will not do any repainting immediately, but will mark the given region
  23074. of the component as 'dirty'. At some point in the near future the operating system
  23075. will send a paint message, which will redraw all the dirty regions of all components.
  23076. There's no guarantee about how soon after calling repaint() the redraw will actually
  23077. happen, and other queued events may be delivered before a redraw is done.
  23078. The region that is passed in will be clipped to keep it within the bounds of this
  23079. component.
  23080. @see repaint()
  23081. */
  23082. void repaint (int x, int y, int width, int height);
  23083. /** Marks a subsection of this component as needing to be redrawn.
  23084. Calling this will not do any repainting immediately, but will mark the given region
  23085. of the component as 'dirty'. At some point in the near future the operating system
  23086. will send a paint message, which will redraw all the dirty regions of all components.
  23087. There's no guarantee about how soon after calling repaint() the redraw will actually
  23088. happen, and other queued events may be delivered before a redraw is done.
  23089. The region that is passed in will be clipped to keep it within the bounds of this
  23090. component.
  23091. @see repaint()
  23092. */
  23093. void repaint (const Rectangle<int>& area);
  23094. /** Makes the component use an internal buffer to optimise its redrawing.
  23095. Setting this flag to true will cause the component to allocate an
  23096. internal buffer into which it paints itself, so that when asked to
  23097. redraw itself, it can use this buffer rather than actually calling the
  23098. paint() method.
  23099. The buffer is kept until the repaint() method is called directly on
  23100. this component (or until it is resized), when the image is invalidated
  23101. and then redrawn the next time the component is painted.
  23102. Note that only the drawing that happens within the component's paint()
  23103. method is drawn into the buffer, it's child components are not buffered, and
  23104. nor is the paintOverChildren() method.
  23105. @see repaint, paint, createComponentSnapshot
  23106. */
  23107. void setBufferedToImage (bool shouldBeBuffered);
  23108. /** Generates a snapshot of part of this component.
  23109. This will return a new Image, the size of the rectangle specified,
  23110. containing a snapshot of the specified area of the component and all
  23111. its children.
  23112. The image may or may not have an alpha-channel, depending on whether the
  23113. image is opaque or not.
  23114. If the clipImageToComponentBounds parameter is true and the area is greater than
  23115. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  23116. then parts of the component beyond its bounds can be drawn.
  23117. @see paintEntireComponent
  23118. */
  23119. const Image createComponentSnapshot (const Rectangle<int>& areaToGrab,
  23120. bool clipImageToComponentBounds = true);
  23121. /** Draws this component and all its subcomponents onto the specified graphics
  23122. context.
  23123. You should very rarely have to use this method, it's simply there in case you need
  23124. to draw a component with a custom graphics context for some reason, e.g. for
  23125. creating a snapshot of the component.
  23126. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  23127. on its children in order to render the entire tree.
  23128. The graphics context may be left in an undefined state after this method returns,
  23129. so you may need to reset it if you're going to use it again.
  23130. If ignoreAlphaLevel is false, then the component will be drawn with the opacity level
  23131. specified by getAlpha(); if ignoreAlphaLevel is true, then this will be ignored and
  23132. an alpha of 1.0 will be used.
  23133. */
  23134. void paintEntireComponent (Graphics& context, bool ignoreAlphaLevel);
  23135. /** This allows you to indicate that this component doesn't require its graphics
  23136. context to be clipped when it is being painted.
  23137. Most people will never need to use this setting, but in situations where you have a very large
  23138. number of simple components being rendered, and where they are guaranteed never to do any drawing
  23139. beyond their own boundaries, setting this to true will reduce the overhead involved in clipping
  23140. the graphics context that gets passed to the component's paint() callback.
  23141. If you enable this mode, you'll need to make sure your paint method doesn't call anything like
  23142. Graphics::fillAll(), and doesn't draw beyond the component's bounds, because that'll produce
  23143. artifacts. Your component also can't have any child components that may be placed beyond its
  23144. bounds.
  23145. */
  23146. void setPaintingIsUnclipped (bool shouldPaintWithoutClipping) throw();
  23147. /** Adds an effect filter to alter the component's appearance.
  23148. When a component has an effect filter set, then this is applied to the
  23149. results of its paint() method. There are a few preset effects, such as
  23150. a drop-shadow or glow, but they can be user-defined as well.
  23151. The effect that is passed in will not be deleted by the component - the
  23152. caller must take care of deleting it.
  23153. To remove an effect from a component, pass a null pointer in as the parameter.
  23154. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  23155. */
  23156. void setComponentEffect (ImageEffectFilter* newEffect);
  23157. /** Returns the current component effect.
  23158. @see setComponentEffect
  23159. */
  23160. ImageEffectFilter* getComponentEffect() const throw() { return effect; }
  23161. /** Finds the appropriate look-and-feel to use for this component.
  23162. If the component hasn't had a look-and-feel explicitly set, this will
  23163. return the parent's look-and-feel, or just the default one if there's no
  23164. parent.
  23165. @see setLookAndFeel, lookAndFeelChanged
  23166. */
  23167. LookAndFeel& getLookAndFeel() const throw();
  23168. /** Sets the look and feel to use for this component.
  23169. This will also change the look and feel for any child components that haven't
  23170. had their look set explicitly.
  23171. The object passed in will not be deleted by the component, so it's the caller's
  23172. responsibility to manage it. It may be used at any time until this component
  23173. has been deleted.
  23174. Calling this method will also invoke the sendLookAndFeelChange() method.
  23175. @see getLookAndFeel, lookAndFeelChanged
  23176. */
  23177. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  23178. /** Called to let the component react to a change in the look-and-feel setting.
  23179. When the look-and-feel is changed for a component, this will be called in
  23180. all its child components, recursively.
  23181. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  23182. an application uses a LookAndFeel class that might have changed internally.
  23183. @see sendLookAndFeelChange, getLookAndFeel
  23184. */
  23185. virtual void lookAndFeelChanged();
  23186. /** Calls the lookAndFeelChanged() method in this component and all its children.
  23187. This will recurse through the children and their children, calling lookAndFeelChanged()
  23188. on them all.
  23189. @see lookAndFeelChanged
  23190. */
  23191. void sendLookAndFeelChange();
  23192. /** Indicates whether any parts of the component might be transparent.
  23193. Components that always paint all of their contents with solid colour and
  23194. thus completely cover any components behind them should use this method
  23195. to tell the repaint system that they are opaque.
  23196. This information is used to optimise drawing, because it means that
  23197. objects underneath opaque windows don't need to be painted.
  23198. By default, components are considered transparent, unless this is used to
  23199. make it otherwise.
  23200. @see isOpaque, getVisibleArea
  23201. */
  23202. void setOpaque (bool shouldBeOpaque);
  23203. /** Returns true if no parts of this component are transparent.
  23204. @returns the value that was set by setOpaque, (the default being false)
  23205. @see setOpaque
  23206. */
  23207. bool isOpaque() const throw();
  23208. /** Indicates whether the component should be brought to the front when clicked.
  23209. Setting this flag to true will cause the component to be brought to the front
  23210. when the mouse is clicked somewhere inside it or its child components.
  23211. Note that a top-level desktop window might still be brought to the front by the
  23212. operating system when it's clicked, depending on how the OS works.
  23213. By default this is set to false.
  23214. @see setMouseClickGrabsKeyboardFocus
  23215. */
  23216. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) throw();
  23217. /** Indicates whether the component should be brought to the front when clicked-on.
  23218. @see setBroughtToFrontOnMouseClick
  23219. */
  23220. bool isBroughtToFrontOnMouseClick() const throw();
  23221. // Keyboard focus methods
  23222. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  23223. By default components aren't actually interested in gaining the
  23224. focus, but this method can be used to turn this on.
  23225. See the grabKeyboardFocus() method for details about the way a component
  23226. is chosen to receive the focus.
  23227. @see grabKeyboardFocus, getWantsKeyboardFocus
  23228. */
  23229. void setWantsKeyboardFocus (bool wantsFocus) throw();
  23230. /** Returns true if the component is interested in getting keyboard focus.
  23231. This returns the flag set by setWantsKeyboardFocus(). The default
  23232. setting is false.
  23233. @see setWantsKeyboardFocus
  23234. */
  23235. bool getWantsKeyboardFocus() const throw();
  23236. /** Chooses whether a click on this component automatically grabs the focus.
  23237. By default this is set to true, but you might want a component which can
  23238. be focused, but where you don't want the user to be able to affect it directly
  23239. by clicking.
  23240. */
  23241. void setMouseClickGrabsKeyboardFocus (bool shouldGrabFocus);
  23242. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  23243. See setMouseClickGrabsKeyboardFocus() for more info.
  23244. */
  23245. bool getMouseClickGrabsKeyboardFocus() const throw();
  23246. /** Tries to give keyboard focus to this component.
  23247. When the user clicks on a component or its grabKeyboardFocus()
  23248. method is called, the following procedure is used to work out which
  23249. component should get it:
  23250. - if the component that was clicked on actually wants focus (as indicated
  23251. by calling getWantsKeyboardFocus), it gets it.
  23252. - if the component itself doesn't want focus, it will try to pass it
  23253. on to whichever of its children is the default component, as determined by
  23254. KeyboardFocusTraverser::getDefaultComponent()
  23255. - if none of its children want focus at all, it will pass it up to its
  23256. parent instead, unless it's a top-level component without a parent,
  23257. in which case it just takes the focus itself.
  23258. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  23259. getCurrentlyFocusedComponent, focusGained, focusLost,
  23260. keyPressed, keyStateChanged
  23261. */
  23262. void grabKeyboardFocus();
  23263. /** Returns true if this component currently has the keyboard focus.
  23264. @param trueIfChildIsFocused if this is true, then the method returns true if
  23265. either this component or any of its children (recursively)
  23266. have the focus. If false, the method only returns true if
  23267. this component has the focus.
  23268. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  23269. focusGained, focusLost
  23270. */
  23271. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  23272. /** Returns the component that currently has the keyboard focus.
  23273. @returns the focused component, or null if nothing is focused.
  23274. */
  23275. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  23276. /** Tries to move the keyboard focus to one of this component's siblings.
  23277. This will try to move focus to either the next or previous component. (This
  23278. is the method that is used when shifting focus by pressing the tab key).
  23279. Components for which getWantsKeyboardFocus() returns false are not looked at.
  23280. @param moveToNext if true, the focus will move forwards; if false, it will
  23281. move backwards
  23282. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  23283. */
  23284. void moveKeyboardFocusToSibling (bool moveToNext);
  23285. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  23286. which focus should be passed from this component.
  23287. The default implementation of this method will return a default
  23288. KeyboardFocusTraverser if this component is a focus container (as determined
  23289. by the setFocusContainer() method). If the component isn't a focus
  23290. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  23291. If you overrride this to return a custom KeyboardFocusTraverser, then
  23292. this component and all its sub-components will use the new object to
  23293. make their focusing decisions.
  23294. The method should return a new object, which the caller is required to
  23295. delete when no longer needed.
  23296. */
  23297. virtual KeyboardFocusTraverser* createFocusTraverser();
  23298. /** Returns the focus order of this component, if one has been specified.
  23299. By default components don't have a focus order - in that case, this
  23300. will return 0. Lower numbers indicate that the component will be
  23301. earlier in the focus traversal order.
  23302. To change the order, call setExplicitFocusOrder().
  23303. The focus order may be used by the KeyboardFocusTraverser class as part of
  23304. its algorithm for deciding the order in which components should be traversed.
  23305. See the KeyboardFocusTraverser class for more details on this.
  23306. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  23307. */
  23308. int getExplicitFocusOrder() const;
  23309. /** Sets the index used in determining the order in which focusable components
  23310. should be traversed.
  23311. A value of 0 or less is taken to mean that no explicit order is wanted, and
  23312. that traversal should use other factors, like the component's position.
  23313. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  23314. */
  23315. void setExplicitFocusOrder (int newFocusOrderIndex);
  23316. /** Indicates whether this component is a parent for components that can have
  23317. their focus traversed.
  23318. This flag is used by the default implementation of the createFocusTraverser()
  23319. method, which uses the flag to find the first parent component (of the currently
  23320. focused one) which wants to be a focus container.
  23321. So using this method to set the flag to 'true' causes this component to
  23322. act as the top level within which focus is passed around.
  23323. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  23324. */
  23325. void setFocusContainer (bool shouldBeFocusContainer) throw();
  23326. /** Returns true if this component has been marked as a focus container.
  23327. See setFocusContainer() for more details.
  23328. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  23329. */
  23330. bool isFocusContainer() const throw();
  23331. /** Returns true if the component (and all its parents) are enabled.
  23332. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  23333. what difference this makes to the component depends on the type. E.g. buttons
  23334. and sliders will choose to draw themselves differently, etc.
  23335. Note that if one of this component's parents is disabled, this will always
  23336. return false, even if this component itself is enabled.
  23337. @see setEnabled, enablementChanged
  23338. */
  23339. bool isEnabled() const throw();
  23340. /** Enables or disables this component.
  23341. Disabling a component will also cause all of its child components to become
  23342. disabled.
  23343. Similarly, enabling a component which is inside a disabled parent
  23344. component won't make any difference until the parent is re-enabled.
  23345. @see isEnabled, enablementChanged
  23346. */
  23347. void setEnabled (bool shouldBeEnabled);
  23348. /** Callback to indicate that this component has been enabled or disabled.
  23349. This can be triggered by one of the component's parent components
  23350. being enabled or disabled, as well as changes to the component itself.
  23351. The default implementation of this method does nothing; your class may
  23352. wish to repaint itself or something when this happens.
  23353. @see setEnabled, isEnabled
  23354. */
  23355. virtual void enablementChanged();
  23356. /** Changes the transparency of this component.
  23357. When painted, the entire component and all its children will be rendered
  23358. with this as the overall opacity level, where 0 is completely invisible, and
  23359. 1.0 is fully opaque (i.e. normal).
  23360. @see getAlpha
  23361. */
  23362. void setAlpha (float newAlpha);
  23363. /** Returns the component's current transparancy level.
  23364. See setAlpha() for more details.
  23365. */
  23366. float getAlpha() const;
  23367. /** Changes the mouse cursor shape to use when the mouse is over this component.
  23368. Note that the cursor set by this method can be overridden by the getMouseCursor
  23369. method.
  23370. @see MouseCursor
  23371. */
  23372. void setMouseCursor (const MouseCursor& cursorType);
  23373. /** Returns the mouse cursor shape to use when the mouse is over this component.
  23374. The default implementation will return the cursor that was set by setCursor()
  23375. but can be overridden for more specialised purposes, e.g. returning different
  23376. cursors depending on the mouse position.
  23377. @see MouseCursor
  23378. */
  23379. virtual const MouseCursor getMouseCursor();
  23380. /** Forces the current mouse cursor to be updated.
  23381. If you're overriding the getMouseCursor() method to control which cursor is
  23382. displayed, then this will only be checked each time the user moves the mouse. So
  23383. if you want to force the system to check that the cursor being displayed is
  23384. up-to-date (even if the mouse is just sitting there), call this method.
  23385. (If you're changing the cursor using setMouseCursor(), you don't need to bother
  23386. calling this).
  23387. */
  23388. void updateMouseCursor() const;
  23389. /** Components can override this method to draw their content.
  23390. The paint() method gets called when a region of a component needs redrawing,
  23391. either because the component's repaint() method has been called, or because
  23392. something has happened on the screen that means a section of a window needs
  23393. to be redrawn.
  23394. Any child components will draw themselves over whatever this method draws. If
  23395. you need to paint over the top of your child components, you can also implement
  23396. the paintOverChildren() method to do this.
  23397. If you want to cause a component to redraw itself, this is done asynchronously -
  23398. calling the repaint() method marks a region of the component as "dirty", and the
  23399. paint() method will automatically be called sometime later, by the message thread,
  23400. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  23401. you never redraw something synchronously.
  23402. You should never need to call this method directly - to take a snapshot of the
  23403. component you could use createComponentSnapshot() or paintEntireComponent().
  23404. @param g the graphics context that must be used to do the drawing operations.
  23405. @see repaint, paintOverChildren, Graphics
  23406. */
  23407. virtual void paint (Graphics& g);
  23408. /** Components can override this method to draw over the top of their children.
  23409. For most drawing operations, it's better to use the normal paint() method,
  23410. but if you need to overlay something on top of the children, this can be
  23411. used.
  23412. @see paint, Graphics
  23413. */
  23414. virtual void paintOverChildren (Graphics& g);
  23415. /** Called when the mouse moves inside this component.
  23416. If the mouse button isn't pressed and the mouse moves over a component,
  23417. this will be called to let the component react to this.
  23418. A component will always get a mouseEnter callback before a mouseMove.
  23419. @param e details about the position and status of the mouse event
  23420. @see mouseEnter, mouseExit, mouseDrag, contains
  23421. */
  23422. virtual void mouseMove (const MouseEvent& e);
  23423. /** Called when the mouse first enters this component.
  23424. If the mouse button isn't pressed and the mouse moves into a component,
  23425. this will be called to let the component react to this.
  23426. When the mouse button is pressed and held down while being moved in
  23427. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  23428. mouseDrag messages are sent to the component that the mouse was originally
  23429. clicked on, until the button is released.
  23430. If you're writing a component that needs to repaint itself when the mouse
  23431. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  23432. method.
  23433. @param e details about the position and status of the mouse event
  23434. @see mouseExit, mouseDrag, mouseMove, contains
  23435. */
  23436. virtual void mouseEnter (const MouseEvent& e);
  23437. /** Called when the mouse moves out of this component.
  23438. This will be called when the mouse moves off the edge of this
  23439. component.
  23440. If the mouse button was pressed, and it was then dragged off the
  23441. edge of the component and released, then this callback will happen
  23442. when the button is released, after the mouseUp callback.
  23443. If you're writing a component that needs to repaint itself when the mouse
  23444. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  23445. method.
  23446. @param e details about the position and status of the mouse event
  23447. @see mouseEnter, mouseDrag, mouseMove, contains
  23448. */
  23449. virtual void mouseExit (const MouseEvent& e);
  23450. /** Called when a mouse button is pressed while it's over this component.
  23451. The MouseEvent object passed in contains lots of methods for finding out
  23452. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  23453. were held down at the time.
  23454. Once a button is held down, the mouseDrag method will be called when the
  23455. mouse moves, until the button is released.
  23456. @param e details about the position and status of the mouse event
  23457. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  23458. */
  23459. virtual void mouseDown (const MouseEvent& e);
  23460. /** Called when the mouse is moved while a button is held down.
  23461. When a mouse button is pressed inside a component, that component
  23462. receives mouseDrag callbacks each time the mouse moves, even if the
  23463. mouse strays outside the component's bounds.
  23464. If you want to be able to drag things off the edge of a component
  23465. and have the component scroll when you get to the edges, the
  23466. beginDragAutoRepeat() method might be useful.
  23467. @param e details about the position and status of the mouse event
  23468. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  23469. */
  23470. virtual void mouseDrag (const MouseEvent& e);
  23471. /** Called when a mouse button is released.
  23472. A mouseUp callback is sent to the component in which a button was pressed
  23473. even if the mouse is actually over a different component when the
  23474. button is released.
  23475. The MouseEvent object passed in contains lots of methods for finding out
  23476. which buttons were down just before they were released.
  23477. @param e details about the position and status of the mouse event
  23478. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  23479. */
  23480. virtual void mouseUp (const MouseEvent& e);
  23481. /** Called when a mouse button has been double-clicked in this component.
  23482. The MouseEvent object passed in contains lots of methods for finding out
  23483. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  23484. were held down at the time.
  23485. For altering the time limit used to detect double-clicks,
  23486. see MouseEvent::setDoubleClickTimeout.
  23487. @param e details about the position and status of the mouse event
  23488. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  23489. MouseEvent::getDoubleClickTimeout
  23490. */
  23491. virtual void mouseDoubleClick (const MouseEvent& e);
  23492. /** Called when the mouse-wheel is moved.
  23493. This callback is sent to the component that the mouse is over when the
  23494. wheel is moved.
  23495. If not overridden, the component will forward this message to its parent, so
  23496. that parent components can collect mouse-wheel messages that happen to
  23497. child components which aren't interested in them.
  23498. @param e details about the position and status of the mouse event
  23499. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  23500. value means the wheel has been pushed to the right, negative means it
  23501. was pushed to the left
  23502. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  23503. value means the wheel has been pushed upwards, negative means it
  23504. was pushed downwards
  23505. */
  23506. virtual void mouseWheelMove (const MouseEvent& e,
  23507. float wheelIncrementX,
  23508. float wheelIncrementY);
  23509. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  23510. current mouse-drag operation.
  23511. This allows you to make sure that mouseDrag() events are sent continuously, even
  23512. when the mouse isn't moving. This can be useful for things like auto-scrolling
  23513. components when the mouse is near an edge.
  23514. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  23515. minimum interval between consecutive mouse drag callbacks. The callbacks
  23516. will continue until the mouse is released, and then the interval will be reset,
  23517. so you need to make sure it's called every time you begin a drag event.
  23518. Passing an interval of 0 or less will cancel the auto-repeat.
  23519. @see mouseDrag, Desktop::beginDragAutoRepeat
  23520. */
  23521. static void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  23522. /** Causes automatic repaints when the mouse enters or exits this component.
  23523. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  23524. on the component, it will trigger a repaint.
  23525. This is handy for things like buttons that need to draw themselves differently when
  23526. the mouse moves over them, and it avoids having to override all the different mouse
  23527. callbacks and call repaint().
  23528. @see mouseEnter, mouseExit, mouseDown, mouseUp
  23529. */
  23530. void setRepaintsOnMouseActivity (bool shouldRepaint) throw();
  23531. /** Registers a listener to be told when mouse events occur in this component.
  23532. If you need to get informed about mouse events in a component but can't or
  23533. don't want to override its methods, you can attach any number of listeners
  23534. to the component, and these will get told about the events in addition to
  23535. the component's own callbacks being called.
  23536. Note that a MouseListener can also be attached to more than one component.
  23537. @param newListener the listener to register
  23538. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  23539. for events that happen to any child component
  23540. within this component, including deeply-nested
  23541. child components. If false, it will only be
  23542. told about events that this component handles.
  23543. @see MouseListener, removeMouseListener
  23544. */
  23545. void addMouseListener (MouseListener* newListener,
  23546. bool wantsEventsForAllNestedChildComponents);
  23547. /** Deregisters a mouse listener.
  23548. @see addMouseListener, MouseListener
  23549. */
  23550. void removeMouseListener (MouseListener* listenerToRemove);
  23551. /** Adds a listener that wants to hear about keypresses that this component receives.
  23552. The listeners that are registered with a component are called by its keyPressed() or
  23553. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  23554. If you add an object as a key listener, be careful to remove it when the object
  23555. is deleted, or the component will be left with a dangling pointer.
  23556. @see keyPressed, keyStateChanged, removeKeyListener
  23557. */
  23558. void addKeyListener (KeyListener* newListener);
  23559. /** Removes a previously-registered key listener.
  23560. @see addKeyListener
  23561. */
  23562. void removeKeyListener (KeyListener* listenerToRemove);
  23563. /** Called when a key is pressed.
  23564. When a key is pressed, the component that has the keyboard focus will have this
  23565. method called. Remember that a component will only be given the focus if its
  23566. setWantsKeyboardFocus() method has been used to enable this.
  23567. If your implementation returns true, the event will be consumed and not passed
  23568. on to any other listeners. If it returns false, the key will be passed to any
  23569. KeyListeners that have been registered with this component. As soon as one of these
  23570. returns true, the process will stop, but if they all return false, the event will
  23571. be passed upwards to this component's parent, and so on.
  23572. The default implementation of this method does nothing and returns false.
  23573. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  23574. */
  23575. virtual bool keyPressed (const KeyPress& key);
  23576. /** Called when a key is pressed or released.
  23577. Whenever a key on the keyboard is pressed or released (including modifier keys
  23578. like shift and ctrl), this method will be called on the component that currently
  23579. has the keyboard focus. Remember that a component will only be given the focus if
  23580. its setWantsKeyboardFocus() method has been used to enable this.
  23581. If your implementation returns true, the event will be consumed and not passed
  23582. on to any other listeners. If it returns false, then any KeyListeners that have
  23583. been registered with this component will have their keyStateChanged methods called.
  23584. As soon as one of these returns true, the process will stop, but if they all return
  23585. false, the event will be passed upwards to this component's parent, and so on.
  23586. The default implementation of this method does nothing and returns false.
  23587. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  23588. method.
  23589. @param isKeyDown true if a key has been pressed; false if it has been released
  23590. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  23591. */
  23592. virtual bool keyStateChanged (bool isKeyDown);
  23593. /** Called when a modifier key is pressed or released.
  23594. Whenever the shift, control, alt or command keys are pressed or released,
  23595. this method will be called on the component that currently has the keyboard focus.
  23596. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  23597. method has been used to enable this.
  23598. The default implementation of this method actually calls its parent's modifierKeysChanged
  23599. method, so that focused components which aren't interested in this will give their
  23600. parents a chance to act on the event instead.
  23601. @see keyStateChanged, ModifierKeys
  23602. */
  23603. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  23604. /** Enumeration used by the focusChanged() and focusLost() methods. */
  23605. enum FocusChangeType
  23606. {
  23607. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  23608. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  23609. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  23610. };
  23611. /** Called to indicate that this component has just acquired the keyboard focus.
  23612. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  23613. */
  23614. virtual void focusGained (FocusChangeType cause);
  23615. /** Called to indicate that this component has just lost the keyboard focus.
  23616. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  23617. */
  23618. virtual void focusLost (FocusChangeType cause);
  23619. /** Called to indicate that one of this component's children has been focused or unfocused.
  23620. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  23621. changed. It happens when focus moves from one of this component's children (at any depth)
  23622. to a component that isn't contained in this one, (or vice-versa).
  23623. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  23624. */
  23625. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  23626. /** Returns true if the mouse is currently over this component.
  23627. If the mouse isn't over the component, this will return false, even if the
  23628. mouse is currently being dragged - so you can use this in your mouseDrag
  23629. method to find out whether it's really over the component or not.
  23630. Note that when the mouse button is being held down, then the only component
  23631. for which this method will return true is the one that was originally
  23632. clicked on.
  23633. If includeChildren is true, then this will also return true if the mouse is over
  23634. any of the component's children (recursively) as well as the component itself.
  23635. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  23636. */
  23637. bool isMouseOver (bool includeChildren = false) const;
  23638. /** Returns true if the mouse button is currently held down in this component.
  23639. Note that this is a test to see whether the mouse is being pressed in this
  23640. component, so it'll return false if called on component A when the mouse
  23641. is actually being dragged in component B.
  23642. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  23643. */
  23644. bool isMouseButtonDown() const throw();
  23645. /** True if the mouse is over this component, or if it's being dragged in this component.
  23646. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  23647. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  23648. */
  23649. bool isMouseOverOrDragging() const throw();
  23650. /** Returns true if a mouse button is currently down.
  23651. Unlike isMouseButtonDown, this will test the current state of the
  23652. buttons without regard to which component (if any) it has been
  23653. pressed in.
  23654. @see isMouseButtonDown, ModifierKeys
  23655. */
  23656. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  23657. /** Returns the mouse's current position, relative to this component.
  23658. The return value is relative to the component's top-left corner.
  23659. */
  23660. const Point<int> getMouseXYRelative() const;
  23661. /** Called when this component's size has been changed.
  23662. A component can implement this method to do things such as laying out its
  23663. child components when its width or height changes.
  23664. The method is called synchronously as a result of the setBounds or setSize
  23665. methods, so repeatedly changing a components size will repeatedly call its
  23666. resized method (unlike things like repainting, where multiple calls to repaint
  23667. are coalesced together).
  23668. If the component is a top-level window on the desktop, its size could also
  23669. be changed by operating-system factors beyond the application's control.
  23670. @see moved, setSize
  23671. */
  23672. virtual void resized();
  23673. /** Called when this component's position has been changed.
  23674. This is called when the position relative to its parent changes, not when
  23675. its absolute position on the screen changes (so it won't be called for
  23676. all child components when a parent component is moved).
  23677. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  23678. or any of the other repositioning methods, and like resized(), it will be
  23679. called each time those methods are called.
  23680. If the component is a top-level window on the desktop, its position could also
  23681. be changed by operating-system factors beyond the application's control.
  23682. @see resized, setBounds
  23683. */
  23684. virtual void moved();
  23685. /** Called when one of this component's children is moved or resized.
  23686. If the parent wants to know about changes to its immediate children (not
  23687. to children of its children), this is the method to override.
  23688. @see moved, resized, parentSizeChanged
  23689. */
  23690. virtual void childBoundsChanged (Component* child);
  23691. /** Called when this component's immediate parent has been resized.
  23692. If the component is a top-level window, this indicates that the screen size
  23693. has changed.
  23694. @see childBoundsChanged, moved, resized
  23695. */
  23696. virtual void parentSizeChanged();
  23697. /** Called when this component has been moved to the front of its siblings.
  23698. The component may have been brought to the front by the toFront() method, or
  23699. by the operating system if it's a top-level window.
  23700. @see toFront
  23701. */
  23702. virtual void broughtToFront();
  23703. /** Adds a listener to be told about changes to the component hierarchy or position.
  23704. Component listeners get called when this component's size, position or children
  23705. change - see the ComponentListener class for more details.
  23706. @param newListener the listener to register - if this is already registered, it
  23707. will be ignored.
  23708. @see ComponentListener, removeComponentListener
  23709. */
  23710. void addComponentListener (ComponentListener* newListener);
  23711. /** Removes a component listener.
  23712. @see addComponentListener
  23713. */
  23714. void removeComponentListener (ComponentListener* listenerToRemove);
  23715. /** Dispatches a numbered message to this component.
  23716. This is a quick and cheap way of allowing simple asynchronous messages to
  23717. be sent to components. It's also safe, because if the component that you
  23718. send the message to is a null or dangling pointer, this won't cause an error.
  23719. The command ID is later delivered to the component's handleCommandMessage() method by
  23720. the application's message queue.
  23721. @see handleCommandMessage
  23722. */
  23723. void postCommandMessage (int commandId);
  23724. /** Called to handle a command that was sent by postCommandMessage().
  23725. This is called by the message thread when a command message arrives, and
  23726. the component can override this method to process it in any way it needs to.
  23727. @see postCommandMessage
  23728. */
  23729. virtual void handleCommandMessage (int commandId);
  23730. /** Runs a component modally, waiting until the loop terminates.
  23731. This method first makes the component visible, brings it to the front and
  23732. gives it the keyboard focus.
  23733. It then runs a loop, dispatching messages from the system message queue, but
  23734. blocking all mouse or keyboard messages from reaching any components other
  23735. than this one and its children.
  23736. This loop continues until the component's exitModalState() method is called (or
  23737. the component is deleted), and then this method returns, returning the value
  23738. passed into exitModalState().
  23739. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  23740. isCurrentlyBlockedByAnotherModalComponent, ModalComponentManager
  23741. */
  23742. int runModalLoop();
  23743. /** Puts the component into a modal state.
  23744. This makes the component modal, so that messages are blocked from reaching
  23745. any components other than this one and its children, but unlike runModalLoop(),
  23746. this method returns immediately.
  23747. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  23748. get the focus, which is usually what you'll want it to do. If not, it will leave
  23749. the focus unchanged.
  23750. The callback is an optional object which will receive a callback when the modal
  23751. component loses its modal status, either by being hidden or when exitModalState()
  23752. is called. If you pass an object in here, the system will take care of deleting it
  23753. later, after making the callback
  23754. @see exitModalState, runModalLoop, ModalComponentManager::attachCallback
  23755. */
  23756. void enterModalState (bool takeKeyboardFocus = true,
  23757. ModalComponentManager::Callback* callback = 0);
  23758. /** Ends a component's modal state.
  23759. If this component is currently modal, this will turn of its modalness, and return
  23760. a value to the runModalLoop() method that might have be running its modal loop.
  23761. @see runModalLoop, enterModalState, isCurrentlyModal
  23762. */
  23763. void exitModalState (int returnValue);
  23764. /** Returns true if this component is the modal one.
  23765. It's possible to have nested modal components, e.g. a pop-up dialog box
  23766. that launches another pop-up, but this will only return true for
  23767. the one at the top of the stack.
  23768. @see getCurrentlyModalComponent
  23769. */
  23770. bool isCurrentlyModal() const throw();
  23771. /** Returns the number of components that are currently in a modal state.
  23772. @see getCurrentlyModalComponent
  23773. */
  23774. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  23775. /** Returns one of the components that are currently modal.
  23776. The index specifies which of the possible modal components to return. The order
  23777. of the components in this list is the reverse of the order in which they became
  23778. modal - so the component at index 0 is always the active component, and the others
  23779. are progressively earlier ones that are themselves now blocked by later ones.
  23780. @returns the modal component, or null if no components are modal (or if the
  23781. index is out of range)
  23782. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  23783. */
  23784. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  23785. /** Checks whether there's a modal component somewhere that's stopping this one
  23786. from receiving messages.
  23787. If there is a modal component, its canModalEventBeSentToComponent() method
  23788. will be called to see if it will still allow this component to receive events.
  23789. @see runModalLoop, getCurrentlyModalComponent
  23790. */
  23791. bool isCurrentlyBlockedByAnotherModalComponent() const;
  23792. /** When a component is modal, this callback allows it to choose which other
  23793. components can still receive events.
  23794. When a modal component is active and the user clicks on a non-modal component,
  23795. this method is called on the modal component, and if it returns true, the
  23796. event is allowed to reach its target. If it returns false, the event is blocked
  23797. and the inputAttemptWhenModal() callback is made.
  23798. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  23799. implementation just returns false in all cases.
  23800. */
  23801. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  23802. /** Called when the user tries to click on a component that is blocked by another
  23803. modal component.
  23804. When a component is modal and the user clicks on one of the other components,
  23805. the modal component will receive this callback.
  23806. The default implementation of this method will play a beep, and bring the currently
  23807. modal component to the front, but it can be overridden to do other tasks.
  23808. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  23809. */
  23810. virtual void inputAttemptWhenModal();
  23811. /** Returns the set of properties that belong to this component.
  23812. Each component has a NamedValueSet object which you can use to attach arbitrary
  23813. items of data to it.
  23814. */
  23815. NamedValueSet& getProperties() throw() { return properties; }
  23816. /** Returns the set of properties that belong to this component.
  23817. Each component has a NamedValueSet object which you can use to attach arbitrary
  23818. items of data to it.
  23819. */
  23820. const NamedValueSet& getProperties() const throw() { return properties; }
  23821. /** Looks for a colour that has been registered with the given colour ID number.
  23822. If a colour has been set for this ID number using setColour(), then it is
  23823. returned. If none has been set, the method will try calling the component's
  23824. LookAndFeel class's findColour() method. If none has been registered with the
  23825. look-and-feel either, it will just return black.
  23826. The colour IDs for various purposes are stored as enums in the components that
  23827. they are relevent to - for an example, see Slider::ColourIds,
  23828. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  23829. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  23830. */
  23831. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  23832. /** Registers a colour to be used for a particular purpose.
  23833. Changing a colour will cause a synchronous callback to the colourChanged()
  23834. method, which your component can override if it needs to do something when
  23835. colours are altered.
  23836. For more details about colour IDs, see the comments for findColour().
  23837. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  23838. */
  23839. void setColour (int colourId, const Colour& colour);
  23840. /** If a colour has been set with setColour(), this will remove it.
  23841. This allows you to make a colour revert to its default state.
  23842. */
  23843. void removeColour (int colourId);
  23844. /** Returns true if the specified colour ID has been explicitly set for this
  23845. component using the setColour() method.
  23846. */
  23847. bool isColourSpecified (int colourId) const;
  23848. /** This looks for any colours that have been specified for this component,
  23849. and copies them to the specified target component.
  23850. */
  23851. void copyAllExplicitColoursTo (Component& target) const;
  23852. /** This method is called when a colour is changed by the setColour() method.
  23853. @see setColour, findColour
  23854. */
  23855. virtual void colourChanged();
  23856. /** Components can implement this method to provide a MarkerList.
  23857. The default implementation of this method returns 0, but you can override it to
  23858. return a pointer to the component's marker list. If xAxis is true, it should
  23859. return the X marker list; if false, it should return the Y markers.
  23860. */
  23861. virtual MarkerList* getMarkers (bool xAxis);
  23862. /** Returns the underlying native window handle for this component.
  23863. This is platform-dependent and strictly for power-users only!
  23864. */
  23865. void* getWindowHandle() const;
  23866. /** Holds a pointer to some type of Component, which automatically becomes null if
  23867. the component is deleted.
  23868. If you're using a component which may be deleted by another event that's outside
  23869. of your control, use a SafePointer instead of a normal pointer to refer to it,
  23870. and you can test whether it's null before using it to see if something has deleted
  23871. it.
  23872. The ComponentType typedef must be Component, or some subclass of Component.
  23873. You may also want to use a WeakReference<Component> object for the same purpose.
  23874. */
  23875. template <class ComponentType>
  23876. class SafePointer
  23877. {
  23878. public:
  23879. /** Creates a null SafePointer. */
  23880. SafePointer() throw() {}
  23881. /** Creates a SafePointer that points at the given component. */
  23882. SafePointer (ComponentType* const component) : weakRef (component) {}
  23883. /** Creates a copy of another SafePointer. */
  23884. SafePointer (const SafePointer& other) throw() : weakRef (other.weakRef) {}
  23885. /** Copies another pointer to this one. */
  23886. SafePointer& operator= (const SafePointer& other) { weakRef = other.weakRef; return *this; }
  23887. /** Copies another pointer to this one. */
  23888. SafePointer& operator= (ComponentType* const newComponent) { weakRef = newComponent; return *this; }
  23889. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  23890. ComponentType* getComponent() const throw() { return dynamic_cast <ComponentType*> (weakRef.get()); }
  23891. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  23892. operator ComponentType*() const throw() { return getComponent(); }
  23893. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  23894. ComponentType* operator->() throw() { return getComponent(); }
  23895. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  23896. const ComponentType* operator->() const throw() { return getComponent(); }
  23897. /** If the component is valid, this deletes it and sets this pointer to null. */
  23898. void deleteAndZero() { delete getComponent(); jassert (getComponent() == 0); }
  23899. bool operator== (ComponentType* component) const throw() { return weakRef == component; }
  23900. bool operator!= (ComponentType* component) const throw() { return weakRef != component; }
  23901. private:
  23902. WeakReference<Component> weakRef;
  23903. };
  23904. /** A class to keep an eye on a component and check for it being deleted.
  23905. This is designed for use with the ListenerList::callChecked() methods, to allow
  23906. the list iterator to stop cleanly if the component is deleted by a listener callback
  23907. while the list is still being iterated.
  23908. */
  23909. class JUCE_API BailOutChecker
  23910. {
  23911. public:
  23912. /** Creates a checker that watches one component. */
  23913. BailOutChecker (Component* component);
  23914. /** Returns true if either of the two components have been deleted since this object was created. */
  23915. bool shouldBailOut() const throw();
  23916. private:
  23917. const WeakReference<Component> safePointer;
  23918. JUCE_DECLARE_NON_COPYABLE (BailOutChecker);
  23919. };
  23920. /**
  23921. Base class for objects that can be used to automatically position a component according to
  23922. some kind of algorithm.
  23923. The component class simply holds onto a reference to a Positioner, but doesn't actually do
  23924. anything with it - all the functionality must be implemented by the positioner itself (e.g.
  23925. it might choose to watch some kind of value and move the component when the value changes).
  23926. */
  23927. class JUCE_API Positioner
  23928. {
  23929. public:
  23930. /** Creates a Positioner which can control the specified component. */
  23931. explicit Positioner (Component& component) throw();
  23932. /** Destructor. */
  23933. virtual ~Positioner() {}
  23934. /** Returns the component that this positioner controls. */
  23935. Component& getComponent() const throw() { return component; }
  23936. private:
  23937. Component& component;
  23938. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  23939. };
  23940. /** Returns the Positioner object that has been set for this component.
  23941. @see setPositioner()
  23942. */
  23943. Positioner* getPositioner() const throw();
  23944. /** Sets a new Positioner object for this component.
  23945. If there's currently another positioner set, it will be deleted. The object that is passed in
  23946. will be deleted automatically by this component when it's no longer required. Pass a null pointer
  23947. to clear the current positioner.
  23948. @see getPositioner()
  23949. */
  23950. void setPositioner (Positioner* newPositioner);
  23951. #ifndef DOXYGEN
  23952. // These methods are deprecated - use localPointToGlobal, getLocalPoint, getLocalPoint, etc instead.
  23953. JUCE_DEPRECATED (const Point<int> relativePositionToGlobal (const Point<int>&) const);
  23954. JUCE_DEPRECATED (const Point<int> globalPositionToRelative (const Point<int>&) const);
  23955. JUCE_DEPRECATED (const Point<int> relativePositionToOtherComponent (const Component*, const Point<int>&) const);
  23956. #endif
  23957. private:
  23958. friend class ComponentPeer;
  23959. friend class MouseInputSource;
  23960. friend class MouseInputSourceInternal;
  23961. #ifndef DOXYGEN
  23962. static Component* currentlyFocusedComponent;
  23963. String componentName, componentID;
  23964. Component* parentComponent;
  23965. Rectangle<int> bounds;
  23966. ScopedPointer <Positioner> positioner;
  23967. ScopedPointer <AffineTransform> affineTransform;
  23968. Array <Component*> childComponentList;
  23969. LookAndFeel* lookAndFeel;
  23970. MouseCursor cursor;
  23971. ImageEffectFilter* effect;
  23972. Image bufferedImage;
  23973. class MouseListenerList;
  23974. friend class MouseListenerList;
  23975. friend class ScopedPointer <MouseListenerList>;
  23976. ScopedPointer <MouseListenerList> mouseListeners;
  23977. ScopedPointer <Array <KeyListener*> > keyListeners;
  23978. ListenerList <ComponentListener> componentListeners;
  23979. NamedValueSet properties;
  23980. friend class WeakReference<Component>;
  23981. WeakReference<Component>::Master weakReferenceMaster;
  23982. const WeakReference<Component>::SharedRef& getWeakReference();
  23983. struct ComponentFlags
  23984. {
  23985. bool hasHeavyweightPeerFlag : 1;
  23986. bool visibleFlag : 1;
  23987. bool opaqueFlag : 1;
  23988. bool ignoresMouseClicksFlag : 1;
  23989. bool allowChildMouseClicksFlag : 1;
  23990. bool wantsFocusFlag : 1;
  23991. bool isFocusContainerFlag : 1;
  23992. bool dontFocusOnMouseClickFlag : 1;
  23993. bool alwaysOnTopFlag : 1;
  23994. bool bufferToImageFlag : 1;
  23995. bool bringToFrontOnClickFlag : 1;
  23996. bool repaintOnMouseActivityFlag : 1;
  23997. bool mouseDownFlag : 1;
  23998. bool mouseOverFlag : 1;
  23999. bool mouseInsideFlag : 1;
  24000. bool currentlyModalFlag : 1;
  24001. bool isDisabledFlag : 1;
  24002. bool childCompFocusedFlag : 1;
  24003. bool dontClipGraphicsFlag : 1;
  24004. #if JUCE_DEBUG
  24005. bool isInsidePaintCall : 1;
  24006. #endif
  24007. };
  24008. union
  24009. {
  24010. uint32 componentFlags;
  24011. ComponentFlags flags;
  24012. };
  24013. uint8 componentTransparency;
  24014. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24015. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24016. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24017. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  24018. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24019. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  24020. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  24021. void internalBroughtToFront();
  24022. void internalFocusGain (const FocusChangeType cause, const WeakReference<Component>&);
  24023. void internalFocusGain (const FocusChangeType cause);
  24024. void internalFocusLoss (const FocusChangeType cause);
  24025. void internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>&);
  24026. void internalModalInputAttempt();
  24027. void internalModifierKeysChanged();
  24028. void internalChildrenChanged();
  24029. void internalHierarchyChanged();
  24030. Component* removeChildComponent (int index, bool sendParentEvents, bool sendChildEvents);
  24031. void moveChildInternal (int sourceIndex, int destIndex);
  24032. void paintComponentAndChildren (Graphics& g);
  24033. void paintComponent (Graphics& g);
  24034. void paintWithinParentContext (Graphics& g);
  24035. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  24036. void repaintParent();
  24037. void sendFakeMouseMove() const;
  24038. void takeKeyboardFocus (const FocusChangeType cause);
  24039. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  24040. static void giveAwayFocus (bool sendFocusLossEvent);
  24041. void sendEnablementChangeMessage();
  24042. void sendVisibilityChangeMessage();
  24043. class ComponentHelpers;
  24044. friend class ComponentHelpers;
  24045. /* Components aren't allowed to have copy constructors, as this would mess up parent hierarchies.
  24046. You might need to give your subclasses a private dummy constructor to avoid compiler warnings.
  24047. */
  24048. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Component);
  24049. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  24050. // This is included here just to cause a compile error if your code is still handling
  24051. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  24052. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  24053. // implement its methods instead of this Component method).
  24054. virtual void filesDropped (const StringArray&, int, int) {}
  24055. // This is included here to cause an error if you use or overload it - it has been deprecated in
  24056. // favour of contains (const Point<int>&)
  24057. void contains (int, int);
  24058. #endif
  24059. protected:
  24060. /** @internal */
  24061. virtual void internalRepaint (int x, int y, int w, int h);
  24062. /** @internal */
  24063. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  24064. #endif
  24065. };
  24066. #endif // __JUCE_COMPONENT_JUCEHEADER__
  24067. /*** End of inlined file: juce_Component.h ***/
  24068. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  24069. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  24070. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  24071. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  24072. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  24073. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  24074. /** A type used to hold the unique ID for an application command.
  24075. This is a numeric type, so it can be stored as an integer.
  24076. @see ApplicationCommandInfo, ApplicationCommandManager,
  24077. ApplicationCommandTarget, KeyPressMappingSet
  24078. */
  24079. typedef int CommandID;
  24080. /** A set of general-purpose application command IDs.
  24081. Because these commands are likely to be used in most apps, they're defined
  24082. here to help different apps to use the same numeric values for them.
  24083. Of course you don't have to use these, but some of them are used internally by
  24084. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  24085. @see ApplicationCommandInfo, ApplicationCommandManager,
  24086. ApplicationCommandTarget, KeyPressMappingSet
  24087. */
  24088. namespace StandardApplicationCommandIDs
  24089. {
  24090. /** This command ID should be used to send a "Quit the App" command.
  24091. This command is recognised by the JUCEApplication class, so if it is invoked
  24092. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  24093. object will catch it and call JUCEApplication::systemRequestedQuit().
  24094. */
  24095. static const CommandID quit = 0x1001;
  24096. /** The command ID that should be used to send a "Delete" command. */
  24097. static const CommandID del = 0x1002;
  24098. /** The command ID that should be used to send a "Cut" command. */
  24099. static const CommandID cut = 0x1003;
  24100. /** The command ID that should be used to send a "Copy to clipboard" command. */
  24101. static const CommandID copy = 0x1004;
  24102. /** The command ID that should be used to send a "Paste from clipboard" command. */
  24103. static const CommandID paste = 0x1005;
  24104. /** The command ID that should be used to send a "Select all" command. */
  24105. static const CommandID selectAll = 0x1006;
  24106. /** The command ID that should be used to send a "Deselect all" command. */
  24107. static const CommandID deselectAll = 0x1007;
  24108. }
  24109. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  24110. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  24111. /**
  24112. Holds information describing an application command.
  24113. This object is used to pass information about a particular command, such as its
  24114. name, description and other usage flags.
  24115. When an ApplicationCommandTarget is asked to provide information about the commands
  24116. it can perform, this is the structure gets filled-in to describe each one.
  24117. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  24118. ApplicationCommandManager
  24119. */
  24120. struct JUCE_API ApplicationCommandInfo
  24121. {
  24122. explicit ApplicationCommandInfo (CommandID commandID) throw();
  24123. /** Sets a number of the structures values at once.
  24124. The meanings of each of the parameters is described below, in the appropriate
  24125. member variable's description.
  24126. */
  24127. void setInfo (const String& shortName,
  24128. const String& description,
  24129. const String& categoryName,
  24130. int flags) throw();
  24131. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  24132. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  24133. is false, the bit is set.
  24134. */
  24135. void setActive (bool isActive) throw();
  24136. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  24137. */
  24138. void setTicked (bool isTicked) throw();
  24139. /** Handy method for adding a keypress to the defaultKeypresses array.
  24140. This is just so you can write things like:
  24141. @code
  24142. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  24143. @endcode
  24144. instead of
  24145. @code
  24146. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  24147. @endcode
  24148. */
  24149. void addDefaultKeypress (int keyCode,
  24150. const ModifierKeys& modifiers) throw();
  24151. /** The command's unique ID number.
  24152. */
  24153. CommandID commandID;
  24154. /** A short name to describe the command.
  24155. This should be suitable for use in menus, on buttons that trigger the command, etc.
  24156. You can use the setInfo() method to quickly set this and some of the command's
  24157. other properties.
  24158. */
  24159. String shortName;
  24160. /** A longer description of the command.
  24161. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  24162. pop-up tooltip describing what the command does.
  24163. You can use the setInfo() method to quickly set this and some of the command's
  24164. other properties.
  24165. */
  24166. String description;
  24167. /** A named category that the command fits into.
  24168. You can give your commands any category you like, and these will be displayed in
  24169. contexts such as the KeyMappingEditorComponent, where the category is used to group
  24170. commands together.
  24171. You can use the setInfo() method to quickly set this and some of the command's
  24172. other properties.
  24173. */
  24174. String categoryName;
  24175. /** A list of zero or more keypresses that should be used as the default keys for
  24176. this command.
  24177. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  24178. this list to initialise the default set of key-to-command mappings.
  24179. @see addDefaultKeypress
  24180. */
  24181. Array <KeyPress> defaultKeypresses;
  24182. /** Flags describing the ways in which this command should be used.
  24183. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  24184. variable.
  24185. */
  24186. enum CommandFlags
  24187. {
  24188. /** Indicates that the command can't currently be performed.
  24189. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  24190. not currently permissable to perform the command. If the flag is set, then
  24191. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  24192. command or show themselves as not being enabled.
  24193. @see ApplicationCommandInfo::setActive
  24194. */
  24195. isDisabled = 1 << 0,
  24196. /** Indicates that the command should have a tick next to it on a menu.
  24197. If your command is shown on a menu and this is set, it'll show a tick next to
  24198. it. Other components such as buttons may also use this flag to indicate that it
  24199. is a value that can be toggled, and is currently in the 'on' state.
  24200. @see ApplicationCommandInfo::setTicked
  24201. */
  24202. isTicked = 1 << 1,
  24203. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  24204. it will call the command twice, once on key-down and again on key-up.
  24205. @see ApplicationCommandTarget::InvocationInfo
  24206. */
  24207. wantsKeyUpDownCallbacks = 1 << 2,
  24208. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  24209. command in its list.
  24210. */
  24211. hiddenFromKeyEditor = 1 << 3,
  24212. /** If this flag is present, then a KeyMappingEditorComponent will display the
  24213. command in its list, but won't allow the assigned keypress to be changed.
  24214. */
  24215. readOnlyInKeyEditor = 1 << 4,
  24216. /** If this flag is present and the command is invoked from a keypress, then any
  24217. buttons or menus that are also connected to the command will not flash to
  24218. indicate that they've been triggered.
  24219. */
  24220. dontTriggerVisualFeedback = 1 << 5
  24221. };
  24222. /** A bitwise-OR of the values specified in the CommandFlags enum.
  24223. You can use the setInfo() method to quickly set this and some of the command's
  24224. other properties.
  24225. */
  24226. int flags;
  24227. };
  24228. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  24229. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  24230. /*** Start of inlined file: juce_MessageListener.h ***/
  24231. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  24232. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  24233. /**
  24234. MessageListener subclasses can post and receive Message objects.
  24235. @see Message, MessageManager, ActionListener, ChangeListener
  24236. */
  24237. class JUCE_API MessageListener
  24238. {
  24239. protected:
  24240. /** Creates a MessageListener. */
  24241. MessageListener() throw();
  24242. public:
  24243. /** Destructor.
  24244. When a MessageListener is deleted, it removes itself from a global list
  24245. of registered listeners, so that the isValidMessageListener() method
  24246. will no longer return true.
  24247. */
  24248. virtual ~MessageListener();
  24249. /** This is the callback method that receives incoming messages.
  24250. This is called by the MessageManager from its dispatch loop.
  24251. @see postMessage
  24252. */
  24253. virtual void handleMessage (const Message& message) = 0;
  24254. /** Sends a message to the message queue, for asynchronous delivery to this listener
  24255. later on.
  24256. This method can be called safely by any thread.
  24257. @param message the message object to send - this will be deleted
  24258. automatically by the message queue, so don't keep any
  24259. references to it after calling this method.
  24260. @see handleMessage
  24261. */
  24262. void postMessage (Message* message) const throw();
  24263. /** Checks whether this MessageListener has been deleted.
  24264. Although not foolproof, this method is safe to call on dangling or null
  24265. pointers. A list of active MessageListeners is kept internally, so this
  24266. checks whether the object is on this list or not.
  24267. Note that it's possible to get a false-positive here, if an object is
  24268. deleted and another is subsequently created that happens to be at the
  24269. exact same memory location, but I can't think of a good way of avoiding
  24270. this.
  24271. */
  24272. bool isValidMessageListener() const throw();
  24273. };
  24274. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  24275. /*** End of inlined file: juce_MessageListener.h ***/
  24276. /**
  24277. A command target publishes a list of command IDs that it can perform.
  24278. An ApplicationCommandManager despatches commands to targets, which must be
  24279. able to provide information about what commands they can handle.
  24280. To create a target, you'll need to inherit from this class, implementing all of
  24281. its pure virtual methods.
  24282. For info about how a target is chosen to receive a command, see
  24283. ApplicationCommandManager::getFirstCommandTarget().
  24284. @see ApplicationCommandManager, ApplicationCommandInfo
  24285. */
  24286. class JUCE_API ApplicationCommandTarget
  24287. {
  24288. public:
  24289. /** Creates a command target. */
  24290. ApplicationCommandTarget();
  24291. /** Destructor. */
  24292. virtual ~ApplicationCommandTarget();
  24293. /**
  24294. */
  24295. struct JUCE_API InvocationInfo
  24296. {
  24297. InvocationInfo (const CommandID commandID);
  24298. /** The UID of the command that should be performed. */
  24299. CommandID commandID;
  24300. /** The command's flags.
  24301. See ApplicationCommandInfo for a description of these flag values.
  24302. */
  24303. int commandFlags;
  24304. /** The types of context in which the command might be called. */
  24305. enum InvocationMethod
  24306. {
  24307. direct = 0, /**< The command is being invoked directly by a piece of code. */
  24308. fromKeyPress, /**< The command is being invoked by a key-press. */
  24309. fromMenu, /**< The command is being invoked by a menu selection. */
  24310. fromButton /**< The command is being invoked by a button click. */
  24311. };
  24312. /** The type of event that triggered this command. */
  24313. InvocationMethod invocationMethod;
  24314. /** If triggered by a keypress or menu, this will be the component that had the
  24315. keyboard focus at the time.
  24316. If triggered by a button, it may be set to that component, or it may be null.
  24317. */
  24318. Component* originatingComponent;
  24319. /** The keypress that was used to invoke it.
  24320. Note that this will be an invalid keypress if the command was invoked
  24321. by some other means than a keyboard shortcut.
  24322. */
  24323. KeyPress keyPress;
  24324. /** True if the callback is being invoked when the key is pressed,
  24325. false if the key is being released.
  24326. @see KeyPressMappingSet::addCommand()
  24327. */
  24328. bool isKeyDown;
  24329. /** If the key is being released, this indicates how long it had been held
  24330. down for.
  24331. (Only relevant if isKeyDown is false.)
  24332. */
  24333. int millisecsSinceKeyPressed;
  24334. };
  24335. /** This must return the next target to try after this one.
  24336. When a command is being sent, and the first target can't handle
  24337. that command, this method is used to determine the next target that should
  24338. be tried.
  24339. It may return 0 if it doesn't know of another target.
  24340. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  24341. method to return a parent component that might want to handle it.
  24342. @see invoke
  24343. */
  24344. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  24345. /** This must return a complete list of commands that this target can handle.
  24346. Your target should add all the command IDs that it handles to the array that is
  24347. passed-in.
  24348. */
  24349. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  24350. /** This must provide details about one of the commands that this target can perform.
  24351. This will be called with one of the command IDs that the target provided in its
  24352. getAllCommands() methods.
  24353. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  24354. suitable information about the command. (The commandID field will already have been filled-in
  24355. by the caller).
  24356. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  24357. set all the fields at once.
  24358. If the command is currently inactive for some reason, this method must use
  24359. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  24360. bit of the ApplicationCommandInfo::flags field).
  24361. Any default key-presses for the command should be appended to the
  24362. ApplicationCommandInfo::defaultKeypresses field.
  24363. Note that if you change something that affects the status of the commands
  24364. that would be returned by this method (e.g. something that makes some commands
  24365. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  24366. to cause the manager to refresh its status.
  24367. */
  24368. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  24369. /** This must actually perform the specified command.
  24370. If this target is able to perform the command specified by the commandID field of the
  24371. InvocationInfo structure, then it should do so, and must return true.
  24372. If it can't handle this command, it should return false, which tells the caller to pass
  24373. the command on to the next target in line.
  24374. @see invoke, ApplicationCommandManager::invoke
  24375. */
  24376. virtual bool perform (const InvocationInfo& info) = 0;
  24377. /** Makes this target invoke a command.
  24378. Your code can call this method to invoke a command on this target, but normally
  24379. you'd call it indirectly via ApplicationCommandManager::invoke() or
  24380. ApplicationCommandManager::invokeDirectly().
  24381. If this target can perform the given command, it will call its perform() method to
  24382. do so. If not, then getNextCommandTarget() will be used to determine the next target
  24383. to try, and the command will be passed along to it.
  24384. @param invocationInfo this must be correctly filled-in, describing the context for
  24385. the invocation.
  24386. @param asynchronously if false, the command will be performed before this method returns.
  24387. If true, a message will be posted so that the command will be performed
  24388. later on the message thread, and this method will return immediately.
  24389. @see perform, ApplicationCommandManager::invoke
  24390. */
  24391. bool invoke (const InvocationInfo& invocationInfo,
  24392. const bool asynchronously);
  24393. /** Invokes a given command directly on this target.
  24394. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  24395. structure.
  24396. */
  24397. bool invokeDirectly (const CommandID commandID,
  24398. const bool asynchronously);
  24399. /** Searches this target and all subsequent ones for the first one that can handle
  24400. the specified command.
  24401. This will use getNextCommandTarget() to determine the chain of targets to try
  24402. after this one.
  24403. */
  24404. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  24405. /** Checks whether this command can currently be performed by this target.
  24406. This will return true only if a call to getCommandInfo() doesn't set the
  24407. isDisabled flag to indicate that the command is inactive.
  24408. */
  24409. bool isCommandActive (const CommandID commandID);
  24410. /** If this object is a Component, this method will seach upwards in its current
  24411. UI hierarchy for the next parent component that implements the
  24412. ApplicationCommandTarget class.
  24413. If your target is a Component, this is a very handy method to use in your
  24414. getNextCommandTarget() implementation.
  24415. */
  24416. ApplicationCommandTarget* findFirstTargetParentComponent();
  24417. private:
  24418. // (for async invocation of commands)
  24419. class CommandTargetMessageInvoker : public MessageListener
  24420. {
  24421. public:
  24422. CommandTargetMessageInvoker (ApplicationCommandTarget* owner);
  24423. ~CommandTargetMessageInvoker();
  24424. void handleMessage (const Message& message);
  24425. private:
  24426. ApplicationCommandTarget* const owner;
  24427. JUCE_DECLARE_NON_COPYABLE (CommandTargetMessageInvoker);
  24428. };
  24429. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  24430. friend class CommandTargetMessageInvoker;
  24431. bool tryToInvoke (const InvocationInfo& info, bool async);
  24432. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandTarget);
  24433. };
  24434. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  24435. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  24436. /*** Start of inlined file: juce_ActionListener.h ***/
  24437. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  24438. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  24439. /**
  24440. Receives callbacks to indicate that some kind of event has occurred.
  24441. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  24442. about something that's happened.
  24443. @see ActionBroadcaster, ChangeListener
  24444. */
  24445. class JUCE_API ActionListener
  24446. {
  24447. public:
  24448. /** Destructor. */
  24449. virtual ~ActionListener() {}
  24450. /** Overridden by your subclass to receive the callback.
  24451. @param message the string that was specified when the event was triggered
  24452. by a call to ActionBroadcaster::sendActionMessage()
  24453. */
  24454. virtual void actionListenerCallback (const String& message) = 0;
  24455. };
  24456. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  24457. /*** End of inlined file: juce_ActionListener.h ***/
  24458. /**
  24459. An instance of this class is used to specify initialisation and shutdown
  24460. code for the application.
  24461. An application that wants to run in the JUCE framework needs to declare a
  24462. subclass of JUCEApplication and implement its various pure virtual methods.
  24463. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  24464. to declare an instance of this class and generate a suitable platform-specific
  24465. main() function.
  24466. e.g. @code
  24467. class MyJUCEApp : public JUCEApplication
  24468. {
  24469. public:
  24470. MyJUCEApp()
  24471. {
  24472. }
  24473. ~MyJUCEApp()
  24474. {
  24475. }
  24476. void initialise (const String& commandLine)
  24477. {
  24478. myMainWindow = new MyApplicationWindow();
  24479. myMainWindow->setBounds (100, 100, 400, 500);
  24480. myMainWindow->setVisible (true);
  24481. }
  24482. void shutdown()
  24483. {
  24484. myMainWindow = 0;
  24485. }
  24486. const String getApplicationName()
  24487. {
  24488. return "Super JUCE-o-matic";
  24489. }
  24490. const String getApplicationVersion()
  24491. {
  24492. return "1.0";
  24493. }
  24494. private:
  24495. ScopedPointer <MyApplicationWindow> myMainWindow;
  24496. };
  24497. // this creates wrapper code to actually launch the app properly.
  24498. START_JUCE_APPLICATION (MyJUCEApp)
  24499. @endcode
  24500. @see MessageManager, DeletedAtShutdown
  24501. */
  24502. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  24503. private ActionListener
  24504. {
  24505. protected:
  24506. /** Constructs a JUCE app object.
  24507. If subclasses implement a constructor or destructor, they shouldn't call any
  24508. JUCE code in there - put your startup/shutdown code in initialise() and
  24509. shutdown() instead.
  24510. */
  24511. JUCEApplication();
  24512. public:
  24513. /** Destructor.
  24514. If subclasses implement a constructor or destructor, they shouldn't call any
  24515. JUCE code in there - put your startup/shutdown code in initialise() and
  24516. shutdown() instead.
  24517. */
  24518. virtual ~JUCEApplication();
  24519. /** Returns the global instance of the application object being run. */
  24520. static JUCEApplication* getInstance() throw() { return appInstance; }
  24521. /** Called when the application starts.
  24522. This will be called once to let the application do whatever initialisation
  24523. it needs, create its windows, etc.
  24524. After the method returns, the normal event-dispatch loop will be run,
  24525. until the quit() method is called, at which point the shutdown()
  24526. method will be called to let the application clear up anything it needs
  24527. to delete.
  24528. If during the initialise() method, the application decides not to start-up
  24529. after all, it can just call the quit() method and the event loop won't be run.
  24530. @param commandLineParameters the line passed in does not include the
  24531. name of the executable, just the parameter list.
  24532. @see shutdown, quit
  24533. */
  24534. virtual void initialise (const String& commandLineParameters) = 0;
  24535. /** Returns true if the application hasn't yet completed its initialise() method
  24536. and entered the main event loop.
  24537. This is handy for things like splash screens to know when the app's up-and-running
  24538. properly.
  24539. */
  24540. bool isInitialising() const throw() { return stillInitialising; }
  24541. /* Called to allow the application to clear up before exiting.
  24542. After JUCEApplication::quit() has been called, the event-dispatch loop will
  24543. terminate, and this method will get called to allow the app to sort itself
  24544. out.
  24545. Be careful that nothing happens in this method that might rely on messages
  24546. being sent, or any kind of window activity, because the message loop is no
  24547. longer running at this point.
  24548. @see DeletedAtShutdown
  24549. */
  24550. virtual void shutdown() = 0;
  24551. /** Returns the application's name.
  24552. An application must implement this to name itself.
  24553. */
  24554. virtual const String getApplicationName() = 0;
  24555. /** Returns the application's version number.
  24556. */
  24557. virtual const String getApplicationVersion() = 0;
  24558. /** Checks whether multiple instances of the app are allowed.
  24559. If you application class returns true for this, more than one instance is
  24560. permitted to run (except on the Mac where this isn't possible).
  24561. If it's false, the second instance won't start, but it you will still get a
  24562. callback to anotherInstanceStarted() to tell you about this - which
  24563. gives you a chance to react to what the user was trying to do.
  24564. */
  24565. virtual bool moreThanOneInstanceAllowed();
  24566. /** Indicates that the user has tried to start up another instance of the app.
  24567. This will get called even if moreThanOneInstanceAllowed() is false.
  24568. */
  24569. virtual void anotherInstanceStarted (const String& commandLine);
  24570. /** Called when the operating system is trying to close the application.
  24571. The default implementation of this method is to call quit(), but it may
  24572. be overloaded to ignore the request or do some other special behaviour
  24573. instead. For example, you might want to offer the user the chance to save
  24574. their changes before quitting, and give them the chance to cancel.
  24575. If you want to send a quit signal to your app, this is the correct method
  24576. to call, because it means that requests that come from the system get handled
  24577. in the same way as those from your own application code. So e.g. you'd
  24578. call this method from a "quit" item on a menu bar.
  24579. */
  24580. virtual void systemRequestedQuit();
  24581. /** If any unhandled exceptions make it through to the message dispatch loop, this
  24582. callback will be triggered, in case you want to log them or do some other
  24583. type of error-handling.
  24584. If the type of exception is derived from the std::exception class, the pointer
  24585. passed-in will be valid. If the exception is of unknown type, this pointer
  24586. will be null.
  24587. */
  24588. virtual void unhandledException (const std::exception* e,
  24589. const String& sourceFilename,
  24590. int lineNumber);
  24591. /** Signals that the main message loop should stop and the application should terminate.
  24592. This isn't synchronous, it just posts a quit message to the main queue, and
  24593. when this message arrives, the message loop will stop, the shutdown() method
  24594. will be called, and the app will exit.
  24595. Note that this will cause an unconditional quit to happen, so if you need an
  24596. extra level before this, e.g. to give the user the chance to save their work
  24597. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  24598. method - see that method's help for more info.
  24599. @see MessageManager, DeletedAtShutdown
  24600. */
  24601. static void quit();
  24602. /** Sets the value that should be returned as the application's exit code when the
  24603. app quits.
  24604. This is the value that's returned by the main() function. Normally you'd leave this
  24605. as 0 unless you want to indicate an error code.
  24606. @see getApplicationReturnValue
  24607. */
  24608. void setApplicationReturnValue (int newReturnValue) throw();
  24609. /** Returns the value that has been set as the application's exit code.
  24610. @see setApplicationReturnValue
  24611. */
  24612. int getApplicationReturnValue() const throw() { return appReturnValue; }
  24613. /** Returns the application's command line params.
  24614. */
  24615. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  24616. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  24617. /** @internal */
  24618. static int main (const String& commandLine);
  24619. /** @internal */
  24620. static int main (int argc, const char* argv[]);
  24621. /** @internal */
  24622. static void sendUnhandledException (const std::exception* e, const char* sourceFile, int lineNumber);
  24623. /** Returns true if this executable is running as an app (as opposed to being a plugin
  24624. or other kind of shared library. */
  24625. static inline bool isStandaloneApp() throw() { return createInstance != 0; }
  24626. /** @internal */
  24627. ApplicationCommandTarget* getNextCommandTarget();
  24628. /** @internal */
  24629. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  24630. /** @internal */
  24631. void getAllCommands (Array <CommandID>& commands);
  24632. /** @internal */
  24633. bool perform (const InvocationInfo& info);
  24634. /** @internal */
  24635. void actionListenerCallback (const String& message);
  24636. /** @internal */
  24637. bool initialiseApp (const String& commandLine);
  24638. /** @internal */
  24639. int shutdownApp();
  24640. /** @internal */
  24641. static void appWillTerminateByForce();
  24642. /** @internal */
  24643. typedef JUCEApplication* (*CreateInstanceFunction)();
  24644. /** @internal */
  24645. static CreateInstanceFunction createInstance;
  24646. private:
  24647. String commandLineParameters;
  24648. int appReturnValue;
  24649. bool stillInitialising;
  24650. ScopedPointer<InterProcessLock> appLock;
  24651. static JUCEApplication* appInstance;
  24652. JUCE_DECLARE_NON_COPYABLE (JUCEApplication);
  24653. };
  24654. #endif // __JUCE_APPLICATION_JUCEHEADER__
  24655. /*** End of inlined file: juce_Application.h ***/
  24656. #endif
  24657. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  24658. #endif
  24659. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  24660. #endif
  24661. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  24662. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  24663. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  24664. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  24665. /*** Start of inlined file: juce_Desktop.h ***/
  24666. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  24667. #define __JUCE_DESKTOP_JUCEHEADER__
  24668. /*** Start of inlined file: juce_Timer.h ***/
  24669. #ifndef __JUCE_TIMER_JUCEHEADER__
  24670. #define __JUCE_TIMER_JUCEHEADER__
  24671. class InternalTimerThread;
  24672. /**
  24673. Makes repeated callbacks to a virtual method at a specified time interval.
  24674. A Timer's timerCallback() method will be repeatedly called at a given
  24675. interval. When you create a Timer object, it will do nothing until the
  24676. startTimer() method is called, which will cause the message thread to
  24677. start making callbacks at the specified interval, until stopTimer() is called
  24678. or the object is deleted.
  24679. The time interval isn't guaranteed to be precise to any more than maybe
  24680. 10-20ms, and the intervals may end up being much longer than requested if the
  24681. system is busy. Because the callbacks are made by the main message thread,
  24682. anything that blocks the message queue for a period of time will also prevent
  24683. any timers from running until it can carry on.
  24684. If you need to have a single callback that is shared by multiple timers with
  24685. different frequencies, then the MultiTimer class allows you to do that - its
  24686. structure is very similar to the Timer class, but contains multiple timers
  24687. internally, each one identified by an ID number.
  24688. @see MultiTimer
  24689. */
  24690. class JUCE_API Timer
  24691. {
  24692. protected:
  24693. /** Creates a Timer.
  24694. When created, the timer is stopped, so use startTimer() to get it going.
  24695. */
  24696. Timer() throw();
  24697. /** Creates a copy of another timer.
  24698. Note that this timer won't be started, even if the one you're copying
  24699. is running.
  24700. */
  24701. Timer (const Timer& other) throw();
  24702. public:
  24703. /** Destructor. */
  24704. virtual ~Timer();
  24705. /** The user-defined callback routine that actually gets called periodically.
  24706. It's perfectly ok to call startTimer() or stopTimer() from within this
  24707. callback to change the subsequent intervals.
  24708. */
  24709. virtual void timerCallback() = 0;
  24710. /** Starts the timer and sets the length of interval required.
  24711. If the timer is already started, this will reset it, so the
  24712. time between calling this method and the next timer callback
  24713. will not be less than the interval length passed in.
  24714. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  24715. rounded up to 1)
  24716. */
  24717. void startTimer (int intervalInMilliseconds) throw();
  24718. /** Stops the timer.
  24719. No more callbacks will be made after this method returns.
  24720. If this is called from a different thread, any callbacks that may
  24721. be currently executing may be allowed to finish before the method
  24722. returns.
  24723. */
  24724. void stopTimer() throw();
  24725. /** Checks if the timer has been started.
  24726. @returns true if the timer is running.
  24727. */
  24728. bool isTimerRunning() const throw() { return periodMs > 0; }
  24729. /** Returns the timer's interval.
  24730. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  24731. */
  24732. int getTimerInterval() const throw() { return periodMs; }
  24733. private:
  24734. friend class InternalTimerThread;
  24735. int countdownMs, periodMs;
  24736. Timer* previous;
  24737. Timer* next;
  24738. Timer& operator= (const Timer&);
  24739. };
  24740. #endif // __JUCE_TIMER_JUCEHEADER__
  24741. /*** End of inlined file: juce_Timer.h ***/
  24742. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  24743. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  24744. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  24745. /**
  24746. Animates a set of components, moving them to a new position and/or fading their
  24747. alpha levels.
  24748. To animate a component, create a ComponentAnimator instance or (preferably) use the
  24749. global animator object provided by Desktop::getAnimator(), and call its animateComponent()
  24750. method to commence the movement.
  24751. If you're using your own ComponentAnimator instance, you'll need to make sure it isn't
  24752. deleted before it finishes moving the components, or they'll be abandoned before reaching their
  24753. destinations.
  24754. It's ok to delete components while they're being animated - the animator will detect this
  24755. and safely stop using them.
  24756. The class is a ChangeBroadcaster and sends a notification when any components
  24757. start or finish being animated.
  24758. @see Desktop::getAnimator
  24759. */
  24760. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  24761. private Timer
  24762. {
  24763. public:
  24764. /** Creates a ComponentAnimator. */
  24765. ComponentAnimator();
  24766. /** Destructor. */
  24767. ~ComponentAnimator();
  24768. /** Starts a component moving from its current position to a specified position.
  24769. If the component is already in the middle of an animation, that will be abandoned,
  24770. and a new animation will begin, moving the component from its current location.
  24771. The start and end speed parameters let you apply some acceleration to the component's
  24772. movement.
  24773. @param component the component to move
  24774. @param finalBounds the destination bounds to which the component should move. To leave the
  24775. component in the same place, just pass component->getBounds() for this value
  24776. @param finalAlpha the alpha value that the component should have at the end of the animation
  24777. @param animationDurationMilliseconds how long the animation should last, in milliseconds
  24778. @param useProxyComponent if true, this means the component should be replaced by an internally
  24779. managed temporary component which is a snapshot of the original component.
  24780. This avoids the component having to paint itself as it moves, so may
  24781. be more efficient. This option also allows you to delete the original
  24782. component immediately after starting the animation, because the animation
  24783. can proceed without it. If you use a proxy, the original component will be
  24784. made invisible by this call, and then will become visible again at the end
  24785. of the animation. It'll also mean that the proxy component will be temporarily
  24786. added to the component's parent, so avoid it if this might confuse the parent
  24787. component, or if there's a chance the parent might decide to delete its children.
  24788. @param startSpeed a value to indicate the relative start speed of the animation. If this is 0,
  24789. the component will start by accelerating from rest; higher values mean that it
  24790. will have an initial speed greater than zero. If the value if greater than 1, it
  24791. will decelerate towards the middle of its journey. To move the component at a
  24792. constant rate for its entire animation, set both the start and end speeds to 1.0
  24793. @param endSpeed a relative speed at which the component should be moving when the animation finishes.
  24794. If this is 0, the component will decelerate to a standstill at its final position;
  24795. higher values mean the component will still be moving when it stops. To move the component
  24796. at a constant rate for its entire animation, set both the start and end speeds to 1.0
  24797. */
  24798. void animateComponent (Component* component,
  24799. const Rectangle<int>& finalBounds,
  24800. float finalAlpha,
  24801. int animationDurationMilliseconds,
  24802. bool useProxyComponent,
  24803. double startSpeed,
  24804. double endSpeed);
  24805. /** Begins a fade-out of this components alpha level.
  24806. This is a quick way of invoking animateComponent() with a target alpha value of 0.0f, using
  24807. a proxy. You're safe to delete the component after calling this method, and this won't
  24808. interfere with the animation's progress.
  24809. */
  24810. void fadeOut (Component* component, int millisecondsToTake);
  24811. /** Begins a fade-in of a component.
  24812. This is a quick way of invoking animateComponent() with a target alpha value of 1.0f.
  24813. */
  24814. void fadeIn (Component* component, int millisecondsToTake);
  24815. /** Stops a component if it's currently being animated.
  24816. If moveComponentToItsFinalPosition is true, then the component will
  24817. be immediately moved to its destination position and size. If false, it will be
  24818. left in whatever location it currently occupies.
  24819. */
  24820. void cancelAnimation (Component* component,
  24821. bool moveComponentToItsFinalPosition);
  24822. /** Clears all of the active animations.
  24823. If moveComponentsToTheirFinalPositions is true, all the components will
  24824. be immediately set to their final positions. If false, they will be
  24825. left in whatever locations they currently occupy.
  24826. */
  24827. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  24828. /** Returns the destination position for a component.
  24829. If the component is being animated, this will return the target position that
  24830. was specified when animateComponent() was called.
  24831. If the specified component isn't currently being animated, this method will just
  24832. return its current position.
  24833. */
  24834. const Rectangle<int> getComponentDestination (Component* component);
  24835. /** Returns true if the specified component is currently being animated. */
  24836. bool isAnimating (Component* component) const;
  24837. private:
  24838. class AnimationTask;
  24839. OwnedArray <AnimationTask> tasks;
  24840. uint32 lastTime;
  24841. AnimationTask* findTaskFor (Component* component) const;
  24842. void timerCallback();
  24843. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentAnimator);
  24844. };
  24845. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  24846. /*** End of inlined file: juce_ComponentAnimator.h ***/
  24847. class MouseInputSource;
  24848. class MouseInputSourceInternal;
  24849. class MouseListener;
  24850. /**
  24851. Classes can implement this interface and register themselves with the Desktop class
  24852. to receive callbacks when the currently focused component changes.
  24853. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  24854. */
  24855. class JUCE_API FocusChangeListener
  24856. {
  24857. public:
  24858. /** Destructor. */
  24859. virtual ~FocusChangeListener() {}
  24860. /** Callback to indicate that the currently focused component has changed. */
  24861. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  24862. };
  24863. /**
  24864. Describes and controls aspects of the computer's desktop.
  24865. */
  24866. class JUCE_API Desktop : private DeletedAtShutdown,
  24867. private Timer,
  24868. private AsyncUpdater
  24869. {
  24870. public:
  24871. /** There's only one dektop object, and this method will return it.
  24872. */
  24873. static Desktop& JUCE_CALLTYPE getInstance();
  24874. /** Returns a list of the positions of all the monitors available.
  24875. The first rectangle in the list will be the main monitor area.
  24876. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  24877. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  24878. */
  24879. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const throw();
  24880. /** Returns the position and size of the main monitor.
  24881. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  24882. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  24883. */
  24884. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const throw();
  24885. /** Returns the position and size of the monitor which contains this co-ordinate.
  24886. If none of the monitors contains the point, this will just return the
  24887. main monitor.
  24888. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  24889. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  24890. */
  24891. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  24892. /** Returns the mouse position.
  24893. The co-ordinates are relative to the top-left of the main monitor.
  24894. Note that this is just a shortcut for calling getMainMouseSource().getScreenPosition(), and
  24895. you should only resort to grabbing the global mouse position if there's really no
  24896. way to get the coordinates via a mouse event callback instead.
  24897. */
  24898. static const Point<int> getMousePosition();
  24899. /** Makes the mouse pointer jump to a given location.
  24900. The co-ordinates are relative to the top-left of the main monitor.
  24901. */
  24902. static void setMousePosition (const Point<int>& newPosition);
  24903. /** Returns the last position at which a mouse button was pressed.
  24904. Note that this is just a shortcut for calling getMainMouseSource().getLastMouseDownPosition(),
  24905. and in a multi-touch environment, it doesn't make much sense. ALWAYS prefer to
  24906. get this information via other means, such as MouseEvent::getMouseDownScreenPosition()
  24907. if possible, and only ever call this as a last resort.
  24908. */
  24909. static const Point<int> getLastMouseDownPosition();
  24910. /** Returns the number of times the mouse button has been clicked since the
  24911. app started.
  24912. Each mouse-down event increments this number by 1.
  24913. */
  24914. static int getMouseButtonClickCounter();
  24915. /** This lets you prevent the screensaver from becoming active.
  24916. Handy if you're running some sort of presentation app where having a screensaver
  24917. appear would be annoying.
  24918. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  24919. won't enable a screensaver unless the user has actually set one up).
  24920. The disablement will only happen while the Juce application is the foreground
  24921. process - if another task is running in front of it, then the screensaver will
  24922. be unaffected.
  24923. @see isScreenSaverEnabled
  24924. */
  24925. static void setScreenSaverEnabled (bool isEnabled);
  24926. /** Returns true if the screensaver has not been turned off.
  24927. This will return the last value passed into setScreenSaverEnabled(). Note that
  24928. it won't tell you whether the user is actually using a screen saver, just
  24929. whether this app is deliberately preventing one from running.
  24930. @see setScreenSaverEnabled
  24931. */
  24932. static bool isScreenSaverEnabled();
  24933. /** Registers a MouseListener that will receive all mouse events that occur on
  24934. any component.
  24935. @see removeGlobalMouseListener
  24936. */
  24937. void addGlobalMouseListener (MouseListener* listener);
  24938. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  24939. method.
  24940. @see addGlobalMouseListener
  24941. */
  24942. void removeGlobalMouseListener (MouseListener* listener);
  24943. /** Registers a MouseListener that will receive a callback whenever the focused
  24944. component changes.
  24945. */
  24946. void addFocusChangeListener (FocusChangeListener* listener);
  24947. /** Unregisters a listener that was added with addFocusChangeListener(). */
  24948. void removeFocusChangeListener (FocusChangeListener* listener);
  24949. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  24950. The component must already be on the desktop for this method to work. It will
  24951. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  24952. etc will be hidden.
  24953. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  24954. the component that's currently being used will be resized back to the size
  24955. and position it was in before being put into this mode.
  24956. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  24957. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  24958. to hide as much on-screen paraphenalia as possible.
  24959. */
  24960. void setKioskModeComponent (Component* componentToUse,
  24961. bool allowMenusAndBars = true);
  24962. /** Returns the component that is currently being used in kiosk-mode.
  24963. This is the component that was last set by setKioskModeComponent(). If none
  24964. has been set, this returns 0.
  24965. */
  24966. Component* getKioskModeComponent() const throw() { return kioskModeComponent; }
  24967. /** Returns the number of components that are currently active as top-level
  24968. desktop windows.
  24969. @see getComponent, Component::addToDesktop
  24970. */
  24971. int getNumComponents() const throw();
  24972. /** Returns one of the top-level desktop window components.
  24973. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  24974. index is out-of-range.
  24975. @see getNumComponents, Component::addToDesktop
  24976. */
  24977. Component* getComponent (int index) const throw();
  24978. /** Finds the component at a given screen location.
  24979. This will drill down into top-level windows to find the child component at
  24980. the given position.
  24981. Returns 0 if the co-ordinates are inside a non-Juce window.
  24982. */
  24983. Component* findComponentAt (const Point<int>& screenPosition) const;
  24984. /** The Desktop object has a ComponentAnimator instance which can be used for performing
  24985. your animations.
  24986. Having a single shared ComponentAnimator object makes it more efficient when multiple
  24987. components are being moved around simultaneously. It's also more convenient than having
  24988. to manage your own instance of one.
  24989. @see ComponentAnimator
  24990. */
  24991. ComponentAnimator& getAnimator() throw() { return animator; }
  24992. /** Returns the number of MouseInputSource objects the system has at its disposal.
  24993. In a traditional single-mouse system, there might be only one object. On a multi-touch
  24994. system, there could be one input source per potential finger.
  24995. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  24996. @see getMouseSource
  24997. */
  24998. int getNumMouseSources() const throw() { return mouseSources.size(); }
  24999. /** Returns one of the system's MouseInputSource objects.
  25000. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  25001. a null pointer.
  25002. In a traditional single-mouse system, there might be only one object. On a multi-touch
  25003. system, there could be one input source per potential finger.
  25004. */
  25005. MouseInputSource* getMouseSource (int index) const throw() { return mouseSources [index]; }
  25006. /** Returns the main mouse input device that the system is using.
  25007. @see getNumMouseSources()
  25008. */
  25009. MouseInputSource& getMainMouseSource() const throw() { return *mouseSources.getUnchecked(0); }
  25010. /** Returns the number of mouse-sources that are currently being dragged.
  25011. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  25012. juce component has the button down on it. In a multi-touch system, this could
  25013. be any number from 0 to the number of simultaneous touches that can be detected.
  25014. */
  25015. int getNumDraggingMouseSources() const throw();
  25016. /** Returns one of the mouse sources that's currently being dragged.
  25017. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  25018. out of range, or if no mice or fingers are down, this will return a null pointer.
  25019. */
  25020. MouseInputSource* getDraggingMouseSource (int index) const throw();
  25021. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  25022. current mouse-drag operation.
  25023. This allows you to make sure that mouseDrag() events are sent continuously, even
  25024. when the mouse isn't moving. This can be useful for things like auto-scrolling
  25025. components when the mouse is near an edge.
  25026. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  25027. minimum interval between consecutive mouse drag callbacks. The callbacks
  25028. will continue until the mouse is released, and then the interval will be reset,
  25029. so you need to make sure it's called every time you begin a drag event.
  25030. Passing an interval of 0 or less will cancel the auto-repeat.
  25031. @see mouseDrag
  25032. */
  25033. void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
  25034. /** In a tablet device which can be turned around, this is used to inidicate the orientation. */
  25035. enum DisplayOrientation
  25036. {
  25037. upright = 1, /**< Indicates that the display is the normal way up. */
  25038. upsideDown = 2, /**< Indicates that the display is upside-down. */
  25039. rotatedClockwise = 4, /**< Indicates that the display is turned 90 degrees clockwise from its upright position. */
  25040. rotatedAntiClockwise = 8, /**< Indicates that the display is turned 90 degrees anti-clockwise from its upright position. */
  25041. allOrientations = 1 + 2 + 4 + 8 /**< A combination of all the orientation values */
  25042. };
  25043. /** In a tablet device which can be turned around, this returns the current orientation. */
  25044. DisplayOrientation getCurrentOrientation() const;
  25045. /** Sets which orientations the display is allowed to auto-rotate to.
  25046. For devices that support rotating desktops, this lets you specify which of the orientations your app can use.
  25047. The parameter is a bitwise or-ed combination of the values in DisplayOrientation, and must contain at least one
  25048. set bit.
  25049. */
  25050. void setOrientationsEnabled (int allowedOrientations);
  25051. /** Returns whether the display is allowed to auto-rotate to the given orientation.
  25052. Each orientation can be enabled using setOrientationEnabled(). By default, all orientations are allowed.
  25053. */
  25054. bool isOrientationEnabled (DisplayOrientation orientation) const throw();
  25055. /** Tells this object to refresh its idea of what the screen resolution is.
  25056. (Called internally by the native code).
  25057. */
  25058. void refreshMonitorSizes();
  25059. /** True if the OS supports semitransparent windows */
  25060. static bool canUseSemiTransparentWindows() throw();
  25061. private:
  25062. static Desktop* instance;
  25063. friend class Component;
  25064. friend class ComponentPeer;
  25065. friend class MouseInputSource;
  25066. friend class MouseInputSourceInternal;
  25067. friend class DeletedAtShutdown;
  25068. friend class TopLevelWindowManager;
  25069. OwnedArray <MouseInputSource> mouseSources;
  25070. void createMouseInputSources();
  25071. ListenerList <MouseListener> mouseListeners;
  25072. ListenerList <FocusChangeListener> focusListeners;
  25073. Array <Component*> desktopComponents;
  25074. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  25075. Point<int> lastFakeMouseMove;
  25076. void sendMouseMove();
  25077. int mouseClickCounter;
  25078. void incrementMouseClickCounter() throw();
  25079. ScopedPointer<Timer> dragRepeater;
  25080. Component* kioskModeComponent;
  25081. Rectangle<int> kioskComponentOriginalBounds;
  25082. int allowedOrientations;
  25083. ComponentAnimator animator;
  25084. void timerCallback();
  25085. void resetTimer();
  25086. int getNumDisplayMonitors() const throw();
  25087. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const throw();
  25088. void addDesktopComponent (Component* c);
  25089. void removeDesktopComponent (Component* c);
  25090. void componentBroughtToFront (Component* c);
  25091. void triggerFocusCallback();
  25092. void handleAsyncUpdate();
  25093. Desktop();
  25094. ~Desktop();
  25095. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Desktop);
  25096. };
  25097. #endif // __JUCE_DESKTOP_JUCEHEADER__
  25098. /*** End of inlined file: juce_Desktop.h ***/
  25099. class KeyPressMappingSet;
  25100. class ApplicationCommandManagerListener;
  25101. /**
  25102. One of these objects holds a list of all the commands your app can perform,
  25103. and despatches these commands when needed.
  25104. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  25105. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  25106. to invoke automatically, which means you don't have to handle the result of a menu
  25107. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  25108. which can choose which events they want to handle.
  25109. This architecture also allows for nested ApplicationCommandTargets, so that for example
  25110. you could have two different objects, one inside the other, both of which can respond to
  25111. a "delete" command. Depending on which one has focus, the command will be sent to the
  25112. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  25113. method.
  25114. To set up your app to use commands, you'll need to do the following:
  25115. - Create a global ApplicationCommandManager to hold the list of all possible
  25116. commands. (This will also manage a set of key-mappings for them).
  25117. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  25118. This allows the object to provide a list of commands that it can perform, and
  25119. to handle them.
  25120. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  25121. or ApplicationCommandManager::registerCommand().
  25122. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  25123. method to access the key-mapper object, which you will need to register as a key-listener
  25124. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  25125. about setting this up.
  25126. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  25127. cause these commands to be invoked automatically.
  25128. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  25129. When a command is invoked, the ApplicationCommandManager will try to choose the best
  25130. ApplicationCommandTarget to receive the specified command. To do this it will use the
  25131. current keyboard focus to see which component might be interested, and will search the
  25132. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  25133. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  25134. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  25135. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  25136. point if the command still hasn't been performed, it will be passed to the current
  25137. JUCEApplication object (which is itself an ApplicationCommandTarget).
  25138. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  25139. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  25140. the object yourself.
  25141. @see ApplicationCommandTarget, ApplicationCommandInfo
  25142. */
  25143. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  25144. private FocusChangeListener
  25145. {
  25146. public:
  25147. /** Creates an ApplicationCommandManager.
  25148. Once created, you'll need to register all your app's commands with it, using
  25149. ApplicationCommandManager::registerAllCommandsForTarget() or
  25150. ApplicationCommandManager::registerCommand().
  25151. */
  25152. ApplicationCommandManager();
  25153. /** Destructor.
  25154. Make sure that you don't delete this if pointers to it are still being used by
  25155. objects such as PopupMenus or Buttons.
  25156. */
  25157. virtual ~ApplicationCommandManager();
  25158. /** Clears the current list of all commands.
  25159. Note that this will also clear the contents of the KeyPressMappingSet.
  25160. */
  25161. void clearCommands();
  25162. /** Adds a command to the list of registered commands.
  25163. @see registerAllCommandsForTarget
  25164. */
  25165. void registerCommand (const ApplicationCommandInfo& newCommand);
  25166. /** Adds all the commands that this target publishes to the manager's list.
  25167. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  25168. to get details about all the commands that this target can do, and will call
  25169. registerCommand() to add each one to the manger's list.
  25170. @see registerCommand
  25171. */
  25172. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  25173. /** Removes the command with a specified ID.
  25174. Note that this will also remove any key mappings that are mapped to the command.
  25175. */
  25176. void removeCommand (CommandID commandID);
  25177. /** This should be called to tell the manager that one of its registered commands may have changed
  25178. its active status.
  25179. Because the command manager only finds out whether a command is active or inactive by querying
  25180. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  25181. allows things like buttons to update their enablement, etc.
  25182. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  25183. for any registered listeners.
  25184. */
  25185. void commandStatusChanged();
  25186. /** Returns the number of commands that have been registered.
  25187. @see registerCommand
  25188. */
  25189. int getNumCommands() const throw() { return commands.size(); }
  25190. /** Returns the details about one of the registered commands.
  25191. The index is between 0 and (getNumCommands() - 1).
  25192. */
  25193. const ApplicationCommandInfo* getCommandForIndex (int index) const throw() { return commands [index]; }
  25194. /** Returns the details about a given command ID.
  25195. This will search the list of registered commands for one with the given command
  25196. ID number, and return its associated info. If no matching command is found, this
  25197. will return 0.
  25198. */
  25199. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const throw();
  25200. /** Returns the name field for a command.
  25201. An empty string is returned if no command with this ID has been registered.
  25202. @see getDescriptionOfCommand
  25203. */
  25204. const String getNameOfCommand (CommandID commandID) const throw();
  25205. /** Returns the description field for a command.
  25206. An empty string is returned if no command with this ID has been registered. If the
  25207. command has no description, this will return its short name field instead.
  25208. @see getNameOfCommand
  25209. */
  25210. const String getDescriptionOfCommand (CommandID commandID) const throw();
  25211. /** Returns the list of categories.
  25212. This will go through all registered commands, and return a list of all the distict
  25213. categoryName values from their ApplicationCommandInfo structure.
  25214. @see getCommandsInCategory()
  25215. */
  25216. const StringArray getCommandCategories() const;
  25217. /** Returns a list of all the command UIDs in a particular category.
  25218. @see getCommandCategories()
  25219. */
  25220. const Array <CommandID> getCommandsInCategory (const String& categoryName) const;
  25221. /** Returns the manager's internal set of key mappings.
  25222. This object can be used to edit the keypresses. To actually link this object up
  25223. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  25224. class.
  25225. @see KeyPressMappingSet
  25226. */
  25227. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  25228. /** Invokes the given command directly, sending it to the default target.
  25229. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  25230. structure.
  25231. */
  25232. bool invokeDirectly (CommandID commandID, bool asynchronously);
  25233. /** Sends a command to the default target.
  25234. This will choose a target using getFirstCommandTarget(), and send the specified command
  25235. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  25236. first target can't handle the command, it will be passed on to targets further down the
  25237. chain (see ApplicationCommandTarget::invoke() for more info).
  25238. @param invocationInfo this must be correctly filled-in, describing the context for
  25239. the invocation.
  25240. @param asynchronously if false, the command will be performed before this method returns.
  25241. If true, a message will be posted so that the command will be performed
  25242. later on the message thread, and this method will return immediately.
  25243. @see ApplicationCommandTarget::invoke
  25244. */
  25245. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  25246. bool asynchronously);
  25247. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  25248. Whenever the manager needs to know which target a command should be sent to, it calls
  25249. this method to determine the first one to try.
  25250. By default, this method will return the target that was set by calling setFirstCommandTarget().
  25251. If no target is set, it will return the result of findDefaultComponentTarget().
  25252. If you need to make sure all commands go via your own custom target, then you can
  25253. either use setFirstCommandTarget() to specify a single target, or override this method
  25254. if you need more complex logic to choose one.
  25255. It may return 0 if no targets are available.
  25256. @see getTargetForCommand, invoke, invokeDirectly
  25257. */
  25258. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  25259. /** Sets a target to be returned by getFirstCommandTarget().
  25260. If this is set to 0, then getFirstCommandTarget() will by default return the
  25261. result of findDefaultComponentTarget().
  25262. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  25263. deleting the target object.
  25264. */
  25265. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) throw();
  25266. /** Tries to find the best target to use to perform a given command.
  25267. This will call getFirstCommandTarget() to find the preferred target, and will
  25268. check whether that target can handle the given command. If it can't, then it'll use
  25269. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  25270. so on until no more are available.
  25271. If no targets are found that can perform the command, this method will return 0.
  25272. If a target is found, then it will get the target to fill-in the upToDateInfo
  25273. structure with the latest info about that command, so that the caller can see
  25274. whether the command is disabled, ticked, etc.
  25275. */
  25276. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  25277. ApplicationCommandInfo& upToDateInfo);
  25278. /** Registers a listener that will be called when various events occur. */
  25279. void addListener (ApplicationCommandManagerListener* listener);
  25280. /** Deregisters a previously-added listener. */
  25281. void removeListener (ApplicationCommandManagerListener* listener);
  25282. /** Looks for a suitable command target based on which Components have the keyboard focus.
  25283. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  25284. but is exposed here in case it's useful.
  25285. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  25286. windows, etc., and using the findTargetForComponent() method.
  25287. */
  25288. static ApplicationCommandTarget* findDefaultComponentTarget();
  25289. /** Examines this component and all its parents in turn, looking for the first one
  25290. which is a ApplicationCommandTarget.
  25291. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  25292. that class.
  25293. */
  25294. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  25295. private:
  25296. OwnedArray <ApplicationCommandInfo> commands;
  25297. ListenerList <ApplicationCommandManagerListener> listeners;
  25298. ScopedPointer <KeyPressMappingSet> keyMappings;
  25299. ApplicationCommandTarget* firstTarget;
  25300. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  25301. void handleAsyncUpdate();
  25302. void globalFocusChanged (Component*);
  25303. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  25304. // This is just here to cause a compile error in old code that hasn't been changed to use the new
  25305. // version of this method.
  25306. virtual short getFirstCommandTarget() { return 0; }
  25307. #endif
  25308. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandManager);
  25309. };
  25310. /**
  25311. A listener that receives callbacks from an ApplicationCommandManager when
  25312. commands are invoked or the command list is changed.
  25313. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  25314. */
  25315. class JUCE_API ApplicationCommandManagerListener
  25316. {
  25317. public:
  25318. /** Destructor. */
  25319. virtual ~ApplicationCommandManagerListener() {}
  25320. /** Called when an app command is about to be invoked. */
  25321. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  25322. /** Called when commands are registered or deregistered from the
  25323. command manager, or when commands are made active or inactive.
  25324. Note that if you're using this to watch for changes to whether a command is disabled,
  25325. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  25326. whenever the status of your command might have changed.
  25327. */
  25328. virtual void applicationCommandListChanged() = 0;
  25329. };
  25330. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  25331. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  25332. #endif
  25333. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  25334. #endif
  25335. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  25336. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  25337. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  25338. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  25339. /*** Start of inlined file: juce_PropertiesFile.h ***/
  25340. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  25341. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  25342. /** Wrapper on a file that stores a list of key/value data pairs.
  25343. Useful for storing application settings, etc. See the PropertySet class for
  25344. the interfaces that read and write values.
  25345. Not designed for very large amounts of data, as it keeps all the values in
  25346. memory and writes them out to disk lazily when they are changed.
  25347. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  25348. with it, and these will be signalled when a value changes.
  25349. @see PropertySet
  25350. */
  25351. class JUCE_API PropertiesFile : public PropertySet,
  25352. public ChangeBroadcaster,
  25353. private Timer
  25354. {
  25355. public:
  25356. enum FileFormatOptions
  25357. {
  25358. ignoreCaseOfKeyNames = 1,
  25359. storeAsBinary = 2,
  25360. storeAsCompressedBinary = 4,
  25361. storeAsXML = 8
  25362. };
  25363. /**
  25364. Creates a PropertiesFile object.
  25365. @param file the file to use
  25366. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  25367. is changed, the object will wait for this amount
  25368. of time and then save the file. If zero, the file
  25369. will be written to disk immediately on being changed
  25370. (which might be slow, as it'll re-write synchronously
  25371. each time a value-change method is called). If it is
  25372. less than zero, the file won't be saved until
  25373. save() or saveIfNeeded() are explicitly called.
  25374. @param optionFlags a combination of the flags in the FileFormatOptions
  25375. enum, which specify the type of file to save, and other
  25376. options.
  25377. @param processLock an optional InterprocessLock object that will be used to
  25378. prevent multiple threads or processes from writing to the file
  25379. at the same time. The PropertiesFile will keep a pointer to
  25380. this object but will not take ownership of it - the caller is
  25381. responsible for making sure that the lock doesn't get deleted
  25382. before the PropertiesFile has been deleted.
  25383. */
  25384. PropertiesFile (const File& file,
  25385. int millisecondsBeforeSaving,
  25386. int optionFlags,
  25387. InterProcessLock* processLock = 0);
  25388. /** Destructor.
  25389. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  25390. */
  25391. ~PropertiesFile();
  25392. /** Returns true if this file was created from a valid (or non-existent) file.
  25393. If the file failed to load correctly because it was corrupt or had insufficient
  25394. access, this will be false.
  25395. */
  25396. bool isValidFile() const throw() { return loadedOk; }
  25397. /** This will flush all the values to disk if they've changed since the last
  25398. time they were saved.
  25399. Returns false if it fails to write to the file for some reason (maybe because
  25400. it's read-only or the directory doesn't exist or something).
  25401. @see save
  25402. */
  25403. bool saveIfNeeded();
  25404. /** This will force a write-to-disk of the current values, regardless of whether
  25405. anything has changed since the last save.
  25406. Returns false if it fails to write to the file for some reason (maybe because
  25407. it's read-only or the directory doesn't exist or something).
  25408. @see saveIfNeeded
  25409. */
  25410. bool save();
  25411. /** Returns true if the properties have been altered since the last time they were saved.
  25412. The file is flagged as needing to be saved when you change a value, but you can
  25413. explicitly set this flag with setNeedsToBeSaved().
  25414. */
  25415. bool needsToBeSaved() const;
  25416. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  25417. @see needsToBeSaved
  25418. */
  25419. void setNeedsToBeSaved (bool needsToBeSaved);
  25420. /** Returns the file that's being used. */
  25421. const File getFile() const { return file; }
  25422. /** Handy utility to create a properties file in whatever the standard OS-specific
  25423. location is for these things.
  25424. This uses getDefaultAppSettingsFile() to decide what file to create, then
  25425. creates a PropertiesFile object with the specified properties. See
  25426. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  25427. what the parameters do.
  25428. @see getDefaultAppSettingsFile
  25429. */
  25430. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  25431. const String& fileNameSuffix,
  25432. const String& folderName,
  25433. bool commonToAllUsers,
  25434. int millisecondsBeforeSaving,
  25435. int propertiesFileOptions,
  25436. InterProcessLock* processLock = 0);
  25437. /** Handy utility to choose a file in the standard OS-dependent location for application
  25438. settings files.
  25439. So on a Mac, this will return a file called:
  25440. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  25441. On Windows it'll return something like:
  25442. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  25443. On Linux it'll return
  25444. ~/.[folderName]/[applicationName].[fileNameSuffix]
  25445. If you pass an empty string as the folder name, it'll use the app name for this (or
  25446. omit the folder name on the Mac).
  25447. If commonToAllUsers is true, then this will return the same file for all users of the
  25448. computer, regardless of the current user. If it is false, the file will be specific to
  25449. only the current user. Use this to choose whether you're saving settings that are common
  25450. or user-specific.
  25451. */
  25452. static const File getDefaultAppSettingsFile (const String& applicationName,
  25453. const String& fileNameSuffix,
  25454. const String& folderName,
  25455. bool commonToAllUsers);
  25456. protected:
  25457. virtual void propertyChanged();
  25458. private:
  25459. File file;
  25460. int timerInterval;
  25461. const int options;
  25462. bool loadedOk, needsWriting;
  25463. InterProcessLock* processLock;
  25464. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  25465. InterProcessLock::ScopedLockType* createProcessLock() const;
  25466. void timerCallback();
  25467. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertiesFile);
  25468. };
  25469. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  25470. /*** End of inlined file: juce_PropertiesFile.h ***/
  25471. /**
  25472. Manages a collection of properties.
  25473. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  25474. as a singleton.
  25475. It holds two different PropertiesFile objects internally, one for user-specific
  25476. settings (stored in your user directory), and one for settings that are common to
  25477. all users (stored in a folder accessible to all users).
  25478. The class manages the creation of these files on-demand, allowing access via the
  25479. getUserSettings() and getCommonSettings() methods. It also has a few handy
  25480. methods like testWriteAccess() to check that the files can be saved.
  25481. If you're using one of these as a singleton, then your app's start-up code should
  25482. first of all call setStorageParameters() to tell it the parameters to use to create
  25483. the properties files.
  25484. @see PropertiesFile
  25485. */
  25486. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  25487. {
  25488. public:
  25489. /**
  25490. Creates an ApplicationProperties object.
  25491. Before using it, you must call setStorageParameters() to give it the info
  25492. it needs to create the property files.
  25493. */
  25494. ApplicationProperties();
  25495. /** Destructor. */
  25496. ~ApplicationProperties();
  25497. juce_DeclareSingleton (ApplicationProperties, false)
  25498. /** Gives the object the information it needs to create the appropriate properties files.
  25499. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  25500. info about how these parameters are used.
  25501. */
  25502. void setStorageParameters (const String& applicationName,
  25503. const String& fileNameSuffix,
  25504. const String& folderName,
  25505. int millisecondsBeforeSaving,
  25506. int propertiesFileOptions,
  25507. InterProcessLock* processLock = 0);
  25508. /** Tests whether the files can be successfully written to, and can show
  25509. an error message if not.
  25510. Returns true if none of the tests fail.
  25511. @param testUserSettings if true, the user settings file will be tested
  25512. @param testCommonSettings if true, the common settings file will be tested
  25513. @param showWarningDialogOnFailure if true, the method will show a helpful error
  25514. message box if either of the tests fail
  25515. */
  25516. bool testWriteAccess (bool testUserSettings,
  25517. bool testCommonSettings,
  25518. bool showWarningDialogOnFailure);
  25519. /** Returns the user settings file.
  25520. The first time this is called, it will create and load the properties file.
  25521. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  25522. the common settings are used as a second-chance place to look. This is done via the
  25523. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  25524. to the fallback for the user settings.
  25525. @see getCommonSettings
  25526. */
  25527. PropertiesFile* getUserSettings();
  25528. /** Returns the common settings file.
  25529. The first time this is called, it will create and load the properties file.
  25530. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  25531. read-only (e.g. because the user doesn't have permission to write
  25532. to shared files), then this will return the user settings instead,
  25533. (like getUserSettings() would do). This is handy if you'd like to
  25534. write a value to the common settings, but if that's no possible,
  25535. then you'd rather write to the user settings than none at all.
  25536. If returnUserPropsIfReadOnly is false, this method will always return
  25537. the common settings, even if any changes to them can't be saved.
  25538. @see getUserSettings
  25539. */
  25540. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly);
  25541. /** Saves both files if they need to be saved.
  25542. @see PropertiesFile::saveIfNeeded
  25543. */
  25544. bool saveIfNeeded();
  25545. /** Flushes and closes both files if they are open.
  25546. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  25547. and closes both files. They will then be re-opened the next time getUserSettings()
  25548. or getCommonSettings() is called.
  25549. */
  25550. void closeFiles();
  25551. private:
  25552. ScopedPointer <PropertiesFile> userProps, commonProps;
  25553. String appName, fileSuffix, folderName;
  25554. int msBeforeSaving, options;
  25555. int commonSettingsAreReadOnly;
  25556. InterProcessLock* processLock;
  25557. void openFiles();
  25558. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationProperties);
  25559. };
  25560. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  25561. /*** End of inlined file: juce_ApplicationProperties.h ***/
  25562. #endif
  25563. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  25564. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  25565. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  25566. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  25567. /*** Start of inlined file: juce_AudioFormat.h ***/
  25568. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  25569. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  25570. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  25571. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  25572. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  25573. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  25574. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  25575. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  25576. /**
  25577. This class a container which holds all the classes pertaining to the AudioData::Pointer
  25578. audio sample format class.
  25579. @see AudioData::Pointer.
  25580. */
  25581. class JUCE_API AudioData
  25582. {
  25583. public:
  25584. // These types can be used as the SampleFormat template parameter for the AudioData::Pointer class.
  25585. class Int8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit integer packed data format. */
  25586. class UInt8; /**< Used as a template parameter for AudioData::Pointer. Indicates an 8-bit unsigned integer packed data format. */
  25587. class Int16; /**< Used as a template parameter for AudioData::Pointer. Indicates an 16-bit integer packed data format. */
  25588. class Int24; /**< Used as a template parameter for AudioData::Pointer. Indicates an 24-bit integer packed data format. */
  25589. class Int32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit integer packed data format. */
  25590. class Float32; /**< Used as a template parameter for AudioData::Pointer. Indicates an 32-bit float data format. */
  25591. // These types can be used as the Endianness template parameter for the AudioData::Pointer class.
  25592. class BigEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in big-endian order. */
  25593. class LittleEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in little-endian order. */
  25594. class NativeEndian; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored in the CPU's native endianness. */
  25595. // These types can be used as the InterleavingType template parameter for the AudioData::Pointer class.
  25596. class NonInterleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are stored contiguously. */
  25597. class Interleaved; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples are interleaved with a number of other channels. */
  25598. // These types can be used as the Constness template parameter for the AudioData::Pointer class.
  25599. class NonConst; /**< Used as a template parameter for AudioData::Pointer. Indicates that the pointer can be used for non-const data. */
  25600. class Const; /**< Used as a template parameter for AudioData::Pointer. Indicates that the samples can only be used for const data.. */
  25601. #ifndef DOXYGEN
  25602. class BigEndian
  25603. {
  25604. public:
  25605. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) throw() { return s.getAsFloatBE(); }
  25606. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) throw() { s.setAsFloatBE (newValue); }
  25607. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) throw() { return s.getAsInt32BE(); }
  25608. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) throw() { s.setAsInt32BE (newValue); }
  25609. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) throw() { dest.copyFromBE (source); }
  25610. enum { isBigEndian = 1 };
  25611. };
  25612. class LittleEndian
  25613. {
  25614. public:
  25615. template <class SampleFormatType> static inline float getAsFloat (SampleFormatType& s) throw() { return s.getAsFloatLE(); }
  25616. template <class SampleFormatType> static inline void setAsFloat (SampleFormatType& s, float newValue) throw() { s.setAsFloatLE (newValue); }
  25617. template <class SampleFormatType> static inline int32 getAsInt32 (SampleFormatType& s) throw() { return s.getAsInt32LE(); }
  25618. template <class SampleFormatType> static inline void setAsInt32 (SampleFormatType& s, int32 newValue) throw() { s.setAsInt32LE (newValue); }
  25619. template <class SourceType, class DestType> static inline void copyFrom (DestType& dest, SourceType& source) throw() { dest.copyFromLE (source); }
  25620. enum { isBigEndian = 0 };
  25621. };
  25622. #if JUCE_BIG_ENDIAN
  25623. class NativeEndian : public BigEndian {};
  25624. #else
  25625. class NativeEndian : public LittleEndian {};
  25626. #endif
  25627. class Int8
  25628. {
  25629. public:
  25630. inline Int8 (void* data_) throw() : data (static_cast <int8*> (data_)) {}
  25631. inline void advance() throw() { ++data; }
  25632. inline void skip (int numSamples) throw() { data += numSamples; }
  25633. inline float getAsFloatLE() const throw() { return (float) (*data * (1.0 / (1.0 + maxValue))); }
  25634. inline float getAsFloatBE() const throw() { return getAsFloatLE(); }
  25635. inline void setAsFloatLE (float newValue) throw() { *data = (int8) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))); }
  25636. inline void setAsFloatBE (float newValue) throw() { setAsFloatLE (newValue); }
  25637. inline int32 getAsInt32LE() const throw() { return (int) (*data << 24); }
  25638. inline int32 getAsInt32BE() const throw() { return getAsInt32LE(); }
  25639. inline void setAsInt32LE (int newValue) throw() { *data = (int8) (newValue >> 24); }
  25640. inline void setAsInt32BE (int newValue) throw() { setAsInt32LE (newValue); }
  25641. inline void clear() throw() { *data = 0; }
  25642. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  25643. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  25644. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  25645. inline void copyFromSameType (Int8& source) throw() { *data = *source.data; }
  25646. int8* data;
  25647. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  25648. };
  25649. class UInt8
  25650. {
  25651. public:
  25652. inline UInt8 (void* data_) throw() : data (static_cast <uint8*> (data_)) {}
  25653. inline void advance() throw() { ++data; }
  25654. inline void skip (int numSamples) throw() { data += numSamples; }
  25655. inline float getAsFloatLE() const throw() { return (float) ((*data - 128) * (1.0 / (1.0 + maxValue))); }
  25656. inline float getAsFloatBE() const throw() { return getAsFloatLE(); }
  25657. inline void setAsFloatLE (float newValue) throw() { *data = (uint8) jlimit (0, 255, 128 + roundToInt (newValue * (1.0 + maxValue))); }
  25658. inline void setAsFloatBE (float newValue) throw() { setAsFloatLE (newValue); }
  25659. inline int32 getAsInt32LE() const throw() { return (int) ((*data - 128) << 24); }
  25660. inline int32 getAsInt32BE() const throw() { return getAsInt32LE(); }
  25661. inline void setAsInt32LE (int newValue) throw() { *data = (uint8) (128 + (newValue >> 24)); }
  25662. inline void setAsInt32BE (int newValue) throw() { setAsInt32LE (newValue); }
  25663. inline void clear() throw() { *data = 128; }
  25664. inline void clearMultiple (int num) throw() { memset (data, 128, num) ;}
  25665. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  25666. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  25667. inline void copyFromSameType (UInt8& source) throw() { *data = *source.data; }
  25668. uint8* data;
  25669. enum { bytesPerSample = 1, maxValue = 0x7f, resolution = (1 << 24), isFloat = 0 };
  25670. };
  25671. class Int16
  25672. {
  25673. public:
  25674. inline Int16 (void* data_) throw() : data (static_cast <uint16*> (data_)) {}
  25675. inline void advance() throw() { ++data; }
  25676. inline void skip (int numSamples) throw() { data += numSamples; }
  25677. inline float getAsFloatLE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfBigEndian (*data)); }
  25678. inline float getAsFloatBE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int16) ByteOrder::swapIfLittleEndian (*data)); }
  25679. inline void setAsFloatLE (float newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint16) jlimit ((int16) -maxValue, (int16) maxValue, (int16) roundToInt (newValue * (1.0 + maxValue)))); }
  25680. inline void setAsFloatBE (float newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint16) jlimit ((int16) -maxValue, (int16) maxValue, (int16) roundToInt (newValue * (1.0 + maxValue)))); }
  25681. inline int32 getAsInt32LE() const throw() { return (int32) (ByteOrder::swapIfBigEndian ((uint16) *data) << 16); }
  25682. inline int32 getAsInt32BE() const throw() { return (int32) (ByteOrder::swapIfLittleEndian ((uint16) *data) << 16); }
  25683. inline void setAsInt32LE (int32 newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint16) (newValue >> 16)); }
  25684. inline void setAsInt32BE (int32 newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint16) (newValue >> 16)); }
  25685. inline void clear() throw() { *data = 0; }
  25686. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  25687. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  25688. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  25689. inline void copyFromSameType (Int16& source) throw() { *data = *source.data; }
  25690. uint16* data;
  25691. enum { bytesPerSample = 2, maxValue = 0x7fff, resolution = (1 << 16), isFloat = 0 };
  25692. };
  25693. class Int24
  25694. {
  25695. public:
  25696. inline Int24 (void* data_) throw() : data (static_cast <char*> (data_)) {}
  25697. inline void advance() throw() { data += 3; }
  25698. inline void skip (int numSamples) throw() { data += 3 * numSamples; }
  25699. inline float getAsFloatLE() const throw() { return (float) (ByteOrder::littleEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  25700. inline float getAsFloatBE() const throw() { return (float) (ByteOrder::bigEndian24Bit (data) * (1.0 / (1.0 + maxValue))); }
  25701. inline void setAsFloatLE (float newValue) throw() { ByteOrder::littleEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  25702. inline void setAsFloatBE (float newValue) throw() { ByteOrder::bigEndian24BitToChars (jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue))), data); }
  25703. inline int32 getAsInt32LE() const throw() { return (int32) ByteOrder::littleEndian24Bit (data) << 8; }
  25704. inline int32 getAsInt32BE() const throw() { return (int32) ByteOrder::bigEndian24Bit (data) << 8; }
  25705. inline void setAsInt32LE (int32 newValue) throw() { ByteOrder::littleEndian24BitToChars (newValue >> 8, data); }
  25706. inline void setAsInt32BE (int32 newValue) throw() { ByteOrder::bigEndian24BitToChars (newValue >> 8, data); }
  25707. inline void clear() throw() { data[0] = 0; data[1] = 0; data[2] = 0; }
  25708. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  25709. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  25710. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  25711. inline void copyFromSameType (Int24& source) throw() { data[0] = source.data[0]; data[1] = source.data[1]; data[2] = source.data[2]; }
  25712. char* data;
  25713. enum { bytesPerSample = 3, maxValue = 0x7fffff, resolution = (1 << 8), isFloat = 0 };
  25714. };
  25715. class Int32
  25716. {
  25717. public:
  25718. inline Int32 (void* data_) throw() : data (static_cast <uint32*> (data_)) {}
  25719. inline void advance() throw() { ++data; }
  25720. inline void skip (int numSamples) throw() { data += numSamples; }
  25721. inline float getAsFloatLE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfBigEndian (*data)); }
  25722. inline float getAsFloatBE() const throw() { return (float) ((1.0 / (1.0 + maxValue)) * (int32) ByteOrder::swapIfLittleEndian (*data)); }
  25723. inline void setAsFloatLE (float newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint32) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  25724. inline void setAsFloatBE (float newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint32) jlimit ((int) -maxValue, (int) maxValue, roundToInt (newValue * (1.0 + maxValue)))); }
  25725. inline int32 getAsInt32LE() const throw() { return (int32) ByteOrder::swapIfBigEndian (*data); }
  25726. inline int32 getAsInt32BE() const throw() { return (int32) ByteOrder::swapIfLittleEndian (*data); }
  25727. inline void setAsInt32LE (int32 newValue) throw() { *data = ByteOrder::swapIfBigEndian ((uint32) newValue); }
  25728. inline void setAsInt32BE (int32 newValue) throw() { *data = ByteOrder::swapIfLittleEndian ((uint32) newValue); }
  25729. inline void clear() throw() { *data = 0; }
  25730. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  25731. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsInt32LE (source.getAsInt32()); }
  25732. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsInt32BE (source.getAsInt32()); }
  25733. inline void copyFromSameType (Int32& source) throw() { *data = *source.data; }
  25734. uint32* data;
  25735. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = 1, isFloat = 0 };
  25736. };
  25737. class Float32
  25738. {
  25739. public:
  25740. inline Float32 (void* data_) throw() : data (static_cast <float*> (data_)) {}
  25741. inline void advance() throw() { ++data; }
  25742. inline void skip (int numSamples) throw() { data += numSamples; }
  25743. #if JUCE_BIG_ENDIAN
  25744. inline float getAsFloatBE() const throw() { return *data; }
  25745. inline void setAsFloatBE (float newValue) throw() { *data = newValue; }
  25746. inline float getAsFloatLE() const throw() { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  25747. inline void setAsFloatLE (float newValue) throw() { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  25748. #else
  25749. inline float getAsFloatLE() const throw() { return *data; }
  25750. inline void setAsFloatLE (float newValue) throw() { *data = newValue; }
  25751. inline float getAsFloatBE() const throw() { union { uint32 asInt; float asFloat; } n; n.asInt = ByteOrder::swap (*(uint32*) data); return n.asFloat; }
  25752. inline void setAsFloatBE (float newValue) throw() { union { uint32 asInt; float asFloat; } n; n.asFloat = newValue; *(uint32*) data = ByteOrder::swap (n.asInt); }
  25753. #endif
  25754. inline int32 getAsInt32LE() const throw() { return (int32) roundToInt (jlimit (-1.0f, 1.0f, getAsFloatLE()) * (1.0 + maxValue)); }
  25755. inline int32 getAsInt32BE() const throw() { return (int32) roundToInt (jlimit (-1.0f, 1.0f, getAsFloatBE()) * (1.0 + maxValue)); }
  25756. inline void setAsInt32LE (int32 newValue) throw() { setAsFloatLE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  25757. inline void setAsInt32BE (int32 newValue) throw() { setAsFloatBE ((float) (newValue * (1.0 / (1.0 + maxValue)))); }
  25758. inline void clear() throw() { *data = 0; }
  25759. inline void clearMultiple (int num) throw() { zeromem (data, num * bytesPerSample) ;}
  25760. template <class SourceType> inline void copyFromLE (SourceType& source) throw() { setAsFloatLE (source.getAsFloat()); }
  25761. template <class SourceType> inline void copyFromBE (SourceType& source) throw() { setAsFloatBE (source.getAsFloat()); }
  25762. inline void copyFromSameType (Float32& source) throw() { *data = *source.data; }
  25763. float* data;
  25764. enum { bytesPerSample = 4, maxValue = 0x7fffffff, resolution = (1 << 8), isFloat = 1 };
  25765. };
  25766. class NonInterleaved
  25767. {
  25768. public:
  25769. inline NonInterleaved() throw() {}
  25770. inline NonInterleaved (const NonInterleaved&) throw() {}
  25771. inline NonInterleaved (const int) throw() {}
  25772. inline void copyFrom (const NonInterleaved&) throw() {}
  25773. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) throw() { s.advance(); }
  25774. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) throw() { s.skip (numSamples); }
  25775. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) throw() { s.clearMultiple (numSamples); }
  25776. template <class SampleFormatType> inline static int getNumBytesBetweenSamples (const SampleFormatType&) throw() { return SampleFormatType::bytesPerSample; }
  25777. enum { isInterleavedType = 0, numInterleavedChannels = 1 };
  25778. };
  25779. class Interleaved
  25780. {
  25781. public:
  25782. inline Interleaved() throw() : numInterleavedChannels (1) {}
  25783. inline Interleaved (const Interleaved& other) throw() : numInterleavedChannels (other.numInterleavedChannels) {}
  25784. inline Interleaved (const int numInterleavedChannels_) throw() : numInterleavedChannels (numInterleavedChannels_) {}
  25785. inline void copyFrom (const Interleaved& other) throw() { numInterleavedChannels = other.numInterleavedChannels; }
  25786. template <class SampleFormatType> inline void advanceData (SampleFormatType& s) throw() { s.skip (numInterleavedChannels); }
  25787. template <class SampleFormatType> inline void advanceDataBy (SampleFormatType& s, int numSamples) throw() { s.skip (numInterleavedChannels * numSamples); }
  25788. template <class SampleFormatType> inline void clear (SampleFormatType& s, int numSamples) throw() { while (--numSamples >= 0) { s.clear(); s.skip (numInterleavedChannels); } }
  25789. template <class SampleFormatType> inline int getNumBytesBetweenSamples (const SampleFormatType&) const throw() { return numInterleavedChannels * SampleFormatType::bytesPerSample; }
  25790. int numInterleavedChannels;
  25791. enum { isInterleavedType = 1 };
  25792. };
  25793. class NonConst
  25794. {
  25795. public:
  25796. typedef void VoidType;
  25797. static inline void* toVoidPtr (VoidType* v) throw() { return v; }
  25798. enum { isConst = 0 };
  25799. };
  25800. class Const
  25801. {
  25802. public:
  25803. typedef const void VoidType;
  25804. static inline void* toVoidPtr (VoidType* v) throw() { return const_cast<void*> (v); }
  25805. enum { isConst = 1 };
  25806. };
  25807. #endif
  25808. /**
  25809. A pointer to a block of audio data with a particular encoding.
  25810. This object can be used to read and write from blocks of encoded audio samples. To create one, you specify
  25811. the audio format as a series of template parameters, e.g.
  25812. @code
  25813. // this creates a pointer for reading from a const array of 16-bit little-endian packed samples.
  25814. AudioData::Pointer <AudioData::Int16,
  25815. AudioData::LittleEndian,
  25816. AudioData::NonInterleaved,
  25817. AudioData::Const> pointer (someRawAudioData);
  25818. // These methods read the sample that is being pointed to
  25819. float firstSampleAsFloat = pointer.getAsFloat();
  25820. int32 firstSampleAsInt = pointer.getAsInt32();
  25821. ++pointer; // moves the pointer to the next sample.
  25822. pointer += 3; // skips the next 3 samples.
  25823. @endcode
  25824. The convertSamples() method lets you copy a range of samples from one format to another, automatically
  25825. converting its format.
  25826. @see AudioData::Converter
  25827. */
  25828. template <typename SampleFormat,
  25829. typename Endianness,
  25830. typename InterleavingType,
  25831. typename Constness>
  25832. class Pointer
  25833. {
  25834. public:
  25835. /** Creates a non-interleaved pointer from some raw data in the appropriate format.
  25836. This constructor is only used if you've specified the AudioData::NonInterleaved option -
  25837. for interleaved formats, use the constructor that also takes a number of channels.
  25838. */
  25839. Pointer (typename Constness::VoidType* sourceData) throw()
  25840. : data (Constness::toVoidPtr (sourceData))
  25841. {
  25842. // If you're using interleaved data, call the other constructor! If you're using non-interleaved data,
  25843. // you should pass NonInterleaved as the template parameter for the interleaving type!
  25844. static_jassert (InterleavingType::isInterleavedType == 0);
  25845. }
  25846. /** Creates a pointer from some raw data in the appropriate format with the specified number of interleaved channels.
  25847. For non-interleaved data, use the other constructor.
  25848. */
  25849. Pointer (typename Constness::VoidType* sourceData, int numInterleavedChannels) throw()
  25850. : data (Constness::toVoidPtr (sourceData)),
  25851. interleaving (numInterleavedChannels)
  25852. {
  25853. }
  25854. /** Creates a copy of another pointer. */
  25855. Pointer (const Pointer& other) throw()
  25856. : data (other.data),
  25857. interleaving (other.interleaving)
  25858. {
  25859. }
  25860. Pointer& operator= (const Pointer& other) throw()
  25861. {
  25862. data = other.data;
  25863. interleaving.copyFrom (other.interleaving);
  25864. return *this;
  25865. }
  25866. /** Returns the value of the first sample as a floating point value.
  25867. The value will be in the range -1.0 to 1.0 for integer formats. For floating point
  25868. formats, the value could be outside that range, although -1 to 1 is the standard range.
  25869. */
  25870. inline float getAsFloat() const throw() { return Endianness::getAsFloat (data); }
  25871. /** Sets the value of the first sample as a floating point value.
  25872. (This method can only be used if the AudioData::NonConst option was used).
  25873. The value should be in the range -1.0 to 1.0 - for integer formats, values outside that
  25874. range will be clipped. For floating point formats, any value passed in here will be
  25875. written directly, although -1 to 1 is the standard range.
  25876. */
  25877. inline void setAsFloat (float newValue) throw()
  25878. {
  25879. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  25880. Endianness::setAsFloat (data, newValue);
  25881. }
  25882. /** Returns the value of the first sample as a 32-bit integer.
  25883. The value returned will be in the range 0x80000000 to 0x7fffffff, and shorter values will be
  25884. shifted to fill this range (e.g. if you're reading from 24-bit data, the values will be shifted up
  25885. by 8 bits when returned here). If the source data is floating point, values beyond -1.0 to 1.0 will
  25886. be clipped so that -1.0 maps onto -0x7fffffff and 1.0 maps to 0x7fffffff.
  25887. */
  25888. inline int32 getAsInt32() const throw() { return Endianness::getAsInt32 (data); }
  25889. /** Sets the value of the first sample as a 32-bit integer.
  25890. This will be mapped to the range of the format that is being written - see getAsInt32().
  25891. */
  25892. inline void setAsInt32 (int32 newValue) throw()
  25893. {
  25894. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  25895. Endianness::setAsInt32 (data, newValue);
  25896. }
  25897. /** Moves the pointer along to the next sample. */
  25898. inline Pointer& operator++() throw() { advance(); return *this; }
  25899. /** Moves the pointer back to the previous sample. */
  25900. inline Pointer& operator--() throw() { interleaving.advanceDataBy (data, -1); return *this; }
  25901. /** Adds a number of samples to the pointer's position. */
  25902. Pointer& operator+= (int samplesToJump) throw() { interleaving.advanceDataBy (data, samplesToJump); return *this; }
  25903. /** Writes a stream of samples into this pointer from another pointer.
  25904. This will copy the specified number of samples, converting between formats appropriately.
  25905. */
  25906. void convertSamples (Pointer source, int numSamples) const throw()
  25907. {
  25908. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  25909. Pointer dest (*this);
  25910. while (--numSamples >= 0)
  25911. {
  25912. dest.data.copyFromSameType (source.data);
  25913. dest.advance();
  25914. source.advance();
  25915. }
  25916. }
  25917. /** Writes a stream of samples into this pointer from another pointer.
  25918. This will copy the specified number of samples, converting between formats appropriately.
  25919. */
  25920. template <class OtherPointerType>
  25921. void convertSamples (OtherPointerType source, int numSamples) const throw()
  25922. {
  25923. static_jassert (Constness::isConst == 0); // trying to write to a const pointer! For a writeable one, use AudioData::NonConst instead!
  25924. Pointer dest (*this);
  25925. if (source.getRawData() != getRawData() || source.getNumBytesBetweenSamples() >= getNumBytesBetweenSamples())
  25926. {
  25927. while (--numSamples >= 0)
  25928. {
  25929. Endianness::copyFrom (dest.data, source);
  25930. dest.advance();
  25931. ++source;
  25932. }
  25933. }
  25934. else // copy backwards if we're increasing the sample width..
  25935. {
  25936. dest += numSamples;
  25937. source += numSamples;
  25938. while (--numSamples >= 0)
  25939. Endianness::copyFrom ((--dest).data, --source);
  25940. }
  25941. }
  25942. /** Sets a number of samples to zero. */
  25943. void clearSamples (int numSamples) const throw()
  25944. {
  25945. Pointer dest (*this);
  25946. dest.interleaving.clear (dest.data, numSamples);
  25947. }
  25948. /** Returns true if the pointer is using a floating-point format. */
  25949. static bool isFloatingPoint() throw() { return (bool) SampleFormat::isFloat; }
  25950. /** Returns true if the format is big-endian. */
  25951. static bool isBigEndian() throw() { return (bool) Endianness::isBigEndian; }
  25952. /** Returns the number of bytes in each sample (ignoring the number of interleaved channels). */
  25953. static int getBytesPerSample() throw() { return (int) SampleFormat::bytesPerSample; }
  25954. /** Returns the number of interleaved channels in the format. */
  25955. int getNumInterleavedChannels() const throw() { return (int) this->numInterleavedChannels; }
  25956. /** Returns the number of bytes between the start address of each sample. */
  25957. int getNumBytesBetweenSamples() const throw() { return interleaving.getNumBytesBetweenSamples (data); }
  25958. /** Returns the accuracy of this format when represented as a 32-bit integer.
  25959. This is the smallest number above 0 that can be represented in the sample format, converted to
  25960. a 32-bit range. E,g. if the format is 8-bit, its resolution is 0x01000000; if the format is 24-bit,
  25961. its resolution is 0x100.
  25962. */
  25963. static int get32BitResolution() throw() { return (int) SampleFormat::resolution; }
  25964. /** Returns a pointer to the underlying data. */
  25965. const void* getRawData() const throw() { return data.data; }
  25966. private:
  25967. SampleFormat data;
  25968. InterleavingType interleaving; // annoyingly, making the interleaving type a superclass to take
  25969. // advantage of EBCO causes an internal compiler error in VC6..
  25970. inline void advance() throw() { interleaving.advanceData (data); }
  25971. Pointer operator++ (int); // private to force you to use the more efficient pre-increment!
  25972. Pointer operator-- (int);
  25973. };
  25974. /** A base class for objects that are used to convert between two different sample formats.
  25975. The AudioData::ConverterInstance implements this base class and can be templated, so
  25976. you can create an instance that converts between two particular formats, and then
  25977. store this in the abstract base class.
  25978. @see AudioData::ConverterInstance
  25979. */
  25980. class Converter
  25981. {
  25982. public:
  25983. virtual ~Converter() {}
  25984. /** Converts a sequence of samples from the converter's source format into the dest format. */
  25985. virtual void convertSamples (void* destSamples, const void* sourceSamples, int numSamples) const = 0;
  25986. /** Converts a sequence of samples from the converter's source format into the dest format.
  25987. This method takes sub-channel indexes, which can be used with interleaved formats in order to choose a
  25988. particular sub-channel of the data to be used.
  25989. */
  25990. virtual void convertSamples (void* destSamples, int destSubChannel,
  25991. const void* sourceSamples, int sourceSubChannel, int numSamples) const = 0;
  25992. };
  25993. /**
  25994. A class that converts between two templated AudioData::Pointer types, and which
  25995. implements the AudioData::Converter interface.
  25996. This can be used as a concrete instance of the AudioData::Converter abstract class.
  25997. @see AudioData::Converter
  25998. */
  25999. template <class SourceSampleType, class DestSampleType>
  26000. class ConverterInstance : public Converter
  26001. {
  26002. public:
  26003. ConverterInstance (int numSourceChannels = 1, int numDestChannels = 1)
  26004. : sourceChannels (numSourceChannels), destChannels (numDestChannels)
  26005. {}
  26006. ~ConverterInstance() {}
  26007. void convertSamples (void* dest, const void* source, int numSamples) const
  26008. {
  26009. SourceSampleType s (source, sourceChannels);
  26010. DestSampleType d (dest, destChannels);
  26011. d.convertSamples (s, numSamples);
  26012. }
  26013. void convertSamples (void* dest, int destSubChannel,
  26014. const void* source, int sourceSubChannel, int numSamples) const
  26015. {
  26016. jassert (destSubChannel < destChannels && sourceSubChannel < sourceChannels);
  26017. SourceSampleType s (addBytesToPointer (source, sourceSubChannel * SourceSampleType::getBytesPerSample()), sourceChannels);
  26018. DestSampleType d (addBytesToPointer (dest, destSubChannel * DestSampleType::getBytesPerSample()), destChannels);
  26019. d.convertSamples (s, numSamples);
  26020. }
  26021. private:
  26022. JUCE_DECLARE_NON_COPYABLE (ConverterInstance);
  26023. const int sourceChannels, destChannels;
  26024. };
  26025. };
  26026. /**
  26027. A set of routines to convert buffers of 32-bit floating point data to and from
  26028. various integer formats.
  26029. Note that these functions are deprecated - the AudioData class provides a much more
  26030. flexible set of conversion classes now.
  26031. */
  26032. class JUCE_API AudioDataConverters
  26033. {
  26034. public:
  26035. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  26036. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  26037. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  26038. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  26039. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  26040. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  26041. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  26042. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  26043. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  26044. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  26045. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  26046. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  26047. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  26048. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  26049. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  26050. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  26051. enum DataFormat
  26052. {
  26053. int16LE,
  26054. int16BE,
  26055. int24LE,
  26056. int24BE,
  26057. int32LE,
  26058. int32BE,
  26059. float32LE,
  26060. float32BE,
  26061. };
  26062. static void convertFloatToFormat (DataFormat destFormat,
  26063. const float* source, void* dest, int numSamples);
  26064. static void convertFormatToFloat (DataFormat sourceFormat,
  26065. const void* source, float* dest, int numSamples);
  26066. static void interleaveSamples (const float** source, float* dest,
  26067. int numSamples, int numChannels);
  26068. static void deinterleaveSamples (const float* source, float** dest,
  26069. int numSamples, int numChannels);
  26070. private:
  26071. AudioDataConverters();
  26072. JUCE_DECLARE_NON_COPYABLE (AudioDataConverters);
  26073. };
  26074. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26075. /*** End of inlined file: juce_AudioDataConverters.h ***/
  26076. class AudioFormat;
  26077. /**
  26078. Reads samples from an audio file stream.
  26079. A subclass that reads a specific type of audio format will be created by
  26080. an AudioFormat object.
  26081. @see AudioFormat, AudioFormatWriter
  26082. */
  26083. class JUCE_API AudioFormatReader
  26084. {
  26085. protected:
  26086. /** Creates an AudioFormatReader object.
  26087. @param sourceStream the stream to read from - this will be deleted
  26088. by this object when it is no longer needed. (Some
  26089. specialised readers might not use this parameter and
  26090. can leave it as 0).
  26091. @param formatName the description that will be returned by the getFormatName()
  26092. method
  26093. */
  26094. AudioFormatReader (InputStream* sourceStream,
  26095. const String& formatName);
  26096. public:
  26097. /** Destructor. */
  26098. virtual ~AudioFormatReader();
  26099. /** Returns a description of what type of format this is.
  26100. E.g. "AIFF"
  26101. */
  26102. const String getFormatName() const throw() { return formatName; }
  26103. /** Reads samples from the stream.
  26104. @param destSamples an array of buffers into which the sample data for each
  26105. channel will be written.
  26106. If the format is fixed-point, each channel will be written
  26107. as an array of 32-bit signed integers using the full
  26108. range -0x80000000 to 0x7fffffff, regardless of the source's
  26109. bit-depth. If it is a floating-point format, you should cast
  26110. the resulting array to a (float**) to get the values (in the
  26111. range -1.0 to 1.0 or beyond)
  26112. If the format is stereo, then destSamples[0] is the left channel
  26113. data, and destSamples[1] is the right channel.
  26114. The numDestChannels parameter indicates how many pointers this array
  26115. contains, but some of these pointers can be null if you don't want to
  26116. read data for some of the channels
  26117. @param numDestChannels the number of array elements in the destChannels array
  26118. @param startSampleInSource the position in the audio file or stream at which the samples
  26119. should be read, as a number of samples from the start of the
  26120. stream. It's ok for this to be beyond the start or end of the
  26121. available data - any samples that are out-of-range will be returned
  26122. as zeros.
  26123. @param numSamplesToRead the number of samples to read. If this is greater than the number
  26124. of samples that the file or stream contains. the result will be padded
  26125. with zeros
  26126. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  26127. for some of the channels that you pass in, then they should be filled with
  26128. copies of valid source channels.
  26129. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  26130. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  26131. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  26132. was false, then only the first channel would be filled with the file's contents, and
  26133. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  26134. from a stereo file, then the last 3 would all end up with copies of the same data.
  26135. @returns true if the operation succeeded, false if there was an error. Note
  26136. that reading sections of data beyond the extent of the stream isn't an
  26137. error - the reader should just return zeros for these regions
  26138. @see readMaxLevels
  26139. */
  26140. bool read (int* const* destSamples,
  26141. int numDestChannels,
  26142. int64 startSampleInSource,
  26143. int numSamplesToRead,
  26144. bool fillLeftoverChannelsWithCopies);
  26145. /** Finds the highest and lowest sample levels from a section of the audio stream.
  26146. This will read a block of samples from the stream, and measure the
  26147. highest and lowest sample levels from the channels in that section, returning
  26148. these as normalised floating-point levels.
  26149. @param startSample the offset into the audio stream to start reading from. It's
  26150. ok for this to be beyond the start or end of the stream.
  26151. @param numSamples how many samples to read
  26152. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  26153. @param highestLeft on return, this is the highest absolute sample from the left channel
  26154. @param lowestRight on return, this is the lowest absolute sample from the right
  26155. channel (if there is one)
  26156. @param highestRight on return, this is the highest absolute sample from the right
  26157. channel (if there is one)
  26158. @see read
  26159. */
  26160. virtual void readMaxLevels (int64 startSample,
  26161. int64 numSamples,
  26162. float& lowestLeft,
  26163. float& highestLeft,
  26164. float& lowestRight,
  26165. float& highestRight);
  26166. /** Scans the source looking for a sample whose magnitude is in a specified range.
  26167. This will read from the source, either forwards or backwards between two sample
  26168. positions, until it finds a sample whose magnitude lies between two specified levels.
  26169. If it finds a suitable sample, it returns its position; if not, it will return -1.
  26170. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  26171. points when you're searching for a continuous range of samples
  26172. @param startSample the first sample to look at
  26173. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  26174. the search will go backwards
  26175. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  26176. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  26177. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  26178. of this many consecutive samples, all of which lie
  26179. within the target range. When it finds such a sequence,
  26180. it returns the position of the first in-range sample
  26181. it found (i.e. the earliest one if scanning forwards, the
  26182. latest one if scanning backwards)
  26183. */
  26184. int64 searchForLevel (int64 startSample,
  26185. int64 numSamplesToSearch,
  26186. double magnitudeRangeMinimum,
  26187. double magnitudeRangeMaximum,
  26188. int minimumConsecutiveSamples);
  26189. /** The sample-rate of the stream. */
  26190. double sampleRate;
  26191. /** The number of bits per sample, e.g. 16, 24, 32. */
  26192. unsigned int bitsPerSample;
  26193. /** The total number of samples in the audio stream. */
  26194. int64 lengthInSamples;
  26195. /** The total number of channels in the audio stream. */
  26196. unsigned int numChannels;
  26197. /** Indicates whether the data is floating-point or fixed. */
  26198. bool usesFloatingPointData;
  26199. /** A set of metadata values that the reader has pulled out of the stream.
  26200. Exactly what these values are depends on the format, so you can
  26201. check out the format implementation code to see what kind of stuff
  26202. they understand.
  26203. */
  26204. StringPairArray metadataValues;
  26205. /** The input stream, for use by subclasses. */
  26206. InputStream* input;
  26207. /** Subclasses must implement this method to perform the low-level read operation.
  26208. Callers should use read() instead of calling this directly.
  26209. @param destSamples the array of destination buffers to fill. Some of these
  26210. pointers may be null
  26211. @param numDestChannels the number of items in the destSamples array. This
  26212. value is guaranteed not to be greater than the number of
  26213. channels that this reader object contains
  26214. @param startOffsetInDestBuffer the number of samples from the start of the
  26215. dest data at which to begin writing
  26216. @param startSampleInFile the number of samples into the source data at which
  26217. to begin reading. This value is guaranteed to be >= 0.
  26218. @param numSamples the number of samples to read
  26219. */
  26220. virtual bool readSamples (int** destSamples,
  26221. int numDestChannels,
  26222. int startOffsetInDestBuffer,
  26223. int64 startSampleInFile,
  26224. int numSamples) = 0;
  26225. protected:
  26226. /** Used by AudioFormatReader subclasses to copy data to different formats. */
  26227. template <class DestSampleType, class SourceSampleType, class SourceEndianness>
  26228. struct ReadHelper
  26229. {
  26230. typedef AudioData::Pointer <DestSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  26231. typedef AudioData::Pointer <SourceSampleType, SourceEndianness, AudioData::Interleaved, AudioData::Const> SourceType;
  26232. static void read (int** destData, int destOffset, int numDestChannels, const void* sourceData, int numSourceChannels, int numSamples) throw()
  26233. {
  26234. for (int i = 0; i < numDestChannels; ++i)
  26235. {
  26236. if (destData[i] != 0)
  26237. {
  26238. DestType dest (destData[i]);
  26239. dest += destOffset;
  26240. if (i < numSourceChannels)
  26241. dest.convertSamples (SourceType (addBytesToPointer (sourceData, i * SourceType::getBytesPerSample()), numSourceChannels), numSamples);
  26242. else
  26243. dest.clearSamples (numSamples);
  26244. }
  26245. }
  26246. }
  26247. };
  26248. private:
  26249. String formatName;
  26250. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReader);
  26251. };
  26252. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  26253. /*** End of inlined file: juce_AudioFormatReader.h ***/
  26254. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  26255. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26256. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26257. /*** Start of inlined file: juce_AudioSource.h ***/
  26258. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  26259. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  26260. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  26261. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  26262. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  26263. class AudioFormatReader;
  26264. class AudioFormatWriter;
  26265. /**
  26266. A multi-channel buffer of 32-bit floating point audio samples.
  26267. */
  26268. class JUCE_API AudioSampleBuffer
  26269. {
  26270. public:
  26271. /** Creates a buffer with a specified number of channels and samples.
  26272. The contents of the buffer will initially be undefined, so use clear() to
  26273. set all the samples to zero.
  26274. The buffer will allocate its memory internally, and this will be released
  26275. when the buffer is deleted.
  26276. */
  26277. AudioSampleBuffer (int numChannels,
  26278. int numSamples) throw();
  26279. /** Creates a buffer using a pre-allocated block of memory.
  26280. Note that if the buffer is resized or its number of channels is changed, it
  26281. will re-allocate memory internally and copy the existing data to this new area,
  26282. so it will then stop directly addressing this memory.
  26283. @param dataToReferTo a pre-allocated array containing pointers to the data
  26284. for each channel that should be used by this buffer. The
  26285. buffer will only refer to this memory, it won't try to delete
  26286. it when the buffer is deleted or resized.
  26287. @param numChannels the number of channels to use - this must correspond to the
  26288. number of elements in the array passed in
  26289. @param numSamples the number of samples to use - this must correspond to the
  26290. size of the arrays passed in
  26291. */
  26292. AudioSampleBuffer (float** dataToReferTo,
  26293. int numChannels,
  26294. int numSamples) throw();
  26295. /** Copies another buffer.
  26296. This buffer will make its own copy of the other's data, unless the buffer was created
  26297. using an external data buffer, in which case boths buffers will just point to the same
  26298. shared block of data.
  26299. */
  26300. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  26301. /** Copies another buffer onto this one.
  26302. This buffer's size will be changed to that of the other buffer.
  26303. */
  26304. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  26305. /** Destructor.
  26306. This will free any memory allocated by the buffer.
  26307. */
  26308. virtual ~AudioSampleBuffer() throw();
  26309. /** Returns the number of channels of audio data that this buffer contains.
  26310. @see getSampleData
  26311. */
  26312. int getNumChannels() const throw() { return numChannels; }
  26313. /** Returns the number of samples allocated in each of the buffer's channels.
  26314. @see getSampleData
  26315. */
  26316. int getNumSamples() const throw() { return size; }
  26317. /** Returns a pointer one of the buffer's channels.
  26318. For speed, this doesn't check whether the channel number is out of range,
  26319. so be careful when using it!
  26320. */
  26321. float* getSampleData (const int channelNumber) const throw()
  26322. {
  26323. jassert (isPositiveAndBelow (channelNumber, numChannels));
  26324. return channels [channelNumber];
  26325. }
  26326. /** Returns a pointer to a sample in one of the buffer's channels.
  26327. For speed, this doesn't check whether the channel and sample number
  26328. are out-of-range, so be careful when using it!
  26329. */
  26330. float* getSampleData (const int channelNumber,
  26331. const int sampleOffset) const throw()
  26332. {
  26333. jassert (isPositiveAndBelow (channelNumber, numChannels));
  26334. jassert (isPositiveAndBelow (sampleOffset, size));
  26335. return channels [channelNumber] + sampleOffset;
  26336. }
  26337. /** Returns an array of pointers to the channels in the buffer.
  26338. Don't modify any of the pointers that are returned, and bear in mind that
  26339. these will become invalid if the buffer is resized.
  26340. */
  26341. float** getArrayOfChannels() const throw() { return channels; }
  26342. /** Changes the buffer's size or number of channels.
  26343. This can expand or contract the buffer's length, and add or remove channels.
  26344. If keepExistingContent is true, it will try to preserve as much of the
  26345. old data as it can in the new buffer.
  26346. If clearExtraSpace is true, then any extra channels or space that is
  26347. allocated will be also be cleared. If false, then this space is left
  26348. uninitialised.
  26349. If avoidReallocating is true, then changing the buffer's size won't reduce the
  26350. amount of memory that is currently allocated (but it will still increase it if
  26351. the new size is bigger than the amount it currently has). If this is false, then
  26352. a new allocation will be done so that the buffer uses takes up the minimum amount
  26353. of memory that it needs.
  26354. */
  26355. void setSize (int newNumChannels,
  26356. int newNumSamples,
  26357. bool keepExistingContent = false,
  26358. bool clearExtraSpace = false,
  26359. bool avoidReallocating = false) throw();
  26360. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  26361. There's also a constructor that lets you specify arrays like this, but this
  26362. lets you change the channels dynamically.
  26363. Note that if the buffer is resized or its number of channels is changed, it
  26364. will re-allocate memory internally and copy the existing data to this new area,
  26365. so it will then stop directly addressing this memory.
  26366. @param dataToReferTo a pre-allocated array containing pointers to the data
  26367. for each channel that should be used by this buffer. The
  26368. buffer will only refer to this memory, it won't try to delete
  26369. it when the buffer is deleted or resized.
  26370. @param numChannels the number of channels to use - this must correspond to the
  26371. number of elements in the array passed in
  26372. @param numSamples the number of samples to use - this must correspond to the
  26373. size of the arrays passed in
  26374. */
  26375. void setDataToReferTo (float** dataToReferTo,
  26376. int numChannels,
  26377. int numSamples) throw();
  26378. /** Clears all the samples in all channels. */
  26379. void clear() throw();
  26380. /** Clears a specified region of all the channels.
  26381. For speed, this doesn't check whether the channel and sample number
  26382. are in-range, so be careful!
  26383. */
  26384. void clear (int startSample,
  26385. int numSamples) throw();
  26386. /** Clears a specified region of just one channel.
  26387. For speed, this doesn't check whether the channel and sample number
  26388. are in-range, so be careful!
  26389. */
  26390. void clear (int channel,
  26391. int startSample,
  26392. int numSamples) throw();
  26393. /** Applies a gain multiple to a region of one channel.
  26394. For speed, this doesn't check whether the channel and sample number
  26395. are in-range, so be careful!
  26396. */
  26397. void applyGain (int channel,
  26398. int startSample,
  26399. int numSamples,
  26400. float gain) throw();
  26401. /** Applies a gain multiple to a region of all the channels.
  26402. For speed, this doesn't check whether the sample numbers
  26403. are in-range, so be careful!
  26404. */
  26405. void applyGain (int startSample,
  26406. int numSamples,
  26407. float gain) throw();
  26408. /** Applies a range of gains to a region of a channel.
  26409. The gain that is applied to each sample will vary from
  26410. startGain on the first sample to endGain on the last Sample,
  26411. so it can be used to do basic fades.
  26412. For speed, this doesn't check whether the sample numbers
  26413. are in-range, so be careful!
  26414. */
  26415. void applyGainRamp (int channel,
  26416. int startSample,
  26417. int numSamples,
  26418. float startGain,
  26419. float endGain) throw();
  26420. /** Adds samples from another buffer to this one.
  26421. @param destChannel the channel within this buffer to add the samples to
  26422. @param destStartSample the start sample within this buffer's channel
  26423. @param source the source buffer to add from
  26424. @param sourceChannel the channel within the source buffer to read from
  26425. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  26426. @param numSamples the number of samples to process
  26427. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  26428. added to this buffer's samples
  26429. @see copyFrom
  26430. */
  26431. void addFrom (int destChannel,
  26432. int destStartSample,
  26433. const AudioSampleBuffer& source,
  26434. int sourceChannel,
  26435. int sourceStartSample,
  26436. int numSamples,
  26437. float gainToApplyToSource = 1.0f) throw();
  26438. /** Adds samples from an array of floats to one of the channels.
  26439. @param destChannel the channel within this buffer to add the samples to
  26440. @param destStartSample the start sample within this buffer's channel
  26441. @param source the source data to use
  26442. @param numSamples the number of samples to process
  26443. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  26444. added to this buffer's samples
  26445. @see copyFrom
  26446. */
  26447. void addFrom (int destChannel,
  26448. int destStartSample,
  26449. const float* source,
  26450. int numSamples,
  26451. float gainToApplyToSource = 1.0f) throw();
  26452. /** Adds samples from an array of floats, applying a gain ramp to them.
  26453. @param destChannel the channel within this buffer to add the samples to
  26454. @param destStartSample the start sample within this buffer's channel
  26455. @param source the source data to use
  26456. @param numSamples the number of samples to process
  26457. @param startGain the gain to apply to the first sample (this is multiplied with
  26458. the source samples before they are added to this buffer)
  26459. @param endGain the gain to apply to the final sample. The gain is linearly
  26460. interpolated between the first and last samples.
  26461. */
  26462. void addFromWithRamp (int destChannel,
  26463. int destStartSample,
  26464. const float* source,
  26465. int numSamples,
  26466. float startGain,
  26467. float endGain) throw();
  26468. /** Copies samples from another buffer to this one.
  26469. @param destChannel the channel within this buffer to copy the samples to
  26470. @param destStartSample the start sample within this buffer's channel
  26471. @param source the source buffer to read from
  26472. @param sourceChannel the channel within the source buffer to read from
  26473. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  26474. @param numSamples the number of samples to process
  26475. @see addFrom
  26476. */
  26477. void copyFrom (int destChannel,
  26478. int destStartSample,
  26479. const AudioSampleBuffer& source,
  26480. int sourceChannel,
  26481. int sourceStartSample,
  26482. int numSamples) throw();
  26483. /** Copies samples from an array of floats into one of the channels.
  26484. @param destChannel the channel within this buffer to copy the samples to
  26485. @param destStartSample the start sample within this buffer's channel
  26486. @param source the source buffer to read from
  26487. @param numSamples the number of samples to process
  26488. @see addFrom
  26489. */
  26490. void copyFrom (int destChannel,
  26491. int destStartSample,
  26492. const float* source,
  26493. int numSamples) throw();
  26494. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  26495. @param destChannel the channel within this buffer to copy the samples to
  26496. @param destStartSample the start sample within this buffer's channel
  26497. @param source the source buffer to read from
  26498. @param numSamples the number of samples to process
  26499. @param gain the gain to apply
  26500. @see addFrom
  26501. */
  26502. void copyFrom (int destChannel,
  26503. int destStartSample,
  26504. const float* source,
  26505. int numSamples,
  26506. float gain) throw();
  26507. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  26508. @param destChannel the channel within this buffer to copy the samples to
  26509. @param destStartSample the start sample within this buffer's channel
  26510. @param source the source buffer to read from
  26511. @param numSamples the number of samples to process
  26512. @param startGain the gain to apply to the first sample (this is multiplied with
  26513. the source samples before they are copied to this buffer)
  26514. @param endGain the gain to apply to the final sample. The gain is linearly
  26515. interpolated between the first and last samples.
  26516. @see addFrom
  26517. */
  26518. void copyFromWithRamp (int destChannel,
  26519. int destStartSample,
  26520. const float* source,
  26521. int numSamples,
  26522. float startGain,
  26523. float endGain) throw();
  26524. /** Finds the highest and lowest sample values in a given range.
  26525. @param channel the channel to read from
  26526. @param startSample the start sample within the channel
  26527. @param numSamples the number of samples to check
  26528. @param minVal on return, the lowest value that was found
  26529. @param maxVal on return, the highest value that was found
  26530. */
  26531. void findMinMax (int channel,
  26532. int startSample,
  26533. int numSamples,
  26534. float& minVal,
  26535. float& maxVal) const throw();
  26536. /** Finds the highest absolute sample value within a region of a channel.
  26537. */
  26538. float getMagnitude (int channel,
  26539. int startSample,
  26540. int numSamples) const throw();
  26541. /** Finds the highest absolute sample value within a region on all channels.
  26542. */
  26543. float getMagnitude (int startSample,
  26544. int numSamples) const throw();
  26545. /** Returns the root mean squared level for a region of a channel.
  26546. */
  26547. float getRMSLevel (int channel,
  26548. int startSample,
  26549. int numSamples) const throw();
  26550. /** Fills a section of the buffer using an AudioReader as its source.
  26551. This will convert the reader's fixed- or floating-point data to
  26552. the buffer's floating-point format, and will try to intelligently
  26553. cope with mismatches between the number of channels in the reader
  26554. and the buffer.
  26555. @see writeToAudioWriter
  26556. */
  26557. void readFromAudioReader (AudioFormatReader* reader,
  26558. int startSample,
  26559. int numSamples,
  26560. int64 readerStartSample,
  26561. bool useReaderLeftChan,
  26562. bool useReaderRightChan);
  26563. /** Writes a section of this buffer to an audio writer.
  26564. This saves you having to mess about with channels or floating/fixed
  26565. point conversion.
  26566. @see readFromAudioReader
  26567. */
  26568. void writeToAudioWriter (AudioFormatWriter* writer,
  26569. int startSample,
  26570. int numSamples) const;
  26571. private:
  26572. int numChannels, size;
  26573. size_t allocatedBytes;
  26574. float** channels;
  26575. HeapBlock <char> allocatedData;
  26576. float* preallocatedChannelSpace [32];
  26577. void allocateData();
  26578. void allocateChannels (float** dataToReferTo);
  26579. JUCE_LEAK_DETECTOR (AudioSampleBuffer);
  26580. };
  26581. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  26582. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  26583. /**
  26584. Used by AudioSource::getNextAudioBlock().
  26585. */
  26586. struct JUCE_API AudioSourceChannelInfo
  26587. {
  26588. /** The destination buffer to fill with audio data.
  26589. When the AudioSource::getNextAudioBlock() method is called, the active section
  26590. of this buffer should be filled with whatever output the source produces.
  26591. Only the samples specified by the startSample and numSamples members of this structure
  26592. should be affected by the call.
  26593. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  26594. method can be treated as the input if the source is performing some kind of filter operation,
  26595. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  26596. a handy way of doing this.
  26597. The number of channels in the buffer could be anything, so the AudioSource
  26598. must cope with this in whatever way is appropriate for its function.
  26599. */
  26600. AudioSampleBuffer* buffer;
  26601. /** The first sample in the buffer from which the callback is expected
  26602. to write data. */
  26603. int startSample;
  26604. /** The number of samples in the buffer which the callback is expected to
  26605. fill with data. */
  26606. int numSamples;
  26607. /** Convenient method to clear the buffer if the source is not producing any data. */
  26608. void clearActiveBufferRegion() const
  26609. {
  26610. if (buffer != 0)
  26611. buffer->clear (startSample, numSamples);
  26612. }
  26613. };
  26614. /**
  26615. Base class for objects that can produce a continuous stream of audio.
  26616. An AudioSource has two states: 'prepared' and 'unprepared'.
  26617. When a source needs to be played, it is first put into a 'prepared' state by a call to
  26618. prepareToPlay(), and then repeated calls will be made to its getNextAudioBlock() method to
  26619. process the audio data.
  26620. Once playback has finished, the releaseResources() method is called to put the stream
  26621. back into an 'unprepared' state.
  26622. @see AudioFormatReaderSource, ResamplingAudioSource
  26623. */
  26624. class JUCE_API AudioSource
  26625. {
  26626. protected:
  26627. /** Creates an AudioSource. */
  26628. AudioSource() throw() {}
  26629. public:
  26630. /** Destructor. */
  26631. virtual ~AudioSource() {}
  26632. /** Tells the source to prepare for playing.
  26633. An AudioSource has two states: prepared and unprepared.
  26634. The prepareToPlay() method is guaranteed to be called at least once on an 'unpreprared'
  26635. source to put it into a 'prepared' state before any calls will be made to getNextAudioBlock().
  26636. This callback allows the source to initialise any resources it might need when playing.
  26637. Once playback has finished, the releaseResources() method is called to put the stream
  26638. back into an 'unprepared' state.
  26639. Note that this method could be called more than once in succession without
  26640. a matching call to releaseResources(), so make sure your code is robust and
  26641. can handle that kind of situation.
  26642. @param samplesPerBlockExpected the number of samples that the source
  26643. will be expected to supply each time its
  26644. getNextAudioBlock() method is called. This
  26645. number may vary slightly, because it will be dependent
  26646. on audio hardware callbacks, and these aren't
  26647. guaranteed to always use a constant block size, so
  26648. the source should be able to cope with small variations.
  26649. @param sampleRate the sample rate that the output will be used at - this
  26650. is needed by sources such as tone generators.
  26651. @see releaseResources, getNextAudioBlock
  26652. */
  26653. virtual void prepareToPlay (int samplesPerBlockExpected,
  26654. double sampleRate) = 0;
  26655. /** Allows the source to release anything it no longer needs after playback has stopped.
  26656. This will be called when the source is no longer going to have its getNextAudioBlock()
  26657. method called, so it should release any spare memory, etc. that it might have
  26658. allocated during the prepareToPlay() call.
  26659. Note that there's no guarantee that prepareToPlay() will actually have been called before
  26660. releaseResources(), and it may be called more than once in succession, so make sure your
  26661. code is robust and doesn't make any assumptions about when it will be called.
  26662. @see prepareToPlay, getNextAudioBlock
  26663. */
  26664. virtual void releaseResources() = 0;
  26665. /** Called repeatedly to fetch subsequent blocks of audio data.
  26666. After calling the prepareToPlay() method, this callback will be made each
  26667. time the audio playback hardware (or whatever other destination the audio
  26668. data is going to) needs another block of data.
  26669. It will generally be called on a high-priority system thread, or possibly even
  26670. an interrupt, so be careful not to do too much work here, as that will cause
  26671. audio glitches!
  26672. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  26673. */
  26674. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  26675. };
  26676. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  26677. /*** End of inlined file: juce_AudioSource.h ***/
  26678. class AudioThumbnail;
  26679. /**
  26680. Writes samples to an audio file stream.
  26681. A subclass that writes a specific type of audio format will be created by
  26682. an AudioFormat object.
  26683. After creating one of these with the AudioFormat::createWriterFor() method
  26684. you can call its write() method to store the samples, and then delete it.
  26685. @see AudioFormat, AudioFormatReader
  26686. */
  26687. class JUCE_API AudioFormatWriter
  26688. {
  26689. protected:
  26690. /** Creates an AudioFormatWriter object.
  26691. @param destStream the stream to write to - this will be deleted
  26692. by this object when it is no longer needed
  26693. @param formatName the description that will be returned by the getFormatName()
  26694. method
  26695. @param sampleRate the sample rate to use - the base class just stores
  26696. this value, it doesn't do anything with it
  26697. @param numberOfChannels the number of channels to write - the base class just stores
  26698. this value, it doesn't do anything with it
  26699. @param bitsPerSample the bit depth of the stream - the base class just stores
  26700. this value, it doesn't do anything with it
  26701. */
  26702. AudioFormatWriter (OutputStream* destStream,
  26703. const String& formatName,
  26704. double sampleRate,
  26705. unsigned int numberOfChannels,
  26706. unsigned int bitsPerSample);
  26707. public:
  26708. /** Destructor. */
  26709. virtual ~AudioFormatWriter();
  26710. /** Returns a description of what type of format this is.
  26711. E.g. "AIFF file"
  26712. */
  26713. const String getFormatName() const throw() { return formatName; }
  26714. /** Writes a set of samples to the audio stream.
  26715. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  26716. can use AudioSampleBuffer::writeToAudioWriter().
  26717. @param samplesToWrite an array of arrays containing the sample data for
  26718. each channel to write. This is a zero-terminated
  26719. array of arrays, and can contain a different number
  26720. of channels than the actual stream uses, and the
  26721. writer should do its best to cope with this.
  26722. If the format is fixed-point, each channel will be formatted
  26723. as an array of signed integers using the full 32-bit
  26724. range -0x80000000 to 0x7fffffff, regardless of the source's
  26725. bit-depth. If it is a floating-point format, you should treat
  26726. the arrays as arrays of floats, and just cast it to an (int**)
  26727. to pass it into the method.
  26728. @param numSamples the number of samples to write
  26729. */
  26730. virtual bool write (const int** samplesToWrite,
  26731. int numSamples) = 0;
  26732. /** Reads a section of samples from an AudioFormatReader, and writes these to
  26733. the output.
  26734. This will take care of any floating-point conversion that's required to convert
  26735. between the two formats. It won't deal with sample-rate conversion, though.
  26736. If numSamplesToRead < 0, it will write the entire length of the reader.
  26737. @returns false if it can't read or write properly during the operation
  26738. */
  26739. bool writeFromAudioReader (AudioFormatReader& reader,
  26740. int64 startSample,
  26741. int64 numSamplesToRead);
  26742. /** Reads some samples from an AudioSource, and writes these to the output.
  26743. The source must already have been initialised with the AudioSource::prepareToPlay() method
  26744. @param source the source to read from
  26745. @param numSamplesToRead total number of samples to read and write
  26746. @param samplesPerBlock the maximum number of samples to fetch from the source
  26747. @returns false if it can't read or write properly during the operation
  26748. */
  26749. bool writeFromAudioSource (AudioSource& source,
  26750. int numSamplesToRead,
  26751. int samplesPerBlock = 2048);
  26752. /** Writes some samples from an AudioSampleBuffer.
  26753. */
  26754. bool writeFromAudioSampleBuffer (const AudioSampleBuffer& source,
  26755. int startSample, int numSamples);
  26756. /** Returns the sample rate being used. */
  26757. double getSampleRate() const throw() { return sampleRate; }
  26758. /** Returns the number of channels being written. */
  26759. int getNumChannels() const throw() { return numChannels; }
  26760. /** Returns the bit-depth of the data being written. */
  26761. int getBitsPerSample() const throw() { return bitsPerSample; }
  26762. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  26763. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  26764. /**
  26765. Provides a FIFO for an AudioFormatWriter, allowing you to push incoming
  26766. data into a buffer which will be flushed to disk by a background thread.
  26767. */
  26768. class ThreadedWriter
  26769. {
  26770. public:
  26771. /** Creates a ThreadedWriter for a given writer and a thread.
  26772. The writer object which is passed in here will be owned and deleted by
  26773. the ThreadedWriter when it is no longer needed.
  26774. To stop the writer and flush the buffer to disk, simply delete this object.
  26775. */
  26776. ThreadedWriter (AudioFormatWriter* writer,
  26777. TimeSliceThread& backgroundThread,
  26778. int numSamplesToBuffer);
  26779. /** Destructor. */
  26780. ~ThreadedWriter();
  26781. /** Pushes some incoming audio data into the FIFO.
  26782. If there's enough free space in the buffer, this will add the data to it,
  26783. If the FIFO is too full to accept this many samples, the method will return
  26784. false - then you could either wait until the background thread has had time to
  26785. consume some of the buffered data and try again, or you can give up
  26786. and lost this block.
  26787. The data must be an array containing the same number of channels as the
  26788. AudioFormatWriter object is using. None of these channels can be null.
  26789. */
  26790. bool write (const float** data, int numSamples);
  26791. /** Allows you to specify a thumbnail that this writer should update with the
  26792. incoming data.
  26793. The thumbnail will be cleared and will the writer will begin adding data to
  26794. it as it arrives. Pass a null pointer to stop the writer updating any thumbnails.
  26795. */
  26796. void setThumbnailToUpdate (AudioThumbnail* thumbnailToUpdate);
  26797. /** @internal */
  26798. class Buffer; // (only public for VC6 compatibility)
  26799. private:
  26800. friend class ScopedPointer<Buffer>;
  26801. ScopedPointer<Buffer> buffer;
  26802. };
  26803. protected:
  26804. /** The sample rate of the stream. */
  26805. double sampleRate;
  26806. /** The number of channels being written to the stream. */
  26807. unsigned int numChannels;
  26808. /** The bit depth of the file. */
  26809. unsigned int bitsPerSample;
  26810. /** True if it's a floating-point format, false if it's fixed-point. */
  26811. bool usesFloatingPointData;
  26812. /** The output stream for Use by subclasses. */
  26813. OutputStream* output;
  26814. /** Used by AudioFormatWriter subclasses to copy data to different formats. */
  26815. template <class DestSampleType, class SourceSampleType, class DestEndianness>
  26816. struct WriteHelper
  26817. {
  26818. typedef AudioData::Pointer <DestSampleType, DestEndianness, AudioData::Interleaved, AudioData::NonConst> DestType;
  26819. typedef AudioData::Pointer <SourceSampleType, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  26820. static void write (void* destData, int numDestChannels, const int** source, int numSamples) throw()
  26821. {
  26822. for (int i = 0; i < numDestChannels; ++i)
  26823. {
  26824. const DestType dest (addBytesToPointer (destData, i * DestType::getBytesPerSample()), numDestChannels);
  26825. if (*source != 0)
  26826. {
  26827. dest.convertSamples (SourceType (*source), numSamples);
  26828. ++source;
  26829. }
  26830. else
  26831. {
  26832. dest.clearSamples (numSamples);
  26833. }
  26834. }
  26835. }
  26836. };
  26837. private:
  26838. String formatName;
  26839. friend class ThreadedWriter;
  26840. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatWriter);
  26841. };
  26842. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26843. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  26844. /**
  26845. Subclasses of AudioFormat are used to read and write different audio
  26846. file formats.
  26847. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  26848. */
  26849. class JUCE_API AudioFormat
  26850. {
  26851. public:
  26852. /** Destructor. */
  26853. virtual ~AudioFormat();
  26854. /** Returns the name of this format.
  26855. e.g. "WAV file" or "AIFF file"
  26856. */
  26857. const String& getFormatName() const;
  26858. /** Returns all the file extensions that might apply to a file of this format.
  26859. The first item will be the one that's preferred when creating a new file.
  26860. So for a wav file this might just return ".wav"; for an AIFF file it might
  26861. return two items, ".aif" and ".aiff"
  26862. */
  26863. const StringArray& getFileExtensions() const;
  26864. /** Returns true if this the given file can be read by this format.
  26865. Subclasses shouldn't do too much work here, just check the extension or
  26866. file type. The base class implementation just checks the file's extension
  26867. against one of the ones that was registered in the constructor.
  26868. */
  26869. virtual bool canHandleFile (const File& fileToTest);
  26870. /** Returns a set of sample rates that the format can read and write. */
  26871. virtual const Array <int> getPossibleSampleRates() = 0;
  26872. /** Returns a set of bit depths that the format can read and write. */
  26873. virtual const Array <int> getPossibleBitDepths() = 0;
  26874. /** Returns true if the format can do 2-channel audio. */
  26875. virtual bool canDoStereo() = 0;
  26876. /** Returns true if the format can do 1-channel audio. */
  26877. virtual bool canDoMono() = 0;
  26878. /** Returns true if the format uses compressed data. */
  26879. virtual bool isCompressed();
  26880. /** Returns a list of different qualities that can be used when writing.
  26881. Non-compressed formats will just return an empty array, but for something
  26882. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  26883. When calling createWriterFor(), an index from this array is passed in to
  26884. tell the format which option is required.
  26885. */
  26886. virtual const StringArray getQualityOptions();
  26887. /** Tries to create an object that can read from a stream containing audio
  26888. data in this format.
  26889. The reader object that is returned can be used to read from the stream, and
  26890. should then be deleted by the caller.
  26891. @param sourceStream the stream to read from - the AudioFormatReader object
  26892. that is returned will delete this stream when it no longer
  26893. needs it.
  26894. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  26895. should delete the stream object that was passed-in. (If a valid
  26896. reader is returned, it will always be in charge of deleting the
  26897. stream, so this parameter is ignored)
  26898. @see AudioFormatReader
  26899. */
  26900. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  26901. bool deleteStreamIfOpeningFails) = 0;
  26902. /** Tries to create an object that can write to a stream with this audio format.
  26903. The writer object that is returned can be used to write to the stream, and
  26904. should then be deleted by the caller.
  26905. If the stream can't be created for some reason (e.g. the parameters passed in
  26906. here aren't suitable), this will return 0.
  26907. @param streamToWriteTo the stream that the data will go to - this will be
  26908. deleted by the AudioFormatWriter object when it's no longer
  26909. needed. If no AudioFormatWriter can be created by this method,
  26910. the stream will NOT be deleted, so that the caller can re-use it
  26911. to try to open a different format, etc
  26912. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  26913. returned by getPossibleSampleRates()
  26914. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  26915. the choice will depend on the results of canDoMono() and
  26916. canDoStereo()
  26917. @param bitsPerSample the bits per sample to use - this must be one of the values
  26918. returned by getPossibleBitDepths()
  26919. @param metadataValues a set of metadata values that the writer should try to write
  26920. to the stream. Exactly what these are depends on the format,
  26921. and the subclass doesn't actually have to do anything with
  26922. them if it doesn't want to. Have a look at the specific format
  26923. implementation classes to see possible values that can be
  26924. used
  26925. @param qualityOptionIndex the index of one of compression qualities returned by the
  26926. getQualityOptions() method. If there aren't any quality options
  26927. for this format, just pass 0 in this parameter, as it'll be
  26928. ignored
  26929. @see AudioFormatWriter
  26930. */
  26931. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  26932. double sampleRateToUse,
  26933. unsigned int numberOfChannels,
  26934. int bitsPerSample,
  26935. const StringPairArray& metadataValues,
  26936. int qualityOptionIndex) = 0;
  26937. protected:
  26938. /** Creates an AudioFormat object.
  26939. @param formatName this sets the value that will be returned by getFormatName()
  26940. @param fileExtensions a zero-terminated list of file extensions - this is what will
  26941. be returned by getFileExtension()
  26942. */
  26943. AudioFormat (const String& formatName,
  26944. const StringArray& fileExtensions);
  26945. private:
  26946. String formatName;
  26947. StringArray fileExtensions;
  26948. };
  26949. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  26950. /*** End of inlined file: juce_AudioFormat.h ***/
  26951. /**
  26952. Reads and Writes AIFF format audio files.
  26953. @see AudioFormat
  26954. */
  26955. class JUCE_API AiffAudioFormat : public AudioFormat
  26956. {
  26957. public:
  26958. /** Creates an format object. */
  26959. AiffAudioFormat();
  26960. /** Destructor. */
  26961. ~AiffAudioFormat();
  26962. const Array <int> getPossibleSampleRates();
  26963. const Array <int> getPossibleBitDepths();
  26964. bool canDoStereo();
  26965. bool canDoMono();
  26966. #if JUCE_MAC
  26967. bool canHandleFile (const File& fileToTest);
  26968. #endif
  26969. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  26970. bool deleteStreamIfOpeningFails);
  26971. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  26972. double sampleRateToUse,
  26973. unsigned int numberOfChannels,
  26974. int bitsPerSample,
  26975. const StringPairArray& metadataValues,
  26976. int qualityOptionIndex);
  26977. private:
  26978. JUCE_LEAK_DETECTOR (AiffAudioFormat);
  26979. };
  26980. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26981. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  26982. #endif
  26983. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26984. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  26985. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26986. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  26987. #if JUCE_USE_CDBURNER || DOXYGEN
  26988. /**
  26989. */
  26990. class AudioCDBurner : public ChangeBroadcaster
  26991. {
  26992. public:
  26993. /** Returns a list of available optical drives.
  26994. Use openDevice() to open one of the items from this list.
  26995. */
  26996. static const StringArray findAvailableDevices();
  26997. /** Tries to open one of the optical drives.
  26998. The deviceIndex is an index into the array returned by findAvailableDevices().
  26999. */
  27000. static AudioCDBurner* openDevice (const int deviceIndex);
  27001. /** Destructor. */
  27002. ~AudioCDBurner();
  27003. enum DiskState
  27004. {
  27005. unknown, /**< An error condition, if the device isn't responding. */
  27006. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  27007. may seem to be permanently open. */
  27008. noDisc, /**< The drive has no disk in it. */
  27009. writableDiskPresent, /**< The drive contains a writeable disk. */
  27010. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  27011. };
  27012. /** Returns the current status of the device.
  27013. To get informed when the drive's status changes, attach a ChangeListener to
  27014. the AudioCDBurner.
  27015. */
  27016. DiskState getDiskState() const;
  27017. /** Returns true if there's a writable disk in the drive. */
  27018. bool isDiskPresent() const;
  27019. /** Sends an eject signal to the drive.
  27020. The eject will happen asynchronously, so you can use getDiskState() and
  27021. waitUntilStateChange() to monitor its progress.
  27022. */
  27023. bool openTray();
  27024. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  27025. @returns the device's new state
  27026. */
  27027. DiskState waitUntilStateChange (int timeOutMilliseconds);
  27028. /** Returns the set of possible write speeds that the device can handle.
  27029. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  27030. Note that if there's no media present in the drive, this value may be unavailable!
  27031. @see setWriteSpeed, getWriteSpeed
  27032. */
  27033. const Array<int> getAvailableWriteSpeeds() const;
  27034. /** Tries to enable or disable buffer underrun safety on devices that support it.
  27035. @returns true if it's now enabled. If the device doesn't support it, this
  27036. will always return false.
  27037. */
  27038. bool setBufferUnderrunProtection (bool shouldBeEnabled);
  27039. /** Returns the number of free blocks on the disk.
  27040. There are 75 blocks per second, at 44100Hz.
  27041. */
  27042. int getNumAvailableAudioBlocks() const;
  27043. /** Adds a track to be written.
  27044. The source passed-in here will be kept by this object, and it will
  27045. be used and deleted at some point in the future, either during the
  27046. burn() method or when this AudioCDBurner object is deleted. Your caller
  27047. method shouldn't keep a reference to it or use it again after passing
  27048. it in here.
  27049. */
  27050. bool addAudioTrack (AudioSource* source, int numSamples);
  27051. /** Receives progress callbacks during a cd-burn operation.
  27052. @see AudioCDBurner::burn()
  27053. */
  27054. class BurnProgressListener
  27055. {
  27056. public:
  27057. BurnProgressListener() throw() {}
  27058. virtual ~BurnProgressListener() {}
  27059. /** Called at intervals to report on the progress of the AudioCDBurner.
  27060. To cancel the burn, return true from this method.
  27061. */
  27062. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  27063. };
  27064. /** Runs the burn process.
  27065. This method will block until the operation is complete.
  27066. @param listener the object to receive callbacks about progress
  27067. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  27068. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  27069. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  27070. 0 or less to mean the fastest speed.
  27071. */
  27072. const String burn (BurnProgressListener* listener,
  27073. bool ejectDiscAfterwards,
  27074. bool performFakeBurnForTesting,
  27075. int writeSpeed);
  27076. /** If a burn operation is currently in progress, this tells it to stop
  27077. as soon as possible.
  27078. It's also possible to stop the burn process by returning true from
  27079. BurnProgressListener::audioCDBurnProgress()
  27080. */
  27081. void abortBurn();
  27082. private:
  27083. AudioCDBurner (const int deviceIndex);
  27084. class Pimpl;
  27085. friend class ScopedPointer<Pimpl>;
  27086. ScopedPointer<Pimpl> pimpl;
  27087. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDBurner);
  27088. };
  27089. #endif
  27090. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27091. /*** End of inlined file: juce_AudioCDBurner.h ***/
  27092. #endif
  27093. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27094. /*** Start of inlined file: juce_AudioCDReader.h ***/
  27095. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27096. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  27097. #if JUCE_USE_CDREADER || DOXYGEN
  27098. #if JUCE_MAC
  27099. #endif
  27100. /**
  27101. A type of AudioFormatReader that reads from an audio CD.
  27102. One of these can be used to read a CD as if it's one big audio stream. Use the
  27103. getPositionOfTrackStart() method to find where the individual tracks are
  27104. within the stream.
  27105. @see AudioFormatReader
  27106. */
  27107. class JUCE_API AudioCDReader : public AudioFormatReader
  27108. {
  27109. public:
  27110. /** Returns a list of names of Audio CDs currently available for reading.
  27111. If there's a CD drive but no CD in it, this might return an empty list, or
  27112. possibly a device that can be opened but which has no tracks, depending
  27113. on the platform.
  27114. @see createReaderForCD
  27115. */
  27116. static const StringArray getAvailableCDNames();
  27117. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  27118. @param index the index of one of the available CDs - use getAvailableCDNames()
  27119. to find out how many there are.
  27120. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  27121. caller will be responsible for deleting the object returned.
  27122. */
  27123. static AudioCDReader* createReaderForCD (const int index);
  27124. /** Destructor. */
  27125. ~AudioCDReader();
  27126. /** Implementation of the AudioFormatReader method. */
  27127. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  27128. int64 startSampleInFile, int numSamples);
  27129. /** Checks whether the CD has been removed from the drive.
  27130. */
  27131. bool isCDStillPresent() const;
  27132. /** Returns the total number of tracks (audio + data).
  27133. */
  27134. int getNumTracks() const;
  27135. /** Finds the sample offset of the start of a track.
  27136. @param trackNum the track number, where trackNum = 0 is the first track
  27137. and trackNum = getNumTracks() means the end of the CD.
  27138. */
  27139. int getPositionOfTrackStart (int trackNum) const;
  27140. /** Returns true if a given track is an audio track.
  27141. @param trackNum the track number, where 0 is the first track.
  27142. */
  27143. bool isTrackAudio (int trackNum) const;
  27144. /** Returns an array of sample offsets for the start of each track, followed by
  27145. the sample position of the end of the CD.
  27146. */
  27147. const Array<int>& getTrackOffsets() const;
  27148. /** Refreshes the object's table of contents.
  27149. If the disc has been ejected and a different one put in since this
  27150. object was created, this will cause it to update its idea of how many tracks
  27151. there are, etc.
  27152. */
  27153. void refreshTrackLengths();
  27154. /** Enables scanning for indexes within tracks.
  27155. @see getLastIndex
  27156. */
  27157. void enableIndexScanning (bool enabled);
  27158. /** Returns the index number found during the last read() call.
  27159. Index scanning is turned off by default - turn it on with enableIndexScanning().
  27160. Then when the read() method is called, if it comes across an index within that
  27161. block, the index number is stored and returned by this method.
  27162. Some devices might not support indexes, of course.
  27163. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  27164. @see enableIndexScanning
  27165. */
  27166. int getLastIndex() const;
  27167. /** Scans a track to find the position of any indexes within it.
  27168. @param trackNumber the track to look in, where 0 is the first track on the disc
  27169. @returns an array of sample positions of any index points found (not including
  27170. the index that marks the start of the track)
  27171. */
  27172. const Array <int> findIndexesInTrack (const int trackNumber);
  27173. /** Returns the CDDB id number for the CD.
  27174. It's not a great way of identifying a disc, but it's traditional.
  27175. */
  27176. int getCDDBId();
  27177. /** Tries to eject the disk.
  27178. Of course this might not be possible, if some other process is using it.
  27179. */
  27180. void ejectDisk();
  27181. enum
  27182. {
  27183. framesPerSecond = 75,
  27184. samplesPerFrame = 44100 / framesPerSecond
  27185. };
  27186. private:
  27187. Array<int> trackStartSamples;
  27188. #if JUCE_MAC
  27189. File volumeDir;
  27190. Array<File> tracks;
  27191. int currentReaderTrack;
  27192. ScopedPointer <AudioFormatReader> reader;
  27193. AudioCDReader (const File& volume);
  27194. #elif JUCE_WINDOWS
  27195. bool audioTracks [100];
  27196. void* handle;
  27197. bool indexingEnabled;
  27198. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  27199. MemoryBlock buffer;
  27200. AudioCDReader (void* handle);
  27201. int getIndexAt (int samplePos);
  27202. #elif JUCE_LINUX
  27203. AudioCDReader();
  27204. #endif
  27205. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioCDReader);
  27206. };
  27207. #endif
  27208. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  27209. /*** End of inlined file: juce_AudioCDReader.h ***/
  27210. #endif
  27211. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27212. #endif
  27213. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27214. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  27215. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27216. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27217. /**
  27218. A class for keeping a list of available audio formats, and for deciding which
  27219. one to use to open a given file.
  27220. You can either use this class as a singleton object, or create instances of it
  27221. yourself. Once created, use its registerFormat() method to tell it which
  27222. formats it should use.
  27223. @see AudioFormat
  27224. */
  27225. class JUCE_API AudioFormatManager
  27226. {
  27227. public:
  27228. /** Creates an empty format manager.
  27229. Before it'll be any use, you'll need to call registerFormat() with all the
  27230. formats you want it to be able to recognise.
  27231. */
  27232. AudioFormatManager();
  27233. /** Destructor. */
  27234. ~AudioFormatManager();
  27235. /** Adds a format to the manager's list of available file types.
  27236. The object passed-in will be deleted by this object, so don't keep a pointer
  27237. to it!
  27238. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  27239. return this one when called.
  27240. */
  27241. void registerFormat (AudioFormat* newFormat,
  27242. bool makeThisTheDefaultFormat);
  27243. /** Handy method to make it easy to register the formats that come with Juce.
  27244. Currently, this will add WAV and AIFF to the list.
  27245. */
  27246. void registerBasicFormats();
  27247. /** Clears the list of known formats. */
  27248. void clearFormats();
  27249. /** Returns the number of currently registered file formats. */
  27250. int getNumKnownFormats() const;
  27251. /** Returns one of the registered file formats. */
  27252. AudioFormat* getKnownFormat (int index) const;
  27253. /** Looks for which of the known formats is listed as being for a given file
  27254. extension.
  27255. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  27256. */
  27257. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  27258. /** Returns the format which has been set as the default one.
  27259. You can set a format as being the default when it is registered. It's useful
  27260. when you want to write to a file, because the best format may change between
  27261. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  27262. If none has been set as the default, this method will just return the first
  27263. one in the list.
  27264. */
  27265. AudioFormat* getDefaultFormat() const;
  27266. /** Returns a set of wildcards for file-matching that contains the extensions for
  27267. all known formats.
  27268. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  27269. */
  27270. const String getWildcardForAllFormats() const;
  27271. /** Searches through the known formats to try to create a suitable reader for
  27272. this file.
  27273. If none of the registered formats can open the file, it'll return 0. If it
  27274. returns a reader, it's the caller's responsibility to delete the reader.
  27275. */
  27276. AudioFormatReader* createReaderFor (const File& audioFile);
  27277. /** Searches through the known formats to try to create a suitable reader for
  27278. this stream.
  27279. The stream object that is passed-in will be deleted by this method or by the
  27280. reader that is returned, so the caller should not keep any references to it.
  27281. The stream that is passed-in must be capable of being repositioned so
  27282. that all the formats can have a go at opening it.
  27283. If none of the registered formats can open the stream, it'll return 0. If it
  27284. returns a reader, it's the caller's responsibility to delete the reader.
  27285. */
  27286. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  27287. private:
  27288. OwnedArray<AudioFormat> knownFormats;
  27289. int defaultFormatIndex;
  27290. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatManager);
  27291. };
  27292. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27293. /*** End of inlined file: juce_AudioFormatManager.h ***/
  27294. #endif
  27295. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27296. #endif
  27297. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27298. #endif
  27299. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27300. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  27301. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27302. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27303. /**
  27304. This class is used to wrap an AudioFormatReader and only read from a
  27305. subsection of the file.
  27306. So if you have a reader which can read a 1000 sample file, you could wrap it
  27307. in one of these to only access, e.g. samples 100 to 200, and any samples
  27308. outside that will come back as 0. Accessing sample 0 from this reader will
  27309. actually read the first sample from the other's subsection, which might
  27310. be at a non-zero position.
  27311. @see AudioFormatReader
  27312. */
  27313. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  27314. {
  27315. public:
  27316. /** Creates a AudioSubsectionReader for a given data source.
  27317. @param sourceReader the source reader from which we'll be taking data
  27318. @param subsectionStartSample the sample within the source reader which will be
  27319. mapped onto sample 0 for this reader.
  27320. @param subsectionLength the number of samples from the source that will
  27321. make up the subsection. If this reader is asked for
  27322. any samples beyond this region, it will return zero.
  27323. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  27324. this object is deleted.
  27325. */
  27326. AudioSubsectionReader (AudioFormatReader* sourceReader,
  27327. int64 subsectionStartSample,
  27328. int64 subsectionLength,
  27329. bool deleteSourceWhenDeleted);
  27330. /** Destructor. */
  27331. ~AudioSubsectionReader();
  27332. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  27333. int64 startSampleInFile, int numSamples);
  27334. void readMaxLevels (int64 startSample,
  27335. int64 numSamples,
  27336. float& lowestLeft,
  27337. float& highestLeft,
  27338. float& lowestRight,
  27339. float& highestRight);
  27340. private:
  27341. AudioFormatReader* const source;
  27342. int64 startSample, length;
  27343. const bool deleteSourceWhenDeleted;
  27344. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSubsectionReader);
  27345. };
  27346. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27347. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  27348. #endif
  27349. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27350. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  27351. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27352. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27353. class AudioThumbnailCache;
  27354. /**
  27355. Makes it easy to quickly draw scaled views of the waveform shape of an
  27356. audio file.
  27357. To use this class, just create an AudioThumbNail class for the file you want
  27358. to draw, call setSource to tell it which file or resource to use, then call
  27359. drawChannel() to draw it.
  27360. The class will asynchronously scan the wavefile to create its scaled-down view,
  27361. so you should make your UI repaint itself as this data comes in. To do this, the
  27362. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  27363. listeners should repaint themselves.
  27364. The thumbnail stores an internal low-res version of the wave data, and this can
  27365. be loaded and saved to avoid having to scan the file again.
  27366. @see AudioThumbnailCache
  27367. */
  27368. class JUCE_API AudioThumbnail : public ChangeBroadcaster
  27369. {
  27370. public:
  27371. /** Creates an audio thumbnail.
  27372. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  27373. of the audio data, this is the scale at which it should be done. (This
  27374. number is the number of original samples that will be averaged for each
  27375. low-res sample)
  27376. @param formatManagerToUse the audio format manager that is used to open the file
  27377. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  27378. thread and storage that is used to by the thumbnail, and the cache
  27379. object can be shared between multiple thumbnails
  27380. */
  27381. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  27382. AudioFormatManager& formatManagerToUse,
  27383. AudioThumbnailCache& cacheToUse);
  27384. /** Destructor. */
  27385. ~AudioThumbnail();
  27386. /** Clears and resets the thumbnail. */
  27387. void clear();
  27388. /** Specifies the file or stream that contains the audio file.
  27389. For a file, just call
  27390. @code
  27391. setSource (new FileInputSource (file))
  27392. @endcode
  27393. You can pass a zero in here to clear the thumbnail.
  27394. The source that is passed in will be deleted by this object when it is no longer needed.
  27395. @returns true if the source could be opened as a valid audio file, false if this failed for
  27396. some reason.
  27397. */
  27398. bool setSource (InputSource* newSource);
  27399. /** Gives the thumbnail an AudioFormatReader to use directly.
  27400. This will start parsing the audio in a background thread (unless the hash code
  27401. can be looked-up successfully in the thumbnail cache). Note that the reader
  27402. object will be held by the thumbnail and deleted later when no longer needed.
  27403. The thumbnail will actually keep hold of this reader until you clear the thumbnail
  27404. or change the input source, so the file will be held open for all this time. If
  27405. you don't want the thumbnail to keep a file handle open continuously, you
  27406. should use the setSource() method instead, which will only open the file when
  27407. it needs to.
  27408. */
  27409. void setReader (AudioFormatReader* newReader, int64 hashCode);
  27410. /** Resets the thumbnail, ready for adding data with the specified format.
  27411. If you're going to generate a thumbnail yourself, call this before using addBlock()
  27412. to add the data.
  27413. */
  27414. void reset (int numChannels, double sampleRate, int64 totalSamplesInSource = 0);
  27415. /** Adds a block of level data to the thumbnail.
  27416. Call reset() before using this, to tell the thumbnail about the data format.
  27417. */
  27418. void addBlock (int64 sampleNumberInSource, const AudioSampleBuffer& newData,
  27419. int startOffsetInBuffer, int numSamples);
  27420. /** Reloads the low res thumbnail data from an input stream.
  27421. This is not an audio file stream! It takes a stream of thumbnail data that would
  27422. previously have been created by the saveTo() method.
  27423. @see saveTo
  27424. */
  27425. void loadFrom (InputStream& input);
  27426. /** Saves the low res thumbnail data to an output stream.
  27427. The data that is written can later be reloaded using loadFrom().
  27428. @see loadFrom
  27429. */
  27430. void saveTo (OutputStream& output) const;
  27431. /** Returns the number of channels in the file. */
  27432. int getNumChannels() const throw();
  27433. /** Returns the length of the audio file, in seconds. */
  27434. double getTotalLength() const throw();
  27435. /** Draws the waveform for a channel.
  27436. The waveform will be drawn within the specified rectangle, where startTime
  27437. and endTime specify the times within the audio file that should be positioned
  27438. at the left and right edges of the rectangle.
  27439. The waveform will be scaled vertically so that a full-volume sample will fill
  27440. the rectangle vertically, but you can also specify an extra vertical scale factor
  27441. with the verticalZoomFactor parameter.
  27442. */
  27443. void drawChannel (Graphics& g,
  27444. const Rectangle<int>& area,
  27445. double startTimeSeconds,
  27446. double endTimeSeconds,
  27447. int channelNum,
  27448. float verticalZoomFactor);
  27449. /** Draws the waveforms for all channels in the thumbnail.
  27450. This will call drawChannel() to render each of the thumbnail's channels, stacked
  27451. above each other within the specified area.
  27452. @see drawChannel
  27453. */
  27454. void drawChannels (Graphics& g,
  27455. const Rectangle<int>& area,
  27456. double startTimeSeconds,
  27457. double endTimeSeconds,
  27458. float verticalZoomFactor);
  27459. /** Returns true if the low res preview is fully generated. */
  27460. bool isFullyLoaded() const throw();
  27461. /** Returns the number of samples that have been set in the thumbnail. */
  27462. int64 getNumSamplesFinished() const throw();
  27463. /** Returns the highest level in the thumbnail.
  27464. Note that because the thumb only stores low-resolution data, this isn't
  27465. an accurate representation of the highest value, it's only a rough approximation.
  27466. */
  27467. float getApproximatePeak() const;
  27468. /** Returns the hash code that was set by setSource() or setReader(). */
  27469. int64 getHashCode() const;
  27470. #ifndef DOXYGEN
  27471. // (this is only public to avoid a VC6 bug)
  27472. class LevelDataSource;
  27473. #endif
  27474. private:
  27475. AudioFormatManager& formatManagerToUse;
  27476. AudioThumbnailCache& cache;
  27477. struct MinMaxValue;
  27478. class ThumbData;
  27479. class CachedWindow;
  27480. friend class LevelDataSource;
  27481. friend class ScopedPointer<LevelDataSource>;
  27482. friend class ThumbData;
  27483. friend class OwnedArray<ThumbData>;
  27484. friend class CachedWindow;
  27485. friend class ScopedPointer<CachedWindow>;
  27486. ScopedPointer<LevelDataSource> source;
  27487. ScopedPointer<CachedWindow> window;
  27488. OwnedArray<ThumbData> channels;
  27489. int32 samplesPerThumbSample;
  27490. int64 totalSamples, numSamplesFinished;
  27491. int32 numChannels;
  27492. double sampleRate;
  27493. CriticalSection lock;
  27494. bool setDataSource (LevelDataSource* newSource);
  27495. void setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues);
  27496. void createChannels (int length);
  27497. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnail);
  27498. };
  27499. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27500. /*** End of inlined file: juce_AudioThumbnail.h ***/
  27501. #endif
  27502. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27503. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  27504. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27505. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27506. struct ThumbnailCacheEntry;
  27507. /**
  27508. An instance of this class is used to manage multiple AudioThumbnail objects.
  27509. The cache runs a single background thread that is shared by all the thumbnails
  27510. that need it, and it maintains a set of low-res previews in memory, to avoid
  27511. having to re-scan audio files too often.
  27512. @see AudioThumbnail
  27513. */
  27514. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  27515. {
  27516. public:
  27517. /** Creates a cache object.
  27518. The maxNumThumbsToStore parameter lets you specify how many previews should
  27519. be kept in memory at once.
  27520. */
  27521. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  27522. /** Destructor. */
  27523. ~AudioThumbnailCache();
  27524. /** Clears out any stored thumbnails.
  27525. */
  27526. void clear();
  27527. /** Reloads the specified thumb if this cache contains the appropriate stored
  27528. data.
  27529. This is called automatically by the AudioThumbnail class, so you shouldn't
  27530. normally need to call it directly.
  27531. */
  27532. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  27533. /** Stores the cachable data from the specified thumb in this cache.
  27534. This is called automatically by the AudioThumbnail class, so you shouldn't
  27535. normally need to call it directly.
  27536. */
  27537. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  27538. private:
  27539. OwnedArray <ThumbnailCacheEntry> thumbs;
  27540. int maxNumThumbsToStore;
  27541. ThumbnailCacheEntry* findThumbFor (int64 hash) const;
  27542. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioThumbnailCache);
  27543. };
  27544. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27545. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  27546. #endif
  27547. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27548. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  27549. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27550. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27551. #if JUCE_USE_FLAC || defined (DOXYGEN)
  27552. /**
  27553. Reads and writes the lossless-compression FLAC audio format.
  27554. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  27555. and make sure your include search path and library search path are set up to find
  27556. the FLAC header files and static libraries.
  27557. @see AudioFormat
  27558. */
  27559. class JUCE_API FlacAudioFormat : public AudioFormat
  27560. {
  27561. public:
  27562. FlacAudioFormat();
  27563. ~FlacAudioFormat();
  27564. const Array <int> getPossibleSampleRates();
  27565. const Array <int> getPossibleBitDepths();
  27566. bool canDoStereo();
  27567. bool canDoMono();
  27568. bool isCompressed();
  27569. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27570. bool deleteStreamIfOpeningFails);
  27571. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27572. double sampleRateToUse,
  27573. unsigned int numberOfChannels,
  27574. int bitsPerSample,
  27575. const StringPairArray& metadataValues,
  27576. int qualityOptionIndex);
  27577. private:
  27578. JUCE_LEAK_DETECTOR (FlacAudioFormat);
  27579. };
  27580. #endif
  27581. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27582. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  27583. #endif
  27584. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27585. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  27586. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27587. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27588. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  27589. /**
  27590. Reads and writes the Ogg-Vorbis audio format.
  27591. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  27592. and make sure your include search path and library search path are set up to find
  27593. the Vorbis and Ogg header files and static libraries.
  27594. @see AudioFormat,
  27595. */
  27596. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  27597. {
  27598. public:
  27599. OggVorbisAudioFormat();
  27600. ~OggVorbisAudioFormat();
  27601. const Array <int> getPossibleSampleRates();
  27602. const Array <int> getPossibleBitDepths();
  27603. bool canDoStereo();
  27604. bool canDoMono();
  27605. bool isCompressed();
  27606. const StringArray getQualityOptions();
  27607. /** Tries to estimate the quality level of an ogg file based on its size.
  27608. If it can't read the file for some reason, this will just return 1 (medium quality),
  27609. otherwise it will return the approximate quality setting that would have been used
  27610. to create the file.
  27611. @see getQualityOptions
  27612. */
  27613. int estimateOggFileQuality (const File& source);
  27614. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27615. bool deleteStreamIfOpeningFails);
  27616. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27617. double sampleRateToUse,
  27618. unsigned int numberOfChannels,
  27619. int bitsPerSample,
  27620. const StringPairArray& metadataValues,
  27621. int qualityOptionIndex);
  27622. private:
  27623. JUCE_LEAK_DETECTOR (OggVorbisAudioFormat);
  27624. };
  27625. #endif
  27626. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27627. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  27628. #endif
  27629. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27630. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  27631. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27632. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27633. #if JUCE_QUICKTIME
  27634. /**
  27635. Uses QuickTime to read the audio track a movie or media file.
  27636. As well as QuickTime movies, this should also manage to open other audio
  27637. files that quicktime can understand, like mp3, m4a, etc.
  27638. @see AudioFormat
  27639. */
  27640. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  27641. {
  27642. public:
  27643. /** Creates a format object. */
  27644. QuickTimeAudioFormat();
  27645. /** Destructor. */
  27646. ~QuickTimeAudioFormat();
  27647. const Array <int> getPossibleSampleRates();
  27648. const Array <int> getPossibleBitDepths();
  27649. bool canDoStereo();
  27650. bool canDoMono();
  27651. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27652. bool deleteStreamIfOpeningFails);
  27653. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27654. double sampleRateToUse,
  27655. unsigned int numberOfChannels,
  27656. int bitsPerSample,
  27657. const StringPairArray& metadataValues,
  27658. int qualityOptionIndex);
  27659. private:
  27660. JUCE_LEAK_DETECTOR (QuickTimeAudioFormat);
  27661. };
  27662. #endif
  27663. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27664. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  27665. #endif
  27666. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27667. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  27668. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27669. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27670. /**
  27671. Reads and Writes WAV format audio files.
  27672. @see AudioFormat
  27673. */
  27674. class JUCE_API WavAudioFormat : public AudioFormat
  27675. {
  27676. public:
  27677. /** Creates a format object. */
  27678. WavAudioFormat();
  27679. /** Destructor. */
  27680. ~WavAudioFormat();
  27681. /** Metadata property name used by wav readers and writers for adding
  27682. a BWAV chunk to the file.
  27683. @see AudioFormatReader::metadataValues, createWriterFor
  27684. */
  27685. static const char* const bwavDescription;
  27686. /** Metadata property name used by wav readers and writers for adding
  27687. a BWAV chunk to the file.
  27688. @see AudioFormatReader::metadataValues, createWriterFor
  27689. */
  27690. static const char* const bwavOriginator;
  27691. /** Metadata property name used by wav readers and writers for adding
  27692. a BWAV chunk to the file.
  27693. @see AudioFormatReader::metadataValues, createWriterFor
  27694. */
  27695. static const char* const bwavOriginatorRef;
  27696. /** Metadata property name used by wav readers and writers for adding
  27697. a BWAV chunk to the file.
  27698. Date format is: yyyy-mm-dd
  27699. @see AudioFormatReader::metadataValues, createWriterFor
  27700. */
  27701. static const char* const bwavOriginationDate;
  27702. /** Metadata property name used by wav readers and writers for adding
  27703. a BWAV chunk to the file.
  27704. Time format is: hh-mm-ss
  27705. @see AudioFormatReader::metadataValues, createWriterFor
  27706. */
  27707. static const char* const bwavOriginationTime;
  27708. /** Metadata property name used by wav readers and writers for adding
  27709. a BWAV chunk to the file.
  27710. This is the number of samples from the start of an edit that the
  27711. file is supposed to begin at. Seems like an obvious mistake to
  27712. only allow a file to occur in an edit once, but that's the way
  27713. it is..
  27714. @see AudioFormatReader::metadataValues, createWriterFor
  27715. */
  27716. static const char* const bwavTimeReference;
  27717. /** Metadata property name used by wav readers and writers for adding
  27718. a BWAV chunk to the file.
  27719. This is a
  27720. @see AudioFormatReader::metadataValues, createWriterFor
  27721. */
  27722. static const char* const bwavCodingHistory;
  27723. /** Utility function to fill out the appropriate metadata for a BWAV file.
  27724. This just makes it easier than using the property names directly, and it
  27725. fills out the time and date in the right format.
  27726. */
  27727. static const StringPairArray createBWAVMetadata (const String& description,
  27728. const String& originator,
  27729. const String& originatorRef,
  27730. const Time& dateAndTime,
  27731. const int64 timeReferenceSamples,
  27732. const String& codingHistory);
  27733. const Array <int> getPossibleSampleRates();
  27734. const Array <int> getPossibleBitDepths();
  27735. bool canDoStereo();
  27736. bool canDoMono();
  27737. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27738. bool deleteStreamIfOpeningFails);
  27739. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27740. double sampleRateToUse,
  27741. unsigned int numberOfChannels,
  27742. int bitsPerSample,
  27743. const StringPairArray& metadataValues,
  27744. int qualityOptionIndex);
  27745. /** Utility function to replace the metadata in a wav file with a new set of values.
  27746. If possible, this cheats by overwriting just the metadata region of the file, rather
  27747. than by copying the whole file again.
  27748. */
  27749. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  27750. private:
  27751. JUCE_LEAK_DETECTOR (WavAudioFormat);
  27752. };
  27753. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27754. /*** End of inlined file: juce_WavAudioFormat.h ***/
  27755. #endif
  27756. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  27757. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  27758. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  27759. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  27760. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  27761. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  27762. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  27763. /**
  27764. A type of AudioSource which can be repositioned.
  27765. The basic AudioSource just streams continuously with no idea of a current
  27766. time or length, so the PositionableAudioSource is used for a finite stream
  27767. that has a current read position.
  27768. @see AudioSource, AudioTransportSource
  27769. */
  27770. class JUCE_API PositionableAudioSource : public AudioSource
  27771. {
  27772. protected:
  27773. /** Creates the PositionableAudioSource. */
  27774. PositionableAudioSource() throw() {}
  27775. public:
  27776. /** Destructor */
  27777. ~PositionableAudioSource() {}
  27778. /** Tells the stream to move to a new position.
  27779. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  27780. should return samples from this position.
  27781. Note that this may be called on a different thread to getNextAudioBlock(),
  27782. so the subclass should make sure it's synchronised.
  27783. */
  27784. virtual void setNextReadPosition (int64 newPosition) = 0;
  27785. /** Returns the position from which the next block will be returned.
  27786. @see setNextReadPosition
  27787. */
  27788. virtual int64 getNextReadPosition() const = 0;
  27789. /** Returns the total length of the stream (in samples). */
  27790. virtual int64 getTotalLength() const = 0;
  27791. /** Returns true if this source is actually playing in a loop. */
  27792. virtual bool isLooping() const = 0;
  27793. /** Tells the source whether you'd like it to play in a loop. */
  27794. virtual void setLooping (bool shouldLoop) { (void) shouldLoop; }
  27795. };
  27796. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  27797. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  27798. /**
  27799. A type of AudioSource that will read from an AudioFormatReader.
  27800. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  27801. */
  27802. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  27803. {
  27804. public:
  27805. /** Creates an AudioFormatReaderSource for a given reader.
  27806. @param sourceReader the reader to use as the data source
  27807. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  27808. when this object is deleted; if false it will be
  27809. left up to the caller to manage its lifetime
  27810. */
  27811. AudioFormatReaderSource (AudioFormatReader* sourceReader,
  27812. bool deleteReaderWhenThisIsDeleted);
  27813. /** Destructor. */
  27814. ~AudioFormatReaderSource();
  27815. /** Toggles loop-mode.
  27816. If set to true, it will continuously loop the input source. If false,
  27817. it will just emit silence after the source has finished.
  27818. @see isLooping
  27819. */
  27820. void setLooping (bool shouldLoop);
  27821. /** Returns whether loop-mode is turned on or not. */
  27822. bool isLooping() const { return looping; }
  27823. /** Returns the reader that's being used. */
  27824. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  27825. /** Implementation of the AudioSource method. */
  27826. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  27827. /** Implementation of the AudioSource method. */
  27828. void releaseResources();
  27829. /** Implementation of the AudioSource method. */
  27830. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  27831. /** Implements the PositionableAudioSource method. */
  27832. void setNextReadPosition (int64 newPosition);
  27833. /** Implements the PositionableAudioSource method. */
  27834. int64 getNextReadPosition() const;
  27835. /** Implements the PositionableAudioSource method. */
  27836. int64 getTotalLength() const;
  27837. private:
  27838. AudioFormatReader* reader;
  27839. bool deleteReader;
  27840. int64 volatile nextPlayPos;
  27841. bool volatile looping;
  27842. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  27843. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioFormatReaderSource);
  27844. };
  27845. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  27846. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  27847. #endif
  27848. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  27849. #endif
  27850. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  27851. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  27852. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  27853. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  27854. /*** Start of inlined file: juce_AudioIODevice.h ***/
  27855. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  27856. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  27857. class AudioIODevice;
  27858. /**
  27859. One of these is passed to an AudioIODevice object to stream the audio data
  27860. in and out.
  27861. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  27862. method on its own high-priority audio thread, when it needs to send or receive
  27863. the next block of data.
  27864. @see AudioIODevice, AudioDeviceManager
  27865. */
  27866. class JUCE_API AudioIODeviceCallback
  27867. {
  27868. public:
  27869. /** Destructor. */
  27870. virtual ~AudioIODeviceCallback() {}
  27871. /** Processes a block of incoming and outgoing audio data.
  27872. The subclass's implementation should use the incoming audio for whatever
  27873. purposes it needs to, and must fill all the output channels with the next
  27874. block of output data before returning.
  27875. The channel data is arranged with the same array indices as the channel name
  27876. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  27877. that aren't specified in AudioIODevice::open() will have a null pointer for their
  27878. associated channel, so remember to check for this.
  27879. @param inputChannelData a set of arrays containing the audio data for each
  27880. incoming channel - this data is valid until the function
  27881. returns. There will be one channel of data for each input
  27882. channel that was enabled when the audio device was opened
  27883. (see AudioIODevice::open())
  27884. @param numInputChannels the number of pointers to channel data in the
  27885. inputChannelData array.
  27886. @param outputChannelData a set of arrays which need to be filled with the data
  27887. that should be sent to each outgoing channel of the device.
  27888. There will be one channel of data for each output channel
  27889. that was enabled when the audio device was opened (see
  27890. AudioIODevice::open())
  27891. The initial contents of the array is undefined, so the
  27892. callback function must fill all the channels with zeros if
  27893. its output is silence. Failing to do this could cause quite
  27894. an unpleasant noise!
  27895. @param numOutputChannels the number of pointers to channel data in the
  27896. outputChannelData array.
  27897. @param numSamples the number of samples in each channel of the input and
  27898. output arrays. The number of samples will depend on the
  27899. audio device's buffer size and will usually remain constant,
  27900. although this isn't guaranteed, so make sure your code can
  27901. cope with reasonable changes in the buffer size from one
  27902. callback to the next.
  27903. */
  27904. virtual void audioDeviceIOCallback (const float** inputChannelData,
  27905. int numInputChannels,
  27906. float** outputChannelData,
  27907. int numOutputChannels,
  27908. int numSamples) = 0;
  27909. /** Called to indicate that the device is about to start calling back.
  27910. This will be called just before the audio callbacks begin, either when this
  27911. callback has just been added to an audio device, or after the device has been
  27912. restarted because of a sample-rate or block-size change.
  27913. You can use this opportunity to find out the sample rate and block size
  27914. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  27915. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  27916. @param device the audio IO device that will be used to drive the callback.
  27917. Note that if you're going to store this this pointer, it is
  27918. only valid until the next time that audioDeviceStopped is called.
  27919. */
  27920. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  27921. /** Called to indicate that the device has stopped.
  27922. */
  27923. virtual void audioDeviceStopped() = 0;
  27924. };
  27925. /**
  27926. Base class for an audio device with synchronised input and output channels.
  27927. Subclasses of this are used to implement different protocols such as DirectSound,
  27928. ASIO, CoreAudio, etc.
  27929. To create one of these, you'll need to use the AudioIODeviceType class - see the
  27930. documentation for that class for more info.
  27931. For an easier way of managing audio devices and their settings, have a look at the
  27932. AudioDeviceManager class.
  27933. @see AudioIODeviceType, AudioDeviceManager
  27934. */
  27935. class JUCE_API AudioIODevice
  27936. {
  27937. public:
  27938. /** Destructor. */
  27939. virtual ~AudioIODevice();
  27940. /** Returns the device's name, (as set in the constructor). */
  27941. const String& getName() const throw() { return name; }
  27942. /** Returns the type of the device.
  27943. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  27944. */
  27945. const String& getTypeName() const throw() { return typeName; }
  27946. /** Returns the names of all the available output channels on this device.
  27947. To find out which of these are currently in use, call getActiveOutputChannels().
  27948. */
  27949. virtual const StringArray getOutputChannelNames() = 0;
  27950. /** Returns the names of all the available input channels on this device.
  27951. To find out which of these are currently in use, call getActiveInputChannels().
  27952. */
  27953. virtual const StringArray getInputChannelNames() = 0;
  27954. /** Returns the number of sample-rates this device supports.
  27955. To find out which rates are available on this device, use this method to
  27956. find out how many there are, and getSampleRate() to get the rates.
  27957. @see getSampleRate
  27958. */
  27959. virtual int getNumSampleRates() = 0;
  27960. /** Returns one of the sample-rates this device supports.
  27961. To find out which rates are available on this device, use getNumSampleRates() to
  27962. find out how many there are, and getSampleRate() to get the individual rates.
  27963. The sample rate is set by the open() method.
  27964. (Note that for DirectSound some rates might not work, depending on combinations
  27965. of i/o channels that are being opened).
  27966. @see getNumSampleRates
  27967. */
  27968. virtual double getSampleRate (int index) = 0;
  27969. /** Returns the number of sizes of buffer that are available.
  27970. @see getBufferSizeSamples, getDefaultBufferSize
  27971. */
  27972. virtual int getNumBufferSizesAvailable() = 0;
  27973. /** Returns one of the possible buffer-sizes.
  27974. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  27975. @returns a number of samples
  27976. @see getNumBufferSizesAvailable, getDefaultBufferSize
  27977. */
  27978. virtual int getBufferSizeSamples (int index) = 0;
  27979. /** Returns the default buffer-size to use.
  27980. @returns a number of samples
  27981. @see getNumBufferSizesAvailable, getBufferSizeSamples
  27982. */
  27983. virtual int getDefaultBufferSize() = 0;
  27984. /** Tries to open the device ready to play.
  27985. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  27986. input channel should be enabled
  27987. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  27988. output channel should be enabled
  27989. @param sampleRate the sample rate to try to use - to find out which rates are
  27990. available, see getNumSampleRates() and getSampleRate()
  27991. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  27992. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  27993. @returns an error description if there's a problem, or an empty string if it succeeds in
  27994. opening the device
  27995. @see close
  27996. */
  27997. virtual const String open (const BigInteger& inputChannels,
  27998. const BigInteger& outputChannels,
  27999. double sampleRate,
  28000. int bufferSizeSamples) = 0;
  28001. /** Closes and releases the device if it's open. */
  28002. virtual void close() = 0;
  28003. /** Returns true if the device is still open.
  28004. A device might spontaneously close itself if something goes wrong, so this checks if
  28005. it's still open.
  28006. */
  28007. virtual bool isOpen() = 0;
  28008. /** Starts the device actually playing.
  28009. This must be called after the device has been opened.
  28010. @param callback the callback to use for streaming the data.
  28011. @see AudioIODeviceCallback, open
  28012. */
  28013. virtual void start (AudioIODeviceCallback* callback) = 0;
  28014. /** Stops the device playing.
  28015. Once a device has been started, this will stop it. Any pending calls to the
  28016. callback class will be flushed before this method returns.
  28017. */
  28018. virtual void stop() = 0;
  28019. /** Returns true if the device is still calling back.
  28020. The device might mysteriously stop, so this checks whether it's
  28021. still playing.
  28022. */
  28023. virtual bool isPlaying() = 0;
  28024. /** Returns the last error that happened if anything went wrong. */
  28025. virtual const String getLastError() = 0;
  28026. /** Returns the buffer size that the device is currently using.
  28027. If the device isn't actually open, this value doesn't really mean much.
  28028. */
  28029. virtual int getCurrentBufferSizeSamples() = 0;
  28030. /** Returns the sample rate that the device is currently using.
  28031. If the device isn't actually open, this value doesn't really mean much.
  28032. */
  28033. virtual double getCurrentSampleRate() = 0;
  28034. /** Returns the device's current physical bit-depth.
  28035. If the device isn't actually open, this value doesn't really mean much.
  28036. */
  28037. virtual int getCurrentBitDepth() = 0;
  28038. /** Returns a mask showing which of the available output channels are currently
  28039. enabled.
  28040. @see getOutputChannelNames
  28041. */
  28042. virtual const BigInteger getActiveOutputChannels() const = 0;
  28043. /** Returns a mask showing which of the available input channels are currently
  28044. enabled.
  28045. @see getInputChannelNames
  28046. */
  28047. virtual const BigInteger getActiveInputChannels() const = 0;
  28048. /** Returns the device's output latency.
  28049. This is the delay in samples between a callback getting a block of data, and
  28050. that data actually getting played.
  28051. */
  28052. virtual int getOutputLatencyInSamples() = 0;
  28053. /** Returns the device's input latency.
  28054. This is the delay in samples between some audio actually arriving at the soundcard,
  28055. and the callback getting passed this block of data.
  28056. */
  28057. virtual int getInputLatencyInSamples() = 0;
  28058. /** True if this device can show a pop-up control panel for editing its settings.
  28059. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  28060. to display it.
  28061. */
  28062. virtual bool hasControlPanel() const;
  28063. /** Shows a device-specific control panel if there is one.
  28064. This should only be called for devices which return true from hasControlPanel().
  28065. */
  28066. virtual bool showControlPanel();
  28067. protected:
  28068. /** Creates a device, setting its name and type member variables. */
  28069. AudioIODevice (const String& deviceName,
  28070. const String& typeName);
  28071. /** @internal */
  28072. String name, typeName;
  28073. };
  28074. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  28075. /*** End of inlined file: juce_AudioIODevice.h ***/
  28076. /**
  28077. Wrapper class to continuously stream audio from an audio source to an
  28078. AudioIODevice.
  28079. This object acts as an AudioIODeviceCallback, so can be attached to an
  28080. output device, and will stream audio from an AudioSource.
  28081. */
  28082. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  28083. {
  28084. public:
  28085. /** Creates an empty AudioSourcePlayer. */
  28086. AudioSourcePlayer();
  28087. /** Destructor.
  28088. Make sure this object isn't still being used by an AudioIODevice before
  28089. deleting it!
  28090. */
  28091. virtual ~AudioSourcePlayer();
  28092. /** Changes the current audio source to play from.
  28093. If the source passed in is already being used, this method will do nothing.
  28094. If the source is not null, its prepareToPlay() method will be called
  28095. before it starts being used for playback.
  28096. If there's another source currently playing, its releaseResources() method
  28097. will be called after it has been swapped for the new one.
  28098. @param newSource the new source to use - this will NOT be deleted
  28099. by this object when no longer needed, so it's the
  28100. caller's responsibility to manage it.
  28101. */
  28102. void setSource (AudioSource* newSource);
  28103. /** Returns the source that's playing.
  28104. May return 0 if there's no source.
  28105. */
  28106. AudioSource* getCurrentSource() const throw() { return source; }
  28107. /** Sets a gain to apply to the audio data.
  28108. @see getGain
  28109. */
  28110. void setGain (float newGain) throw();
  28111. /** Returns the current gain.
  28112. @see setGain
  28113. */
  28114. float getGain() const throw() { return gain; }
  28115. /** Implementation of the AudioIODeviceCallback method. */
  28116. void audioDeviceIOCallback (const float** inputChannelData,
  28117. int totalNumInputChannels,
  28118. float** outputChannelData,
  28119. int totalNumOutputChannels,
  28120. int numSamples);
  28121. /** Implementation of the AudioIODeviceCallback method. */
  28122. void audioDeviceAboutToStart (AudioIODevice* device);
  28123. /** Implementation of the AudioIODeviceCallback method. */
  28124. void audioDeviceStopped();
  28125. private:
  28126. CriticalSection readLock;
  28127. AudioSource* source;
  28128. double sampleRate;
  28129. int bufferSize;
  28130. float* channels [128];
  28131. float* outputChans [128];
  28132. const float* inputChans [128];
  28133. AudioSampleBuffer tempBuffer;
  28134. float lastGain, gain;
  28135. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSourcePlayer);
  28136. };
  28137. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  28138. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  28139. #endif
  28140. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  28141. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  28142. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  28143. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  28144. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  28145. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  28146. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  28147. /**
  28148. An AudioSource which takes another source as input, and buffers it using a thread.
  28149. Create this as a wrapper around another thread, and it will read-ahead with
  28150. a background thread to smooth out playback. You can either create one of these
  28151. directly, or use it indirectly using an AudioTransportSource.
  28152. @see PositionableAudioSource, AudioTransportSource
  28153. */
  28154. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  28155. {
  28156. public:
  28157. /** Creates a BufferingAudioSource.
  28158. @param source the input source to read from
  28159. @param deleteSourceWhenDeleted if true, then the input source object will
  28160. be deleted when this object is deleted
  28161. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  28162. */
  28163. BufferingAudioSource (PositionableAudioSource* source,
  28164. bool deleteSourceWhenDeleted,
  28165. int numberOfSamplesToBuffer);
  28166. /** Destructor.
  28167. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  28168. flag was set in the constructor.
  28169. */
  28170. ~BufferingAudioSource();
  28171. /** Implementation of the AudioSource method. */
  28172. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28173. /** Implementation of the AudioSource method. */
  28174. void releaseResources();
  28175. /** Implementation of the AudioSource method. */
  28176. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28177. /** Implements the PositionableAudioSource method. */
  28178. void setNextReadPosition (int64 newPosition);
  28179. /** Implements the PositionableAudioSource method. */
  28180. int64 getNextReadPosition() const;
  28181. /** Implements the PositionableAudioSource method. */
  28182. int64 getTotalLength() const { return source->getTotalLength(); }
  28183. /** Implements the PositionableAudioSource method. */
  28184. bool isLooping() const { return source->isLooping(); }
  28185. private:
  28186. PositionableAudioSource* source;
  28187. bool deleteSourceWhenDeleted;
  28188. int numberOfSamplesToBuffer;
  28189. AudioSampleBuffer buffer;
  28190. CriticalSection bufferStartPosLock;
  28191. int64 volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  28192. bool wasSourceLooping;
  28193. double volatile sampleRate;
  28194. friend class SharedBufferingAudioSourceThread;
  28195. bool readNextBufferChunk();
  28196. void readBufferSection (int64 start, int length, int bufferOffset);
  28197. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BufferingAudioSource);
  28198. };
  28199. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  28200. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  28201. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  28202. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  28203. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  28204. /**
  28205. A type of AudioSource that takes an input source and changes its sample rate.
  28206. @see AudioSource
  28207. */
  28208. class JUCE_API ResamplingAudioSource : public AudioSource
  28209. {
  28210. public:
  28211. /** Creates a ResamplingAudioSource for a given input source.
  28212. @param inputSource the input source to read from
  28213. @param deleteInputWhenDeleted if true, the input source will be deleted when
  28214. this object is deleted
  28215. @param numChannels the number of channels to process
  28216. */
  28217. ResamplingAudioSource (AudioSource* inputSource,
  28218. bool deleteInputWhenDeleted,
  28219. int numChannels = 2);
  28220. /** Destructor. */
  28221. ~ResamplingAudioSource();
  28222. /** Changes the resampling ratio.
  28223. (This value can be changed at any time, even while the source is running).
  28224. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  28225. values will speed it up; lower values will slow it
  28226. down. The ratio must be greater than 0
  28227. */
  28228. void setResamplingRatio (double samplesInPerOutputSample);
  28229. /** Returns the current resampling ratio.
  28230. This is the value that was set by setResamplingRatio().
  28231. */
  28232. double getResamplingRatio() const throw() { return ratio; }
  28233. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28234. void releaseResources();
  28235. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28236. private:
  28237. AudioSource* const input;
  28238. const bool deleteInputWhenDeleted;
  28239. double ratio, lastRatio;
  28240. AudioSampleBuffer buffer;
  28241. int bufferPos, sampsInBuffer;
  28242. double subSampleOffset;
  28243. double coefficients[6];
  28244. CriticalSection ratioLock;
  28245. const int numChannels;
  28246. HeapBlock<float*> destBuffers, srcBuffers;
  28247. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  28248. void createLowPass (double proportionalRate);
  28249. struct FilterState
  28250. {
  28251. double x1, x2, y1, y2;
  28252. };
  28253. HeapBlock<FilterState> filterStates;
  28254. void resetFilters();
  28255. void applyFilter (float* samples, int num, FilterState& fs);
  28256. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResamplingAudioSource);
  28257. };
  28258. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  28259. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  28260. /**
  28261. An AudioSource that takes a PositionableAudioSource and allows it to be
  28262. played, stopped, started, etc.
  28263. This can also be told use a buffer and background thread to read ahead, and
  28264. if can correct for different sample-rates.
  28265. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  28266. to control playback of an audio file.
  28267. @see AudioSource, AudioSourcePlayer
  28268. */
  28269. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  28270. public ChangeBroadcaster
  28271. {
  28272. public:
  28273. /** Creates an AudioTransportSource.
  28274. After creating one of these, use the setSource() method to select an input source.
  28275. */
  28276. AudioTransportSource();
  28277. /** Destructor. */
  28278. ~AudioTransportSource();
  28279. /** Sets the reader that is being used as the input source.
  28280. This will stop playback, reset the position to 0 and change to the new reader.
  28281. The source passed in will not be deleted by this object, so must be managed by
  28282. the caller.
  28283. @param newSource the new input source to use. This may be zero
  28284. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  28285. is zero, no reading ahead will be done; if it's
  28286. greater than zero, a BufferingAudioSource will be used
  28287. to do the reading-ahead
  28288. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  28289. rate of the source, and playback will be sample-rate
  28290. adjusted to maintain playback at the correct pitch. If
  28291. this is 0, no sample-rate adjustment will be performed
  28292. @param maxNumChannels the maximum number of channels that may need to be played
  28293. */
  28294. void setSource (PositionableAudioSource* newSource,
  28295. int readAheadBufferSize = 0,
  28296. double sourceSampleRateToCorrectFor = 0.0,
  28297. int maxNumChannels = 2);
  28298. /** Changes the current playback position in the source stream.
  28299. The next time the getNextAudioBlock() method is called, this
  28300. is the time from which it'll read data.
  28301. @see getPosition
  28302. */
  28303. void setPosition (double newPosition);
  28304. /** Returns the position that the next data block will be read from
  28305. This is a time in seconds.
  28306. */
  28307. double getCurrentPosition() const;
  28308. /** Returns the stream's length in seconds. */
  28309. double getLengthInSeconds() const;
  28310. /** Returns true if the player has stopped because its input stream ran out of data.
  28311. */
  28312. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  28313. /** Starts playing (if a source has been selected).
  28314. If it starts playing, this will send a message to any ChangeListeners
  28315. that are registered with this object.
  28316. */
  28317. void start();
  28318. /** Stops playing.
  28319. If it's actually playing, this will send a message to any ChangeListeners
  28320. that are registered with this object.
  28321. */
  28322. void stop();
  28323. /** Returns true if it's currently playing. */
  28324. bool isPlaying() const throw() { return playing; }
  28325. /** Changes the gain to apply to the output.
  28326. @param newGain a factor by which to multiply the outgoing samples,
  28327. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  28328. */
  28329. void setGain (float newGain) throw();
  28330. /** Returns the current gain setting.
  28331. @see setGain
  28332. */
  28333. float getGain() const throw() { return gain; }
  28334. /** Implementation of the AudioSource method. */
  28335. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28336. /** Implementation of the AudioSource method. */
  28337. void releaseResources();
  28338. /** Implementation of the AudioSource method. */
  28339. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28340. /** Implements the PositionableAudioSource method. */
  28341. void setNextReadPosition (int64 newPosition);
  28342. /** Implements the PositionableAudioSource method. */
  28343. int64 getNextReadPosition() const;
  28344. /** Implements the PositionableAudioSource method. */
  28345. int64 getTotalLength() const;
  28346. /** Implements the PositionableAudioSource method. */
  28347. bool isLooping() const;
  28348. private:
  28349. PositionableAudioSource* source;
  28350. ResamplingAudioSource* resamplerSource;
  28351. BufferingAudioSource* bufferingSource;
  28352. PositionableAudioSource* positionableSource;
  28353. AudioSource* masterSource;
  28354. CriticalSection callbackLock;
  28355. float volatile gain, lastGain;
  28356. bool volatile playing, stopped;
  28357. double sampleRate, sourceSampleRate;
  28358. int blockSize, readAheadBufferSize;
  28359. bool isPrepared, inputStreamEOF;
  28360. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioTransportSource);
  28361. };
  28362. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  28363. /*** End of inlined file: juce_AudioTransportSource.h ***/
  28364. #endif
  28365. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  28366. #endif
  28367. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  28368. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  28369. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  28370. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  28371. /**
  28372. An AudioSource that takes the audio from another source, and re-maps its
  28373. input and output channels to a different arrangement.
  28374. You can use this to increase or decrease the number of channels that an
  28375. audio source uses, or to re-order those channels.
  28376. Call the reset() method before using it to set up a default mapping, and then
  28377. the setInputChannelMapping() and setOutputChannelMapping() methods to
  28378. create an appropriate mapping, otherwise no channels will be connected and
  28379. it'll produce silence.
  28380. @see AudioSource
  28381. */
  28382. class ChannelRemappingAudioSource : public AudioSource
  28383. {
  28384. public:
  28385. /** Creates a remapping source that will pass on audio from the given input.
  28386. @param source the input source to use. Make sure that this doesn't
  28387. get deleted before the ChannelRemappingAudioSource object
  28388. @param deleteSourceWhenDeleted if true, the input source will be deleted
  28389. when this object is deleted, if false, the caller is
  28390. responsible for its deletion
  28391. */
  28392. ChannelRemappingAudioSource (AudioSource* source,
  28393. bool deleteSourceWhenDeleted);
  28394. /** Destructor. */
  28395. ~ChannelRemappingAudioSource();
  28396. /** Specifies a number of channels that this audio source must produce from its
  28397. getNextAudioBlock() callback.
  28398. */
  28399. void setNumberOfChannelsToProduce (int requiredNumberOfChannels);
  28400. /** Clears any mapped channels.
  28401. After this, no channels are mapped, so this object will produce silence. Create
  28402. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  28403. */
  28404. void clearAllMappings();
  28405. /** Creates an input channel mapping.
  28406. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  28407. data will be sent to destChannelIndex of our input source.
  28408. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  28409. source specified when this object was created).
  28410. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  28411. during our getNextAudioBlock() callback
  28412. */
  28413. void setInputChannelMapping (int destChannelIndex,
  28414. int sourceChannelIndex);
  28415. /** Creates an output channel mapping.
  28416. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  28417. our input audio source will be copied to channel destChannelIndex of the final buffer.
  28418. @param sourceChannelIndex the index of an output channel coming from our input audio source
  28419. (i.e. the source specified when this object was created).
  28420. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  28421. during our getNextAudioBlock() callback
  28422. */
  28423. void setOutputChannelMapping (int sourceChannelIndex,
  28424. int destChannelIndex);
  28425. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  28426. our input audio source.
  28427. */
  28428. int getRemappedInputChannel (int inputChannelIndex) const;
  28429. /** Returns the output channel to which channel outputChannelIndex of our input audio
  28430. source will be sent to.
  28431. */
  28432. int getRemappedOutputChannel (int outputChannelIndex) const;
  28433. /** Returns an XML object to encapsulate the state of the mappings.
  28434. @see restoreFromXml
  28435. */
  28436. XmlElement* createXml() const;
  28437. /** Restores the mappings from an XML object created by createXML().
  28438. @see createXml
  28439. */
  28440. void restoreFromXml (const XmlElement& e);
  28441. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28442. void releaseResources();
  28443. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28444. private:
  28445. int requiredNumberOfChannels;
  28446. Array <int> remappedInputs, remappedOutputs;
  28447. AudioSource* const source;
  28448. const bool deleteSourceWhenDeleted;
  28449. AudioSampleBuffer buffer;
  28450. AudioSourceChannelInfo remappedInfo;
  28451. CriticalSection lock;
  28452. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelRemappingAudioSource);
  28453. };
  28454. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  28455. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  28456. #endif
  28457. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  28458. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  28459. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  28460. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  28461. /*** Start of inlined file: juce_IIRFilter.h ***/
  28462. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  28463. #define __JUCE_IIRFILTER_JUCEHEADER__
  28464. /**
  28465. An IIR filter that can perform low, high, or band-pass filtering on an
  28466. audio signal.
  28467. @see IIRFilterAudioSource
  28468. */
  28469. class JUCE_API IIRFilter
  28470. {
  28471. public:
  28472. /** Creates a filter.
  28473. Initially the filter is inactive, so will have no effect on samples that
  28474. you process with it. Use the appropriate method to turn it into the type
  28475. of filter needed.
  28476. */
  28477. IIRFilter();
  28478. /** Creates a copy of another filter. */
  28479. IIRFilter (const IIRFilter& other);
  28480. /** Destructor. */
  28481. ~IIRFilter();
  28482. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  28483. Note that this clears the processing state, but the type of filter and
  28484. its coefficients aren't changed. To put a filter into an inactive state, use
  28485. the makeInactive() method.
  28486. */
  28487. void reset() throw();
  28488. /** Performs the filter operation on the given set of samples.
  28489. */
  28490. void processSamples (float* samples,
  28491. int numSamples) throw();
  28492. /** Processes a single sample, without any locking or checking.
  28493. Use this if you need fast processing of a single value, but be aware that
  28494. this isn't thread-safe in the way that processSamples() is.
  28495. */
  28496. float processSingleSampleRaw (float sample) throw();
  28497. /** Sets the filter up to act as a low-pass filter.
  28498. */
  28499. void makeLowPass (double sampleRate,
  28500. double frequency) throw();
  28501. /** Sets the filter up to act as a high-pass filter.
  28502. */
  28503. void makeHighPass (double sampleRate,
  28504. double frequency) throw();
  28505. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  28506. The gain is a scale factor that the low frequencies are multiplied by, so values
  28507. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  28508. attenuate them.
  28509. */
  28510. void makeLowShelf (double sampleRate,
  28511. double cutOffFrequency,
  28512. double Q,
  28513. float gainFactor) throw();
  28514. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  28515. The gain is a scale factor that the high frequencies are multiplied by, so values
  28516. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  28517. attenuate them.
  28518. */
  28519. void makeHighShelf (double sampleRate,
  28520. double cutOffFrequency,
  28521. double Q,
  28522. float gainFactor) throw();
  28523. /** Sets the filter up to act as a band pass filter centred around a
  28524. frequency, with a variable Q and gain.
  28525. The gain is a scale factor that the centre frequencies are multiplied by, so
  28526. values greater than 1.0 will boost the centre frequencies, values less than
  28527. 1.0 will attenuate them.
  28528. */
  28529. void makeBandPass (double sampleRate,
  28530. double centreFrequency,
  28531. double Q,
  28532. float gainFactor) throw();
  28533. /** Clears the filter's coefficients so that it becomes inactive.
  28534. */
  28535. void makeInactive() throw();
  28536. /** Makes this filter duplicate the set-up of another one.
  28537. */
  28538. void copyCoefficientsFrom (const IIRFilter& other) throw();
  28539. protected:
  28540. CriticalSection processLock;
  28541. void setCoefficients (double c1, double c2, double c3,
  28542. double c4, double c5, double c6) throw();
  28543. bool active;
  28544. float coefficients[6];
  28545. float x1, x2, y1, y2;
  28546. // (use the copyCoefficientsFrom() method instead of this operator)
  28547. IIRFilter& operator= (const IIRFilter&);
  28548. JUCE_LEAK_DETECTOR (IIRFilter);
  28549. };
  28550. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  28551. /*** End of inlined file: juce_IIRFilter.h ***/
  28552. /**
  28553. An AudioSource that performs an IIR filter on another source.
  28554. */
  28555. class JUCE_API IIRFilterAudioSource : public AudioSource
  28556. {
  28557. public:
  28558. /** Creates a IIRFilterAudioSource for a given input source.
  28559. @param inputSource the input source to read from
  28560. @param deleteInputWhenDeleted if true, the input source will be deleted when
  28561. this object is deleted
  28562. */
  28563. IIRFilterAudioSource (AudioSource* inputSource,
  28564. bool deleteInputWhenDeleted);
  28565. /** Destructor. */
  28566. ~IIRFilterAudioSource();
  28567. /** Changes the filter to use the same parameters as the one being passed in.
  28568. */
  28569. void setFilterParameters (const IIRFilter& newSettings);
  28570. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28571. void releaseResources();
  28572. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28573. private:
  28574. AudioSource* const input;
  28575. const bool deleteInputWhenDeleted;
  28576. OwnedArray <IIRFilter> iirFilters;
  28577. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IIRFilterAudioSource);
  28578. };
  28579. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  28580. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  28581. #endif
  28582. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  28583. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  28584. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  28585. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  28586. /**
  28587. An AudioSource that mixes together the output of a set of other AudioSources.
  28588. Input sources can be added and removed while the mixer is running as long as their
  28589. prepareToPlay() and releaseResources() methods are called before and after adding
  28590. them to the mixer.
  28591. */
  28592. class JUCE_API MixerAudioSource : public AudioSource
  28593. {
  28594. public:
  28595. /** Creates a MixerAudioSource.
  28596. */
  28597. MixerAudioSource();
  28598. /** Destructor. */
  28599. ~MixerAudioSource();
  28600. /** Adds an input source to the mixer.
  28601. If the mixer is running you'll need to make sure that the input source
  28602. is ready to play by calling its prepareToPlay() method before adding it.
  28603. If the mixer is stopped, then its input sources will be automatically
  28604. prepared when the mixer's prepareToPlay() method is called.
  28605. @param newInput the source to add to the mixer
  28606. @param deleteWhenRemoved if true, then this source will be deleted when
  28607. the mixer is deleted or when removeAllInputs() is
  28608. called (unless the source is previously removed
  28609. with the removeInputSource method)
  28610. */
  28611. void addInputSource (AudioSource* newInput, bool deleteWhenRemoved);
  28612. /** Removes an input source.
  28613. If the mixer is running, this will remove the source but not call its
  28614. releaseResources() method, so the caller might want to do this manually.
  28615. @param input the source to remove
  28616. @param deleteSource whether to delete this source after it's been removed
  28617. */
  28618. void removeInputSource (AudioSource* input, bool deleteSource);
  28619. /** Removes all the input sources.
  28620. If the mixer is running, this will remove the sources but not call their
  28621. releaseResources() method, so the caller might want to do this manually.
  28622. Any sources which were added with the deleteWhenRemoved flag set will be
  28623. deleted by this method.
  28624. */
  28625. void removeAllInputs();
  28626. /** Implementation of the AudioSource method.
  28627. This will call prepareToPlay() on all its input sources.
  28628. */
  28629. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28630. /** Implementation of the AudioSource method.
  28631. This will call releaseResources() on all its input sources.
  28632. */
  28633. void releaseResources();
  28634. /** Implementation of the AudioSource method. */
  28635. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28636. private:
  28637. Array <AudioSource*> inputs;
  28638. BigInteger inputsToDelete;
  28639. CriticalSection lock;
  28640. AudioSampleBuffer tempBuffer;
  28641. double currentSampleRate;
  28642. int bufferSizeExpected;
  28643. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MixerAudioSource);
  28644. };
  28645. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  28646. /*** End of inlined file: juce_MixerAudioSource.h ***/
  28647. #endif
  28648. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  28649. #endif
  28650. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  28651. #endif
  28652. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  28653. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  28654. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  28655. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  28656. /**
  28657. A simple AudioSource that generates a sine wave.
  28658. */
  28659. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  28660. {
  28661. public:
  28662. /** Creates a ToneGeneratorAudioSource. */
  28663. ToneGeneratorAudioSource();
  28664. /** Destructor. */
  28665. ~ToneGeneratorAudioSource();
  28666. /** Sets the signal's amplitude. */
  28667. void setAmplitude (float newAmplitude);
  28668. /** Sets the signal's frequency. */
  28669. void setFrequency (double newFrequencyHz);
  28670. /** Implementation of the AudioSource method. */
  28671. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  28672. /** Implementation of the AudioSource method. */
  28673. void releaseResources();
  28674. /** Implementation of the AudioSource method. */
  28675. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  28676. private:
  28677. double frequency, sampleRate;
  28678. double currentPhase, phasePerSample;
  28679. float amplitude;
  28680. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToneGeneratorAudioSource);
  28681. };
  28682. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  28683. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  28684. #endif
  28685. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  28686. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  28687. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  28688. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  28689. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  28690. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  28691. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  28692. class AudioDeviceManager;
  28693. class Component;
  28694. /**
  28695. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  28696. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  28697. method. Each of the objects returned can then be used to list the available
  28698. devices of that type. E.g.
  28699. @code
  28700. OwnedArray <AudioIODeviceType> types;
  28701. myAudioDeviceManager.createAudioDeviceTypes (types);
  28702. for (int i = 0; i < types.size(); ++i)
  28703. {
  28704. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  28705. types[i]->scanForDevices(); // This must be called before getting the list of devices
  28706. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  28707. for (int j = 0; j < deviceNames.size(); ++j)
  28708. {
  28709. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  28710. ...
  28711. }
  28712. }
  28713. @endcode
  28714. For an easier way of managing audio devices and their settings, have a look at the
  28715. AudioDeviceManager class.
  28716. @see AudioIODevice, AudioDeviceManager
  28717. */
  28718. class JUCE_API AudioIODeviceType
  28719. {
  28720. public:
  28721. /** Returns the name of this type of driver that this object manages.
  28722. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  28723. */
  28724. const String& getTypeName() const throw() { return typeName; }
  28725. /** Refreshes the object's cached list of known devices.
  28726. This must be called at least once before calling getDeviceNames() or any of
  28727. the other device creation methods.
  28728. */
  28729. virtual void scanForDevices() = 0;
  28730. /** Returns the list of available devices of this type.
  28731. The scanForDevices() method must have been called to create this list.
  28732. @param wantInputNames only really used by DirectSound where devices are split up
  28733. into inputs and outputs, this indicates whether to use
  28734. the input or output name to refer to a pair of devices.
  28735. */
  28736. virtual const StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  28737. /** Returns the name of the default device.
  28738. This will be one of the names from the getDeviceNames() list.
  28739. @param forInput if true, this means that a default input device should be
  28740. returned; if false, it should return the default output
  28741. */
  28742. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  28743. /** Returns the index of a given device in the list of device names.
  28744. If asInput is true, it shows the index in the inputs list, otherwise it
  28745. looks for it in the outputs list.
  28746. */
  28747. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  28748. /** Returns true if two different devices can be used for the input and output.
  28749. */
  28750. virtual bool hasSeparateInputsAndOutputs() const = 0;
  28751. /** Creates one of the devices of this type.
  28752. The deviceName must be one of the strings returned by getDeviceNames(), and
  28753. scanForDevices() must have been called before this method is used.
  28754. */
  28755. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  28756. const String& inputDeviceName) = 0;
  28757. struct DeviceSetupDetails
  28758. {
  28759. AudioDeviceManager* manager;
  28760. int minNumInputChannels, maxNumInputChannels;
  28761. int minNumOutputChannels, maxNumOutputChannels;
  28762. bool useStereoPairs;
  28763. };
  28764. /** Destructor. */
  28765. virtual ~AudioIODeviceType();
  28766. protected:
  28767. explicit AudioIODeviceType (const String& typeName);
  28768. private:
  28769. String typeName;
  28770. JUCE_DECLARE_NON_COPYABLE (AudioIODeviceType);
  28771. };
  28772. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  28773. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  28774. /*** Start of inlined file: juce_MidiInput.h ***/
  28775. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  28776. #define __JUCE_MIDIINPUT_JUCEHEADER__
  28777. /*** Start of inlined file: juce_MidiMessage.h ***/
  28778. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  28779. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  28780. /**
  28781. Encapsulates a MIDI message.
  28782. @see MidiMessageSequence, MidiOutput, MidiInput
  28783. */
  28784. class JUCE_API MidiMessage
  28785. {
  28786. public:
  28787. /** Creates a 3-byte short midi message.
  28788. @param byte1 message byte 1
  28789. @param byte2 message byte 2
  28790. @param byte3 message byte 3
  28791. @param timeStamp the time to give the midi message - this value doesn't
  28792. use any particular units, so will be application-specific
  28793. */
  28794. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) throw();
  28795. /** Creates a 2-byte short midi message.
  28796. @param byte1 message byte 1
  28797. @param byte2 message byte 2
  28798. @param timeStamp the time to give the midi message - this value doesn't
  28799. use any particular units, so will be application-specific
  28800. */
  28801. MidiMessage (int byte1, int byte2, double timeStamp = 0) throw();
  28802. /** Creates a 1-byte short midi message.
  28803. @param byte1 message byte 1
  28804. @param timeStamp the time to give the midi message - this value doesn't
  28805. use any particular units, so will be application-specific
  28806. */
  28807. MidiMessage (int byte1, double timeStamp = 0) throw();
  28808. /** Creates a midi message from a block of data. */
  28809. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  28810. /** Reads the next midi message from some data.
  28811. This will read as many bytes from a data stream as it needs to make a
  28812. complete message, and will return the number of bytes it used. This lets
  28813. you read a sequence of midi messages from a file or stream.
  28814. @param data the data to read from
  28815. @param maxBytesToUse the maximum number of bytes it's allowed to read
  28816. @param numBytesUsed returns the number of bytes that were actually needed
  28817. @param lastStatusByte in a sequence of midi messages, the initial byte
  28818. can be dropped from a message if it's the same as the
  28819. first byte of the previous message, so this lets you
  28820. supply the byte to use if the first byte of the message
  28821. has in fact been dropped.
  28822. @param timeStamp the time to give the midi message - this value doesn't
  28823. use any particular units, so will be application-specific
  28824. */
  28825. MidiMessage (const void* data, int maxBytesToUse,
  28826. int& numBytesUsed, uint8 lastStatusByte,
  28827. double timeStamp = 0);
  28828. /** Creates an active-sense message.
  28829. Since the MidiMessage has to contain a valid message, this default constructor
  28830. just initialises it with an empty sysex message.
  28831. */
  28832. MidiMessage() throw();
  28833. /** Creates a copy of another midi message. */
  28834. MidiMessage (const MidiMessage& other);
  28835. /** Creates a copy of another midi message, with a different timestamp. */
  28836. MidiMessage (const MidiMessage& other, double newTimeStamp);
  28837. /** Destructor. */
  28838. ~MidiMessage();
  28839. /** Copies this message from another one. */
  28840. MidiMessage& operator= (const MidiMessage& other);
  28841. /** Returns a pointer to the raw midi data.
  28842. @see getRawDataSize
  28843. */
  28844. uint8* getRawData() const throw() { return data; }
  28845. /** Returns the number of bytes of data in the message.
  28846. @see getRawData
  28847. */
  28848. int getRawDataSize() const throw() { return size; }
  28849. /** Returns the timestamp associated with this message.
  28850. The exact meaning of this time and its units will vary, as messages are used in
  28851. a variety of different contexts.
  28852. If you're getting the message from a midi file, this could be a time in seconds, or
  28853. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  28854. If the message is being used in a MidiBuffer, it might indicate the number of
  28855. audio samples from the start of the buffer.
  28856. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  28857. for details of the way that it initialises this value.
  28858. @see setTimeStamp, addToTimeStamp
  28859. */
  28860. double getTimeStamp() const throw() { return timeStamp; }
  28861. /** Changes the message's associated timestamp.
  28862. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  28863. @see addToTimeStamp, getTimeStamp
  28864. */
  28865. void setTimeStamp (double newTimestamp) throw() { timeStamp = newTimestamp; }
  28866. /** Adds a value to the message's timestamp.
  28867. The units for the timestamp will be application-specific.
  28868. */
  28869. void addToTimeStamp (double delta) throw() { timeStamp += delta; }
  28870. /** Returns the midi channel associated with the message.
  28871. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  28872. if it's a sysex)
  28873. @see isForChannel, setChannel
  28874. */
  28875. int getChannel() const throw();
  28876. /** Returns true if the message applies to the given midi channel.
  28877. @param channelNumber the channel number to look for, in the range 1 to 16
  28878. @see getChannel, setChannel
  28879. */
  28880. bool isForChannel (int channelNumber) const throw();
  28881. /** Changes the message's midi channel.
  28882. This won't do anything for non-channel messages like sysexes.
  28883. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  28884. */
  28885. void setChannel (int newChannelNumber) throw();
  28886. /** Returns true if this is a system-exclusive message.
  28887. */
  28888. bool isSysEx() const throw();
  28889. /** Returns a pointer to the sysex data inside the message.
  28890. If this event isn't a sysex event, it'll return 0.
  28891. @see getSysExDataSize
  28892. */
  28893. const uint8* getSysExData() const throw();
  28894. /** Returns the size of the sysex data.
  28895. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  28896. @see getSysExData
  28897. */
  28898. int getSysExDataSize() const throw();
  28899. /** Returns true if this message is a 'key-down' event.
  28900. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  28901. velocity 0, it will still be considered to be a note-on and the
  28902. method will return true. If returnTrueForVelocity0 is false, then
  28903. if this is a note-on event with velocity 0, it'll be regarded as
  28904. a note-off, and the method will return false
  28905. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  28906. */
  28907. bool isNoteOn (bool returnTrueForVelocity0 = false) const throw();
  28908. /** Creates a key-down message (using a floating-point velocity).
  28909. @param channel the midi channel, in the range 1 to 16
  28910. @param noteNumber the key number, 0 to 127
  28911. @param velocity in the range 0 to 1.0
  28912. @see isNoteOn
  28913. */
  28914. static const MidiMessage noteOn (int channel, int noteNumber, float velocity) throw();
  28915. /** Creates a key-down message (using an integer velocity).
  28916. @param channel the midi channel, in the range 1 to 16
  28917. @param noteNumber the key number, 0 to 127
  28918. @param velocity in the range 0 to 127
  28919. @see isNoteOn
  28920. */
  28921. static const MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) throw();
  28922. /** Returns true if this message is a 'key-up' event.
  28923. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  28924. for a note-on event with a velocity of 0.
  28925. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  28926. */
  28927. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const throw();
  28928. /** Creates a key-up message.
  28929. @param channel the midi channel, in the range 1 to 16
  28930. @param noteNumber the key number, 0 to 127
  28931. @see isNoteOff
  28932. */
  28933. static const MidiMessage noteOff (int channel, int noteNumber, uint8 velocity = 0) throw();
  28934. /** Returns true if this message is a 'key-down' or 'key-up' event.
  28935. @see isNoteOn, isNoteOff
  28936. */
  28937. bool isNoteOnOrOff() const throw();
  28938. /** Returns the midi note number for note-on and note-off messages.
  28939. If the message isn't a note-on or off, the value returned will be
  28940. meaningless.
  28941. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  28942. */
  28943. int getNoteNumber() const throw();
  28944. /** Changes the midi note number of a note-on or note-off message.
  28945. If the message isn't a note on or off, this will do nothing.
  28946. */
  28947. void setNoteNumber (int newNoteNumber) throw();
  28948. /** Returns the velocity of a note-on or note-off message.
  28949. The value returned will be in the range 0 to 127.
  28950. If the message isn't a note-on or off event, it will return 0.
  28951. @see getFloatVelocity
  28952. */
  28953. uint8 getVelocity() const throw();
  28954. /** Returns the velocity of a note-on or note-off message.
  28955. The value returned will be in the range 0 to 1.0
  28956. If the message isn't a note-on or off event, it will return 0.
  28957. @see getVelocity, setVelocity
  28958. */
  28959. float getFloatVelocity() const throw();
  28960. /** Changes the velocity of a note-on or note-off message.
  28961. If the message isn't a note on or off, this will do nothing.
  28962. @param newVelocity the new velocity, in the range 0 to 1.0
  28963. @see getFloatVelocity, multiplyVelocity
  28964. */
  28965. void setVelocity (float newVelocity) throw();
  28966. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  28967. If the message isn't a note on or off, this will do nothing.
  28968. @param scaleFactor the value by which to multiply the velocity
  28969. @see setVelocity
  28970. */
  28971. void multiplyVelocity (float scaleFactor) throw();
  28972. /** Returns true if the message is a program (patch) change message.
  28973. @see getProgramChangeNumber, getGMInstrumentName
  28974. */
  28975. bool isProgramChange() const throw();
  28976. /** Returns the new program number of a program change message.
  28977. If the message isn't a program change, the value returned will be
  28978. nonsense.
  28979. @see isProgramChange, getGMInstrumentName
  28980. */
  28981. int getProgramChangeNumber() const throw();
  28982. /** Creates a program-change message.
  28983. @param channel the midi channel, in the range 1 to 16
  28984. @param programNumber the midi program number, 0 to 127
  28985. @see isProgramChange, getGMInstrumentName
  28986. */
  28987. static const MidiMessage programChange (int channel, int programNumber) throw();
  28988. /** Returns true if the message is a pitch-wheel move.
  28989. @see getPitchWheelValue, pitchWheel
  28990. */
  28991. bool isPitchWheel() const throw();
  28992. /** Returns the pitch wheel position from a pitch-wheel move message.
  28993. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  28994. If called for messages which aren't pitch wheel events, the number returned will be
  28995. nonsense.
  28996. @see isPitchWheel
  28997. */
  28998. int getPitchWheelValue() const throw();
  28999. /** Creates a pitch-wheel move message.
  29000. @param channel the midi channel, in the range 1 to 16
  29001. @param position the wheel position, in the range 0 to 16383
  29002. @see isPitchWheel
  29003. */
  29004. static const MidiMessage pitchWheel (int channel, int position) throw();
  29005. /** Returns true if the message is an aftertouch event.
  29006. For aftertouch events, use the getNoteNumber() method to find out the key
  29007. that it applies to, and getAftertouchValue() to find out the amount. Use
  29008. getChannel() to find out the channel.
  29009. @see getAftertouchValue, getNoteNumber
  29010. */
  29011. bool isAftertouch() const throw();
  29012. /** Returns the amount of aftertouch from an aftertouch messages.
  29013. The value returned is in the range 0 to 127, and will be nonsense for messages
  29014. other than aftertouch messages.
  29015. @see isAftertouch
  29016. */
  29017. int getAfterTouchValue() const throw();
  29018. /** Creates an aftertouch message.
  29019. @param channel the midi channel, in the range 1 to 16
  29020. @param noteNumber the key number, 0 to 127
  29021. @param aftertouchAmount the amount of aftertouch, 0 to 127
  29022. @see isAftertouch
  29023. */
  29024. static const MidiMessage aftertouchChange (int channel,
  29025. int noteNumber,
  29026. int aftertouchAmount) throw();
  29027. /** Returns true if the message is a channel-pressure change event.
  29028. This is like aftertouch, but common to the whole channel rather than a specific
  29029. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  29030. to find out the channel.
  29031. @see channelPressureChange
  29032. */
  29033. bool isChannelPressure() const throw();
  29034. /** Returns the pressure from a channel pressure change message.
  29035. @returns the pressure, in the range 0 to 127
  29036. @see isChannelPressure, channelPressureChange
  29037. */
  29038. int getChannelPressureValue() const throw();
  29039. /** Creates a channel-pressure change event.
  29040. @param channel the midi channel: 1 to 16
  29041. @param pressure the pressure, 0 to 127
  29042. @see isChannelPressure
  29043. */
  29044. static const MidiMessage channelPressureChange (int channel, int pressure) throw();
  29045. /** Returns true if this is a midi controller message.
  29046. @see getControllerNumber, getControllerValue, controllerEvent
  29047. */
  29048. bool isController() const throw();
  29049. /** Returns the controller number of a controller message.
  29050. The name of the controller can be looked up using the getControllerName() method.
  29051. Note that the value returned is invalid for messages that aren't controller changes.
  29052. @see isController, getControllerName, getControllerValue
  29053. */
  29054. int getControllerNumber() const throw();
  29055. /** Returns the controller value from a controller message.
  29056. A value 0 to 127 is returned to indicate the new controller position.
  29057. Note that the value returned is invalid for messages that aren't controller changes.
  29058. @see isController, getControllerNumber
  29059. */
  29060. int getControllerValue() const throw();
  29061. /** Creates a controller message.
  29062. @param channel the midi channel, in the range 1 to 16
  29063. @param controllerType the type of controller
  29064. @param value the controller value
  29065. @see isController
  29066. */
  29067. static const MidiMessage controllerEvent (int channel,
  29068. int controllerType,
  29069. int value) throw();
  29070. /** Checks whether this message is an all-notes-off message.
  29071. @see allNotesOff
  29072. */
  29073. bool isAllNotesOff() const throw();
  29074. /** Checks whether this message is an all-sound-off message.
  29075. @see allSoundOff
  29076. */
  29077. bool isAllSoundOff() const throw();
  29078. /** Creates an all-notes-off message.
  29079. @param channel the midi channel, in the range 1 to 16
  29080. @see isAllNotesOff
  29081. */
  29082. static const MidiMessage allNotesOff (int channel) throw();
  29083. /** Creates an all-sound-off message.
  29084. @param channel the midi channel, in the range 1 to 16
  29085. @see isAllSoundOff
  29086. */
  29087. static const MidiMessage allSoundOff (int channel) throw();
  29088. /** Creates an all-controllers-off message.
  29089. @param channel the midi channel, in the range 1 to 16
  29090. */
  29091. static const MidiMessage allControllersOff (int channel) throw();
  29092. /** Returns true if this event is a meta-event.
  29093. Meta-events are things like tempo changes, track names, etc.
  29094. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  29095. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  29096. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  29097. */
  29098. bool isMetaEvent() const throw();
  29099. /** Returns a meta-event's type number.
  29100. If the message isn't a meta-event, this will return -1.
  29101. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  29102. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  29103. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  29104. */
  29105. int getMetaEventType() const throw();
  29106. /** Returns a pointer to the data in a meta-event.
  29107. @see isMetaEvent, getMetaEventLength
  29108. */
  29109. const uint8* getMetaEventData() const throw();
  29110. /** Returns the length of the data for a meta-event.
  29111. @see isMetaEvent, getMetaEventData
  29112. */
  29113. int getMetaEventLength() const throw();
  29114. /** Returns true if this is a 'track' meta-event. */
  29115. bool isTrackMetaEvent() const throw();
  29116. /** Returns true if this is an 'end-of-track' meta-event. */
  29117. bool isEndOfTrackMetaEvent() const throw();
  29118. /** Creates an end-of-track meta-event.
  29119. @see isEndOfTrackMetaEvent
  29120. */
  29121. static const MidiMessage endOfTrack() throw();
  29122. /** Returns true if this is an 'track name' meta-event.
  29123. You can use the getTextFromTextMetaEvent() method to get the track's name.
  29124. */
  29125. bool isTrackNameEvent() const throw();
  29126. /** Returns true if this is a 'text' meta-event.
  29127. @see getTextFromTextMetaEvent
  29128. */
  29129. bool isTextMetaEvent() const throw();
  29130. /** Returns the text from a text meta-event.
  29131. @see isTextMetaEvent
  29132. */
  29133. const String getTextFromTextMetaEvent() const;
  29134. /** Returns true if this is a 'tempo' meta-event.
  29135. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  29136. */
  29137. bool isTempoMetaEvent() const throw();
  29138. /** Returns the tick length from a tempo meta-event.
  29139. @param timeFormat the 16-bit time format value from the midi file's header.
  29140. @returns the tick length (in seconds).
  29141. @see isTempoMetaEvent
  29142. */
  29143. double getTempoMetaEventTickLength (short timeFormat) const throw();
  29144. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  29145. @see isTempoMetaEvent, getTempoMetaEventTickLength
  29146. */
  29147. double getTempoSecondsPerQuarterNote() const throw();
  29148. /** Creates a tempo meta-event.
  29149. @see isTempoMetaEvent
  29150. */
  29151. static const MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) throw();
  29152. /** Returns true if this is a 'time-signature' meta-event.
  29153. @see getTimeSignatureInfo
  29154. */
  29155. bool isTimeSignatureMetaEvent() const throw();
  29156. /** Returns the time-signature values from a time-signature meta-event.
  29157. @see isTimeSignatureMetaEvent
  29158. */
  29159. void getTimeSignatureInfo (int& numerator, int& denominator) const throw();
  29160. /** Creates a time-signature meta-event.
  29161. @see isTimeSignatureMetaEvent
  29162. */
  29163. static const MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  29164. /** Returns true if this is a 'key-signature' meta-event.
  29165. @see getKeySignatureNumberOfSharpsOrFlats
  29166. */
  29167. bool isKeySignatureMetaEvent() const throw();
  29168. /** Returns the key from a key-signature meta-event.
  29169. @see isKeySignatureMetaEvent
  29170. */
  29171. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  29172. /** Returns true if this is a 'channel' meta-event.
  29173. A channel meta-event specifies the midi channel that should be used
  29174. for subsequent meta-events.
  29175. @see getMidiChannelMetaEventChannel
  29176. */
  29177. bool isMidiChannelMetaEvent() const throw();
  29178. /** Returns the channel number from a channel meta-event.
  29179. @returns the channel, in the range 1 to 16.
  29180. @see isMidiChannelMetaEvent
  29181. */
  29182. int getMidiChannelMetaEventChannel() const throw();
  29183. /** Creates a midi channel meta-event.
  29184. @param channel the midi channel, in the range 1 to 16
  29185. @see isMidiChannelMetaEvent
  29186. */
  29187. static const MidiMessage midiChannelMetaEvent (int channel) throw();
  29188. /** Returns true if this is an active-sense message. */
  29189. bool isActiveSense() const throw();
  29190. /** Returns true if this is a midi start event.
  29191. @see midiStart
  29192. */
  29193. bool isMidiStart() const throw();
  29194. /** Creates a midi start event. */
  29195. static const MidiMessage midiStart() throw();
  29196. /** Returns true if this is a midi continue event.
  29197. @see midiContinue
  29198. */
  29199. bool isMidiContinue() const throw();
  29200. /** Creates a midi continue event. */
  29201. static const MidiMessage midiContinue() throw();
  29202. /** Returns true if this is a midi stop event.
  29203. @see midiStop
  29204. */
  29205. bool isMidiStop() const throw();
  29206. /** Creates a midi stop event. */
  29207. static const MidiMessage midiStop() throw();
  29208. /** Returns true if this is a midi clock event.
  29209. @see midiClock, songPositionPointer
  29210. */
  29211. bool isMidiClock() const throw();
  29212. /** Creates a midi clock event. */
  29213. static const MidiMessage midiClock() throw();
  29214. /** Returns true if this is a song-position-pointer message.
  29215. @see getSongPositionPointerMidiBeat, songPositionPointer
  29216. */
  29217. bool isSongPositionPointer() const throw();
  29218. /** Returns the midi beat-number of a song-position-pointer message.
  29219. @see isSongPositionPointer, songPositionPointer
  29220. */
  29221. int getSongPositionPointerMidiBeat() const throw();
  29222. /** Creates a song-position-pointer message.
  29223. The position is a number of midi beats from the start of the song, where 1 midi
  29224. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  29225. are 4 midi beats in a quarter-note.
  29226. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  29227. */
  29228. static const MidiMessage songPositionPointer (int positionInMidiBeats) throw();
  29229. /** Returns true if this is a quarter-frame midi timecode message.
  29230. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  29231. */
  29232. bool isQuarterFrame() const throw();
  29233. /** Returns the sequence number of a quarter-frame midi timecode message.
  29234. This will be a value between 0 and 7.
  29235. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  29236. */
  29237. int getQuarterFrameSequenceNumber() const throw();
  29238. /** Returns the value from a quarter-frame message.
  29239. This will be the lower nybble of the message's data-byte, a value
  29240. between 0 and 15
  29241. */
  29242. int getQuarterFrameValue() const throw();
  29243. /** Creates a quarter-frame MTC message.
  29244. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  29245. @param value a value 0 to 15 for the lower nybble of the message's data byte
  29246. */
  29247. static const MidiMessage quarterFrame (int sequenceNumber, int value) throw();
  29248. /** SMPTE timecode types.
  29249. Used by the getFullFrameParameters() and fullFrame() methods.
  29250. */
  29251. enum SmpteTimecodeType
  29252. {
  29253. fps24 = 0,
  29254. fps25 = 1,
  29255. fps30drop = 2,
  29256. fps30 = 3
  29257. };
  29258. /** Returns true if this is a full-frame midi timecode message.
  29259. */
  29260. bool isFullFrame() const throw();
  29261. /** Extracts the timecode information from a full-frame midi timecode message.
  29262. You should only call this on messages where you've used isFullFrame() to
  29263. check that they're the right kind.
  29264. */
  29265. void getFullFrameParameters (int& hours,
  29266. int& minutes,
  29267. int& seconds,
  29268. int& frames,
  29269. SmpteTimecodeType& timecodeType) const throw();
  29270. /** Creates a full-frame MTC message.
  29271. */
  29272. static const MidiMessage fullFrame (int hours,
  29273. int minutes,
  29274. int seconds,
  29275. int frames,
  29276. SmpteTimecodeType timecodeType);
  29277. /** Types of MMC command.
  29278. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  29279. */
  29280. enum MidiMachineControlCommand
  29281. {
  29282. mmc_stop = 1,
  29283. mmc_play = 2,
  29284. mmc_deferredplay = 3,
  29285. mmc_fastforward = 4,
  29286. mmc_rewind = 5,
  29287. mmc_recordStart = 6,
  29288. mmc_recordStop = 7,
  29289. mmc_pause = 9
  29290. };
  29291. /** Checks whether this is an MMC message.
  29292. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  29293. */
  29294. bool isMidiMachineControlMessage() const throw();
  29295. /** For an MMC message, this returns its type.
  29296. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  29297. calling this method.
  29298. */
  29299. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  29300. /** Creates an MMC message.
  29301. */
  29302. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  29303. /** Checks whether this is an MMC "goto" message.
  29304. If it is, the parameters passed-in are set to the time that the message contains.
  29305. @see midiMachineControlGoto
  29306. */
  29307. bool isMidiMachineControlGoto (int& hours,
  29308. int& minutes,
  29309. int& seconds,
  29310. int& frames) const throw();
  29311. /** Creates an MMC "goto" message.
  29312. This messages tells the device to go to a specific frame.
  29313. @see isMidiMachineControlGoto
  29314. */
  29315. static const MidiMessage midiMachineControlGoto (int hours,
  29316. int minutes,
  29317. int seconds,
  29318. int frames);
  29319. /** Creates a master-volume change message.
  29320. @param volume the volume, 0 to 1.0
  29321. */
  29322. static const MidiMessage masterVolume (float volume);
  29323. /** Creates a system-exclusive message.
  29324. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  29325. */
  29326. static const MidiMessage createSysExMessage (const uint8* sysexData,
  29327. int dataSize);
  29328. /** Reads a midi variable-length integer.
  29329. @param data the data to read the number from
  29330. @param numBytesUsed on return, this will be set to the number of bytes that were read
  29331. */
  29332. static int readVariableLengthVal (const uint8* data,
  29333. int& numBytesUsed) throw();
  29334. /** Based on the first byte of a short midi message, this uses a lookup table
  29335. to return the message length (either 1, 2, or 3 bytes).
  29336. The value passed in must be 0x80 or higher.
  29337. */
  29338. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  29339. /** Returns the name of a midi note number.
  29340. E.g "C", "D#", etc.
  29341. @param noteNumber the midi note number, 0 to 127
  29342. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  29343. they'll be flattened, e.g. "Db"
  29344. @param includeOctaveNumber if true, the octave number will be appended to the string,
  29345. e.g. "C#4"
  29346. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  29347. number that will be used for middle C's octave
  29348. @see getMidiNoteInHertz
  29349. */
  29350. static const String getMidiNoteName (int noteNumber,
  29351. bool useSharps,
  29352. bool includeOctaveNumber,
  29353. int octaveNumForMiddleC);
  29354. /** Returns the frequency of a midi note number.
  29355. The frequencyOfA parameter is an optional frequency for 'A', normally 440-444Hz for concert pitch.
  29356. @see getMidiNoteName
  29357. */
  29358. static const double getMidiNoteInHertz (int noteNumber, const double frequencyOfA = 440.0) throw();
  29359. /** Returns the standard name of a GM instrument.
  29360. @param midiInstrumentNumber the program number 0 to 127
  29361. @see getProgramChangeNumber
  29362. */
  29363. static const String getGMInstrumentName (int midiInstrumentNumber);
  29364. /** Returns the name of a bank of GM instruments.
  29365. @param midiBankNumber the bank, 0 to 15
  29366. */
  29367. static const String getGMInstrumentBankName (int midiBankNumber);
  29368. /** Returns the standard name of a channel 10 percussion sound.
  29369. @param midiNoteNumber the key number, 35 to 81
  29370. */
  29371. static const String getRhythmInstrumentName (int midiNoteNumber);
  29372. /** Returns the name of a controller type number.
  29373. @see getControllerNumber
  29374. */
  29375. static const String getControllerName (int controllerNumber);
  29376. private:
  29377. double timeStamp;
  29378. uint8* data;
  29379. int size;
  29380. #ifndef DOXYGEN
  29381. union
  29382. {
  29383. uint8 asBytes[4];
  29384. uint32 asInt32;
  29385. } preallocatedData;
  29386. #endif
  29387. };
  29388. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  29389. /*** End of inlined file: juce_MidiMessage.h ***/
  29390. class MidiInput;
  29391. /**
  29392. Receives midi messages from a midi input device.
  29393. This class is overridden to handle incoming midi messages. See the MidiInput
  29394. class for more details.
  29395. @see MidiInput
  29396. */
  29397. class JUCE_API MidiInputCallback
  29398. {
  29399. public:
  29400. /** Destructor. */
  29401. virtual ~MidiInputCallback() {}
  29402. /** Receives an incoming message.
  29403. A MidiInput object will call this method when a midi event arrives. It'll be
  29404. called on a high-priority system thread, so avoid doing anything time-consuming
  29405. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  29406. for queueing incoming messages for use later.
  29407. @param source the MidiInput object that generated the message
  29408. @param message the incoming message. The message's timestamp is set to a value
  29409. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  29410. time when the message arrived.
  29411. */
  29412. virtual void handleIncomingMidiMessage (MidiInput* source,
  29413. const MidiMessage& message) = 0;
  29414. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  29415. If a long sysex message is broken up into multiple packets, this callback is made
  29416. for each packet that arrives until the message is finished, at which point
  29417. the normal handleIncomingMidiMessage() callback will be made with the entire
  29418. message.
  29419. The message passed in will contain the start of a sysex, but won't be finished
  29420. with the terminating 0xf7 byte.
  29421. */
  29422. virtual void handlePartialSysexMessage (MidiInput* source,
  29423. const uint8* messageData,
  29424. const int numBytesSoFar,
  29425. const double timestamp)
  29426. {
  29427. // (this bit is just to avoid compiler warnings about unused variables)
  29428. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  29429. }
  29430. };
  29431. /**
  29432. Represents a midi input device.
  29433. To create one of these, use the static getDevices() method to find out what inputs are
  29434. available, and then use the openDevice() method to try to open one.
  29435. @see MidiOutput
  29436. */
  29437. class JUCE_API MidiInput
  29438. {
  29439. public:
  29440. /** Returns a list of the available midi input devices.
  29441. You can open one of the devices by passing its index into the
  29442. openDevice() method.
  29443. @see getDefaultDeviceIndex, openDevice
  29444. */
  29445. static const StringArray getDevices();
  29446. /** Returns the index of the default midi input device to use.
  29447. This refers to the index in the list returned by getDevices().
  29448. */
  29449. static int getDefaultDeviceIndex();
  29450. /** Tries to open one of the midi input devices.
  29451. This will return a MidiInput object if it manages to open it. You can then
  29452. call start() and stop() on this device, and delete it when no longer needed.
  29453. If the device can't be opened, this will return a null pointer.
  29454. @param deviceIndex the index of a device from the list returned by getDevices()
  29455. @param callback the object that will receive the midi messages from this device.
  29456. @see MidiInputCallback, getDevices
  29457. */
  29458. static MidiInput* openDevice (int deviceIndex,
  29459. MidiInputCallback* callback);
  29460. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  29461. /** This will try to create a new midi input device (Not available on Windows).
  29462. This will attempt to create a new midi input device with the specified name,
  29463. for other apps to connect to.
  29464. Returns 0 if a device can't be created.
  29465. @param deviceName the name to use for the new device
  29466. @param callback the object that will receive the midi messages from this device.
  29467. */
  29468. static MidiInput* createNewDevice (const String& deviceName,
  29469. MidiInputCallback* callback);
  29470. #endif
  29471. /** Destructor. */
  29472. virtual ~MidiInput();
  29473. /** Returns the name of this device.
  29474. */
  29475. virtual const String getName() const throw() { return name; }
  29476. /** Allows you to set a custom name for the device, in case you don't like the name
  29477. it was given when created.
  29478. */
  29479. virtual void setName (const String& newName) throw() { name = newName; }
  29480. /** Starts the device running.
  29481. After calling this, the device will start sending midi messages to the
  29482. MidiInputCallback object that was specified when the openDevice() method
  29483. was called.
  29484. @see stop
  29485. */
  29486. virtual void start();
  29487. /** Stops the device running.
  29488. @see start
  29489. */
  29490. virtual void stop();
  29491. protected:
  29492. String name;
  29493. void* internal;
  29494. explicit MidiInput (const String& name);
  29495. private:
  29496. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInput);
  29497. };
  29498. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  29499. /*** End of inlined file: juce_MidiInput.h ***/
  29500. /*** Start of inlined file: juce_MidiOutput.h ***/
  29501. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  29502. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  29503. /*** Start of inlined file: juce_MidiBuffer.h ***/
  29504. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  29505. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  29506. /**
  29507. Holds a sequence of time-stamped midi events.
  29508. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  29509. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  29510. @see MidiMessage
  29511. */
  29512. class JUCE_API MidiBuffer
  29513. {
  29514. public:
  29515. /** Creates an empty MidiBuffer. */
  29516. MidiBuffer() throw();
  29517. /** Creates a MidiBuffer containing a single midi message. */
  29518. explicit MidiBuffer (const MidiMessage& message) throw();
  29519. /** Creates a copy of another MidiBuffer. */
  29520. MidiBuffer (const MidiBuffer& other) throw();
  29521. /** Makes a copy of another MidiBuffer. */
  29522. MidiBuffer& operator= (const MidiBuffer& other) throw();
  29523. /** Destructor */
  29524. ~MidiBuffer();
  29525. /** Removes all events from the buffer. */
  29526. void clear() throw();
  29527. /** Removes all events between two times from the buffer.
  29528. All events for which (start <= event position < start + numSamples) will
  29529. be removed.
  29530. */
  29531. void clear (int start, int numSamples);
  29532. /** Returns true if the buffer is empty.
  29533. To actually retrieve the events, use a MidiBuffer::Iterator object
  29534. */
  29535. bool isEmpty() const throw();
  29536. /** Counts the number of events in the buffer.
  29537. This is actually quite a slow operation, as it has to iterate through all
  29538. the events, so you might prefer to call isEmpty() if that's all you need
  29539. to know.
  29540. */
  29541. int getNumEvents() const throw();
  29542. /** Adds an event to the buffer.
  29543. The sample number will be used to determine the position of the event in
  29544. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  29545. ignored.
  29546. If an event is added whose sample position is the same as one or more events
  29547. already in the buffer, the new event will be placed after the existing ones.
  29548. To retrieve events, use a MidiBuffer::Iterator object
  29549. */
  29550. void addEvent (const MidiMessage& midiMessage, int sampleNumber);
  29551. /** Adds an event to the buffer from raw midi data.
  29552. The sample number will be used to determine the position of the event in
  29553. the buffer, which is always kept sorted.
  29554. If an event is added whose sample position is the same as one or more events
  29555. already in the buffer, the new event will be placed after the existing ones.
  29556. The event data will be inspected to calculate the number of bytes in length that
  29557. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  29558. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  29559. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  29560. add an event at all.
  29561. To retrieve events, use a MidiBuffer::Iterator object
  29562. */
  29563. void addEvent (const void* rawMidiData,
  29564. int maxBytesOfMidiData,
  29565. int sampleNumber);
  29566. /** Adds some events from another buffer to this one.
  29567. @param otherBuffer the buffer containing the events you want to add
  29568. @param startSample the lowest sample number in the source buffer for which
  29569. events should be added. Any source events whose timestamp is
  29570. less than this will be ignored
  29571. @param numSamples the valid range of samples from the source buffer for which
  29572. events should be added - i.e. events in the source buffer whose
  29573. timestamp is greater than or equal to (startSample + numSamples)
  29574. will be ignored. If this value is less than 0, all events after
  29575. startSample will be taken.
  29576. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  29577. that are added to this buffer
  29578. */
  29579. void addEvents (const MidiBuffer& otherBuffer,
  29580. int startSample,
  29581. int numSamples,
  29582. int sampleDeltaToAdd);
  29583. /** Returns the sample number of the first event in the buffer.
  29584. If the buffer's empty, this will just return 0.
  29585. */
  29586. int getFirstEventTime() const throw();
  29587. /** Returns the sample number of the last event in the buffer.
  29588. If the buffer's empty, this will just return 0.
  29589. */
  29590. int getLastEventTime() const throw();
  29591. /** Exchanges the contents of this buffer with another one.
  29592. This is a quick operation, because no memory allocating or copying is done, it
  29593. just swaps the internal state of the two buffers.
  29594. */
  29595. void swapWith (MidiBuffer& other) throw();
  29596. /** Preallocates some memory for the buffer to use.
  29597. This helps to avoid needing to reallocate space when the buffer has messages
  29598. added to it.
  29599. */
  29600. void ensureSize (size_t minimumNumBytes);
  29601. /**
  29602. Used to iterate through the events in a MidiBuffer.
  29603. Note that altering the buffer while an iterator is using it isn't a
  29604. safe operation.
  29605. @see MidiBuffer
  29606. */
  29607. class Iterator
  29608. {
  29609. public:
  29610. /** Creates an Iterator for this MidiBuffer. */
  29611. Iterator (const MidiBuffer& buffer) throw();
  29612. /** Destructor. */
  29613. ~Iterator() throw();
  29614. /** Repositions the iterator so that the next event retrieved will be the first
  29615. one whose sample position is at greater than or equal to the given position.
  29616. */
  29617. void setNextSamplePosition (int samplePosition) throw();
  29618. /** Retrieves a copy of the next event from the buffer.
  29619. @param result on return, this will be the message (the MidiMessage's timestamp
  29620. is not set)
  29621. @param samplePosition on return, this will be the position of the event
  29622. @returns true if an event was found, or false if the iterator has reached
  29623. the end of the buffer
  29624. */
  29625. bool getNextEvent (MidiMessage& result,
  29626. int& samplePosition) throw();
  29627. /** Retrieves the next event from the buffer.
  29628. @param midiData on return, this pointer will be set to a block of data containing
  29629. the midi message. Note that to make it fast, this is a pointer
  29630. directly into the MidiBuffer's internal data, so is only valid
  29631. temporarily until the MidiBuffer is altered.
  29632. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  29633. midi message
  29634. @param samplePosition on return, this will be the position of the event
  29635. @returns true if an event was found, or false if the iterator has reached
  29636. the end of the buffer
  29637. */
  29638. bool getNextEvent (const uint8* &midiData,
  29639. int& numBytesOfMidiData,
  29640. int& samplePosition) throw();
  29641. private:
  29642. const MidiBuffer& buffer;
  29643. const uint8* data;
  29644. JUCE_DECLARE_NON_COPYABLE (Iterator);
  29645. };
  29646. private:
  29647. friend class MidiBuffer::Iterator;
  29648. MemoryBlock data;
  29649. int bytesUsed;
  29650. uint8* getData() const throw();
  29651. uint8* findEventAfter (uint8* d, int samplePosition) const throw();
  29652. static int getEventTime (const void* d) throw();
  29653. static uint16 getEventDataSize (const void* d) throw();
  29654. static uint16 getEventTotalSize (const void* d) throw();
  29655. JUCE_LEAK_DETECTOR (MidiBuffer);
  29656. };
  29657. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  29658. /*** End of inlined file: juce_MidiBuffer.h ***/
  29659. /**
  29660. Represents a midi output device.
  29661. To create one of these, use the static getDevices() method to find out what
  29662. outputs are available, then use the openDevice() method to try to open one.
  29663. @see MidiInput
  29664. */
  29665. class JUCE_API MidiOutput : private Thread
  29666. {
  29667. public:
  29668. /** Returns a list of the available midi output devices.
  29669. You can open one of the devices by passing its index into the
  29670. openDevice() method.
  29671. @see getDefaultDeviceIndex, openDevice
  29672. */
  29673. static const StringArray getDevices();
  29674. /** Returns the index of the default midi output device to use.
  29675. This refers to the index in the list returned by getDevices().
  29676. */
  29677. static int getDefaultDeviceIndex();
  29678. /** Tries to open one of the midi output devices.
  29679. This will return a MidiOutput object if it manages to open it. You can then
  29680. send messages to this device, and delete it when no longer needed.
  29681. If the device can't be opened, this will return a null pointer.
  29682. @param deviceIndex the index of a device from the list returned by getDevices()
  29683. @see getDevices
  29684. */
  29685. static MidiOutput* openDevice (int deviceIndex);
  29686. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  29687. /** This will try to create a new midi output device (Not available on Windows).
  29688. This will attempt to create a new midi output device that other apps can connect
  29689. to and use as their midi input.
  29690. Returns 0 if a device can't be created.
  29691. @param deviceName the name to use for the new device
  29692. */
  29693. static MidiOutput* createNewDevice (const String& deviceName);
  29694. #endif
  29695. /** Destructor. */
  29696. virtual ~MidiOutput();
  29697. /** Makes this device output a midi message.
  29698. @see MidiMessage
  29699. */
  29700. virtual void sendMessageNow (const MidiMessage& message);
  29701. /** Sends a midi reset to the device. */
  29702. virtual void reset();
  29703. /** Returns the current volume setting for this device. */
  29704. virtual bool getVolume (float& leftVol,
  29705. float& rightVol);
  29706. /** Changes the overall volume for this device. */
  29707. virtual void setVolume (float leftVol,
  29708. float rightVol);
  29709. /** This lets you supply a block of messages that will be sent out at some point
  29710. in the future.
  29711. The MidiOutput class has an internal thread that can send out timestamped
  29712. messages - this appends a set of messages to its internal buffer, ready for
  29713. sending.
  29714. This will only work if you've already started the thread with startBackgroundThread().
  29715. A time is supplied, at which the block of messages should be sent. This time uses
  29716. the same time base as Time::getMillisecondCounter(), and must be in the future.
  29717. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  29718. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  29719. samplesPerSecondForBuffer value is needed to convert this sample position to a
  29720. real time.
  29721. */
  29722. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  29723. double millisecondCounterToStartAt,
  29724. double samplesPerSecondForBuffer);
  29725. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  29726. */
  29727. virtual void clearAllPendingMessages();
  29728. /** Starts up a background thread so that the device can send blocks of data.
  29729. Call this to get the device ready, before using sendBlockOfMessages().
  29730. */
  29731. virtual void startBackgroundThread();
  29732. /** Stops the background thread, and clears any pending midi events.
  29733. @see startBackgroundThread
  29734. */
  29735. virtual void stopBackgroundThread();
  29736. protected:
  29737. void* internal;
  29738. struct PendingMessage
  29739. {
  29740. PendingMessage (const uint8* data, int len, double sampleNumber);
  29741. MidiMessage message;
  29742. PendingMessage* next;
  29743. };
  29744. CriticalSection lock;
  29745. PendingMessage* firstMessage;
  29746. MidiOutput();
  29747. void run();
  29748. private:
  29749. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutput);
  29750. };
  29751. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  29752. /*** End of inlined file: juce_MidiOutput.h ***/
  29753. /*** Start of inlined file: juce_ComboBox.h ***/
  29754. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  29755. #define __JUCE_COMBOBOX_JUCEHEADER__
  29756. /*** Start of inlined file: juce_Label.h ***/
  29757. #ifndef __JUCE_LABEL_JUCEHEADER__
  29758. #define __JUCE_LABEL_JUCEHEADER__
  29759. /*** Start of inlined file: juce_TextEditor.h ***/
  29760. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  29761. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  29762. /*** Start of inlined file: juce_Viewport.h ***/
  29763. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  29764. #define __JUCE_VIEWPORT_JUCEHEADER__
  29765. /*** Start of inlined file: juce_ScrollBar.h ***/
  29766. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  29767. #define __JUCE_SCROLLBAR_JUCEHEADER__
  29768. /*** Start of inlined file: juce_Button.h ***/
  29769. #ifndef __JUCE_BUTTON_JUCEHEADER__
  29770. #define __JUCE_BUTTON_JUCEHEADER__
  29771. /*** Start of inlined file: juce_TooltipWindow.h ***/
  29772. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  29773. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  29774. /*** Start of inlined file: juce_TooltipClient.h ***/
  29775. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  29776. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  29777. /**
  29778. Components that want to use pop-up tooltips should implement this interface.
  29779. A TooltipWindow will wait for the mouse to hover over a component that
  29780. implements the TooltipClient interface, and when it finds one, it will display
  29781. the tooltip returned by its getTooltip() method.
  29782. @see TooltipWindow, SettableTooltipClient
  29783. */
  29784. class JUCE_API TooltipClient
  29785. {
  29786. public:
  29787. /** Destructor. */
  29788. virtual ~TooltipClient() {}
  29789. /** Returns the string that this object wants to show as its tooltip. */
  29790. virtual const String getTooltip() = 0;
  29791. };
  29792. /**
  29793. An implementation of TooltipClient that stores the tooltip string and a method
  29794. for changing it.
  29795. This makes it easy to add a tooltip to a custom component, by simply adding this
  29796. as a base class and calling setTooltip().
  29797. Many of the Juce widgets already use this as a base class to implement their
  29798. tooltips.
  29799. @see TooltipClient, TooltipWindow
  29800. */
  29801. class JUCE_API SettableTooltipClient : public TooltipClient
  29802. {
  29803. public:
  29804. /** Destructor. */
  29805. virtual ~SettableTooltipClient() {}
  29806. /** Assigns a new tooltip to this object. */
  29807. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  29808. /** Returns the tooltip assigned to this object. */
  29809. virtual const String getTooltip() { return tooltipString; }
  29810. protected:
  29811. SettableTooltipClient() {}
  29812. private:
  29813. String tooltipString;
  29814. };
  29815. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  29816. /*** End of inlined file: juce_TooltipClient.h ***/
  29817. /**
  29818. A window that displays a pop-up tooltip when the mouse hovers over another component.
  29819. To enable tooltips in your app, just create a single instance of a TooltipWindow
  29820. object.
  29821. The TooltipWindow object will then stay invisible, waiting until the mouse
  29822. hovers for the specified length of time - it will then see if it's currently
  29823. over a component which implements the TooltipClient interface, and if so,
  29824. it will make itself visible to show the tooltip in the appropriate place.
  29825. @see TooltipClient, SettableTooltipClient
  29826. */
  29827. class JUCE_API TooltipWindow : public Component,
  29828. private Timer
  29829. {
  29830. public:
  29831. /** Creates a tooltip window.
  29832. Make sure your app only creates one instance of this class, otherwise you'll
  29833. get multiple overlaid tooltips appearing. The window will initially be invisible
  29834. and will make itself visible when it needs to display a tip.
  29835. To change the style of tooltips, see the LookAndFeel class for its tooltip
  29836. methods.
  29837. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  29838. otherwise the tooltip will be added to the given parent
  29839. component.
  29840. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  29841. before a tooltip will be shown
  29842. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  29843. */
  29844. explicit TooltipWindow (Component* parentComponent = 0,
  29845. int millisecondsBeforeTipAppears = 700);
  29846. /** Destructor. */
  29847. ~TooltipWindow();
  29848. /** Changes the time before the tip appears.
  29849. This lets you change the value that was set in the constructor.
  29850. */
  29851. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) throw();
  29852. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  29853. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  29854. methods.
  29855. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  29856. */
  29857. enum ColourIds
  29858. {
  29859. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  29860. textColourId = 0x1001c00, /**< The colour to use for the text. */
  29861. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  29862. };
  29863. private:
  29864. int millisecondsBeforeTipAppears;
  29865. Point<int> lastMousePos;
  29866. int mouseClicks;
  29867. unsigned int lastCompChangeTime, lastHideTime;
  29868. Component* lastComponentUnderMouse;
  29869. bool changedCompsSinceShown;
  29870. String tipShowing, lastTipUnderMouse;
  29871. void paint (Graphics& g);
  29872. void mouseEnter (const MouseEvent& e);
  29873. void timerCallback();
  29874. static const String getTipFor (Component* c);
  29875. void showFor (const String& tip);
  29876. void hide();
  29877. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TooltipWindow);
  29878. };
  29879. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  29880. /*** End of inlined file: juce_TooltipWindow.h ***/
  29881. #if JUCE_VC6
  29882. #define Listener ButtonListener
  29883. #endif
  29884. /**
  29885. A base class for buttons.
  29886. This contains all the logic for button behaviours such as enabling/disabling,
  29887. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  29888. and radio groups, etc.
  29889. @see TextButton, DrawableButton, ToggleButton
  29890. */
  29891. class JUCE_API Button : public Component,
  29892. public SettableTooltipClient,
  29893. public ApplicationCommandManagerListener,
  29894. public ValueListener,
  29895. private KeyListener
  29896. {
  29897. protected:
  29898. /** Creates a button.
  29899. @param buttonName the text to put in the button (the component's name is also
  29900. initially set to this string, but these can be changed later
  29901. using the setName() and setButtonText() methods)
  29902. */
  29903. explicit Button (const String& buttonName);
  29904. public:
  29905. /** Destructor. */
  29906. virtual ~Button();
  29907. /** Changes the button's text.
  29908. @see getButtonText
  29909. */
  29910. void setButtonText (const String& newText);
  29911. /** Returns the text displayed in the button.
  29912. @see setButtonText
  29913. */
  29914. const String getButtonText() const { return text; }
  29915. /** Returns true if the button is currently being held down by the mouse.
  29916. @see isOver
  29917. */
  29918. bool isDown() const throw();
  29919. /** Returns true if the mouse is currently over the button.
  29920. This will be also be true if the mouse is being held down.
  29921. @see isDown
  29922. */
  29923. bool isOver() const throw();
  29924. /** A button has an on/off state associated with it, and this changes that.
  29925. By default buttons are 'off' and for simple buttons that you click to perform
  29926. an action you won't change this. Toggle buttons, however will want to
  29927. change their state when turned on or off.
  29928. @param shouldBeOn whether to set the button's toggle state to be on or
  29929. off. If it's a member of a button group, this will
  29930. always try to turn it on, and to turn off any other
  29931. buttons in the group
  29932. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  29933. the button will be repainted but no notification will
  29934. be sent
  29935. @see getToggleState, setRadioGroupId
  29936. */
  29937. void setToggleState (bool shouldBeOn,
  29938. bool sendChangeNotification);
  29939. /** Returns true if the button in 'on'.
  29940. By default buttons are 'off' and for simple buttons that you click to perform
  29941. an action you won't change this. Toggle buttons, however will want to
  29942. change their state when turned on or off.
  29943. @see setToggleState
  29944. */
  29945. bool getToggleState() const throw() { return isOn.getValue(); }
  29946. /** Returns the Value object that represents the botton's toggle state.
  29947. You can use this Value object to connect the button's state to external values or setters,
  29948. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  29949. your own Value object.
  29950. @see getToggleState, Value
  29951. */
  29952. Value& getToggleStateValue() { return isOn; }
  29953. /** This tells the button to automatically flip the toggle state when
  29954. the button is clicked.
  29955. If set to true, then before the clicked() callback occurs, the toggle-state
  29956. of the button is flipped.
  29957. */
  29958. void setClickingTogglesState (bool shouldToggle) throw();
  29959. /** Returns true if this button is set to be an automatic toggle-button.
  29960. This returns the last value that was passed to setClickingTogglesState().
  29961. */
  29962. bool getClickingTogglesState() const throw();
  29963. /** Enables the button to act as a member of a mutually-exclusive group
  29964. of 'radio buttons'.
  29965. If the group ID is set to a non-zero number, then this button will
  29966. act as part of a group of buttons with the same ID, only one of
  29967. which can be 'on' at the same time. Note that when it's part of
  29968. a group, clicking a toggle-button that's 'on' won't turn it off.
  29969. To find other buttons with the same ID, this button will search through
  29970. its sibling components for ToggleButtons, so all the buttons for a
  29971. particular group must be placed inside the same parent component.
  29972. Set the group ID back to zero if you want it to act as a normal toggle
  29973. button again.
  29974. @see getRadioGroupId
  29975. */
  29976. void setRadioGroupId (int newGroupId);
  29977. /** Returns the ID of the group to which this button belongs.
  29978. (See setRadioGroupId() for an explanation of this).
  29979. */
  29980. int getRadioGroupId() const throw() { return radioGroupId; }
  29981. /**
  29982. Used to receive callbacks when a button is clicked.
  29983. @see Button::addListener, Button::removeListener
  29984. */
  29985. class JUCE_API Listener
  29986. {
  29987. public:
  29988. /** Destructor. */
  29989. virtual ~Listener() {}
  29990. /** Called when the button is clicked. */
  29991. virtual void buttonClicked (Button* button) = 0;
  29992. /** Called when the button's state changes. */
  29993. virtual void buttonStateChanged (Button*) {}
  29994. };
  29995. /** Registers a listener to receive events when this button's state changes.
  29996. If the listener is already registered, this will not register it again.
  29997. @see removeListener
  29998. */
  29999. void addListener (Listener* newListener);
  30000. /** Removes a previously-registered button listener
  30001. @see addListener
  30002. */
  30003. void removeListener (Listener* listener);
  30004. /** Causes the button to act as if it's been clicked.
  30005. This will asynchronously make the button draw itself going down and up, and
  30006. will then call back the clicked() method as if mouse was clicked on it.
  30007. @see clicked
  30008. */
  30009. virtual void triggerClick();
  30010. /** Sets a command ID for this button to automatically invoke when it's clicked.
  30011. When the button is pressed, it will use the given manager to trigger the
  30012. command ID.
  30013. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  30014. before this button is. To disable the command triggering, call this method and
  30015. pass 0 for the parameters.
  30016. If generateTooltip is true, then the button's tooltip will be automatically
  30017. generated based on the name of this command and its current shortcut key.
  30018. @see addShortcut, getCommandID
  30019. */
  30020. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  30021. int commandID,
  30022. bool generateTooltip);
  30023. /** Returns the command ID that was set by setCommandToTrigger().
  30024. */
  30025. int getCommandID() const throw() { return commandID; }
  30026. /** Assigns a shortcut key to trigger the button.
  30027. The button registers itself with its top-level parent component for keypresses.
  30028. Note that a different way of linking buttons to keypresses is by using the
  30029. setCommandToTrigger() method to invoke a command.
  30030. @see clearShortcuts
  30031. */
  30032. void addShortcut (const KeyPress& key);
  30033. /** Removes all key shortcuts that had been set for this button.
  30034. @see addShortcut
  30035. */
  30036. void clearShortcuts();
  30037. /** Returns true if the given keypress is a shortcut for this button.
  30038. @see addShortcut
  30039. */
  30040. bool isRegisteredForShortcut (const KeyPress& key) const;
  30041. /** Sets an auto-repeat speed for the button when it is held down.
  30042. (Auto-repeat is disabled by default).
  30043. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  30044. triggering the next click. If this is zero, auto-repeat
  30045. is disabled
  30046. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  30047. triggered
  30048. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  30049. get faster, the longer the button is held down, up to the
  30050. minimum interval specified here
  30051. */
  30052. void setRepeatSpeed (int initialDelayInMillisecs,
  30053. int repeatDelayInMillisecs,
  30054. int minimumDelayInMillisecs = -1) throw();
  30055. /** Sets whether the button click should happen when the mouse is pressed or released.
  30056. By default the button is only considered to have been clicked when the mouse is
  30057. released, but setting this to true will make it call the clicked() method as soon
  30058. as the button is pressed.
  30059. This is useful if the button is being used to show a pop-up menu, as it allows
  30060. the click to be used as a drag onto the menu.
  30061. */
  30062. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) throw();
  30063. /** Returns the number of milliseconds since the last time the button
  30064. went into the 'down' state.
  30065. */
  30066. uint32 getMillisecondsSinceButtonDown() const throw();
  30067. /** Sets the tooltip for this button.
  30068. @see TooltipClient, TooltipWindow
  30069. */
  30070. void setTooltip (const String& newTooltip);
  30071. // (implementation of the TooltipClient method)
  30072. const String getTooltip();
  30073. /** A combination of these flags are used by setConnectedEdges().
  30074. */
  30075. enum ConnectedEdgeFlags
  30076. {
  30077. ConnectedOnLeft = 1,
  30078. ConnectedOnRight = 2,
  30079. ConnectedOnTop = 4,
  30080. ConnectedOnBottom = 8
  30081. };
  30082. /** Hints about which edges of the button might be connected to adjoining buttons.
  30083. The value passed in is a bitwise combination of any of the values in the
  30084. ConnectedEdgeFlags enum.
  30085. E.g. if you are placing two buttons adjacent to each other, you could use this to
  30086. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  30087. without rounded corners on the edges that connect. It's only a hint, so the
  30088. LookAndFeel can choose to ignore it if it's not relevent for this type of
  30089. button.
  30090. */
  30091. void setConnectedEdges (int connectedEdgeFlags);
  30092. /** Returns the set of flags passed into setConnectedEdges(). */
  30093. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  30094. /** Indicates whether the button adjoins another one on its left edge.
  30095. @see setConnectedEdges
  30096. */
  30097. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  30098. /** Indicates whether the button adjoins another one on its right edge.
  30099. @see setConnectedEdges
  30100. */
  30101. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  30102. /** Indicates whether the button adjoins another one on its top edge.
  30103. @see setConnectedEdges
  30104. */
  30105. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  30106. /** Indicates whether the button adjoins another one on its bottom edge.
  30107. @see setConnectedEdges
  30108. */
  30109. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  30110. /** Used by setState(). */
  30111. enum ButtonState
  30112. {
  30113. buttonNormal,
  30114. buttonOver,
  30115. buttonDown
  30116. };
  30117. /** Can be used to force the button into a particular state.
  30118. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  30119. from happening.
  30120. The state that you set here will only last until it is automatically changed when the mouse
  30121. enters or exits the button, or the mouse-button is pressed or released.
  30122. */
  30123. void setState (const ButtonState newState);
  30124. // These are deprecated - please use addListener() and removeListener() instead!
  30125. JUCE_DEPRECATED (void addButtonListener (Listener*));
  30126. JUCE_DEPRECATED (void removeButtonListener (Listener*));
  30127. protected:
  30128. /** This method is called when the button has been clicked.
  30129. Subclasses can override this to perform whatever they actions they need
  30130. to do.
  30131. Alternatively, a ButtonListener can be added to the button, and these listeners
  30132. will be called when the click occurs.
  30133. @see triggerClick
  30134. */
  30135. virtual void clicked();
  30136. /** This method is called when the button has been clicked.
  30137. By default it just calls clicked(), but you might want to override it to handle
  30138. things like clicking when a modifier key is pressed, etc.
  30139. @see ModifierKeys
  30140. */
  30141. virtual void clicked (const ModifierKeys& modifiers);
  30142. /** Subclasses should override this to actually paint the button's contents.
  30143. It's better to use this than the paint method, because it gives you information
  30144. about the over/down state of the button.
  30145. @param g the graphics context to use
  30146. @param isMouseOverButton true if the button is either in the 'over' or
  30147. 'down' state
  30148. @param isButtonDown true if the button should be drawn in the 'down' position
  30149. */
  30150. virtual void paintButton (Graphics& g,
  30151. bool isMouseOverButton,
  30152. bool isButtonDown) = 0;
  30153. /** Called when the button's up/down/over state changes.
  30154. Subclasses can override this if they need to do something special when the button
  30155. goes up or down.
  30156. @see isDown, isOver
  30157. */
  30158. virtual void buttonStateChanged();
  30159. /** @internal */
  30160. virtual void internalClickCallback (const ModifierKeys& modifiers);
  30161. /** @internal */
  30162. void handleCommandMessage (int commandId);
  30163. /** @internal */
  30164. void mouseEnter (const MouseEvent& e);
  30165. /** @internal */
  30166. void mouseExit (const MouseEvent& e);
  30167. /** @internal */
  30168. void mouseDown (const MouseEvent& e);
  30169. /** @internal */
  30170. void mouseDrag (const MouseEvent& e);
  30171. /** @internal */
  30172. void mouseUp (const MouseEvent& e);
  30173. /** @internal */
  30174. bool keyPressed (const KeyPress& key);
  30175. /** @internal */
  30176. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  30177. /** @internal */
  30178. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  30179. /** @internal */
  30180. void paint (Graphics& g);
  30181. /** @internal */
  30182. void parentHierarchyChanged();
  30183. /** @internal */
  30184. void visibilityChanged();
  30185. /** @internal */
  30186. void focusGained (FocusChangeType cause);
  30187. /** @internal */
  30188. void focusLost (FocusChangeType cause);
  30189. /** @internal */
  30190. void enablementChanged();
  30191. /** @internal */
  30192. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  30193. /** @internal */
  30194. void applicationCommandListChanged();
  30195. /** @internal */
  30196. void valueChanged (Value& value);
  30197. private:
  30198. Array <KeyPress> shortcuts;
  30199. WeakReference<Component> keySource;
  30200. String text;
  30201. ListenerList <Listener> buttonListeners;
  30202. class RepeatTimer;
  30203. friend class RepeatTimer;
  30204. friend class ScopedPointer <RepeatTimer>;
  30205. ScopedPointer <RepeatTimer> repeatTimer;
  30206. uint32 buttonPressTime, lastRepeatTime;
  30207. ApplicationCommandManager* commandManagerToUse;
  30208. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  30209. int radioGroupId, commandID, connectedEdgeFlags;
  30210. ButtonState buttonState;
  30211. Value isOn;
  30212. bool lastToggleState : 1;
  30213. bool clickTogglesState : 1;
  30214. bool needsToRelease : 1;
  30215. bool needsRepainting : 1;
  30216. bool isKeyDown : 1;
  30217. bool triggerOnMouseDown : 1;
  30218. bool generateTooltip : 1;
  30219. void repeatTimerCallback();
  30220. RepeatTimer& getRepeatTimer();
  30221. ButtonState updateState();
  30222. ButtonState updateState (bool isOver, bool isDown);
  30223. bool isShortcutPressed() const;
  30224. void turnOffOtherButtonsInGroup (bool sendChangeNotification);
  30225. void flashButtonState();
  30226. void sendClickMessage (const ModifierKeys& modifiers);
  30227. void sendStateMessage();
  30228. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Button);
  30229. };
  30230. #ifndef DOXYGEN
  30231. /** This typedef is just for compatibility with old code and VC6 - newer code should use Button::Listener instead. */
  30232. typedef Button::Listener ButtonListener;
  30233. #endif
  30234. #if JUCE_VC6
  30235. #undef Listener
  30236. #endif
  30237. #endif // __JUCE_BUTTON_JUCEHEADER__
  30238. /*** End of inlined file: juce_Button.h ***/
  30239. /**
  30240. A scrollbar component.
  30241. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  30242. sets the range of values it can represent. Then you can use setCurrentRange() to
  30243. change the position and size of the scrollbar's 'thumb'.
  30244. Registering a ScrollBar::Listener with the scrollbar will allow you to find out when
  30245. the user moves it, and you can use the getCurrentRangeStart() to find out where
  30246. they moved it to.
  30247. The scrollbar will adjust its own visibility according to whether its thumb size
  30248. allows it to actually be scrolled.
  30249. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  30250. instead of handling a scrollbar directly.
  30251. @see ScrollBar::Listener
  30252. */
  30253. class JUCE_API ScrollBar : public Component,
  30254. public AsyncUpdater,
  30255. private Timer
  30256. {
  30257. public:
  30258. /** Creates a Scrollbar.
  30259. @param isVertical whether it should be a vertical or horizontal bar
  30260. @param buttonsAreVisible whether to show the up/down or left/right buttons
  30261. */
  30262. ScrollBar (bool isVertical,
  30263. bool buttonsAreVisible = true);
  30264. /** Destructor. */
  30265. ~ScrollBar();
  30266. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  30267. bool isVertical() const throw() { return vertical; }
  30268. /** Changes the scrollbar's direction.
  30269. You'll also need to resize the bar appropriately - this just changes its internal
  30270. layout.
  30271. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  30272. */
  30273. void setOrientation (bool shouldBeVertical);
  30274. /** Shows or hides the scrollbar's buttons. */
  30275. void setButtonVisibility (bool buttonsAreVisible);
  30276. /** Tells the scrollbar whether to make itself invisible when not needed.
  30277. The default behaviour is for a scrollbar to become invisible when the thumb
  30278. fills the whole of its range (i.e. when it can't be moved). Setting this
  30279. value to false forces the bar to always be visible.
  30280. @see autoHides()
  30281. */
  30282. void setAutoHide (bool shouldHideWhenFullRange);
  30283. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  30284. as its maximum range.
  30285. @see setAutoHide
  30286. */
  30287. bool autoHides() const throw();
  30288. /** Sets the minimum and maximum values that the bar will move between.
  30289. The bar's thumb will always be constrained so that the entire thumb lies
  30290. within this range.
  30291. @see setCurrentRange
  30292. */
  30293. void setRangeLimits (const Range<double>& newRangeLimit);
  30294. /** Sets the minimum and maximum values that the bar will move between.
  30295. The bar's thumb will always be constrained so that the entire thumb lies
  30296. within this range.
  30297. @see setCurrentRange
  30298. */
  30299. void setRangeLimits (double minimum, double maximum);
  30300. /** Returns the current limits on the thumb position.
  30301. @see setRangeLimits
  30302. */
  30303. const Range<double> getRangeLimit() const throw() { return totalRange; }
  30304. /** Returns the lower value that the thumb can be set to.
  30305. This is the value set by setRangeLimits().
  30306. */
  30307. double getMinimumRangeLimit() const throw() { return totalRange.getStart(); }
  30308. /** Returns the upper value that the thumb can be set to.
  30309. This is the value set by setRangeLimits().
  30310. */
  30311. double getMaximumRangeLimit() const throw() { return totalRange.getEnd(); }
  30312. /** Changes the position of the scrollbar's 'thumb'.
  30313. If this method call actually changes the scrollbar's position, it will trigger an
  30314. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  30315. are registered.
  30316. @see getCurrentRange. setCurrentRangeStart
  30317. */
  30318. void setCurrentRange (const Range<double>& newRange);
  30319. /** Changes the position of the scrollbar's 'thumb'.
  30320. This sets both the position and size of the thumb - to just set the position without
  30321. changing the size, you can use setCurrentRangeStart().
  30322. If this method call actually changes the scrollbar's position, it will trigger an
  30323. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  30324. are registered.
  30325. @param newStart the top (or left) of the thumb, in the range
  30326. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  30327. value is beyond these limits, it will be clipped.
  30328. @param newSize the size of the thumb, such that
  30329. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  30330. size is beyond these limits, it will be clipped.
  30331. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  30332. */
  30333. void setCurrentRange (double newStart, double newSize);
  30334. /** Moves the bar's thumb position.
  30335. This will move the thumb position without changing the thumb size. Note
  30336. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  30337. If this method call actually changes the scrollbar's position, it will trigger an
  30338. asynchronous call to ScrollBar::Listener::scrollBarMoved() for all the listeners that
  30339. are registered.
  30340. @see setCurrentRange
  30341. */
  30342. void setCurrentRangeStart (double newStart);
  30343. /** Returns the current thumb range.
  30344. @see getCurrentRange, setCurrentRange
  30345. */
  30346. const Range<double> getCurrentRange() const throw() { return visibleRange; }
  30347. /** Returns the position of the top of the thumb.
  30348. @see getCurrentRange, setCurrentRangeStart
  30349. */
  30350. double getCurrentRangeStart() const throw() { return visibleRange.getStart(); }
  30351. /** Returns the current size of the thumb.
  30352. @see getCurrentRange, setCurrentRange
  30353. */
  30354. double getCurrentRangeSize() const throw() { return visibleRange.getLength(); }
  30355. /** Sets the amount by which the up and down buttons will move the bar.
  30356. The value here is in terms of the total range, and is added or subtracted
  30357. from the thumb position when the user clicks an up/down (or left/right) button.
  30358. */
  30359. void setSingleStepSize (double newSingleStepSize);
  30360. /** Moves the scrollbar by a number of single-steps.
  30361. This will move the bar by a multiple of its single-step interval (as
  30362. specified using the setSingleStepSize() method).
  30363. A positive value here will move the bar down or to the right, a negative
  30364. value moves it up or to the left.
  30365. */
  30366. void moveScrollbarInSteps (int howManySteps);
  30367. /** Moves the scroll bar up or down in pages.
  30368. This will move the bar by a multiple of its current thumb size, effectively
  30369. doing a page-up or down.
  30370. A positive value here will move the bar down or to the right, a negative
  30371. value moves it up or to the left.
  30372. */
  30373. void moveScrollbarInPages (int howManyPages);
  30374. /** Scrolls to the top (or left).
  30375. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  30376. */
  30377. void scrollToTop();
  30378. /** Scrolls to the bottom (or right).
  30379. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  30380. */
  30381. void scrollToBottom();
  30382. /** Changes the delay before the up and down buttons autorepeat when they are held
  30383. down.
  30384. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  30385. @see Button::setRepeatSpeed
  30386. */
  30387. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  30388. int repeatDelayInMillisecs,
  30389. int minimumDelayInMillisecs = -1);
  30390. /** A set of colour IDs to use to change the colour of various aspects of the component.
  30391. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30392. methods.
  30393. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30394. */
  30395. enum ColourIds
  30396. {
  30397. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  30398. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  30399. 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. */
  30400. };
  30401. /**
  30402. A class for receiving events from a ScrollBar.
  30403. You can register a ScrollBar::Listener with a ScrollBar using the ScrollBar::addListener()
  30404. method, and it will be called when the bar's position changes.
  30405. @see ScrollBar::addListener, ScrollBar::removeListener
  30406. */
  30407. class JUCE_API Listener
  30408. {
  30409. public:
  30410. /** Destructor. */
  30411. virtual ~Listener() {}
  30412. /** Called when a ScrollBar is moved.
  30413. @param scrollBarThatHasMoved the bar that has moved
  30414. @param newRangeStart the new range start of this bar
  30415. */
  30416. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  30417. double newRangeStart) = 0;
  30418. };
  30419. /** Registers a listener that will be called when the scrollbar is moved. */
  30420. void addListener (Listener* listener);
  30421. /** Deregisters a previously-registered listener. */
  30422. void removeListener (Listener* listener);
  30423. /** @internal */
  30424. bool keyPressed (const KeyPress& key);
  30425. /** @internal */
  30426. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  30427. /** @internal */
  30428. void lookAndFeelChanged();
  30429. /** @internal */
  30430. void handleAsyncUpdate();
  30431. /** @internal */
  30432. void mouseDown (const MouseEvent& e);
  30433. /** @internal */
  30434. void mouseDrag (const MouseEvent& e);
  30435. /** @internal */
  30436. void mouseUp (const MouseEvent& e);
  30437. /** @internal */
  30438. void paint (Graphics& g);
  30439. /** @internal */
  30440. void resized();
  30441. private:
  30442. Range <double> totalRange, visibleRange;
  30443. double singleStepSize, dragStartRange;
  30444. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  30445. int dragStartMousePos, lastMousePos;
  30446. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  30447. bool vertical, isDraggingThumb, autohides;
  30448. class ScrollbarButton;
  30449. friend class ScopedPointer<ScrollbarButton>;
  30450. ScopedPointer<ScrollbarButton> upButton, downButton;
  30451. ListenerList <Listener> listeners;
  30452. void updateThumbPosition();
  30453. void timerCallback();
  30454. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollBar);
  30455. };
  30456. /** This typedef is just for compatibility with old code - newer code should use the ScrollBar::Listener class directly. */
  30457. typedef ScrollBar::Listener ScrollBarListener;
  30458. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  30459. /*** End of inlined file: juce_ScrollBar.h ***/
  30460. /**
  30461. A Viewport is used to contain a larger child component, and allows the child
  30462. to be automatically scrolled around.
  30463. To use a Viewport, just create one and set the component that goes inside it
  30464. using the setViewedComponent() method. When the child component changes size,
  30465. the Viewport will adjust its scrollbars accordingly.
  30466. A subclass of the viewport can be created which will receive calls to its
  30467. visibleAreaChanged() method when the subcomponent changes position or size.
  30468. */
  30469. class JUCE_API Viewport : public Component,
  30470. private ComponentListener,
  30471. private ScrollBar::Listener
  30472. {
  30473. public:
  30474. /** Creates a Viewport.
  30475. The viewport is initially empty - use the setViewedComponent() method to
  30476. add a child component for it to manage.
  30477. */
  30478. explicit Viewport (const String& componentName = String::empty);
  30479. /** Destructor. */
  30480. ~Viewport();
  30481. /** Sets the component that this viewport will contain and scroll around.
  30482. This will add the given component to this Viewport and position it at
  30483. (0, 0).
  30484. (Don't add or remove any child components directly using the normal
  30485. Component::addChildComponent() methods).
  30486. @param newViewedComponent the component to add to this viewport (this pointer
  30487. may be null). The component passed in will be deleted
  30488. by the Viewport when it's no longer needed
  30489. @see getViewedComponent
  30490. */
  30491. void setViewedComponent (Component* newViewedComponent);
  30492. /** Returns the component that's currently being used inside the Viewport.
  30493. @see setViewedComponent
  30494. */
  30495. Component* getViewedComponent() const throw() { return contentComp; }
  30496. /** Changes the position of the viewed component.
  30497. The inner component will be moved so that the pixel at the top left of
  30498. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  30499. within the inner component.
  30500. This will update the scrollbars and might cause a call to visibleAreaChanged().
  30501. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  30502. */
  30503. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  30504. /** Changes the position of the viewed component.
  30505. The inner component will be moved so that the pixel at the top left of
  30506. the viewport will be the pixel at the specified coordinates within the
  30507. inner component.
  30508. This will update the scrollbars and might cause a call to visibleAreaChanged().
  30509. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  30510. */
  30511. void setViewPosition (const Point<int>& newPosition);
  30512. /** Changes the view position as a proportion of the distance it can move.
  30513. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  30514. visible area in the top-left, and (1, 1) would put it as far down and
  30515. to the right as it's possible to go whilst keeping the child component
  30516. on-screen.
  30517. */
  30518. void setViewPositionProportionately (double proportionX, double proportionY);
  30519. /** If the specified position is at the edges of the viewport, this method scrolls
  30520. the viewport to bring that position nearer to the centre.
  30521. Call this if you're dragging an object inside a viewport and want to make it scroll
  30522. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  30523. useful when auto-scrolling.
  30524. @param mouseX the x position, relative to the Viewport's top-left
  30525. @param mouseY the y position, relative to the Viewport's top-left
  30526. @param distanceFromEdge specifies how close to an edge the position needs to be
  30527. before the viewport should scroll in that direction
  30528. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  30529. to scroll by.
  30530. @returns true if the viewport was scrolled
  30531. */
  30532. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  30533. /** Returns the position within the child component of the top-left of its visible area.
  30534. */
  30535. const Point<int> getViewPosition() const throw() { return lastVisibleArea.getPosition(); }
  30536. /** Returns the position within the child component of the top-left of its visible area.
  30537. @see getViewWidth, setViewPosition
  30538. */
  30539. int getViewPositionX() const throw() { return lastVisibleArea.getX(); }
  30540. /** Returns the position within the child component of the top-left of its visible area.
  30541. @see getViewHeight, setViewPosition
  30542. */
  30543. int getViewPositionY() const throw() { return lastVisibleArea.getY(); }
  30544. /** Returns the width of the visible area of the child component.
  30545. This may be less than the width of this Viewport if there's a vertical scrollbar
  30546. or if the child component is itself smaller.
  30547. */
  30548. int getViewWidth() const throw() { return lastVisibleArea.getWidth(); }
  30549. /** Returns the height of the visible area of the child component.
  30550. This may be less than the height of this Viewport if there's a horizontal scrollbar
  30551. or if the child component is itself smaller.
  30552. */
  30553. int getViewHeight() const throw() { return lastVisibleArea.getHeight(); }
  30554. /** Returns the width available within this component for the contents.
  30555. This will be the width of the viewport component minus the width of a
  30556. vertical scrollbar (if visible).
  30557. */
  30558. int getMaximumVisibleWidth() const;
  30559. /** Returns the height available within this component for the contents.
  30560. This will be the height of the viewport component minus the space taken up
  30561. by a horizontal scrollbar (if visible).
  30562. */
  30563. int getMaximumVisibleHeight() const;
  30564. /** Callback method that is called when the visible area changes.
  30565. This will be called when the visible area is moved either be scrolling or
  30566. by calls to setViewPosition(), etc.
  30567. */
  30568. virtual void visibleAreaChanged (const Rectangle<int>& newVisibleArea);
  30569. /** Turns scrollbars on or off.
  30570. If set to false, the scrollbars won't ever appear. When true (the default)
  30571. they will appear only when needed.
  30572. */
  30573. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  30574. bool showHorizontalScrollbarIfNeeded);
  30575. /** True if the vertical scrollbar is enabled.
  30576. @see setScrollBarsShown
  30577. */
  30578. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  30579. /** True if the horizontal scrollbar is enabled.
  30580. @see setScrollBarsShown
  30581. */
  30582. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  30583. /** Changes the width of the scrollbars.
  30584. If this isn't specified, the default width from the LookAndFeel class will be used.
  30585. @see LookAndFeel::getDefaultScrollbarWidth
  30586. */
  30587. void setScrollBarThickness (int thickness);
  30588. /** Returns the thickness of the scrollbars.
  30589. @see setScrollBarThickness
  30590. */
  30591. int getScrollBarThickness() const;
  30592. /** Changes the distance that a single-step click on a scrollbar button
  30593. will move the viewport.
  30594. */
  30595. void setSingleStepSizes (int stepX, int stepY);
  30596. /** Shows or hides the buttons on any scrollbars that are used.
  30597. @see ScrollBar::setButtonVisibility
  30598. */
  30599. void setScrollBarButtonVisibility (bool buttonsVisible);
  30600. /** Returns a pointer to the scrollbar component being used.
  30601. Handy if you need to customise the bar somehow.
  30602. */
  30603. ScrollBar* getVerticalScrollBar() throw() { return &verticalScrollBar; }
  30604. /** Returns a pointer to the scrollbar component being used.
  30605. Handy if you need to customise the bar somehow.
  30606. */
  30607. ScrollBar* getHorizontalScrollBar() throw() { return &horizontalScrollBar; }
  30608. /** @internal */
  30609. void resized();
  30610. /** @internal */
  30611. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  30612. /** @internal */
  30613. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  30614. /** @internal */
  30615. bool keyPressed (const KeyPress& key);
  30616. /** @internal */
  30617. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  30618. /** @internal */
  30619. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  30620. private:
  30621. WeakReference<Component> contentComp;
  30622. Rectangle<int> lastVisibleArea;
  30623. int scrollBarThickness;
  30624. int singleStepX, singleStepY;
  30625. bool showHScrollbar, showVScrollbar;
  30626. Component contentHolder;
  30627. ScrollBar verticalScrollBar;
  30628. ScrollBar horizontalScrollBar;
  30629. void updateVisibleArea();
  30630. void deleteContentComp();
  30631. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  30632. // If you get an error here, it's because this method's parameters have changed! See the new definition above..
  30633. virtual int visibleAreaChanged (int, int, int, int) { return 0; }
  30634. #endif
  30635. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Viewport);
  30636. };
  30637. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  30638. /*** End of inlined file: juce_Viewport.h ***/
  30639. /*** Start of inlined file: juce_PopupMenu.h ***/
  30640. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  30641. #define __JUCE_POPUPMENU_JUCEHEADER__
  30642. /** Creates and displays a popup-menu.
  30643. To show a popup-menu, you create one of these, add some items to it, then
  30644. call its show() method, which returns the id of the item the user selects.
  30645. E.g. @code
  30646. void MyWidget::mouseDown (const MouseEvent& e)
  30647. {
  30648. PopupMenu m;
  30649. m.addItem (1, "item 1");
  30650. m.addItem (2, "item 2");
  30651. const int result = m.show();
  30652. if (result == 0)
  30653. {
  30654. // user dismissed the menu without picking anything
  30655. }
  30656. else if (result == 1)
  30657. {
  30658. // user picked item 1
  30659. }
  30660. else if (result == 2)
  30661. {
  30662. // user picked item 2
  30663. }
  30664. }
  30665. @endcode
  30666. Submenus are easy too: @code
  30667. void MyWidget::mouseDown (const MouseEvent& e)
  30668. {
  30669. PopupMenu subMenu;
  30670. subMenu.addItem (1, "item 1");
  30671. subMenu.addItem (2, "item 2");
  30672. PopupMenu mainMenu;
  30673. mainMenu.addItem (3, "item 3");
  30674. mainMenu.addSubMenu ("other choices", subMenu);
  30675. const int result = m.show();
  30676. ...etc
  30677. }
  30678. @endcode
  30679. */
  30680. class JUCE_API PopupMenu
  30681. {
  30682. public:
  30683. /** Creates an empty popup menu. */
  30684. PopupMenu();
  30685. /** Creates a copy of another menu. */
  30686. PopupMenu (const PopupMenu& other);
  30687. /** Destructor. */
  30688. ~PopupMenu();
  30689. /** Copies this menu from another one. */
  30690. PopupMenu& operator= (const PopupMenu& other);
  30691. /** Resets the menu, removing all its items. */
  30692. void clear();
  30693. /** Appends a new text item for this menu to show.
  30694. @param itemResultId the number that will be returned from the show() method
  30695. if the user picks this item. The value should never be
  30696. zero, because that's used to indicate that the user didn't
  30697. select anything.
  30698. @param itemText the text to show.
  30699. @param isActive if false, the item will be shown 'greyed-out' and can't be
  30700. picked
  30701. @param isTicked if true, the item will be shown with a tick next to it
  30702. @param iconToUse if this is non-zero, it should be an image that will be
  30703. displayed to the left of the item. This method will take its
  30704. own copy of the image passed-in, so there's no need to keep
  30705. it hanging around.
  30706. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  30707. */
  30708. void addItem (int itemResultId,
  30709. const String& itemText,
  30710. bool isActive = true,
  30711. bool isTicked = false,
  30712. const Image& iconToUse = Image::null);
  30713. /** Adds an item that represents one of the commands in a command manager object.
  30714. @param commandManager the manager to use to trigger the command and get information
  30715. about it
  30716. @param commandID the ID of the command
  30717. @param displayName if this is non-empty, then this string will be used instead of
  30718. the command's registered name
  30719. */
  30720. void addCommandItem (ApplicationCommandManager* commandManager,
  30721. int commandID,
  30722. const String& displayName = String::empty);
  30723. /** Appends a text item with a special colour.
  30724. This is the same as addItem(), but specifies a colour to use for the
  30725. text, which will override the default colours that are used by the
  30726. current look-and-feel. See addItem() for a description of the parameters.
  30727. */
  30728. void addColouredItem (int itemResultId,
  30729. const String& itemText,
  30730. const Colour& itemTextColour,
  30731. bool isActive = true,
  30732. bool isTicked = false,
  30733. const Image& iconToUse = Image::null);
  30734. /** Appends a custom menu item that can't be used to trigger a result.
  30735. This will add a user-defined component to use as a menu item. Unlike the
  30736. addCustomItem() method that takes a PopupMenu::CustomComponent, this version
  30737. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  30738. delete the component when it's finished, so it's the caller's responsibility
  30739. to manage the component that is passed-in.
  30740. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  30741. detection of a mouse-click on your component, and use that to trigger the
  30742. menu ID specified in itemResultId. If this is false, the menu item can't
  30743. be triggered, so itemResultId is not used.
  30744. @see CustomComponent
  30745. */
  30746. void addCustomItem (int itemResultId,
  30747. Component* customComponent,
  30748. int idealWidth, int idealHeight,
  30749. bool triggerMenuItemAutomaticallyWhenClicked);
  30750. /** Appends a sub-menu.
  30751. If the menu that's passed in is empty, it will appear as an inactive item.
  30752. */
  30753. void addSubMenu (const String& subMenuName,
  30754. const PopupMenu& subMenu,
  30755. bool isActive = true,
  30756. const Image& iconToUse = Image::null,
  30757. bool isTicked = false);
  30758. /** Appends a separator to the menu, to help break it up into sections.
  30759. The menu class is smart enough not to display separators at the top or bottom
  30760. of the menu, and it will replace mutliple adjacent separators with a single
  30761. one, so your code can be quite free and easy about adding these, and it'll
  30762. always look ok.
  30763. */
  30764. void addSeparator();
  30765. /** Adds a non-clickable text item to the menu.
  30766. This is a bold-font items which can be used as a header to separate the items
  30767. into named groups.
  30768. */
  30769. void addSectionHeader (const String& title);
  30770. /** Returns the number of items that the menu currently contains.
  30771. (This doesn't count separators).
  30772. */
  30773. int getNumItems() const throw();
  30774. /** Returns true if the menu contains a command item that triggers the given command. */
  30775. bool containsCommandItem (int commandID) const;
  30776. /** Returns true if the menu contains any items that can be used. */
  30777. bool containsAnyActiveItems() const throw();
  30778. /** Displays the menu and waits for the user to pick something.
  30779. This will display the menu modally, and return the ID of the item that the
  30780. user picks. If they click somewhere off the menu to get rid of it without
  30781. choosing anything, this will return 0.
  30782. The current location of the mouse will be used as the position to show the
  30783. menu - to explicitly set the menu's position, use showAt() instead. Depending
  30784. on where this point is on the screen, the menu will appear above, below or
  30785. to the side of the point.
  30786. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  30787. then when the menu first appears, it will make sure
  30788. that this item is visible. So if the menu has too many
  30789. items to fit on the screen, it will be scrolled to a
  30790. position where this item is visible.
  30791. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  30792. than this if some items are too long to fit.
  30793. @param maximumNumColumns if there are too many items to fit on-screen in a single
  30794. vertical column, the menu may be laid out as a series of
  30795. columns - this is the maximum number allowed. To use the
  30796. default value for this (probably about 7), you can pass
  30797. in zero.
  30798. @param standardItemHeight if this is non-zero, it will be used as the standard
  30799. height for menu items (apart from custom items)
  30800. @param callback if this is non-zero, the menu will be launched asynchronously,
  30801. returning immediately, and the callback will receive a
  30802. call when the menu is either dismissed or has an item
  30803. selected. This object will be owned and deleted by the
  30804. system, so make sure that it works safely and that any
  30805. pointers that it uses are safely within scope.
  30806. @see showAt
  30807. */
  30808. int show (int itemIdThatMustBeVisible = 0,
  30809. int minimumWidth = 0,
  30810. int maximumNumColumns = 0,
  30811. int standardItemHeight = 0,
  30812. ModalComponentManager::Callback* callback = 0);
  30813. /** Displays the menu at a specific location.
  30814. This is the same as show(), but uses a specific location (in global screen
  30815. co-ordinates) rather than the current mouse position.
  30816. The screenAreaToAttachTo parameter indicates a screen area to which the menu
  30817. will be adjacent. Depending on where this is, the menu will decide which edge to
  30818. attach itself to, in order to fit itself fully on-screen. If you just want to
  30819. trigger a menu at a specific point, you can pass in a rectangle of size (0, 0)
  30820. with the position that you want.
  30821. @see show()
  30822. */
  30823. int showAt (const Rectangle<int>& screenAreaToAttachTo,
  30824. int itemIdThatMustBeVisible = 0,
  30825. int minimumWidth = 0,
  30826. int maximumNumColumns = 0,
  30827. int standardItemHeight = 0,
  30828. ModalComponentManager::Callback* callback = 0);
  30829. /** Displays the menu as if it's attached to a component such as a button.
  30830. This is similar to showAt(), but will position it next to the given component, e.g.
  30831. so that the menu's edge is aligned with that of the component. This is intended for
  30832. things like buttons that trigger a pop-up menu.
  30833. */
  30834. int showAt (Component* componentToAttachTo,
  30835. int itemIdThatMustBeVisible = 0,
  30836. int minimumWidth = 0,
  30837. int maximumNumColumns = 0,
  30838. int standardItemHeight = 0,
  30839. ModalComponentManager::Callback* callback = 0);
  30840. /** Closes any menus that are currently open.
  30841. This might be useful if you have a situation where your window is being closed
  30842. by some means other than a user action, and you'd like to make sure that menus
  30843. aren't left hanging around.
  30844. */
  30845. static bool JUCE_CALLTYPE dismissAllActiveMenus();
  30846. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  30847. This can be called before show() if you need a customised menu. Be careful
  30848. not to delete the LookAndFeel object before the menu has been deleted.
  30849. */
  30850. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  30851. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  30852. These constants can be used either via the LookAndFeel::setColour()
  30853. method for the look and feel that is set for this menu with setLookAndFeel()
  30854. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  30855. */
  30856. enum ColourIds
  30857. {
  30858. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  30859. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  30860. colour is specified when the item is added). */
  30861. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  30862. addSectionHeader() method). */
  30863. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  30864. highlighted menu item. */
  30865. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  30866. highlighted item. */
  30867. };
  30868. /**
  30869. Allows you to iterate through the items in a pop-up menu, and examine
  30870. their properties.
  30871. To use this, just create one and repeatedly call its next() method. When this
  30872. returns true, all the member variables of the iterator are filled-out with
  30873. information describing the menu item. When it returns false, the end of the
  30874. list has been reached.
  30875. */
  30876. class JUCE_API MenuItemIterator
  30877. {
  30878. public:
  30879. /** Creates an iterator that will scan through the items in the specified
  30880. menu.
  30881. Be careful not to add any items to a menu while it is being iterated,
  30882. or things could get out of step.
  30883. */
  30884. MenuItemIterator (const PopupMenu& menu);
  30885. /** Destructor. */
  30886. ~MenuItemIterator();
  30887. /** Returns true if there is another item, and sets up all this object's
  30888. member variables to reflect that item's properties.
  30889. */
  30890. bool next();
  30891. String itemName;
  30892. const PopupMenu* subMenu;
  30893. int itemId;
  30894. bool isSeparator;
  30895. bool isTicked;
  30896. bool isEnabled;
  30897. bool isCustomComponent;
  30898. bool isSectionHeader;
  30899. const Colour* customColour;
  30900. Image customImage;
  30901. ApplicationCommandManager* commandManager;
  30902. private:
  30903. const PopupMenu& menu;
  30904. int index;
  30905. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuItemIterator);
  30906. };
  30907. /** A user-defined copmonent that can be used as an item in a popup menu.
  30908. @see PopupMenu::addCustomItem
  30909. */
  30910. class JUCE_API CustomComponent : public Component,
  30911. public ReferenceCountedObject
  30912. {
  30913. public:
  30914. /** Creates a custom item.
  30915. If isTriggeredAutomatically is true, then the menu will automatically detect
  30916. a mouse-click on this component and use that to invoke the menu item. If it's
  30917. false, then it's up to your class to manually trigger the item when it wants to.
  30918. */
  30919. CustomComponent (bool isTriggeredAutomatically = true);
  30920. /** Destructor. */
  30921. ~CustomComponent();
  30922. /** Returns a rectangle with the size that this component would like to have.
  30923. Note that the size which this method returns isn't necessarily the one that
  30924. the menu will give it, as the items will be stretched to have a uniform width.
  30925. */
  30926. virtual void getIdealSize (int& idealWidth, int& idealHeight) = 0;
  30927. /** Dismisses the menu, indicating that this item has been chosen.
  30928. This will cause the menu to exit from its modal state, returning
  30929. this item's id as the result.
  30930. */
  30931. void triggerMenuItem();
  30932. /** Returns true if this item should be highlighted because the mouse is over it.
  30933. You can call this method in your paint() method to find out whether
  30934. to draw a highlight.
  30935. */
  30936. bool isItemHighlighted() const throw() { return isHighlighted; }
  30937. /** @internal. */
  30938. bool isTriggeredAutomatically() const throw() { return triggeredAutomatically; }
  30939. /** @internal. */
  30940. void setHighlighted (bool shouldBeHighlighted);
  30941. private:
  30942. bool isHighlighted, triggeredAutomatically;
  30943. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponent);
  30944. };
  30945. /** Appends a custom menu item.
  30946. This will add a user-defined component to use as a menu item. The component
  30947. passed in will be deleted by this menu when it's no longer needed.
  30948. @see CustomComponent
  30949. */
  30950. void addCustomItem (int itemResultId, CustomComponent* customComponent);
  30951. private:
  30952. class Item;
  30953. class ItemComponent;
  30954. class Window;
  30955. friend class MenuItemIterator;
  30956. friend class ItemComponent;
  30957. friend class Window;
  30958. friend class CustomComponent;
  30959. friend class MenuBarComponent;
  30960. friend class OwnedArray <Item>;
  30961. friend class OwnedArray <ItemComponent>;
  30962. friend class ScopedPointer <Window>;
  30963. OwnedArray <Item> items;
  30964. LookAndFeel* lookAndFeel;
  30965. bool separatorPending;
  30966. void addSeparatorIfPending();
  30967. int showMenu (const Rectangle<int>& target, int itemIdThatMustBeVisible,
  30968. int minimumWidth, int maximumNumColumns, int standardItemHeight,
  30969. Component* componentAttachedTo, ModalComponentManager::Callback* callback);
  30970. JUCE_LEAK_DETECTOR (PopupMenu);
  30971. };
  30972. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  30973. /*** End of inlined file: juce_PopupMenu.h ***/
  30974. /*** Start of inlined file: juce_TextInputTarget.h ***/
  30975. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  30976. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  30977. /** An abstract base class that is implemented by components that wish to be used
  30978. as text editors.
  30979. This class allows different types of text editor component to provide a uniform
  30980. interface, which can be used by things like OS-specific input methods, on-screen
  30981. keyboards, etc.
  30982. */
  30983. class JUCE_API TextInputTarget
  30984. {
  30985. public:
  30986. /** */
  30987. TextInputTarget() {}
  30988. /** Destructor. */
  30989. virtual ~TextInputTarget() {}
  30990. /** Returns true if this input target is currently accepting input.
  30991. For example, a text editor might return false if it's in read-only mode.
  30992. */
  30993. virtual bool isTextInputActive() const = 0;
  30994. /** Returns the extents of the selected text region, or an empty range if
  30995. nothing is selected,
  30996. */
  30997. virtual const Range<int> getHighlightedRegion() const = 0;
  30998. /** Sets the currently-selected text region.
  30999. */
  31000. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  31001. /** Returns a specified sub-section of the text.
  31002. */
  31003. virtual const String getTextInRange (const Range<int>& range) const = 0;
  31004. /** Inserts some text, overwriting the selected text region, if there is one. */
  31005. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  31006. };
  31007. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  31008. /*** End of inlined file: juce_TextInputTarget.h ***/
  31009. /**
  31010. A component containing text that can be edited.
  31011. A TextEditor can either be in single- or multi-line mode, and supports mixed
  31012. fonts and colours.
  31013. @see TextEditor::Listener, Label
  31014. */
  31015. class JUCE_API TextEditor : public Component,
  31016. public TextInputTarget,
  31017. public SettableTooltipClient
  31018. {
  31019. public:
  31020. /** Creates a new, empty text editor.
  31021. @param componentName the name to pass to the component for it to use as its name
  31022. @param passwordCharacter if this is not zero, this character will be used as a replacement
  31023. for all characters that are drawn on screen - e.g. to create
  31024. a password-style textbox containing circular blobs instead of text,
  31025. you could set this value to 0x25cf, which is the unicode character
  31026. for a black splodge (not all fonts include this, though), or 0x2022,
  31027. which is a bullet (probably the best choice for linux).
  31028. */
  31029. explicit TextEditor (const String& componentName = String::empty,
  31030. juce_wchar passwordCharacter = 0);
  31031. /** Destructor. */
  31032. virtual ~TextEditor();
  31033. /** Puts the editor into either multi- or single-line mode.
  31034. By default, the editor will be in single-line mode, so use this if you need a multi-line
  31035. editor.
  31036. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  31037. on if you want a multi-line editor with line-breaks.
  31038. @see isMultiLine, setReturnKeyStartsNewLine
  31039. */
  31040. void setMultiLine (bool shouldBeMultiLine,
  31041. bool shouldWordWrap = true);
  31042. /** Returns true if the editor is in multi-line mode.
  31043. */
  31044. bool isMultiLine() const;
  31045. /** Changes the behaviour of the return key.
  31046. If set to true, the return key will insert a new-line into the text; if false
  31047. it will trigger a call to the TextEditor::Listener::textEditorReturnKeyPressed()
  31048. method. By default this is set to false, and when true it will only insert
  31049. new-lines when in multi-line mode (see setMultiLine()).
  31050. */
  31051. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  31052. /** Returns the value set by setReturnKeyStartsNewLine().
  31053. See setReturnKeyStartsNewLine() for more info.
  31054. */
  31055. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  31056. /** Indicates whether the tab key should be accepted and used to input a tab character,
  31057. or whether it gets ignored.
  31058. By default the tab key is ignored, so that it can be used to switch keyboard focus
  31059. between components.
  31060. */
  31061. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  31062. /** Returns true if the tab key is being used for input.
  31063. @see setTabKeyUsedAsCharacter
  31064. */
  31065. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  31066. /** Changes the editor to read-only mode.
  31067. By default, the text editor is not read-only. If you're making it read-only, you
  31068. might also want to call setCaretVisible (false) to get rid of the caret.
  31069. The text can still be highlighted and copied when in read-only mode.
  31070. @see isReadOnly, setCaretVisible
  31071. */
  31072. void setReadOnly (bool shouldBeReadOnly);
  31073. /** Returns true if the editor is in read-only mode.
  31074. */
  31075. bool isReadOnly() const;
  31076. /** Makes the caret visible or invisible.
  31077. By default the caret is visible.
  31078. @see setCaretColour, setCaretPosition
  31079. */
  31080. void setCaretVisible (bool shouldBeVisible);
  31081. /** Returns true if the caret is enabled.
  31082. @see setCaretVisible
  31083. */
  31084. bool isCaretVisible() const { return caretVisible; }
  31085. /** Enables/disables a vertical scrollbar.
  31086. (This only applies when in multi-line mode). When the text gets too long to fit
  31087. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  31088. this is enabled, the scrollbar will be hidden unless it's needed.
  31089. By default the scrollbar is enabled.
  31090. */
  31091. void setScrollbarsShown (bool shouldBeEnabled);
  31092. /** Returns true if scrollbars are enabled.
  31093. @see setScrollbarsShown
  31094. */
  31095. bool areScrollbarsShown() const { return scrollbarVisible; }
  31096. /** Changes the password character used to disguise the text.
  31097. @param passwordCharacter if this is not zero, this character will be used as a replacement
  31098. for all characters that are drawn on screen - e.g. to create
  31099. a password-style textbox containing circular blobs instead of text,
  31100. you could set this value to 0x25cf, which is the unicode character
  31101. for a black splodge (not all fonts include this, though), or 0x2022,
  31102. which is a bullet (probably the best choice for linux).
  31103. */
  31104. void setPasswordCharacter (juce_wchar passwordCharacter);
  31105. /** Returns the current password character.
  31106. @see setPasswordCharacter
  31107. */
  31108. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  31109. /** Allows a right-click menu to appear for the editor.
  31110. (This defaults to being enabled).
  31111. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  31112. of options such as cut/copy/paste, undo/redo, etc.
  31113. */
  31114. void setPopupMenuEnabled (bool menuEnabled);
  31115. /** Returns true if the right-click menu is enabled.
  31116. @see setPopupMenuEnabled
  31117. */
  31118. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  31119. /** Returns true if a popup-menu is currently being displayed.
  31120. */
  31121. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  31122. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  31123. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31124. methods.
  31125. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31126. */
  31127. enum ColourIds
  31128. {
  31129. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  31130. transparent if necessary. */
  31131. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  31132. that because the editor can contain multiple colours, calling this
  31133. method won't change the colour of existing text - to do that, call
  31134. applyFontToAllText() after calling this method.*/
  31135. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  31136. the text - this can be transparent if you don't want to show any
  31137. highlighting.*/
  31138. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  31139. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  31140. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  31141. the edge of the component. */
  31142. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  31143. the edge of the component when it has focus. */
  31144. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  31145. around the edge of the editor. */
  31146. };
  31147. /** Sets the font to use for newly added text.
  31148. This will change the font that will be used next time any text is added or entered
  31149. into the editor. It won't change the font of any existing text - to do that, use
  31150. applyFontToAllText() instead.
  31151. @see applyFontToAllText
  31152. */
  31153. void setFont (const Font& newFont);
  31154. /** Applies a font to all the text in the editor.
  31155. This will also set the current font to use for any new text that's added.
  31156. @see setFont
  31157. */
  31158. void applyFontToAllText (const Font& newFont);
  31159. /** Returns the font that's currently being used for new text.
  31160. @see setFont
  31161. */
  31162. const Font getFont() const;
  31163. /** If set to true, focusing on the editor will highlight all its text.
  31164. (Set to false by default).
  31165. This is useful for boxes where you expect the user to re-enter all the
  31166. text when they focus on the component, rather than editing what's already there.
  31167. */
  31168. void setSelectAllWhenFocused (bool b);
  31169. /** Sets limits on the characters that can be entered.
  31170. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  31171. limit is set
  31172. @param allowedCharacters if this is non-empty, then only characters that occur in
  31173. this string are allowed to be entered into the editor.
  31174. */
  31175. void setInputRestrictions (int maxTextLength,
  31176. const String& allowedCharacters = String::empty);
  31177. /** When the text editor is empty, it can be set to display a message.
  31178. This is handy for things like telling the user what to type in the box - the
  31179. string is only displayed, it's not taken to actually be the contents of
  31180. the editor.
  31181. */
  31182. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  31183. /** Changes the size of the scrollbars that are used.
  31184. Handy if you need smaller scrollbars for a small text box.
  31185. */
  31186. void setScrollBarThickness (int newThicknessPixels);
  31187. /** Shows or hides the buttons on any scrollbars that are used.
  31188. @see ScrollBar::setButtonVisibility
  31189. */
  31190. void setScrollBarButtonVisibility (bool buttonsVisible);
  31191. /**
  31192. Receives callbacks from a TextEditor component when it changes.
  31193. @see TextEditor::addListener
  31194. */
  31195. class JUCE_API Listener
  31196. {
  31197. public:
  31198. /** Destructor. */
  31199. virtual ~Listener() {}
  31200. /** Called when the user changes the text in some way. */
  31201. virtual void textEditorTextChanged (TextEditor& editor);
  31202. /** Called when the user presses the return key. */
  31203. virtual void textEditorReturnKeyPressed (TextEditor& editor);
  31204. /** Called when the user presses the escape key. */
  31205. virtual void textEditorEscapeKeyPressed (TextEditor& editor);
  31206. /** Called when the text editor loses focus. */
  31207. virtual void textEditorFocusLost (TextEditor& editor);
  31208. };
  31209. /** Registers a listener to be told when things happen to the text.
  31210. @see removeListener
  31211. */
  31212. void addListener (Listener* newListener);
  31213. /** Deregisters a listener.
  31214. @see addListener
  31215. */
  31216. void removeListener (Listener* listenerToRemove);
  31217. /** Returns the entire contents of the editor. */
  31218. const String getText() const;
  31219. /** Returns a section of the contents of the editor. */
  31220. const String getTextInRange (const Range<int>& textRange) const;
  31221. /** Returns true if there are no characters in the editor.
  31222. This is more efficient than calling getText().isEmpty().
  31223. */
  31224. bool isEmpty() const;
  31225. /** Sets the entire content of the editor.
  31226. This will clear the editor and insert the given text (using the current text colour
  31227. and font). You can set the current text colour using
  31228. @code setColour (TextEditor::textColourId, ...);
  31229. @endcode
  31230. @param newText the text to add
  31231. @param sendTextChangeMessage if true, this will cause a change message to
  31232. be sent to all the listeners.
  31233. @see insertText
  31234. */
  31235. void setText (const String& newText,
  31236. bool sendTextChangeMessage = true);
  31237. /** Returns a Value object that can be used to get or set the text.
  31238. Bear in mind that this operate quite slowly if your text box contains large
  31239. amounts of text, as it needs to dynamically build the string that's involved. It's
  31240. best used for small text boxes.
  31241. */
  31242. Value& getTextValue();
  31243. /** Inserts some text at the current cursor position.
  31244. If a section of the text is highlighted, it will be replaced by
  31245. this string, otherwise it will be inserted.
  31246. To delete a section of text, you can use setHighlightedRegion() to
  31247. highlight it, and call insertTextAtCursor (String::empty).
  31248. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  31249. */
  31250. void insertTextAtCaret (const String& textToInsert);
  31251. /** Deletes all the text from the editor. */
  31252. void clear();
  31253. /** Deletes the currently selected region, and puts it on the clipboard.
  31254. @see copy, paste, SystemClipboard
  31255. */
  31256. void cut();
  31257. /** Copies any currently selected region to the clipboard.
  31258. @see cut, paste, SystemClipboard
  31259. */
  31260. void copy();
  31261. /** Pastes the contents of the clipboard into the editor at the cursor position.
  31262. @see cut, copy, SystemClipboard
  31263. */
  31264. void paste();
  31265. /** Moves the caret to be in front of a given character.
  31266. @see getCaretPosition
  31267. */
  31268. void setCaretPosition (int newIndex);
  31269. /** Returns the current index of the caret.
  31270. @see setCaretPosition
  31271. */
  31272. int getCaretPosition() const;
  31273. /** Attempts to scroll the text editor so that the caret ends up at
  31274. a specified position.
  31275. This won't affect the caret's position within the text, it tries to scroll
  31276. the entire editor vertically and horizontally so that the caret is sitting
  31277. at the given position (relative to the top-left of this component).
  31278. Depending on the amount of text available, it might not be possible to
  31279. scroll far enough for the caret to reach this exact position, but it
  31280. will go as far as it can in that direction.
  31281. */
  31282. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  31283. /** Get the graphical position of the caret.
  31284. The rectangle returned is relative to the component's top-left corner.
  31285. @see scrollEditorToPositionCaret
  31286. */
  31287. const Rectangle<int> getCaretRectangle();
  31288. /** Selects a section of the text. */
  31289. void setHighlightedRegion (const Range<int>& newSelection);
  31290. /** Returns the range of characters that are selected.
  31291. If nothing is selected, this will return an empty range.
  31292. @see setHighlightedRegion
  31293. */
  31294. const Range<int> getHighlightedRegion() const { return selection; }
  31295. /** Returns the section of text that is currently selected. */
  31296. const String getHighlightedText() const;
  31297. /** Finds the index of the character at a given position.
  31298. The co-ordinates are relative to the component's top-left.
  31299. */
  31300. int getTextIndexAt (int x, int y);
  31301. /** Counts the number of characters in the text.
  31302. This is quicker than getting the text as a string if you just need to know
  31303. the length.
  31304. */
  31305. int getTotalNumChars() const;
  31306. /** Returns the total width of the text, as it is currently laid-out.
  31307. This may be larger than the size of the TextEditor, and can change when
  31308. the TextEditor is resized or the text changes.
  31309. */
  31310. int getTextWidth() const;
  31311. /** Returns the maximum height of the text, as it is currently laid-out.
  31312. This may be larger than the size of the TextEditor, and can change when
  31313. the TextEditor is resized or the text changes.
  31314. */
  31315. int getTextHeight() const;
  31316. /** Changes the size of the gap at the top and left-edge of the editor.
  31317. By default there's a gap of 4 pixels.
  31318. */
  31319. void setIndents (int newLeftIndent, int newTopIndent);
  31320. /** Changes the size of border left around the edge of the component.
  31321. @see getBorder
  31322. */
  31323. void setBorder (const BorderSize<int>& border);
  31324. /** Returns the size of border around the edge of the component.
  31325. @see setBorder
  31326. */
  31327. const BorderSize<int> getBorder() const;
  31328. /** Used to disable the auto-scrolling which keeps the cursor visible.
  31329. If true (the default), the editor will scroll when the cursor moves offscreen. If
  31330. set to false, it won't.
  31331. */
  31332. void setScrollToShowCursor (bool shouldScrollToShowCursor);
  31333. /** @internal */
  31334. void paint (Graphics& g);
  31335. /** @internal */
  31336. void paintOverChildren (Graphics& g);
  31337. /** @internal */
  31338. void mouseDown (const MouseEvent& e);
  31339. /** @internal */
  31340. void mouseUp (const MouseEvent& e);
  31341. /** @internal */
  31342. void mouseDrag (const MouseEvent& e);
  31343. /** @internal */
  31344. void mouseDoubleClick (const MouseEvent& e);
  31345. /** @internal */
  31346. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31347. /** @internal */
  31348. bool keyPressed (const KeyPress& key);
  31349. /** @internal */
  31350. bool keyStateChanged (bool isKeyDown);
  31351. /** @internal */
  31352. void focusGained (FocusChangeType cause);
  31353. /** @internal */
  31354. void focusLost (FocusChangeType cause);
  31355. /** @internal */
  31356. void resized();
  31357. /** @internal */
  31358. void enablementChanged();
  31359. /** @internal */
  31360. void colourChanged();
  31361. /** @internal */
  31362. bool isTextInputActive() const;
  31363. /** This adds the items to the popup menu.
  31364. By default it adds the cut/copy/paste items, but you can override this if
  31365. you need to replace these with your own items.
  31366. If you want to add your own items to the existing ones, you can override this,
  31367. call the base class's addPopupMenuItems() method, then append your own items.
  31368. When the menu has been shown, performPopupMenuAction() will be called to
  31369. perform the item that the user has chosen.
  31370. The default menu items will be added using item IDs in the range
  31371. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  31372. menu IDs.
  31373. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  31374. a pointer to the info about it, or may be null if the menu is being triggered
  31375. by some other means.
  31376. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  31377. */
  31378. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  31379. const MouseEvent* mouseClickEvent);
  31380. /** This is called to perform one of the items that was shown on the popup menu.
  31381. If you've overridden addPopupMenuItems(), you should also override this
  31382. to perform the actions that you've added.
  31383. If you've overridden addPopupMenuItems() but have still left the default items
  31384. on the menu, remember to call the superclass's performPopupMenuAction()
  31385. so that it can perform the default actions if that's what the user clicked on.
  31386. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  31387. */
  31388. virtual void performPopupMenuAction (int menuItemID);
  31389. protected:
  31390. /** Scrolls the minimum distance needed to get the caret into view. */
  31391. void scrollToMakeSureCursorIsVisible();
  31392. /** @internal */
  31393. void moveCaret (int newCaretPos);
  31394. /** @internal */
  31395. void moveCursorTo (int newPosition, bool isSelecting);
  31396. /** Used internally to dispatch a text-change message. */
  31397. void textChanged();
  31398. /** Begins a new transaction in the UndoManager.
  31399. */
  31400. void newTransaction();
  31401. /** Used internally to trigger an undo or redo. */
  31402. void doUndoRedo (bool isRedo);
  31403. /** Can be overridden to intercept return key presses directly */
  31404. virtual void returnPressed();
  31405. /** Can be overridden to intercept escape key presses directly */
  31406. virtual void escapePressed();
  31407. /** @internal */
  31408. void handleCommandMessage (int commandId);
  31409. private:
  31410. class Iterator;
  31411. class UniformTextSection;
  31412. class TextHolderComponent;
  31413. class InsertAction;
  31414. class RemoveAction;
  31415. friend class InsertAction;
  31416. friend class RemoveAction;
  31417. ScopedPointer <Viewport> viewport;
  31418. TextHolderComponent* textHolder;
  31419. BorderSize<int> borderSize;
  31420. bool readOnly : 1;
  31421. bool multiline : 1;
  31422. bool wordWrap : 1;
  31423. bool returnKeyStartsNewLine : 1;
  31424. bool caretVisible : 1;
  31425. bool popupMenuEnabled : 1;
  31426. bool selectAllTextWhenFocused : 1;
  31427. bool scrollbarVisible : 1;
  31428. bool wasFocused : 1;
  31429. bool caretFlashState : 1;
  31430. bool keepCursorOnScreen : 1;
  31431. bool tabKeyUsed : 1;
  31432. bool menuActive : 1;
  31433. bool valueTextNeedsUpdating : 1;
  31434. UndoManager undoManager;
  31435. float cursorX, cursorY, cursorHeight;
  31436. int maxTextLength;
  31437. Range<int> selection;
  31438. int leftIndent, topIndent;
  31439. unsigned int lastTransactionTime;
  31440. Font currentFont;
  31441. mutable int totalNumChars;
  31442. int caretPosition;
  31443. Array <UniformTextSection*> sections;
  31444. String textToShowWhenEmpty;
  31445. Colour colourForTextWhenEmpty;
  31446. juce_wchar passwordCharacter;
  31447. Value textValue;
  31448. enum
  31449. {
  31450. notDragging,
  31451. draggingSelectionStart,
  31452. draggingSelectionEnd
  31453. } dragType;
  31454. String allowedCharacters;
  31455. ListenerList <Listener> listeners;
  31456. void coalesceSimilarSections();
  31457. void splitSection (int sectionIndex, int charToSplitAt);
  31458. void clearInternal (UndoManager* um);
  31459. void insert (const String& text, int insertIndex, const Font& font,
  31460. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  31461. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  31462. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  31463. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  31464. void updateCaretPosition();
  31465. void textWasChangedByValue();
  31466. int indexAtPosition (float x, float y);
  31467. int findWordBreakAfter (int position) const;
  31468. int findWordBreakBefore (int position) const;
  31469. friend class TextHolderComponent;
  31470. friend class TextEditorViewport;
  31471. void drawContent (Graphics& g);
  31472. void updateTextHolderSize();
  31473. float getWordWrapWidth() const;
  31474. void timerCallbackInt();
  31475. void repaintCaret();
  31476. void repaintText (const Range<int>& range);
  31477. UndoManager* getUndoManager() throw();
  31478. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditor);
  31479. };
  31480. /** This typedef is just for compatibility with old code - newer code should use the TextEditor::Listener class directly. */
  31481. typedef TextEditor::Listener TextEditorListener;
  31482. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  31483. /*** End of inlined file: juce_TextEditor.h ***/
  31484. #if JUCE_VC6
  31485. #define Listener ButtonListener
  31486. #endif
  31487. /**
  31488. A component that displays a text string, and can optionally become a text
  31489. editor when clicked.
  31490. */
  31491. class JUCE_API Label : public Component,
  31492. public SettableTooltipClient,
  31493. protected TextEditorListener,
  31494. private ComponentListener,
  31495. private ValueListener
  31496. {
  31497. public:
  31498. /** Creates a Label.
  31499. @param componentName the name to give the component
  31500. @param labelText the text to show in the label
  31501. */
  31502. Label (const String& componentName = String::empty,
  31503. const String& labelText = String::empty);
  31504. /** Destructor. */
  31505. ~Label();
  31506. /** Changes the label text.
  31507. If broadcastChangeMessage is true and the new text is different to the current
  31508. text, then the class will broadcast a change message to any Label::Listener objects
  31509. that are registered.
  31510. */
  31511. void setText (const String& newText, bool broadcastChangeMessage);
  31512. /** Returns the label's current text.
  31513. @param returnActiveEditorContents if this is true and the label is currently
  31514. being edited, then this method will return the
  31515. text as it's being shown in the editor. If false,
  31516. then the value returned here won't be updated until
  31517. the user has finished typing and pressed the return
  31518. key.
  31519. */
  31520. const String getText (bool returnActiveEditorContents = false) const;
  31521. /** Returns the text content as a Value object.
  31522. You can call Value::referTo() on this object to make the label read and control
  31523. a Value object that you supply.
  31524. */
  31525. Value& getTextValue() { return textValue; }
  31526. /** Changes the font to use to draw the text.
  31527. @see getFont
  31528. */
  31529. void setFont (const Font& newFont);
  31530. /** Returns the font currently being used.
  31531. @see setFont
  31532. */
  31533. const Font& getFont() const throw();
  31534. /** A set of colour IDs to use to change the colour of various aspects of the label.
  31535. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31536. methods.
  31537. Note that you can also use the constants from TextEditor::ColourIds to change the
  31538. colour of the text editor that is opened when a label is editable.
  31539. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31540. */
  31541. enum ColourIds
  31542. {
  31543. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  31544. textColourId = 0x1000281, /**< The colour for the text. */
  31545. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  31546. Leave this transparent to not have an outline. */
  31547. };
  31548. /** Sets the style of justification to be used for positioning the text.
  31549. (The default is Justification::centredLeft)
  31550. */
  31551. void setJustificationType (const Justification& justification);
  31552. /** Returns the type of justification, as set in setJustificationType(). */
  31553. const Justification getJustificationType() const throw() { return justification; }
  31554. /** Changes the gap that is left between the edge of the component and the text.
  31555. By default there's a small gap left at the sides of the component to allow for
  31556. the drawing of the border, but you can change this if necessary.
  31557. */
  31558. void setBorderSize (int horizontalBorder, int verticalBorder);
  31559. /** Returns the size of the horizontal gap being left around the text.
  31560. */
  31561. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  31562. /** Returns the size of the vertical gap being left around the text.
  31563. */
  31564. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  31565. /** Makes this label "stick to" another component.
  31566. This will cause the label to follow another component around, staying
  31567. either to its left or above it.
  31568. @param owner the component to follow
  31569. @param onLeft if true, the label will stay on the left of its component; if
  31570. false, it will stay above it.
  31571. */
  31572. void attachToComponent (Component* owner, bool onLeft);
  31573. /** If this label has been attached to another component using attachToComponent, this
  31574. returns the other component.
  31575. Returns 0 if the label is not attached.
  31576. */
  31577. Component* getAttachedComponent() const;
  31578. /** If the label is attached to the left of another component, this returns true.
  31579. Returns false if the label is above the other component. This is only relevent if
  31580. attachToComponent() has been called.
  31581. */
  31582. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  31583. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  31584. using ellipsis.
  31585. @see Graphics::drawFittedText
  31586. */
  31587. void setMinimumHorizontalScale (float newScale);
  31588. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  31589. /**
  31590. A class for receiving events from a Label.
  31591. You can register a Label::Listener with a Label using the Label::addListener()
  31592. method, and it will be called when the text of the label changes, either because
  31593. of a call to Label::setText() or by the user editing the text (if the label is
  31594. editable).
  31595. @see Label::addListener, Label::removeListener
  31596. */
  31597. class JUCE_API Listener
  31598. {
  31599. public:
  31600. /** Destructor. */
  31601. virtual ~Listener() {}
  31602. /** Called when a Label's text has changed.
  31603. */
  31604. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  31605. };
  31606. /** Registers a listener that will be called when the label's text changes. */
  31607. void addListener (Listener* listener);
  31608. /** Deregisters a previously-registered listener. */
  31609. void removeListener (Listener* listener);
  31610. /** Makes the label turn into a TextEditor when clicked.
  31611. By default this is turned off.
  31612. If turned on, then single- or double-clicking will turn the label into
  31613. an editor. If the user then changes the text, then the ChangeBroadcaster
  31614. base class will be used to send change messages to any listeners that
  31615. have registered.
  31616. If the user changes the text, the textWasEdited() method will be called
  31617. afterwards, and subclasses can override this if they need to do anything
  31618. special.
  31619. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  31620. @param editOnDoubleClick if true, a double-click is needed to start editing
  31621. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  31622. edited will discard any changes; if false, then this will
  31623. commit the changes.
  31624. @see showEditor, setEditorColours, TextEditor
  31625. */
  31626. void setEditable (bool editOnSingleClick,
  31627. bool editOnDoubleClick = false,
  31628. bool lossOfFocusDiscardsChanges = false);
  31629. /** Returns true if this option was set using setEditable(). */
  31630. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  31631. /** Returns true if this option was set using setEditable(). */
  31632. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  31633. /** Returns true if this option has been set in a call to setEditable(). */
  31634. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  31635. /** Returns true if the user can edit this label's text. */
  31636. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  31637. /** Makes the editor appear as if the label had been clicked by the user.
  31638. @see textWasEdited, setEditable
  31639. */
  31640. void showEditor();
  31641. /** Hides the editor if it was being shown.
  31642. @param discardCurrentEditorContents if true, the label's text will be
  31643. reset to whatever it was before the editor
  31644. was shown; if false, the current contents of the
  31645. editor will be used to set the label's text
  31646. before it is hidden.
  31647. */
  31648. void hideEditor (bool discardCurrentEditorContents);
  31649. /** Returns true if the editor is currently focused and active. */
  31650. bool isBeingEdited() const throw();
  31651. protected:
  31652. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  31653. Subclasses can override this if they need to customise this component in some way.
  31654. */
  31655. virtual TextEditor* createEditorComponent();
  31656. /** Called after the user changes the text. */
  31657. virtual void textWasEdited();
  31658. /** Called when the text has been altered. */
  31659. virtual void textWasChanged();
  31660. /** Called when the text editor has just appeared, due to a user click or other focus change. */
  31661. virtual void editorShown (TextEditor* editorComponent);
  31662. /** Called when the text editor is going to be deleted, after editing has finished. */
  31663. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  31664. /** @internal */
  31665. void paint (Graphics& g);
  31666. /** @internal */
  31667. void resized();
  31668. /** @internal */
  31669. void mouseUp (const MouseEvent& e);
  31670. /** @internal */
  31671. void mouseDoubleClick (const MouseEvent& e);
  31672. /** @internal */
  31673. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  31674. /** @internal */
  31675. void componentParentHierarchyChanged (Component& component);
  31676. /** @internal */
  31677. void componentVisibilityChanged (Component& component);
  31678. /** @internal */
  31679. void inputAttemptWhenModal();
  31680. /** @internal */
  31681. void focusGained (FocusChangeType);
  31682. /** @internal */
  31683. void enablementChanged();
  31684. /** @internal */
  31685. KeyboardFocusTraverser* createFocusTraverser();
  31686. /** @internal */
  31687. void textEditorTextChanged (TextEditor& editor);
  31688. /** @internal */
  31689. void textEditorReturnKeyPressed (TextEditor& editor);
  31690. /** @internal */
  31691. void textEditorEscapeKeyPressed (TextEditor& editor);
  31692. /** @internal */
  31693. void textEditorFocusLost (TextEditor& editor);
  31694. /** @internal */
  31695. void colourChanged();
  31696. /** @internal */
  31697. void valueChanged (Value&);
  31698. private:
  31699. Value textValue;
  31700. String lastTextValue;
  31701. Font font;
  31702. Justification justification;
  31703. ScopedPointer<TextEditor> editor;
  31704. ListenerList<Listener> listeners;
  31705. WeakReference<Component> ownerComponent;
  31706. int horizontalBorderSize, verticalBorderSize;
  31707. float minimumHorizontalScale;
  31708. bool editSingleClick : 1;
  31709. bool editDoubleClick : 1;
  31710. bool lossOfFocusDiscardsChanges : 1;
  31711. bool leftOfOwnerComp : 1;
  31712. bool updateFromTextEditorContents (TextEditor&);
  31713. void callChangeListeners();
  31714. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Label);
  31715. };
  31716. /** This typedef is just for compatibility with old code - newer code should use the Label::Listener class directly. */
  31717. typedef Label::Listener LabelListener;
  31718. #if JUCE_VC6
  31719. #undef Listener
  31720. #endif
  31721. #endif // __JUCE_LABEL_JUCEHEADER__
  31722. /*** End of inlined file: juce_Label.h ***/
  31723. #if JUCE_VC6
  31724. #define Listener SliderListener
  31725. #endif
  31726. /**
  31727. A component that lets the user choose from a drop-down list of choices.
  31728. The combo-box has a list of text strings, each with an associated id number,
  31729. that will be shown in the drop-down list when the user clicks on the component.
  31730. The currently selected choice is displayed in the combo-box, and this can
  31731. either be read-only text, or editable.
  31732. To find out when the user selects a different item or edits the text, you
  31733. can register a ComboBox::Listener to receive callbacks.
  31734. @see ComboBox::Listener
  31735. */
  31736. class JUCE_API ComboBox : public Component,
  31737. public SettableTooltipClient,
  31738. public LabelListener, // (can't use Label::Listener due to idiotic VC2005 bug)
  31739. public ValueListener,
  31740. private AsyncUpdater
  31741. {
  31742. public:
  31743. /** Creates a combo-box.
  31744. On construction, the text field will be empty, so you should call the
  31745. setSelectedId() or setText() method to choose the initial value before
  31746. displaying it.
  31747. @param componentName the name to set for the component (see Component::setName())
  31748. */
  31749. explicit ComboBox (const String& componentName = String::empty);
  31750. /** Destructor. */
  31751. ~ComboBox();
  31752. /** Sets whether the test in the combo-box is editable.
  31753. The default state for a new ComboBox is non-editable, and can only be changed
  31754. by choosing from the drop-down list.
  31755. */
  31756. void setEditableText (bool isEditable);
  31757. /** Returns true if the text is directly editable.
  31758. @see setEditableText
  31759. */
  31760. bool isTextEditable() const throw();
  31761. /** Sets the style of justification to be used for positioning the text.
  31762. The default is Justification::centredLeft. The text is displayed using a
  31763. Label component inside the ComboBox.
  31764. */
  31765. void setJustificationType (const Justification& justification);
  31766. /** Returns the current justification for the text box.
  31767. @see setJustificationType
  31768. */
  31769. const Justification getJustificationType() const throw();
  31770. /** Adds an item to be shown in the drop-down list.
  31771. @param newItemText the text of the item to show in the list
  31772. @param newItemId an associated ID number that can be set or retrieved - see
  31773. getSelectedId() and setSelectedId(). Note that this value can not
  31774. be 0!
  31775. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  31776. */
  31777. void addItem (const String& newItemText, int newItemId);
  31778. /** Adds a separator line to the drop-down list.
  31779. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  31780. */
  31781. void addSeparator();
  31782. /** Adds a heading to the drop-down list, so that you can group the items into
  31783. different sections.
  31784. The headings are indented slightly differently to set them apart from the
  31785. items on the list, and obviously can't be selected. You might want to add
  31786. separators between your sections too.
  31787. @see addItem, addSeparator
  31788. */
  31789. void addSectionHeading (const String& headingName);
  31790. /** This allows items in the drop-down list to be selectively disabled.
  31791. When you add an item, it's enabled by default, but you can call this
  31792. method to change its status.
  31793. If you disable an item which is already selected, this won't change the
  31794. current selection - it just stops the user choosing that item from the list.
  31795. */
  31796. void setItemEnabled (int itemId, bool shouldBeEnabled);
  31797. /** Returns true if the given item is enabled. */
  31798. bool isItemEnabled (int itemId) const throw();
  31799. /** Changes the text for an existing item.
  31800. */
  31801. void changeItemText (int itemId, const String& newText);
  31802. /** Removes all the items from the drop-down list.
  31803. If this call causes the content to be cleared, then a change-message
  31804. will be broadcast unless dontSendChangeMessage is true.
  31805. @see addItem, removeItem, getNumItems
  31806. */
  31807. void clear (bool dontSendChangeMessage = false);
  31808. /** Returns the number of items that have been added to the list.
  31809. Note that this doesn't include headers or separators.
  31810. */
  31811. int getNumItems() const throw();
  31812. /** Returns the text for one of the items in the list.
  31813. Note that this doesn't include headers or separators.
  31814. @param index the item's index from 0 to (getNumItems() - 1)
  31815. */
  31816. const String getItemText (int index) const;
  31817. /** Returns the ID for one of the items in the list.
  31818. Note that this doesn't include headers or separators.
  31819. @param index the item's index from 0 to (getNumItems() - 1)
  31820. */
  31821. int getItemId (int index) const throw();
  31822. /** Returns the index in the list of a particular item ID.
  31823. If no such ID is found, this will return -1.
  31824. */
  31825. int indexOfItemId (int itemId) const throw();
  31826. /** Returns the ID of the item that's currently shown in the box.
  31827. If no item is selected, or if the text is editable and the user
  31828. has entered something which isn't one of the items in the list, then
  31829. this will return 0.
  31830. @see setSelectedId, getSelectedItemIndex, getText
  31831. */
  31832. int getSelectedId() const throw();
  31833. /** Returns a Value object that can be used to get or set the selected item's ID.
  31834. You can call Value::referTo() on this object to make the combo box control
  31835. another Value object.
  31836. */
  31837. Value& getSelectedIdAsValue() { return currentId; }
  31838. /** Sets one of the items to be the current selection.
  31839. This will set the ComboBox's text to that of the item that matches
  31840. this ID.
  31841. @param newItemId the new item to select
  31842. @param dontSendChangeMessage if set to true, this method won't trigger a
  31843. change notification
  31844. @see getSelectedId, setSelectedItemIndex, setText
  31845. */
  31846. void setSelectedId (int newItemId, bool dontSendChangeMessage = false);
  31847. /** Returns the index of the item that's currently shown in the box.
  31848. If no item is selected, or if the text is editable and the user
  31849. has entered something which isn't one of the items in the list, then
  31850. this will return -1.
  31851. @see setSelectedItemIndex, getSelectedId, getText
  31852. */
  31853. int getSelectedItemIndex() const;
  31854. /** Sets one of the items to be the current selection.
  31855. This will set the ComboBox's text to that of the item at the given
  31856. index in the list.
  31857. @param newItemIndex the new item to select
  31858. @param dontSendChangeMessage if set to true, this method won't trigger a
  31859. change notification
  31860. @see getSelectedItemIndex, setSelectedId, setText
  31861. */
  31862. void setSelectedItemIndex (int newItemIndex, bool dontSendChangeMessage = false);
  31863. /** Returns the text that is currently shown in the combo-box's text field.
  31864. If the ComboBox has editable text, then this text may have been edited
  31865. by the user; otherwise it will be one of the items from the list, or
  31866. possibly an empty string if nothing was selected.
  31867. @see setText, getSelectedId, getSelectedItemIndex
  31868. */
  31869. const String getText() const;
  31870. /** Sets the contents of the combo-box's text field.
  31871. The text passed-in will be set as the current text regardless of whether
  31872. it is one of the items in the list. If the current text isn't one of the
  31873. items, then getSelectedId() will return -1, otherwise it wil return
  31874. the approriate ID.
  31875. @param newText the text to select
  31876. @param dontSendChangeMessage if set to true, this method won't trigger a
  31877. change notification
  31878. @see getText
  31879. */
  31880. void setText (const String& newText, bool dontSendChangeMessage = false);
  31881. /** Programmatically opens the text editor to allow the user to edit the current item.
  31882. This is the same effect as when the box is clicked-on.
  31883. @see Label::showEditor();
  31884. */
  31885. void showEditor();
  31886. /** Pops up the combo box's list. */
  31887. void showPopup();
  31888. /**
  31889. A class for receiving events from a ComboBox.
  31890. You can register a ComboBox::Listener with a ComboBox using the ComboBox::addListener()
  31891. method, and it will be called when the selected item in the box changes.
  31892. @see ComboBox::addListener, ComboBox::removeListener
  31893. */
  31894. class JUCE_API Listener
  31895. {
  31896. public:
  31897. /** Destructor. */
  31898. virtual ~Listener() {}
  31899. /** Called when a ComboBox has its selected item changed. */
  31900. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  31901. };
  31902. /** Registers a listener that will be called when the box's content changes. */
  31903. void addListener (Listener* listener);
  31904. /** Deregisters a previously-registered listener. */
  31905. void removeListener (Listener* listener);
  31906. /** Sets a message to display when there is no item currently selected.
  31907. @see getTextWhenNothingSelected
  31908. */
  31909. void setTextWhenNothingSelected (const String& newMessage);
  31910. /** Returns the text that is shown when no item is selected.
  31911. @see setTextWhenNothingSelected
  31912. */
  31913. const String getTextWhenNothingSelected() const;
  31914. /** Sets the message to show when there are no items in the list, and the user clicks
  31915. on the drop-down box.
  31916. By default it just says "no choices", but this lets you change it to something more
  31917. meaningful.
  31918. */
  31919. void setTextWhenNoChoicesAvailable (const String& newMessage);
  31920. /** Returns the text shown when no items have been added to the list.
  31921. @see setTextWhenNoChoicesAvailable
  31922. */
  31923. const String getTextWhenNoChoicesAvailable() const;
  31924. /** Gives the ComboBox a tooltip. */
  31925. void setTooltip (const String& newTooltip);
  31926. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  31927. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31928. methods.
  31929. To change the colours of the menu that pops up
  31930. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31931. */
  31932. enum ColourIds
  31933. {
  31934. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  31935. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  31936. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  31937. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  31938. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  31939. };
  31940. /** @internal */
  31941. void labelTextChanged (Label*);
  31942. /** @internal */
  31943. void enablementChanged();
  31944. /** @internal */
  31945. void colourChanged();
  31946. /** @internal */
  31947. void focusGained (Component::FocusChangeType cause);
  31948. /** @internal */
  31949. void focusLost (Component::FocusChangeType cause);
  31950. /** @internal */
  31951. void handleAsyncUpdate();
  31952. /** @internal */
  31953. const String getTooltip() { return label->getTooltip(); }
  31954. /** @internal */
  31955. void mouseDown (const MouseEvent&);
  31956. /** @internal */
  31957. void mouseDrag (const MouseEvent&);
  31958. /** @internal */
  31959. void mouseUp (const MouseEvent&);
  31960. /** @internal */
  31961. void lookAndFeelChanged();
  31962. /** @internal */
  31963. void paint (Graphics&);
  31964. /** @internal */
  31965. void resized();
  31966. /** @internal */
  31967. bool keyStateChanged (bool isKeyDown);
  31968. /** @internal */
  31969. bool keyPressed (const KeyPress&);
  31970. /** @internal */
  31971. void valueChanged (Value&);
  31972. private:
  31973. struct ItemInfo
  31974. {
  31975. ItemInfo (const String& name, int itemId, bool isEnabled, bool isHeading);
  31976. bool isSeparator() const throw();
  31977. bool isRealItem() const throw();
  31978. String name;
  31979. int itemId;
  31980. bool isEnabled : 1, isHeading : 1;
  31981. };
  31982. class Callback;
  31983. friend class Callback;
  31984. OwnedArray <ItemInfo> items;
  31985. Value currentId;
  31986. int lastCurrentId;
  31987. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  31988. ListenerList <Listener> listeners;
  31989. ScopedPointer<Label> label;
  31990. String textWhenNothingSelected, noChoicesMessage;
  31991. ItemInfo* getItemForId (int itemId) const throw();
  31992. ItemInfo* getItemForIndex (int index) const throw();
  31993. bool selectIfEnabled (int index);
  31994. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBox);
  31995. };
  31996. /** This typedef is just for compatibility with old code - newer code should use the ComboBox::Listener class directly. */
  31997. typedef ComboBox::Listener ComboBoxListener;
  31998. #if JUCE_VC6
  31999. #undef Listener
  32000. #endif
  32001. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  32002. /*** End of inlined file: juce_ComboBox.h ***/
  32003. /**
  32004. Manages the state of some audio and midi i/o devices.
  32005. This class keeps tracks of a currently-selected audio device, through
  32006. with which it continuously streams data from an audio callback, as well as
  32007. one or more midi inputs.
  32008. The idea is that your application will create one global instance of this object,
  32009. and let it take care of creating and deleting specific types of audio devices
  32010. internally. So when the device is changed, your callbacks will just keep running
  32011. without having to worry about this.
  32012. The manager can save and reload all of its device settings as XML, which
  32013. makes it very easy for you to save and reload the audio setup of your
  32014. application.
  32015. And to make it easy to let the user change its settings, there's a component
  32016. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  32017. device selection/sample-rate/latency controls.
  32018. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  32019. call addAudioCallback() to register your audio callback with it, and use that to process
  32020. your audio data.
  32021. The manager also acts as a handy hub for incoming midi messages, allowing a
  32022. listener to register for messages from either a specific midi device, or from whatever
  32023. the current default midi input device is. The listener then doesn't have to worry about
  32024. re-registering with different midi devices if they are changed or deleted.
  32025. And yet another neat trick is that amount of CPU time being used is measured and
  32026. available with the getCpuUsage() method.
  32027. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  32028. listeners whenever one of its settings is changed.
  32029. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  32030. */
  32031. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  32032. {
  32033. public:
  32034. /** Creates a default AudioDeviceManager.
  32035. Initially no audio device will be selected. You should call the initialise() method
  32036. and register an audio callback with setAudioCallback() before it'll be able to
  32037. actually make any noise.
  32038. */
  32039. AudioDeviceManager();
  32040. /** Destructor. */
  32041. ~AudioDeviceManager();
  32042. /**
  32043. This structure holds a set of properties describing the current audio setup.
  32044. An AudioDeviceManager uses this class to save/load its current settings, and to
  32045. specify your preferred options when opening a device.
  32046. @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
  32047. */
  32048. struct JUCE_API AudioDeviceSetup
  32049. {
  32050. /** Creates an AudioDeviceSetup object.
  32051. The default constructor sets all the member variables to indicate default values.
  32052. You can then fill-in any values you want to before passing the object to
  32053. AudioDeviceManager::initialise().
  32054. */
  32055. AudioDeviceSetup();
  32056. bool operator== (const AudioDeviceSetup& other) const;
  32057. /** The name of the audio device used for output.
  32058. The name has to be one of the ones listed by the AudioDeviceManager's currently
  32059. selected device type.
  32060. This may be the same as the input device.
  32061. An empty string indicates the default device.
  32062. */
  32063. String outputDeviceName;
  32064. /** The name of the audio device used for input.
  32065. This may be the same as the output device.
  32066. An empty string indicates the default device.
  32067. */
  32068. String inputDeviceName;
  32069. /** The current sample rate.
  32070. This rate is used for both the input and output devices.
  32071. A value of 0 indicates the default rate.
  32072. */
  32073. double sampleRate;
  32074. /** The buffer size, in samples.
  32075. This buffer size is used for both the input and output devices.
  32076. A value of 0 indicates the default buffer size.
  32077. */
  32078. int bufferSize;
  32079. /** The set of active input channels.
  32080. The bits that are set in this array indicate the channels of the
  32081. input device that are active.
  32082. If useDefaultInputChannels is true, this value is ignored.
  32083. */
  32084. BigInteger inputChannels;
  32085. /** If this is true, it indicates that the inputChannels array
  32086. should be ignored, and instead, the device's default channels
  32087. should be used.
  32088. */
  32089. bool useDefaultInputChannels;
  32090. /** The set of active output channels.
  32091. The bits that are set in this array indicate the channels of the
  32092. input device that are active.
  32093. If useDefaultOutputChannels is true, this value is ignored.
  32094. */
  32095. BigInteger outputChannels;
  32096. /** If this is true, it indicates that the outputChannels array
  32097. should be ignored, and instead, the device's default channels
  32098. should be used.
  32099. */
  32100. bool useDefaultOutputChannels;
  32101. };
  32102. /** Opens a set of audio devices ready for use.
  32103. This will attempt to open either a default audio device, or one that was
  32104. previously saved as XML.
  32105. @param numInputChannelsNeeded a minimum number of input channels needed
  32106. by your app.
  32107. @param numOutputChannelsNeeded a minimum number of output channels to open
  32108. @param savedState either a previously-saved state that was produced
  32109. by createStateXml(), or 0 if you want the manager
  32110. to choose the best device to open.
  32111. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  32112. fails to open, then a default device will be used
  32113. instead. If false, then on failure, no device is
  32114. opened.
  32115. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  32116. name, then that will be used as the default device
  32117. (assuming that there wasn't one specified in the XML).
  32118. The string can actually be a simple wildcard, containing "*"
  32119. and "?" characters
  32120. @param preferredSetupOptions if this is non-null, the structure will be used as the
  32121. set of preferred settings when opening the device. If you
  32122. use this parameter, the preferredDefaultDeviceName
  32123. field will be ignored
  32124. @returns an error message if anything went wrong, or an empty string if it worked ok.
  32125. */
  32126. const String initialise (int numInputChannelsNeeded,
  32127. int numOutputChannelsNeeded,
  32128. const XmlElement* savedState,
  32129. bool selectDefaultDeviceOnFailure,
  32130. const String& preferredDefaultDeviceName = String::empty,
  32131. const AudioDeviceSetup* preferredSetupOptions = 0);
  32132. /** Returns some XML representing the current state of the manager.
  32133. This stores the current device, its samplerate, block size, etc, and
  32134. can be restored later with initialise().
  32135. */
  32136. XmlElement* createStateXml() const;
  32137. /** Returns the current device properties that are in use.
  32138. @see setAudioDeviceSetup
  32139. */
  32140. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  32141. /** Changes the current device or its settings.
  32142. If you want to change a device property, like the current sample rate or
  32143. block size, you can call getAudioDeviceSetup() to retrieve the current
  32144. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  32145. and pass it back into this method to apply the new settings.
  32146. @param newSetup the settings that you'd like to use
  32147. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  32148. settings will be taken as having been explicitly chosen by the
  32149. user, and the next time createStateXml() is called, these settings
  32150. will be returned. If it's false, then the device is treated as a
  32151. temporary or default device, and a call to createStateXml() will
  32152. return either the last settings that were made with treatAsChosenDevice
  32153. as true, or the last XML settings that were passed into initialise().
  32154. @returns an error message if anything went wrong, or an empty string if it worked ok.
  32155. @see getAudioDeviceSetup
  32156. */
  32157. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  32158. bool treatAsChosenDevice);
  32159. /** Returns the currently-active audio device. */
  32160. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  32161. /** Returns the type of audio device currently in use.
  32162. @see setCurrentAudioDeviceType
  32163. */
  32164. const String getCurrentAudioDeviceType() const { return currentDeviceType; }
  32165. /** Returns the currently active audio device type object.
  32166. Don't keep a copy of this pointer - it's owned by the device manager and could
  32167. change at any time.
  32168. */
  32169. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  32170. /** Changes the class of audio device being used.
  32171. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  32172. this because there's only one type: CoreAudio.
  32173. For a list of types, see getAvailableDeviceTypes().
  32174. */
  32175. void setCurrentAudioDeviceType (const String& type,
  32176. bool treatAsChosenDevice);
  32177. /** Closes the currently-open device.
  32178. You can call restartLastAudioDevice() later to reopen it in the same state
  32179. that it was just in.
  32180. */
  32181. void closeAudioDevice();
  32182. /** Tries to reload the last audio device that was running.
  32183. Note that this only reloads the last device that was running before
  32184. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  32185. and can only be called after a device has been opened with SetAudioDevice().
  32186. If a device is already open, this call will do nothing.
  32187. */
  32188. void restartLastAudioDevice();
  32189. /** Registers an audio callback to be used.
  32190. The manager will redirect callbacks from whatever audio device is currently
  32191. in use to all registered callback objects. If more than one callback is
  32192. active, they will all be given the same input data, and their outputs will
  32193. be summed.
  32194. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  32195. object before returning.
  32196. To remove a callback, use removeAudioCallback().
  32197. */
  32198. void addAudioCallback (AudioIODeviceCallback* newCallback);
  32199. /** Deregisters a previously added callback.
  32200. If necessary, this method will invoke audioDeviceStopped() on the callback
  32201. object before returning.
  32202. @see addAudioCallback
  32203. */
  32204. void removeAudioCallback (AudioIODeviceCallback* callback);
  32205. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  32206. Returns a value between 0 and 1.0
  32207. */
  32208. double getCpuUsage() const;
  32209. /** Enables or disables a midi input device.
  32210. The list of devices can be obtained with the MidiInput::getDevices() method.
  32211. Any incoming messages from enabled input devices will be forwarded on to all the
  32212. listeners that have been registered with the addMidiInputCallback() method. They
  32213. can either register for messages from a particular device, or from just the
  32214. "default" midi input.
  32215. Routing the midi input via an AudioDeviceManager means that when a listener
  32216. registers for the default midi input, this default device can be changed by the
  32217. manager without the listeners having to know about it or re-register.
  32218. It also means that a listener can stay registered for a midi input that is disabled
  32219. or not present, so that when the input is re-enabled, the listener will start
  32220. receiving messages again.
  32221. @see addMidiInputCallback, isMidiInputEnabled
  32222. */
  32223. void setMidiInputEnabled (const String& midiInputDeviceName,
  32224. bool enabled);
  32225. /** Returns true if a given midi input device is being used.
  32226. @see setMidiInputEnabled
  32227. */
  32228. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  32229. /** Registers a listener for callbacks when midi events arrive from a midi input.
  32230. The device name can be empty to indicate that it wants events from whatever the
  32231. current "default" device is. Or it can be the name of one of the midi input devices
  32232. (see MidiInput::getDevices() for the names).
  32233. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  32234. events forwarded on to listeners.
  32235. */
  32236. void addMidiInputCallback (const String& midiInputDeviceName,
  32237. MidiInputCallback* callback);
  32238. /** Removes a listener that was previously registered with addMidiInputCallback().
  32239. */
  32240. void removeMidiInputCallback (const String& midiInputDeviceName,
  32241. MidiInputCallback* callback);
  32242. /** Sets a midi output device to use as the default.
  32243. The list of devices can be obtained with the MidiOutput::getDevices() method.
  32244. The specified device will be opened automatically and can be retrieved with the
  32245. getDefaultMidiOutput() method.
  32246. Pass in an empty string to deselect all devices. For the default device, you
  32247. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  32248. @see getDefaultMidiOutput, getDefaultMidiOutputName
  32249. */
  32250. void setDefaultMidiOutput (const String& deviceName);
  32251. /** Returns the name of the default midi output.
  32252. @see setDefaultMidiOutput, getDefaultMidiOutput
  32253. */
  32254. const String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  32255. /** Returns the current default midi output device.
  32256. If no device has been selected, or the device can't be opened, this will
  32257. return 0.
  32258. @see getDefaultMidiOutputName
  32259. */
  32260. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  32261. /** Returns a list of the types of device supported.
  32262. */
  32263. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  32264. /** Creates a list of available types.
  32265. This will add a set of new AudioIODeviceType objects to the specified list, to
  32266. represent each available types of device.
  32267. You can override this if your app needs to do something specific, like avoid
  32268. using DirectSound devices, etc.
  32269. */
  32270. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  32271. /** Plays a beep through the current audio device.
  32272. This is here to allow the audio setup UI panels to easily include a "test"
  32273. button so that the user can check where the audio is coming from.
  32274. */
  32275. void playTestSound();
  32276. /** Turns on level-measuring.
  32277. When enabled, the device manager will measure the peak input level
  32278. across all channels, and you can get this level by calling getCurrentInputLevel().
  32279. This is mainly intended for audio setup UI panels to use to create a mic
  32280. level display, so that the user can check that they've selected the right
  32281. device.
  32282. A simple filter is used to make the level decay smoothly, but this is
  32283. only intended for giving rough feedback, and not for any kind of accurate
  32284. measurement.
  32285. */
  32286. void enableInputLevelMeasurement (bool enableMeasurement);
  32287. /** Returns the current input level.
  32288. To use this, you must first enable it by calling enableInputLevelMeasurement().
  32289. See enableInputLevelMeasurement() for more info.
  32290. */
  32291. double getCurrentInputLevel() const;
  32292. /** Returns the a lock that can be used to synchronise access to the audio callback.
  32293. Obviously while this is locked, you're blocking the audio thread from running, so
  32294. it must only be used for very brief periods when absolutely necessary.
  32295. */
  32296. CriticalSection& getAudioCallbackLock() throw() { return audioCallbackLock; }
  32297. /** Returns the a lock that can be used to synchronise access to the midi callback.
  32298. Obviously while this is locked, you're blocking the midi system from running, so
  32299. it must only be used for very brief periods when absolutely necessary.
  32300. */
  32301. CriticalSection& getMidiCallbackLock() throw() { return midiCallbackLock; }
  32302. private:
  32303. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  32304. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  32305. AudioDeviceSetup currentSetup;
  32306. ScopedPointer <AudioIODevice> currentAudioDevice;
  32307. SortedSet <AudioIODeviceCallback*> callbacks;
  32308. int numInputChansNeeded, numOutputChansNeeded;
  32309. String currentDeviceType;
  32310. BigInteger inputChannels, outputChannels;
  32311. ScopedPointer <XmlElement> lastExplicitSettings;
  32312. mutable bool listNeedsScanning;
  32313. bool useInputNames;
  32314. int inputLevelMeasurementEnabledCount;
  32315. double inputLevel;
  32316. ScopedPointer <AudioSampleBuffer> testSound;
  32317. int testSoundPosition;
  32318. AudioSampleBuffer tempBuffer;
  32319. StringArray midiInsFromXml;
  32320. OwnedArray <MidiInput> enabledMidiInputs;
  32321. Array <MidiInputCallback*> midiCallbacks;
  32322. StringArray midiCallbackDevices;
  32323. String defaultMidiOutputName;
  32324. ScopedPointer <MidiOutput> defaultMidiOutput;
  32325. CriticalSection audioCallbackLock, midiCallbackLock;
  32326. double cpuUsageMs, timeToCpuScale;
  32327. class CallbackHandler : public AudioIODeviceCallback,
  32328. public MidiInputCallback
  32329. {
  32330. public:
  32331. AudioDeviceManager* owner;
  32332. void audioDeviceIOCallback (const float** inputChannelData,
  32333. int totalNumInputChannels,
  32334. float** outputChannelData,
  32335. int totalNumOutputChannels,
  32336. int numSamples);
  32337. void audioDeviceAboutToStart (AudioIODevice*);
  32338. void audioDeviceStopped();
  32339. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  32340. };
  32341. CallbackHandler callbackHandler;
  32342. friend class CallbackHandler;
  32343. void audioDeviceIOCallbackInt (const float** inputChannelData,
  32344. int totalNumInputChannels,
  32345. float** outputChannelData,
  32346. int totalNumOutputChannels,
  32347. int numSamples);
  32348. void audioDeviceAboutToStartInt (AudioIODevice* device);
  32349. void audioDeviceStoppedInt();
  32350. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  32351. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  32352. const BigInteger& ins, const BigInteger& outs);
  32353. void stopDevice();
  32354. void updateXml();
  32355. void createDeviceTypesIfNeeded();
  32356. void scanDevicesIfNeeded();
  32357. void deleteCurrentDevice();
  32358. double chooseBestSampleRate (double preferred) const;
  32359. int chooseBestBufferSize (int preferred) const;
  32360. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  32361. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  32362. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager);
  32363. };
  32364. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  32365. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  32366. #endif
  32367. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  32368. #endif
  32369. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  32370. #endif
  32371. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  32372. #endif
  32373. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  32374. #endif
  32375. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  32376. #endif
  32377. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  32378. #endif
  32379. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  32380. /*** Start of inlined file: juce_Decibels.h ***/
  32381. #ifndef __JUCE_DECIBELS_JUCEHEADER__
  32382. #define __JUCE_DECIBELS_JUCEHEADER__
  32383. /**
  32384. This class contains some helpful static methods for dealing with decibel values.
  32385. */
  32386. class Decibels
  32387. {
  32388. public:
  32389. /** Converts a dBFS value to its equivalent gain level.
  32390. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values. Any
  32391. decibel value lower than minusInfinityDb will return a gain of 0.
  32392. */
  32393. template <typename Type>
  32394. static Type decibelsToGain (const Type decibels,
  32395. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  32396. {
  32397. return decibels > minusInfinityDb ? powf ((Type) 10.0, decibels * (Type) 0.05)
  32398. : Type();
  32399. }
  32400. /** Converts a gain level into a dBFS value.
  32401. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values.
  32402. If the gain is 0 (or negative), then the method will return the value
  32403. provided as minusInfinityDb.
  32404. */
  32405. template <typename Type>
  32406. static Type gainToDecibels (const Type gain,
  32407. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  32408. {
  32409. return gain > Type() ? jmax (minusInfinityDb, (Type) std::log (gain) * (Type) 20.0)
  32410. : minusInfinityDb;
  32411. }
  32412. /** Converts a decibel reading to a string, with the 'dB' suffix.
  32413. If the decibel value is lower than minusInfinityDb, the return value will
  32414. be "-INF dB".
  32415. */
  32416. template <typename Type>
  32417. static const String toString (const Type decibels,
  32418. const int decimalPlaces = 2,
  32419. const Type minusInfinityDb = (Type) defaultMinusInfinitydB)
  32420. {
  32421. String s;
  32422. if (decibels <= minusInfinityDb)
  32423. {
  32424. s = "-INF dB";
  32425. }
  32426. else
  32427. {
  32428. if (decibels >= Type())
  32429. s << '+';
  32430. s << String (decibels, decimalPlaces) << " dB";
  32431. }
  32432. return s;
  32433. }
  32434. private:
  32435. enum
  32436. {
  32437. defaultMinusInfinitydB = -100
  32438. };
  32439. Decibels(); // This class can't be instantiated, it's just a holder for static methods..
  32440. JUCE_DECLARE_NON_COPYABLE (Decibels);
  32441. };
  32442. #endif // __JUCE_DECIBELS_JUCEHEADER__
  32443. /*** End of inlined file: juce_Decibels.h ***/
  32444. #endif
  32445. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  32446. #endif
  32447. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  32448. #endif
  32449. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  32450. /*** Start of inlined file: juce_MidiFile.h ***/
  32451. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  32452. #define __JUCE_MIDIFILE_JUCEHEADER__
  32453. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  32454. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  32455. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  32456. /**
  32457. A sequence of timestamped midi messages.
  32458. This allows the sequence to be manipulated, and also to be read from and
  32459. written to a standard midi file.
  32460. @see MidiMessage, MidiFile
  32461. */
  32462. class JUCE_API MidiMessageSequence
  32463. {
  32464. public:
  32465. /** Creates an empty midi sequence object. */
  32466. MidiMessageSequence();
  32467. /** Creates a copy of another sequence. */
  32468. MidiMessageSequence (const MidiMessageSequence& other);
  32469. /** Replaces this sequence with another one. */
  32470. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  32471. /** Destructor. */
  32472. ~MidiMessageSequence();
  32473. /** Structure used to hold midi events in the sequence.
  32474. These structures act as 'handles' on the events as they are moved about in
  32475. the list, and make it quick to find the matching note-offs for note-on events.
  32476. @see MidiMessageSequence::getEventPointer
  32477. */
  32478. class MidiEventHolder
  32479. {
  32480. public:
  32481. /** Destructor. */
  32482. ~MidiEventHolder();
  32483. /** The message itself, whose timestamp is used to specify the event's time.
  32484. */
  32485. MidiMessage message;
  32486. /** The matching note-off event (if this is a note-on event).
  32487. If this isn't a note-on, this pointer will be null.
  32488. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  32489. note-offs up-to-date after events have been moved around in the sequence
  32490. or deleted.
  32491. */
  32492. MidiEventHolder* noteOffObject;
  32493. private:
  32494. friend class MidiMessageSequence;
  32495. MidiEventHolder (const MidiMessage& message);
  32496. JUCE_LEAK_DETECTOR (MidiEventHolder);
  32497. };
  32498. /** Clears the sequence. */
  32499. void clear();
  32500. /** Returns the number of events in the sequence. */
  32501. int getNumEvents() const;
  32502. /** Returns a pointer to one of the events. */
  32503. MidiEventHolder* getEventPointer (int index) const;
  32504. /** Returns the time of the note-up that matches the note-on at this index.
  32505. If the event at this index isn't a note-on, it'll just return 0.
  32506. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  32507. */
  32508. double getTimeOfMatchingKeyUp (int index) const;
  32509. /** Returns the index of the note-up that matches the note-on at this index.
  32510. If the event at this index isn't a note-on, it'll just return -1.
  32511. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  32512. */
  32513. int getIndexOfMatchingKeyUp (int index) const;
  32514. /** Returns the index of an event. */
  32515. int getIndexOf (MidiEventHolder* event) const;
  32516. /** Returns the index of the first event on or after the given timestamp.
  32517. If the time is beyond the end of the sequence, this will return the
  32518. number of events.
  32519. */
  32520. int getNextIndexAtTime (double timeStamp) const;
  32521. /** Returns the timestamp of the first event in the sequence.
  32522. @see getEndTime
  32523. */
  32524. double getStartTime() const;
  32525. /** Returns the timestamp of the last event in the sequence.
  32526. @see getStartTime
  32527. */
  32528. double getEndTime() const;
  32529. /** Returns the timestamp of the event at a given index.
  32530. If the index is out-of-range, this will return 0.0
  32531. */
  32532. double getEventTime (int index) const;
  32533. /** Inserts a midi message into the sequence.
  32534. The index at which the new message gets inserted will depend on its timestamp,
  32535. because the sequence is kept sorted.
  32536. Remember to call updateMatchedPairs() after adding note-on events.
  32537. @param newMessage the new message to add (an internal copy will be made)
  32538. @param timeAdjustment an optional value to add to the timestamp of the message
  32539. that will be inserted
  32540. @see updateMatchedPairs
  32541. */
  32542. void addEvent (const MidiMessage& newMessage,
  32543. double timeAdjustment = 0);
  32544. /** Deletes one of the events in the sequence.
  32545. Remember to call updateMatchedPairs() after removing events.
  32546. @param index the index of the event to delete
  32547. @param deleteMatchingNoteUp whether to also remove the matching note-off
  32548. if the event you're removing is a note-on
  32549. */
  32550. void deleteEvent (int index, bool deleteMatchingNoteUp);
  32551. /** Merges another sequence into this one.
  32552. Remember to call updateMatchedPairs() after using this method.
  32553. @param other the sequence to add from
  32554. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  32555. as they are read from the other sequence
  32556. @param firstAllowableDestTime events will not be added if their time is earlier
  32557. than this time. (This is after their time has been adjusted
  32558. by the timeAdjustmentDelta)
  32559. @param endOfAllowableDestTimes events will not be added if their time is equal to
  32560. or greater than this time. (This is after their time has
  32561. been adjusted by the timeAdjustmentDelta)
  32562. */
  32563. void addSequence (const MidiMessageSequence& other,
  32564. double timeAdjustmentDelta,
  32565. double firstAllowableDestTime,
  32566. double endOfAllowableDestTimes);
  32567. /** Makes sure all the note-on and note-off pairs are up-to-date.
  32568. Call this after moving messages about or deleting/adding messages, and it
  32569. will scan the list and make sure all the note-offs in the MidiEventHolder
  32570. structures are pointing at the correct ones.
  32571. */
  32572. void updateMatchedPairs();
  32573. /** Copies all the messages for a particular midi channel to another sequence.
  32574. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  32575. @param destSequence the sequence that the chosen events should be copied to
  32576. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  32577. channel) will also be copied across.
  32578. @see extractSysExMessages
  32579. */
  32580. void extractMidiChannelMessages (int channelNumberToExtract,
  32581. MidiMessageSequence& destSequence,
  32582. bool alsoIncludeMetaEvents) const;
  32583. /** Copies all midi sys-ex messages to another sequence.
  32584. @param destSequence this is the sequence to which any sys-exes in this sequence
  32585. will be added
  32586. @see extractMidiChannelMessages
  32587. */
  32588. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  32589. /** Removes any messages in this sequence that have a specific midi channel.
  32590. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  32591. */
  32592. void deleteMidiChannelMessages (int channelNumberToRemove);
  32593. /** Removes any sys-ex messages from this sequence.
  32594. */
  32595. void deleteSysExMessages();
  32596. /** Adds an offset to the timestamps of all events in the sequence.
  32597. @param deltaTime the amount to add to each timestamp.
  32598. */
  32599. void addTimeToMessages (double deltaTime);
  32600. /** Scans through the sequence to determine the state of any midi controllers at
  32601. a given time.
  32602. This will create a sequence of midi controller changes that can be
  32603. used to set all midi controllers to the state they would be in at the
  32604. specified time within this sequence.
  32605. As well as controllers, it will also recreate the midi program number
  32606. and pitch bend position.
  32607. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  32608. for other channels will be ignored.
  32609. @param time the time at which you want to find out the state - there are
  32610. no explicit units for this time measurement, it's the same units
  32611. as used for the timestamps of the messages
  32612. @param resultMessages an array to which midi controller-change messages will be added. This
  32613. will be the minimum number of controller changes to recreate the
  32614. state at the required time.
  32615. */
  32616. void createControllerUpdatesForTime (int channelNumber, double time,
  32617. OwnedArray<MidiMessage>& resultMessages);
  32618. /** Swaps this sequence with another one. */
  32619. void swapWith (MidiMessageSequence& other) throw();
  32620. /** @internal */
  32621. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  32622. const MidiMessageSequence::MidiEventHolder* second) throw();
  32623. private:
  32624. friend class MidiFile;
  32625. OwnedArray <MidiEventHolder> list;
  32626. void sort();
  32627. JUCE_LEAK_DETECTOR (MidiMessageSequence);
  32628. };
  32629. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  32630. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  32631. /**
  32632. Reads/writes standard midi format files.
  32633. To read a midi file, create a MidiFile object and call its readFrom() method. You
  32634. can then get the individual midi tracks from it using the getTrack() method.
  32635. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  32636. to it using the addTrack() method, and then call its writeTo() method to stream
  32637. it out.
  32638. @see MidiMessageSequence
  32639. */
  32640. class JUCE_API MidiFile
  32641. {
  32642. public:
  32643. /** Creates an empty MidiFile object.
  32644. */
  32645. MidiFile();
  32646. /** Destructor. */
  32647. ~MidiFile();
  32648. /** Returns the number of tracks in the file.
  32649. @see getTrack, addTrack
  32650. */
  32651. int getNumTracks() const throw();
  32652. /** Returns a pointer to one of the tracks in the file.
  32653. @returns a pointer to the track, or 0 if the index is out-of-range
  32654. @see getNumTracks, addTrack
  32655. */
  32656. const MidiMessageSequence* getTrack (int index) const throw();
  32657. /** Adds a midi track to the file.
  32658. This will make its own internal copy of the sequence that is passed-in.
  32659. @see getNumTracks, getTrack
  32660. */
  32661. void addTrack (const MidiMessageSequence& trackSequence);
  32662. /** Removes all midi tracks from the file.
  32663. @see getNumTracks
  32664. */
  32665. void clear();
  32666. /** Returns the raw time format code that will be written to a stream.
  32667. After reading a midi file, this method will return the time-format that
  32668. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  32669. or setSmpteTimeFormat() methods.
  32670. If the value returned is positive, it indicates the number of midi ticks
  32671. per quarter-note - see setTicksPerQuarterNote().
  32672. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  32673. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  32674. */
  32675. short getTimeFormat() const throw();
  32676. /** Sets the time format to use when this file is written to a stream.
  32677. If this is called, the file will be written as bars/beats using the
  32678. specified resolution, rather than SMPTE absolute times, as would be
  32679. used if setSmpteTimeFormat() had been called instead.
  32680. @param ticksPerQuarterNote e.g. 96, 960
  32681. @see setSmpteTimeFormat
  32682. */
  32683. void setTicksPerQuarterNote (int ticksPerQuarterNote) throw();
  32684. /** Sets the time format to use when this file is written to a stream.
  32685. If this is called, the file will be written using absolute times, rather
  32686. than bars/beats as would be the case if setTicksPerBeat() had been called
  32687. instead.
  32688. @param framesPerSecond must be 24, 25, 29 or 30
  32689. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  32690. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  32691. timing, setSmpteTimeFormat (25, 40)
  32692. @see setTicksPerBeat
  32693. */
  32694. void setSmpteTimeFormat (int framesPerSecond,
  32695. int subframeResolution) throw();
  32696. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  32697. Useful for finding the positions of all the tempo changes in a file.
  32698. @param tempoChangeEvents a list to which all the events will be added
  32699. */
  32700. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  32701. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  32702. Useful for finding the positions of all the tempo changes in a file.
  32703. @param timeSigEvents a list to which all the events will be added
  32704. */
  32705. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  32706. /** Returns the latest timestamp in any of the tracks.
  32707. (Useful for finding the length of the file).
  32708. */
  32709. double getLastTimestamp() const;
  32710. /** Reads a midi file format stream.
  32711. After calling this, you can get the tracks that were read from the file by using the
  32712. getNumTracks() and getTrack() methods.
  32713. The timestamps of the midi events in the tracks will represent their positions in
  32714. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  32715. method.
  32716. @returns true if the stream was read successfully
  32717. */
  32718. bool readFrom (InputStream& sourceStream);
  32719. /** Writes the midi tracks as a standard midi file.
  32720. @returns true if the operation succeeded.
  32721. */
  32722. bool writeTo (OutputStream& destStream);
  32723. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  32724. This will use the midi time format and tempo/time signature info in the
  32725. tracks to convert all the timestamps to absolute values in seconds.
  32726. */
  32727. void convertTimestampTicksToSeconds();
  32728. private:
  32729. OwnedArray <MidiMessageSequence> tracks;
  32730. short timeFormat;
  32731. void readNextTrack (const uint8* data, int size);
  32732. void writeTrack (OutputStream& mainOut, int trackNum);
  32733. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiFile);
  32734. };
  32735. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  32736. /*** End of inlined file: juce_MidiFile.h ***/
  32737. #endif
  32738. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32739. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  32740. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32741. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32742. class MidiKeyboardState;
  32743. /**
  32744. Receives events from a MidiKeyboardState object.
  32745. @see MidiKeyboardState
  32746. */
  32747. class JUCE_API MidiKeyboardStateListener
  32748. {
  32749. public:
  32750. MidiKeyboardStateListener() throw() {}
  32751. virtual ~MidiKeyboardStateListener() {}
  32752. /** Called when one of the MidiKeyboardState's keys is pressed.
  32753. This will be called synchronously when the state is either processing a
  32754. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  32755. when a note is being played with its MidiKeyboardState::noteOn() method.
  32756. Note that this callback could happen from an audio callback thread, so be
  32757. careful not to block, and avoid any UI activity in the callback.
  32758. */
  32759. virtual void handleNoteOn (MidiKeyboardState* source,
  32760. int midiChannel, int midiNoteNumber, float velocity) = 0;
  32761. /** Called when one of the MidiKeyboardState's keys is released.
  32762. This will be called synchronously when the state is either processing a
  32763. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  32764. when a note is being played with its MidiKeyboardState::noteOff() method.
  32765. Note that this callback could happen from an audio callback thread, so be
  32766. careful not to block, and avoid any UI activity in the callback.
  32767. */
  32768. virtual void handleNoteOff (MidiKeyboardState* source,
  32769. int midiChannel, int midiNoteNumber) = 0;
  32770. };
  32771. /**
  32772. Represents a piano keyboard, keeping track of which keys are currently pressed.
  32773. This object can parse a stream of midi events, using them to update its idea
  32774. of which keys are pressed for each individiual midi channel.
  32775. When keys go up or down, it can broadcast these events to listener objects.
  32776. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  32777. methods, and midi messages for these events will be merged into the
  32778. midi stream that gets processed by processNextMidiBuffer().
  32779. */
  32780. class JUCE_API MidiKeyboardState
  32781. {
  32782. public:
  32783. MidiKeyboardState();
  32784. ~MidiKeyboardState();
  32785. /** Resets the state of the object.
  32786. All internal data for all the channels is reset, but no events are sent as a
  32787. result.
  32788. If you want to release any keys that are currently down, and to send out note-up
  32789. midi messages for this, use the allNotesOff() method instead.
  32790. */
  32791. void reset();
  32792. /** Returns true if the given midi key is currently held down for the given midi channel.
  32793. The channel number must be between 1 and 16. If you want to see if any notes are
  32794. on for a range of channels, use the isNoteOnForChannels() method.
  32795. */
  32796. bool isNoteOn (int midiChannel, int midiNoteNumber) const throw();
  32797. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  32798. The channel mask has a bit set for each midi channel you want to test for - bit
  32799. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  32800. If a note is on for at least one of the specified channels, this returns true.
  32801. */
  32802. bool isNoteOnForChannels (int midiChannelMask, int midiNoteNumber) const throw();
  32803. /** Turns a specified note on.
  32804. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  32805. next call to processNextMidiBuffer().
  32806. It will also trigger a synchronous callback to the listeners to tell them that the key has
  32807. gone down.
  32808. */
  32809. void noteOn (int midiChannel, int midiNoteNumber, float velocity);
  32810. /** Turns a specified note off.
  32811. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  32812. next call to processNextMidiBuffer().
  32813. It will also trigger a synchronous callback to the listeners to tell them that the key has
  32814. gone up.
  32815. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  32816. */
  32817. void noteOff (int midiChannel, int midiNoteNumber);
  32818. /** This will turn off any currently-down notes for the given midi channel.
  32819. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  32820. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  32821. and events being added to the midi stream.
  32822. */
  32823. void allNotesOff (int midiChannel);
  32824. /** Looks at a key-up/down event and uses it to update the state of this object.
  32825. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  32826. instead.
  32827. */
  32828. void processNextMidiEvent (const MidiMessage& message);
  32829. /** Scans a midi stream for up/down events and adds its own events to it.
  32830. This will look for any up/down events and use them to update the internal state,
  32831. synchronously making suitable callbacks to the listeners.
  32832. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  32833. and noteOff() calls will be added into the buffer.
  32834. Only the section of the buffer whose timestamps are between startSample and
  32835. (startSample + numSamples) will be affected, and any events added will be placed
  32836. between these times.
  32837. If you're going to use this method, you'll need to keep calling it regularly for
  32838. it to work satisfactorily.
  32839. To process a single midi event at a time, use the processNextMidiEvent() method
  32840. instead.
  32841. */
  32842. void processNextMidiBuffer (MidiBuffer& buffer,
  32843. int startSample,
  32844. int numSamples,
  32845. bool injectIndirectEvents);
  32846. /** Registers a listener for callbacks when keys go up or down.
  32847. @see removeListener
  32848. */
  32849. void addListener (MidiKeyboardStateListener* listener);
  32850. /** Deregisters a listener.
  32851. @see addListener
  32852. */
  32853. void removeListener (MidiKeyboardStateListener* listener);
  32854. private:
  32855. CriticalSection lock;
  32856. uint16 noteStates [128];
  32857. MidiBuffer eventsToAdd;
  32858. Array <MidiKeyboardStateListener*> listeners;
  32859. void noteOnInternal (int midiChannel, int midiNoteNumber, float velocity);
  32860. void noteOffInternal (int midiChannel, int midiNoteNumber);
  32861. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardState);
  32862. };
  32863. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  32864. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  32865. #endif
  32866. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  32867. #endif
  32868. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32869. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  32870. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32871. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32872. /**
  32873. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  32874. processing by a block-based audio callback.
  32875. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  32876. so it can easily use a midi input or keyboard component as its source.
  32877. @see MidiMessage, MidiInput
  32878. */
  32879. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  32880. public MidiInputCallback
  32881. {
  32882. public:
  32883. /** Creates a MidiMessageCollector. */
  32884. MidiMessageCollector();
  32885. /** Destructor. */
  32886. ~MidiMessageCollector();
  32887. /** Clears any messages from the queue.
  32888. You need to call this method before starting to use the collector, so that
  32889. it knows the correct sample rate to use.
  32890. */
  32891. void reset (double sampleRate);
  32892. /** Takes an incoming real-time message and adds it to the queue.
  32893. The message's timestamp is taken, and it will be ready for retrieval as part
  32894. of the block returned by the next call to removeNextBlockOfMessages().
  32895. This method is fully thread-safe when overlapping calls are made with
  32896. removeNextBlockOfMessages().
  32897. */
  32898. void addMessageToQueue (const MidiMessage& message);
  32899. /** Removes all the pending messages from the queue as a buffer.
  32900. This will also correct the messages' timestamps to make sure they're in
  32901. the range 0 to numSamples - 1.
  32902. This call should be made regularly by something like an audio processing
  32903. callback, because the time that it happens is used in calculating the
  32904. midi event positions.
  32905. This method is fully thread-safe when overlapping calls are made with
  32906. addMessageToQueue().
  32907. */
  32908. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  32909. /** @internal */
  32910. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  32911. /** @internal */
  32912. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  32913. /** @internal */
  32914. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  32915. private:
  32916. double lastCallbackTime;
  32917. CriticalSection midiCallbackLock;
  32918. MidiBuffer incomingMessages;
  32919. double sampleRate;
  32920. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiMessageCollector);
  32921. };
  32922. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  32923. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  32924. #endif
  32925. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  32926. #endif
  32927. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  32928. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  32929. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  32930. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  32931. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  32932. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  32933. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  32934. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  32935. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  32936. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  32937. /*** Start of inlined file: juce_AudioProcessor.h ***/
  32938. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  32939. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  32940. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  32941. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  32942. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  32943. class AudioProcessor;
  32944. /**
  32945. Base class for the component that acts as the GUI for an AudioProcessor.
  32946. Derive your editor component from this class, and create an instance of it
  32947. by overriding the AudioProcessor::createEditor() method.
  32948. @see AudioProcessor, GenericAudioProcessorEditor
  32949. */
  32950. class JUCE_API AudioProcessorEditor : public Component
  32951. {
  32952. protected:
  32953. /** Creates an editor for the specified processor.
  32954. */
  32955. AudioProcessorEditor (AudioProcessor* owner);
  32956. public:
  32957. /** Destructor. */
  32958. ~AudioProcessorEditor();
  32959. /** Returns a pointer to the processor that this editor represents. */
  32960. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  32961. private:
  32962. AudioProcessor* const owner;
  32963. JUCE_DECLARE_NON_COPYABLE (AudioProcessorEditor);
  32964. };
  32965. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  32966. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  32967. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  32968. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  32969. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  32970. class AudioProcessor;
  32971. /**
  32972. Base class for listeners that want to know about changes to an AudioProcessor.
  32973. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  32974. @see AudioProcessor
  32975. */
  32976. class JUCE_API AudioProcessorListener
  32977. {
  32978. public:
  32979. /** Destructor. */
  32980. virtual ~AudioProcessorListener() {}
  32981. /** Receives a callback when a parameter is changed.
  32982. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  32983. many audio processors will change their parameter during their audio callback.
  32984. This means that not only has your handler code got to be completely thread-safe,
  32985. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  32986. this event on your message thread, use this callback to trigger an AsyncUpdater
  32987. or ChangeBroadcaster which you can respond to on the message thread.
  32988. */
  32989. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  32990. int parameterIndex,
  32991. float newValue) = 0;
  32992. /** Called to indicate that something else in the plugin has changed, like its
  32993. program, number of parameters, etc.
  32994. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  32995. call it during their audio callback. This means that not only has your handler code
  32996. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  32997. blocking. If you need to handle this event on your message thread, use this callback
  32998. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  32999. message thread.
  33000. */
  33001. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  33002. /** Indicates that a parameter change gesture has started.
  33003. E.g. if the user is dragging a slider, this would be called when they first
  33004. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  33005. called when they release it.
  33006. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  33007. call it during their audio callback. This means that not only has your handler code
  33008. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  33009. blocking. If you need to handle this event on your message thread, use this callback
  33010. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  33011. message thread.
  33012. @see audioProcessorParameterChangeGestureEnd
  33013. */
  33014. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  33015. int parameterIndex);
  33016. /** Indicates that a parameter change gesture has finished.
  33017. E.g. if the user is dragging a slider, this would be called when they release
  33018. the mouse button.
  33019. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  33020. call it during their audio callback. This means that not only has your handler code
  33021. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  33022. blocking. If you need to handle this event on your message thread, use this callback
  33023. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  33024. message thread.
  33025. @see audioProcessorParameterChangeGestureBegin
  33026. */
  33027. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  33028. int parameterIndex);
  33029. };
  33030. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  33031. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  33032. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  33033. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  33034. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  33035. /**
  33036. A subclass of AudioPlayHead can supply information about the position and
  33037. status of a moving play head during audio playback.
  33038. One of these can be supplied to an AudioProcessor object so that it can find
  33039. out about the position of the audio that it is rendering.
  33040. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  33041. */
  33042. class JUCE_API AudioPlayHead
  33043. {
  33044. protected:
  33045. AudioPlayHead() {}
  33046. public:
  33047. virtual ~AudioPlayHead() {}
  33048. /** Frame rate types. */
  33049. enum FrameRateType
  33050. {
  33051. fps24 = 0,
  33052. fps25 = 1,
  33053. fps2997 = 2,
  33054. fps30 = 3,
  33055. fps2997drop = 4,
  33056. fps30drop = 5,
  33057. fpsUnknown = 99
  33058. };
  33059. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  33060. */
  33061. struct CurrentPositionInfo
  33062. {
  33063. /** The tempo in BPM */
  33064. double bpm;
  33065. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  33066. int timeSigNumerator;
  33067. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  33068. int timeSigDenominator;
  33069. /** The current play position, in seconds from the start of the edit. */
  33070. double timeInSeconds;
  33071. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  33072. double editOriginTime;
  33073. /** The current play position in pulses-per-quarter-note.
  33074. This is the number of quarter notes since the edit start.
  33075. */
  33076. double ppqPosition;
  33077. /** The position of the start of the last bar, in pulses-per-quarter-note.
  33078. This is the number of quarter notes from the start of the edit to the
  33079. start of the current bar.
  33080. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  33081. it's not available, the value will be 0.
  33082. */
  33083. double ppqPositionOfLastBarStart;
  33084. /** The video frame rate, if applicable. */
  33085. FrameRateType frameRate;
  33086. /** True if the transport is currently playing. */
  33087. bool isPlaying;
  33088. /** True if the transport is currently recording.
  33089. (When isRecording is true, then isPlaying will also be true).
  33090. */
  33091. bool isRecording;
  33092. bool operator== (const CurrentPositionInfo& other) const throw();
  33093. bool operator!= (const CurrentPositionInfo& other) const throw();
  33094. void resetToDefault();
  33095. };
  33096. /** Fills-in the given structure with details about the transport's
  33097. position at the start of the current processing block.
  33098. */
  33099. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  33100. };
  33101. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  33102. /*** End of inlined file: juce_AudioPlayHead.h ***/
  33103. /**
  33104. Base class for audio processing filters or plugins.
  33105. This is intended to act as a base class of audio filter that is general enough to
  33106. be wrapped as a VST, AU, RTAS, etc, or used internally.
  33107. It is also used by the plugin hosting code as the wrapper around an instance
  33108. of a loaded plugin.
  33109. Derive your filter class from this base class, and if you're building a plugin,
  33110. you should implement a global function called createPluginFilter() which creates
  33111. and returns a new instance of your subclass.
  33112. */
  33113. class JUCE_API AudioProcessor
  33114. {
  33115. protected:
  33116. /** Constructor.
  33117. You can also do your initialisation tasks in the initialiseFilterInfo()
  33118. call, which will be made after this object has been created.
  33119. */
  33120. AudioProcessor();
  33121. public:
  33122. /** Destructor. */
  33123. virtual ~AudioProcessor();
  33124. /** Returns the name of this processor.
  33125. */
  33126. virtual const String getName() const = 0;
  33127. /** Called before playback starts, to let the filter prepare itself.
  33128. The sample rate is the target sample rate, and will remain constant until
  33129. playback stops.
  33130. The estimatedSamplesPerBlock value is a HINT about the typical number of
  33131. samples that will be processed for each callback, but isn't any kind
  33132. of guarantee. The actual block sizes that the host uses may be different
  33133. each time the callback happens, and may be more or less than this value.
  33134. */
  33135. virtual void prepareToPlay (double sampleRate,
  33136. int estimatedSamplesPerBlock) = 0;
  33137. /** Called after playback has stopped, to let the filter free up any resources it
  33138. no longer needs.
  33139. */
  33140. virtual void releaseResources() = 0;
  33141. /** Renders the next block.
  33142. When this method is called, the buffer contains a number of channels which is
  33143. at least as great as the maximum number of input and output channels that
  33144. this filter is using. It will be filled with the filter's input data and
  33145. should be replaced with the filter's output.
  33146. So for example if your filter has 2 input channels and 4 output channels, then
  33147. the buffer will contain 4 channels, the first two being filled with the
  33148. input data. Your filter should read these, do its processing, and replace
  33149. the contents of all 4 channels with its output.
  33150. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  33151. all filled with data, and your filter should overwrite the first 2 of these
  33152. with its output. But be VERY careful not to write anything to the last 3
  33153. channels, as these might be mapped to memory that the host assumes is read-only!
  33154. Note that if you have more outputs than inputs, then only those channels that
  33155. correspond to an input channel are guaranteed to contain sensible data - e.g.
  33156. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  33157. but the last two channels may contain garbage, so you should be careful not to
  33158. let this pass through without being overwritten or cleared.
  33159. Also note that the buffer may have more channels than are strictly necessary,
  33160. but your should only read/write from the ones that your filter is supposed to
  33161. be using.
  33162. The number of samples in these buffers is NOT guaranteed to be the same for every
  33163. callback, and may be more or less than the estimated value given to prepareToPlay().
  33164. Your code must be able to cope with variable-sized blocks, or you're going to get
  33165. clicks and crashes!
  33166. If the filter is receiving a midi input, then the midiMessages array will be filled
  33167. with the midi messages for this block. Each message's timestamp will indicate the
  33168. message's time, as a number of samples from the start of the block.
  33169. Any messages left in the midi buffer when this method has finished are assumed to
  33170. be the filter's midi output. This means that your filter should be careful to
  33171. clear any incoming messages from the array if it doesn't want them to be passed-on.
  33172. Be very careful about what you do in this callback - it's going to be called by
  33173. the audio thread, so any kind of interaction with the UI is absolutely
  33174. out of the question. If you change a parameter in here and need to tell your UI to
  33175. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  33176. the UI components register as listeners, and then call sendChangeMessage() inside the
  33177. processBlock() method to send out an asynchronous message. You could also use
  33178. the AsyncUpdater class in a similar way.
  33179. */
  33180. virtual void processBlock (AudioSampleBuffer& buffer,
  33181. MidiBuffer& midiMessages) = 0;
  33182. /** Returns the current AudioPlayHead object that should be used to find
  33183. out the state and position of the playhead.
  33184. You can call this from your processBlock() method, and use the AudioPlayHead
  33185. object to get the details about the time of the start of the block currently
  33186. being processed.
  33187. If the host hasn't supplied a playhead object, this will return 0.
  33188. */
  33189. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  33190. /** Returns the current sample rate.
  33191. This can be called from your processBlock() method - it's not guaranteed
  33192. to be valid at any other time, and may return 0 if it's unknown.
  33193. */
  33194. double getSampleRate() const throw() { return sampleRate; }
  33195. /** Returns the current typical block size that is being used.
  33196. This can be called from your processBlock() method - it's not guaranteed
  33197. to be valid at any other time.
  33198. Remember it's not the ONLY block size that may be used when calling
  33199. processBlock, it's just the normal one. The actual block sizes used may be
  33200. larger or smaller than this, and will vary between successive calls.
  33201. */
  33202. int getBlockSize() const throw() { return blockSize; }
  33203. /** Returns the number of input channels that the host will be sending the filter.
  33204. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  33205. number of channels that your filter would prefer to have, and this method lets
  33206. you know how many the host is actually using.
  33207. Note that this method is only valid during or after the prepareToPlay()
  33208. method call. Until that point, the number of channels will be unknown.
  33209. */
  33210. int getNumInputChannels() const throw() { return numInputChannels; }
  33211. /** Returns the number of output channels that the host will be sending the filter.
  33212. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  33213. number of channels that your filter would prefer to have, and this method lets
  33214. you know how many the host is actually using.
  33215. Note that this method is only valid during or after the prepareToPlay()
  33216. method call. Until that point, the number of channels will be unknown.
  33217. */
  33218. int getNumOutputChannels() const throw() { return numOutputChannels; }
  33219. /** Returns the name of one of the input channels, as returned by the host.
  33220. The host might not supply very useful names for channels, and this might be
  33221. something like "1", "2", "left", "right", etc.
  33222. */
  33223. virtual const String getInputChannelName (int channelIndex) const = 0;
  33224. /** Returns the name of one of the output channels, as returned by the host.
  33225. The host might not supply very useful names for channels, and this might be
  33226. something like "1", "2", "left", "right", etc.
  33227. */
  33228. virtual const String getOutputChannelName (int channelIndex) const = 0;
  33229. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  33230. virtual bool isInputChannelStereoPair (int index) const = 0;
  33231. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  33232. virtual bool isOutputChannelStereoPair (int index) const = 0;
  33233. /** This returns the number of samples delay that the filter imposes on the audio
  33234. passing through it.
  33235. The host will call this to find the latency - the filter itself should set this value
  33236. by calling setLatencySamples() as soon as it can during its initialisation.
  33237. */
  33238. int getLatencySamples() const throw() { return latencySamples; }
  33239. /** The filter should call this to set the number of samples delay that it introduces.
  33240. The filter should call this as soon as it can during initialisation, and can call it
  33241. later if the value changes.
  33242. */
  33243. void setLatencySamples (int newLatency);
  33244. /** Returns true if the processor wants midi messages. */
  33245. virtual bool acceptsMidi() const = 0;
  33246. /** Returns true if the processor produces midi messages. */
  33247. virtual bool producesMidi() const = 0;
  33248. /** This returns a critical section that will automatically be locked while the host
  33249. is calling the processBlock() method.
  33250. Use it from your UI or other threads to lock access to variables that are used
  33251. by the process callback, but obviously be careful not to keep it locked for
  33252. too long, because that could cause stuttering playback. If you need to do something
  33253. that'll take a long time and need the processing to stop while it happens, use the
  33254. suspendProcessing() method instead.
  33255. @see suspendProcessing
  33256. */
  33257. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  33258. /** Enables and disables the processing callback.
  33259. If you need to do something time-consuming on a thread and would like to make sure
  33260. the audio processing callback doesn't happen until you've finished, use this
  33261. to disable the callback and re-enable it again afterwards.
  33262. E.g.
  33263. @code
  33264. void loadNewPatch()
  33265. {
  33266. suspendProcessing (true);
  33267. ..do something that takes ages..
  33268. suspendProcessing (false);
  33269. }
  33270. @endcode
  33271. If the host tries to make an audio callback while processing is suspended, the
  33272. filter will return an empty buffer, but won't block the audio thread like it would
  33273. do if you use the getCallbackLock() critical section to synchronise access.
  33274. If you're going to use this, your processBlock() method must call isSuspended() and
  33275. check whether it's suspended or not. If it is, then it should skip doing any real
  33276. processing, either emitting silence or passing the input through unchanged.
  33277. @see getCallbackLock
  33278. */
  33279. void suspendProcessing (bool shouldBeSuspended);
  33280. /** Returns true if processing is currently suspended.
  33281. @see suspendProcessing
  33282. */
  33283. bool isSuspended() const throw() { return suspended; }
  33284. /** A plugin can override this to be told when it should reset any playing voices.
  33285. The default implementation does nothing, but a host may call this to tell the
  33286. plugin that it should stop any tails or sounds that have been left running.
  33287. */
  33288. virtual void reset();
  33289. /** Returns true if the processor is being run in an offline mode for rendering.
  33290. If the processor is being run live on realtime signals, this returns false.
  33291. If the mode is unknown, this will assume it's realtime and return false.
  33292. This value may be unreliable until the prepareToPlay() method has been called,
  33293. and could change each time prepareToPlay() is called.
  33294. @see setNonRealtime()
  33295. */
  33296. bool isNonRealtime() const throw() { return nonRealtime; }
  33297. /** Called by the host to tell this processor whether it's being used in a non-realime
  33298. capacity for offline rendering or bouncing.
  33299. Whatever value is passed-in will be
  33300. */
  33301. void setNonRealtime (bool isNonRealtime) throw();
  33302. /** Creates the filter's UI.
  33303. This can return 0 if you want a UI-less filter, in which case the host may create
  33304. a generic UI that lets the user twiddle the parameters directly.
  33305. If you do want to pass back a component, the component should be created and set to
  33306. the correct size before returning it. If you implement this method, you must
  33307. also implement the hasEditor() method and make it return true.
  33308. Remember not to do anything silly like allowing your filter to keep a pointer to
  33309. the component that gets created - it could be deleted later without any warning, which
  33310. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  33311. The correct way to handle the connection between an editor component and its
  33312. filter is to use something like a ChangeBroadcaster so that the editor can
  33313. register itself as a listener, and be told when a change occurs. This lets them
  33314. safely unregister themselves when they are deleted.
  33315. Here are a few things to bear in mind when writing an editor:
  33316. - Initially there won't be an editor, until the user opens one, or they might
  33317. not open one at all. Your filter mustn't rely on it being there.
  33318. - An editor object may be deleted and a replacement one created again at any time.
  33319. - It's safe to assume that an editor will be deleted before its filter.
  33320. @see hasEditor
  33321. */
  33322. virtual AudioProcessorEditor* createEditor() = 0;
  33323. /** Your filter must override this and return true if it can create an editor component.
  33324. @see createEditor
  33325. */
  33326. virtual bool hasEditor() const = 0;
  33327. /** Returns the active editor, if there is one.
  33328. Bear in mind this can return 0, even if an editor has previously been
  33329. opened.
  33330. */
  33331. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  33332. /** Returns the active editor, or if there isn't one, it will create one.
  33333. This may call createEditor() internally to create the component.
  33334. */
  33335. AudioProcessorEditor* createEditorIfNeeded();
  33336. /** This must return the correct value immediately after the object has been
  33337. created, and mustn't change the number of parameters later.
  33338. */
  33339. virtual int getNumParameters() = 0;
  33340. /** Returns the name of a particular parameter. */
  33341. virtual const String getParameterName (int parameterIndex) = 0;
  33342. /** Called by the host to find out the value of one of the filter's parameters.
  33343. The host will expect the value returned to be between 0 and 1.0.
  33344. This could be called quite frequently, so try to make your code efficient.
  33345. It's also likely to be called by non-UI threads, so the code in here should
  33346. be thread-aware.
  33347. */
  33348. virtual float getParameter (int parameterIndex) = 0;
  33349. /** Returns the value of a parameter as a text string. */
  33350. virtual const String getParameterText (int parameterIndex) = 0;
  33351. /** The host will call this method to change the value of one of the filter's parameters.
  33352. The host may call this at any time, including during the audio processing
  33353. callback, so the filter has to process this very fast and avoid blocking.
  33354. If you want to set the value of a parameter internally, e.g. from your
  33355. editor component, then don't call this directly - instead, use the
  33356. setParameterNotifyingHost() method, which will also send a message to
  33357. the host telling it about the change. If the message isn't sent, the host
  33358. won't be able to automate your parameters properly.
  33359. The value passed will be between 0 and 1.0.
  33360. */
  33361. virtual void setParameter (int parameterIndex,
  33362. float newValue) = 0;
  33363. /** Your filter can call this when it needs to change one of its parameters.
  33364. This could happen when the editor or some other internal operation changes
  33365. a parameter. This method will call the setParameter() method to change the
  33366. value, and will then send a message to the host telling it about the change.
  33367. Note that to make sure the host correctly handles automation, you should call
  33368. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  33369. tell the host when the user has started and stopped changing the parameter.
  33370. */
  33371. void setParameterNotifyingHost (int parameterIndex,
  33372. float newValue);
  33373. /** Returns true if the host can automate this parameter.
  33374. By default, this returns true for all parameters.
  33375. */
  33376. virtual bool isParameterAutomatable (int parameterIndex) const;
  33377. /** Should return true if this parameter is a "meta" parameter.
  33378. A meta-parameter is a parameter that changes other params. It is used
  33379. by some hosts (e.g. AudioUnit hosts).
  33380. By default this returns false.
  33381. */
  33382. virtual bool isMetaParameter (int parameterIndex) const;
  33383. /** Sends a signal to the host to tell it that the user is about to start changing this
  33384. parameter.
  33385. This allows the host to know when a parameter is actively being held by the user, and
  33386. it may use this information to help it record automation.
  33387. If you call this, it must be matched by a later call to endParameterChangeGesture().
  33388. */
  33389. void beginParameterChangeGesture (int parameterIndex);
  33390. /** Tells the host that the user has finished changing this parameter.
  33391. This allows the host to know when a parameter is actively being held by the user, and
  33392. it may use this information to help it record automation.
  33393. A call to this method must follow a call to beginParameterChangeGesture().
  33394. */
  33395. void endParameterChangeGesture (int parameterIndex);
  33396. /** The filter can call this when something (apart from a parameter value) has changed.
  33397. It sends a hint to the host that something like the program, number of parameters,
  33398. etc, has changed, and that it should update itself.
  33399. */
  33400. void updateHostDisplay();
  33401. /** Returns the number of preset programs the filter supports.
  33402. The value returned must be valid as soon as this object is created, and
  33403. must not change over its lifetime.
  33404. This value shouldn't be less than 1.
  33405. */
  33406. virtual int getNumPrograms() = 0;
  33407. /** Returns the number of the currently active program.
  33408. */
  33409. virtual int getCurrentProgram() = 0;
  33410. /** Called by the host to change the current program.
  33411. */
  33412. virtual void setCurrentProgram (int index) = 0;
  33413. /** Must return the name of a given program. */
  33414. virtual const String getProgramName (int index) = 0;
  33415. /** Called by the host to rename a program.
  33416. */
  33417. virtual void changeProgramName (int index, const String& newName) = 0;
  33418. /** The host will call this method when it wants to save the filter's internal state.
  33419. This must copy any info about the filter's state into the block of memory provided,
  33420. so that the host can store this and later restore it using setStateInformation().
  33421. Note that there's also a getCurrentProgramStateInformation() method, which only
  33422. stores the current program, not the state of the entire filter.
  33423. See also the helper function copyXmlToBinary() for storing settings as XML.
  33424. @see getCurrentProgramStateInformation
  33425. */
  33426. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  33427. /** The host will call this method if it wants to save the state of just the filter's
  33428. current program.
  33429. Unlike getStateInformation, this should only return the current program's state.
  33430. Not all hosts support this, and if you don't implement it, the base class
  33431. method just calls getStateInformation() instead. If you do implement it, be
  33432. sure to also implement getCurrentProgramStateInformation.
  33433. @see getStateInformation, setCurrentProgramStateInformation
  33434. */
  33435. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  33436. /** This must restore the filter's state from a block of data previously created
  33437. using getStateInformation().
  33438. Note that there's also a setCurrentProgramStateInformation() method, which tries
  33439. to restore just the current program, not the state of the entire filter.
  33440. See also the helper function getXmlFromBinary() for loading settings as XML.
  33441. @see setCurrentProgramStateInformation
  33442. */
  33443. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  33444. /** The host will call this method if it wants to restore the state of just the filter's
  33445. current program.
  33446. Not all hosts support this, and if you don't implement it, the base class
  33447. method just calls setStateInformation() instead. If you do implement it, be
  33448. sure to also implement getCurrentProgramStateInformation.
  33449. @see setStateInformation, getCurrentProgramStateInformation
  33450. */
  33451. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  33452. /** Adds a listener that will be called when an aspect of this processor changes. */
  33453. void addListener (AudioProcessorListener* newListener);
  33454. /** Removes a previously added listener. */
  33455. void removeListener (AudioProcessorListener* listenerToRemove);
  33456. /** Tells the processor to use this playhead object.
  33457. The processor will not take ownership of the object, so the caller must delete it when
  33458. it is no longer being used.
  33459. */
  33460. void setPlayHead (AudioPlayHead* newPlayHead) throw();
  33461. /** Not for public use - this is called before deleting an editor component. */
  33462. void editorBeingDeleted (AudioProcessorEditor* editor) throw();
  33463. /** Not for public use - this is called to initialise the processor before playing. */
  33464. void setPlayConfigDetails (int numIns, int numOuts,
  33465. double sampleRate,
  33466. int blockSize) throw();
  33467. protected:
  33468. /** Helper function that just converts an xml element into a binary blob.
  33469. Use this in your filter's getStateInformation() method if you want to
  33470. store its state as xml.
  33471. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  33472. from a binary blob.
  33473. */
  33474. static void copyXmlToBinary (const XmlElement& xml,
  33475. JUCE_NAMESPACE::MemoryBlock& destData);
  33476. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  33477. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  33478. an XmlElement object that the caller must delete when no longer needed.
  33479. */
  33480. static XmlElement* getXmlFromBinary (const void* data, int sizeInBytes);
  33481. /** @internal */
  33482. AudioPlayHead* playHead;
  33483. /** @internal */
  33484. void sendParamChangeMessageToListeners (int parameterIndex, float newValue);
  33485. private:
  33486. Array <AudioProcessorListener*> listeners;
  33487. Component::SafePointer<AudioProcessorEditor> activeEditor;
  33488. double sampleRate;
  33489. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  33490. bool suspended, nonRealtime;
  33491. CriticalSection callbackLock, listenerLock;
  33492. #if JUCE_DEBUG
  33493. BigInteger changingParams;
  33494. #endif
  33495. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessor);
  33496. };
  33497. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  33498. /*** End of inlined file: juce_AudioProcessor.h ***/
  33499. /*** Start of inlined file: juce_PluginDescription.h ***/
  33500. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  33501. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  33502. /**
  33503. A small class to represent some facts about a particular type of plugin.
  33504. This class is for storing and managing the details about a plugin without
  33505. actually having to load an instance of it.
  33506. A KnownPluginList contains a list of PluginDescription objects.
  33507. @see KnownPluginList
  33508. */
  33509. class JUCE_API PluginDescription
  33510. {
  33511. public:
  33512. PluginDescription();
  33513. PluginDescription (const PluginDescription& other);
  33514. PluginDescription& operator= (const PluginDescription& other);
  33515. ~PluginDescription();
  33516. /** The name of the plugin. */
  33517. String name;
  33518. /** A more descriptive name for the plugin.
  33519. This may be the same as the 'name' field, but some plugins may provide an
  33520. alternative name.
  33521. */
  33522. String descriptiveName;
  33523. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  33524. */
  33525. String pluginFormatName;
  33526. /** A category, such as "Dynamics", "Reverbs", etc.
  33527. */
  33528. String category;
  33529. /** The manufacturer. */
  33530. String manufacturerName;
  33531. /** The version. This string doesn't have any particular format. */
  33532. String version;
  33533. /** Either the file containing the plugin module, or some other unique way
  33534. of identifying it.
  33535. E.g. for an AU, this would be an ID string that the component manager
  33536. could use to retrieve the plugin. For a VST, it's the file path.
  33537. */
  33538. String fileOrIdentifier;
  33539. /** The last time the plugin file was changed.
  33540. This is handy when scanning for new or changed plugins.
  33541. */
  33542. Time lastFileModTime;
  33543. /** A unique ID for the plugin.
  33544. Note that this might not be unique between formats, e.g. a VST and some
  33545. other format might actually have the same id.
  33546. @see createIdentifierString
  33547. */
  33548. int uid;
  33549. /** True if the plugin identifies itself as a synthesiser. */
  33550. bool isInstrument;
  33551. /** The number of inputs. */
  33552. int numInputChannels;
  33553. /** The number of outputs. */
  33554. int numOutputChannels;
  33555. /** Returns true if the two descriptions refer the the same plugin.
  33556. This isn't quite as simple as them just having the same file (because of
  33557. shell plugins).
  33558. */
  33559. bool isDuplicateOf (const PluginDescription& other) const;
  33560. /** Returns a string that can be saved and used to uniquely identify the
  33561. plugin again.
  33562. This contains less info than the XML encoding, and is independent of the
  33563. plugin's file location, so can be used to store a plugin ID for use
  33564. across different machines.
  33565. */
  33566. const String createIdentifierString() const;
  33567. /** Creates an XML object containing these details.
  33568. @see loadFromXml
  33569. */
  33570. XmlElement* createXml() const;
  33571. /** Reloads the info in this structure from an XML record that was previously
  33572. saved with createXML().
  33573. Returns true if the XML was a valid plugin description.
  33574. */
  33575. bool loadFromXml (const XmlElement& xml);
  33576. private:
  33577. JUCE_LEAK_DETECTOR (PluginDescription);
  33578. };
  33579. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  33580. /*** End of inlined file: juce_PluginDescription.h ***/
  33581. /**
  33582. Base class for an active instance of a plugin.
  33583. This derives from the AudioProcessor class, and adds some extra functionality
  33584. that helps when wrapping dynamically loaded plugins.
  33585. @see AudioProcessor, AudioPluginFormat
  33586. */
  33587. class JUCE_API AudioPluginInstance : public AudioProcessor
  33588. {
  33589. public:
  33590. /** Destructor.
  33591. Make sure that you delete any UI components that belong to this plugin before
  33592. deleting the plugin.
  33593. */
  33594. virtual ~AudioPluginInstance();
  33595. /** Fills-in the appropriate parts of this plugin description object.
  33596. */
  33597. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  33598. /** Returns a pointer to some kind of platform-specific data about the plugin.
  33599. E.g. For a VST, this value can be cast to an AEffect*. For an AudioUnit, it can be
  33600. cast to an AudioUnit handle.
  33601. */
  33602. virtual void* getPlatformSpecificData();
  33603. protected:
  33604. AudioPluginInstance();
  33605. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginInstance);
  33606. };
  33607. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  33608. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  33609. class PluginDescription;
  33610. /**
  33611. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  33612. Use the static getNumFormats() and getFormat() calls to find the types
  33613. of format that are available.
  33614. */
  33615. class JUCE_API AudioPluginFormat
  33616. {
  33617. public:
  33618. /** Destructor. */
  33619. virtual ~AudioPluginFormat();
  33620. /** Returns the format name.
  33621. E.g. "VST", "AudioUnit", etc.
  33622. */
  33623. virtual const String getName() const = 0;
  33624. /** This tries to create descriptions for all the plugin types available in
  33625. a binary module file.
  33626. The file will be some kind of DLL or bundle.
  33627. Normally there will only be one type returned, but some plugins
  33628. (e.g. VST shells) can use a single DLL to create a set of different plugin
  33629. subtypes, so in that case, each subtype is returned as a separate object.
  33630. */
  33631. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  33632. const String& fileOrIdentifier) = 0;
  33633. /** Tries to recreate a type from a previously generated PluginDescription.
  33634. @see PluginDescription::createInstance
  33635. */
  33636. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  33637. /** Should do a quick check to see if this file or directory might be a plugin of
  33638. this format.
  33639. This is for searching for potential files, so it shouldn't actually try to
  33640. load the plugin or do anything time-consuming.
  33641. */
  33642. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  33643. /** Returns a readable version of the name of the plugin that this identifier refers to.
  33644. */
  33645. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  33646. /** Checks whether this plugin could possibly be loaded.
  33647. It doesn't actually need to load it, just to check whether the file or component
  33648. still exists.
  33649. */
  33650. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  33651. /** Searches a suggested set of directories for any plugins in this format.
  33652. The path might be ignored, e.g. by AUs, which are found by the OS rather
  33653. than manually.
  33654. */
  33655. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  33656. bool recursive) = 0;
  33657. /** Returns the typical places to look for this kind of plugin.
  33658. Note that if this returns no paths, it means that the format can't be scanned-for
  33659. (i.e. it's an internal format that doesn't live in files)
  33660. */
  33661. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  33662. protected:
  33663. AudioPluginFormat() throw();
  33664. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormat);
  33665. };
  33666. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  33667. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  33668. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  33669. /**
  33670. Implements a plugin format manager for AudioUnits.
  33671. */
  33672. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  33673. {
  33674. public:
  33675. AudioUnitPluginFormat();
  33676. ~AudioUnitPluginFormat();
  33677. const String getName() const { return "AudioUnit"; }
  33678. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33679. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33680. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33681. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  33682. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  33683. bool doesPluginStillExist (const PluginDescription& desc);
  33684. const FileSearchPath getDefaultLocationsToSearch();
  33685. private:
  33686. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginFormat);
  33687. };
  33688. #endif
  33689. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  33690. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  33691. #endif
  33692. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33693. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  33694. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33695. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33696. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  33697. // Sorry, this file is just a placeholder at the moment!...
  33698. /**
  33699. Implements a plugin format manager for DirectX plugins.
  33700. */
  33701. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  33702. {
  33703. public:
  33704. DirectXPluginFormat();
  33705. ~DirectXPluginFormat();
  33706. const String getName() const { return "DirectX"; }
  33707. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33708. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33709. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33710. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  33711. const FileSearchPath getDefaultLocationsToSearch();
  33712. private:
  33713. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectXPluginFormat);
  33714. };
  33715. #endif
  33716. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  33717. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  33718. #endif
  33719. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33720. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  33721. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33722. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33723. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  33724. // Sorry, this file is just a placeholder at the moment!...
  33725. /**
  33726. Implements a plugin format manager for DirectX plugins.
  33727. */
  33728. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  33729. {
  33730. public:
  33731. LADSPAPluginFormat();
  33732. ~LADSPAPluginFormat();
  33733. const String getName() const { return "LADSPA"; }
  33734. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33735. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33736. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33737. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  33738. const FileSearchPath getDefaultLocationsToSearch();
  33739. private:
  33740. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LADSPAPluginFormat);
  33741. };
  33742. #endif
  33743. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  33744. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  33745. #endif
  33746. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33747. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  33748. #ifdef __aeffect__
  33749. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33750. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33751. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  33752. events to the list.
  33753. This is used by both the VST hosting code and the plugin wrapper.
  33754. */
  33755. class VSTMidiEventList
  33756. {
  33757. public:
  33758. VSTMidiEventList()
  33759. : numEventsUsed (0), numEventsAllocated (0)
  33760. {
  33761. }
  33762. ~VSTMidiEventList()
  33763. {
  33764. freeEvents();
  33765. }
  33766. void clear()
  33767. {
  33768. numEventsUsed = 0;
  33769. if (events != 0)
  33770. events->numEvents = 0;
  33771. }
  33772. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  33773. {
  33774. ensureSize (numEventsUsed + 1);
  33775. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  33776. events->numEvents = ++numEventsUsed;
  33777. if (numBytes <= 4)
  33778. {
  33779. if (e->type == kVstSysExType)
  33780. {
  33781. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  33782. e->type = kVstMidiType;
  33783. e->byteSize = sizeof (VstMidiEvent);
  33784. e->noteLength = 0;
  33785. e->noteOffset = 0;
  33786. e->detune = 0;
  33787. e->noteOffVelocity = 0;
  33788. }
  33789. e->deltaFrames = frameOffset;
  33790. memcpy (e->midiData, midiData, numBytes);
  33791. }
  33792. else
  33793. {
  33794. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  33795. if (se->type == kVstSysExType)
  33796. delete[] se->sysexDump;
  33797. se->sysexDump = new char [numBytes];
  33798. memcpy (se->sysexDump, midiData, numBytes);
  33799. se->type = kVstSysExType;
  33800. se->byteSize = sizeof (VstMidiSysexEvent);
  33801. se->deltaFrames = frameOffset;
  33802. se->flags = 0;
  33803. se->dumpBytes = numBytes;
  33804. se->resvd1 = 0;
  33805. se->resvd2 = 0;
  33806. }
  33807. }
  33808. // Handy method to pull the events out of an event buffer supplied by the host
  33809. // or plugin.
  33810. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  33811. {
  33812. for (int i = 0; i < events->numEvents; ++i)
  33813. {
  33814. const VstEvent* const e = events->events[i];
  33815. if (e != 0)
  33816. {
  33817. if (e->type == kVstMidiType)
  33818. {
  33819. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  33820. 4, e->deltaFrames);
  33821. }
  33822. else if (e->type == kVstSysExType)
  33823. {
  33824. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  33825. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  33826. e->deltaFrames);
  33827. }
  33828. }
  33829. }
  33830. }
  33831. void ensureSize (int numEventsNeeded)
  33832. {
  33833. if (numEventsNeeded > numEventsAllocated)
  33834. {
  33835. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  33836. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  33837. if (events == 0)
  33838. events.calloc (size, 1);
  33839. else
  33840. events.realloc (size, 1);
  33841. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  33842. {
  33843. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  33844. (int) sizeof (VstMidiSysexEvent)));
  33845. e->type = kVstMidiType;
  33846. e->byteSize = sizeof (VstMidiEvent);
  33847. events->events[i] = (VstEvent*) e;
  33848. }
  33849. numEventsAllocated = numEventsNeeded;
  33850. }
  33851. }
  33852. void freeEvents()
  33853. {
  33854. if (events != 0)
  33855. {
  33856. for (int i = numEventsAllocated; --i >= 0;)
  33857. {
  33858. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  33859. if (e->type == kVstSysExType)
  33860. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  33861. juce_free (e);
  33862. }
  33863. events.free();
  33864. numEventsUsed = 0;
  33865. numEventsAllocated = 0;
  33866. }
  33867. }
  33868. HeapBlock <VstEvents> events;
  33869. private:
  33870. int numEventsUsed, numEventsAllocated;
  33871. };
  33872. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33873. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  33874. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  33875. #endif
  33876. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33877. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  33878. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33879. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33880. #if JUCE_PLUGINHOST_VST
  33881. /**
  33882. Implements a plugin format manager for VSTs.
  33883. */
  33884. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  33885. {
  33886. public:
  33887. VSTPluginFormat();
  33888. ~VSTPluginFormat();
  33889. const String getName() const { return "VST"; }
  33890. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  33891. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  33892. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  33893. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  33894. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  33895. bool doesPluginStillExist (const PluginDescription& desc);
  33896. const FileSearchPath getDefaultLocationsToSearch();
  33897. private:
  33898. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  33899. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginFormat);
  33900. };
  33901. #endif
  33902. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  33903. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  33904. #endif
  33905. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  33906. #endif
  33907. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33908. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  33909. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33910. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33911. /**
  33912. This maintains a list of known AudioPluginFormats.
  33913. @see AudioPluginFormat
  33914. */
  33915. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  33916. {
  33917. public:
  33918. AudioPluginFormatManager();
  33919. /** Destructor. */
  33920. ~AudioPluginFormatManager();
  33921. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  33922. /** Adds any formats that it knows about, e.g. VST.
  33923. */
  33924. void addDefaultFormats();
  33925. /** Returns the number of types of format that are available.
  33926. Use getFormat() to get one of them.
  33927. */
  33928. int getNumFormats();
  33929. /** Returns one of the available formats.
  33930. @see getNumFormats
  33931. */
  33932. AudioPluginFormat* getFormat (int index);
  33933. /** Adds a format to the list.
  33934. The object passed in will be owned and deleted by the manager.
  33935. */
  33936. void addFormat (AudioPluginFormat* format);
  33937. /** Tries to load the type for this description, by trying all the formats
  33938. that this manager knows about.
  33939. The caller is responsible for deleting the object that is returned.
  33940. If it can't load the plugin, it returns 0 and leaves a message in the
  33941. errorMessage string.
  33942. */
  33943. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  33944. String& errorMessage) const;
  33945. /** Checks that the file or component for this plugin actually still exists.
  33946. (This won't try to load the plugin)
  33947. */
  33948. bool doesPluginStillExist (const PluginDescription& description) const;
  33949. private:
  33950. OwnedArray <AudioPluginFormat> formats;
  33951. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioPluginFormatManager);
  33952. };
  33953. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  33954. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  33955. #endif
  33956. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  33957. #endif
  33958. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  33959. /*** Start of inlined file: juce_KnownPluginList.h ***/
  33960. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  33961. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  33962. /**
  33963. Manages a list of plugin types.
  33964. This can be easily edited, saved and loaded, and used to create instances of
  33965. the plugin types in it.
  33966. @see PluginListComponent
  33967. */
  33968. class JUCE_API KnownPluginList : public ChangeBroadcaster
  33969. {
  33970. public:
  33971. /** Creates an empty list.
  33972. */
  33973. KnownPluginList();
  33974. /** Destructor. */
  33975. ~KnownPluginList();
  33976. /** Clears the list. */
  33977. void clear();
  33978. /** Returns the number of types currently in the list.
  33979. @see getType
  33980. */
  33981. int getNumTypes() const throw() { return types.size(); }
  33982. /** Returns one of the types.
  33983. @see getNumTypes
  33984. */
  33985. PluginDescription* getType (int index) const throw() { return types [index]; }
  33986. /** Looks for a type in the list which comes from this file.
  33987. */
  33988. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const;
  33989. /** Looks for a type in the list which matches a plugin type ID.
  33990. The identifierString parameter must have been created by
  33991. PluginDescription::createIdentifierString().
  33992. */
  33993. PluginDescription* getTypeForIdentifierString (const String& identifierString) const;
  33994. /** Adds a type manually from its description. */
  33995. bool addType (const PluginDescription& type);
  33996. /** Removes a type. */
  33997. void removeType (int index);
  33998. /** Looks for all types that can be loaded from a given file, and adds them
  33999. to the list.
  34000. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  34001. re-tested if it's not already in the list, or if the file's modification
  34002. time has changed since the list was created. If dontRescanIfAlreadyInList is
  34003. false, the file will always be reloaded and tested.
  34004. Returns true if any new types were added, and all the types found in this
  34005. file (even if it was already known and hasn't been re-scanned) get returned
  34006. in the array.
  34007. */
  34008. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  34009. bool dontRescanIfAlreadyInList,
  34010. OwnedArray <PluginDescription>& typesFound,
  34011. AudioPluginFormat& formatToUse);
  34012. /** Returns true if the specified file is already known about and if it
  34013. hasn't been modified since our entry was created.
  34014. */
  34015. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const;
  34016. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  34017. If any types are found in the files, their descriptions are returned in the array.
  34018. */
  34019. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  34020. OwnedArray <PluginDescription>& typesFound);
  34021. /** Sort methods used to change the order of the plugins in the list.
  34022. */
  34023. enum SortMethod
  34024. {
  34025. defaultOrder = 0,
  34026. sortAlphabetically,
  34027. sortByCategory,
  34028. sortByManufacturer,
  34029. sortByFileSystemLocation
  34030. };
  34031. /** Adds all the plugin types to a popup menu so that the user can select one.
  34032. Depending on the sort method, it may add sub-menus for categories,
  34033. manufacturers, etc.
  34034. Use getIndexChosenByMenu() to find out the type that was chosen.
  34035. */
  34036. void addToMenu (PopupMenu& menu,
  34037. const SortMethod sortMethod) const;
  34038. /** Converts a menu item index that has been chosen into its index in this list.
  34039. Returns -1 if it's not an ID that was used.
  34040. @see addToMenu
  34041. */
  34042. int getIndexChosenByMenu (int menuResultCode) const;
  34043. /** Sorts the list. */
  34044. void sort (const SortMethod method);
  34045. /** Creates some XML that can be used to store the state of this list.
  34046. */
  34047. XmlElement* createXml() const;
  34048. /** Recreates the state of this list from its stored XML format.
  34049. */
  34050. void recreateFromXml (const XmlElement& xml);
  34051. private:
  34052. OwnedArray <PluginDescription> types;
  34053. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KnownPluginList);
  34054. };
  34055. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  34056. /*** End of inlined file: juce_KnownPluginList.h ***/
  34057. #endif
  34058. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  34059. #endif
  34060. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  34061. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  34062. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  34063. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  34064. /**
  34065. Scans a directory for plugins, and adds them to a KnownPluginList.
  34066. To use one of these, create it and call scanNextFile() repeatedly, until
  34067. it returns false.
  34068. */
  34069. class JUCE_API PluginDirectoryScanner
  34070. {
  34071. public:
  34072. /**
  34073. Creates a scanner.
  34074. @param listToAddResultsTo this will get the new types added to it.
  34075. @param formatToLookFor this is the type of format that you want to look for
  34076. @param directoriesToSearch the path to search
  34077. @param searchRecursively true to search recursively
  34078. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  34079. be used as a file to store the names of any plugins
  34080. that crash during initialisation. If there are
  34081. any plugins listed in it, then these will always
  34082. be scanned after all other possible files have
  34083. been tried - in this way, even if there's a few
  34084. dodgy plugins in your path, then a couple of rescans
  34085. will still manage to find all the proper plugins.
  34086. It's probably best to choose a file in the user's
  34087. application data directory (alongside your app's
  34088. settings file) for this. The file format it uses
  34089. is just a list of filenames of the modules that
  34090. failed.
  34091. */
  34092. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  34093. AudioPluginFormat& formatToLookFor,
  34094. FileSearchPath directoriesToSearch,
  34095. bool searchRecursively,
  34096. const File& deadMansPedalFile);
  34097. /** Destructor. */
  34098. ~PluginDirectoryScanner();
  34099. /** Tries the next likely-looking file.
  34100. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  34101. re-tested if it's not already in the list, or if the file's modification
  34102. time has changed since the list was created. If dontRescanIfAlreadyInList is
  34103. false, the file will always be reloaded and tested.
  34104. Returns false when there are no more files to try.
  34105. */
  34106. bool scanNextFile (bool dontRescanIfAlreadyInList);
  34107. /** Skips over the next file without scanning it.
  34108. Returns false when there are no more files to try.
  34109. */
  34110. bool skipNextFile();
  34111. /** Returns the description of the plugin that will be scanned during the next
  34112. call to scanNextFile().
  34113. This is handy if you want to show the user which file is currently getting
  34114. scanned.
  34115. */
  34116. const String getNextPluginFileThatWillBeScanned() const;
  34117. /** Returns the estimated progress, between 0 and 1.
  34118. */
  34119. float getProgress() const { return progress; }
  34120. /** This returns a list of all the filenames of things that looked like being
  34121. a plugin file, but which failed to open for some reason.
  34122. */
  34123. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  34124. private:
  34125. KnownPluginList& list;
  34126. AudioPluginFormat& format;
  34127. StringArray filesOrIdentifiersToScan;
  34128. File deadMansPedalFile;
  34129. StringArray failedFiles;
  34130. int nextIndex;
  34131. float progress;
  34132. const StringArray getDeadMansPedalFile();
  34133. void setDeadMansPedalFile (const StringArray& newContents);
  34134. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginDirectoryScanner);
  34135. };
  34136. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  34137. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  34138. #endif
  34139. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  34140. /*** Start of inlined file: juce_PluginListComponent.h ***/
  34141. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  34142. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  34143. /*** Start of inlined file: juce_ListBox.h ***/
  34144. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  34145. #define __JUCE_LISTBOX_JUCEHEADER__
  34146. class ListViewport;
  34147. /**
  34148. A subclass of this is used to drive a ListBox.
  34149. @see ListBox
  34150. */
  34151. class JUCE_API ListBoxModel
  34152. {
  34153. public:
  34154. /** Destructor. */
  34155. virtual ~ListBoxModel() {}
  34156. /** This has to return the number of items in the list.
  34157. @see ListBox::getNumRows()
  34158. */
  34159. virtual int getNumRows() = 0;
  34160. /** This method must be implemented to draw a row of the list.
  34161. */
  34162. virtual void paintListBoxItem (int rowNumber,
  34163. Graphics& g,
  34164. int width, int height,
  34165. bool rowIsSelected) = 0;
  34166. /** This is used to create or update a custom component to go in a row of the list.
  34167. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  34168. and handle mouse clicks with listBoxItemClicked().
  34169. This method will be called whenever a custom component might need to be updated - e.g.
  34170. when the table is changed, or TableListBox::updateContent() is called.
  34171. If you don't need a custom component for the specified row, then return 0.
  34172. If you do want a custom component, and the existingComponentToUpdate is null, then
  34173. this method must create a suitable new component and return it.
  34174. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  34175. by this method. In this case, the method must either update it to make sure it's correctly representing
  34176. the given row (which may be different from the one that the component was created for), or it can
  34177. delete this component and return a new one.
  34178. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  34179. */
  34180. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  34181. Component* existingComponentToUpdate);
  34182. /** This can be overridden to react to the user clicking on a row.
  34183. @see listBoxItemDoubleClicked
  34184. */
  34185. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  34186. /** This can be overridden to react to the user double-clicking on a row.
  34187. @see listBoxItemClicked
  34188. */
  34189. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  34190. /** This can be overridden to react to the user double-clicking on a part of the list where
  34191. there are no rows.
  34192. @see listBoxItemClicked
  34193. */
  34194. virtual void backgroundClicked();
  34195. /** Override this to be informed when rows are selected or deselected.
  34196. This will be called whenever a row is selected or deselected. If a range of
  34197. rows is selected all at once, this will just be called once for that event.
  34198. @param lastRowSelected the last row that the user selected. If no
  34199. rows are currently selected, this may be -1.
  34200. */
  34201. virtual void selectedRowsChanged (int lastRowSelected);
  34202. /** Override this to be informed when the delete key is pressed.
  34203. If no rows are selected when they press the key, this won't be called.
  34204. @param lastRowSelected the last row that had been selected when they pressed the
  34205. key - if there are multiple selections, this might not be
  34206. very useful
  34207. */
  34208. virtual void deleteKeyPressed (int lastRowSelected);
  34209. /** Override this to be informed when the return key is pressed.
  34210. If no rows are selected when they press the key, this won't be called.
  34211. @param lastRowSelected the last row that had been selected when they pressed the
  34212. key - if there are multiple selections, this might not be
  34213. very useful
  34214. */
  34215. virtual void returnKeyPressed (int lastRowSelected);
  34216. /** Override this to be informed when the list is scrolled.
  34217. This might be caused by the user moving the scrollbar, or by programmatic changes
  34218. to the list position.
  34219. */
  34220. virtual void listWasScrolled();
  34221. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  34222. If this returns a non-empty name then when the user drags a row, the listbox will
  34223. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  34224. a drag-and-drop operation, using this string as the source description, with the listbox
  34225. itself as the source component.
  34226. @see DragAndDropContainer::startDragging
  34227. */
  34228. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  34229. /** You can override this to provide tool tips for specific rows.
  34230. @see TooltipClient
  34231. */
  34232. virtual const String getTooltipForRow (int row);
  34233. };
  34234. /**
  34235. A list of items that can be scrolled vertically.
  34236. To create a list, you'll need to create a subclass of ListBoxModel. This can
  34237. either paint each row of the list and respond to events via callbacks, or for
  34238. more specialised tasks, it can supply a custom component to fill each row.
  34239. @see ComboBox, TableListBox
  34240. */
  34241. class JUCE_API ListBox : public Component,
  34242. public SettableTooltipClient
  34243. {
  34244. public:
  34245. /** Creates a ListBox.
  34246. The model pointer passed-in can be null, in which case you can set it later
  34247. with setModel().
  34248. */
  34249. ListBox (const String& componentName = String::empty,
  34250. ListBoxModel* model = 0);
  34251. /** Destructor. */
  34252. ~ListBox();
  34253. /** Changes the current data model to display. */
  34254. void setModel (ListBoxModel* newModel);
  34255. /** Returns the current list model. */
  34256. ListBoxModel* getModel() const throw() { return model; }
  34257. /** Causes the list to refresh its content.
  34258. Call this when the number of rows in the list changes, or if you want it
  34259. to call refreshComponentForRow() on all the row components.
  34260. Be careful not to call it from a different thread, though, as it's not
  34261. thread-safe.
  34262. */
  34263. void updateContent();
  34264. /** Turns on multiple-selection of rows.
  34265. By default this is disabled.
  34266. When your row component gets clicked you'll need to call the
  34267. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  34268. clicked and to get it to do the appropriate selection based on whether
  34269. the ctrl/shift keys are held down.
  34270. */
  34271. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  34272. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  34273. This function is here primarily for the ComboBox class to use, but might be
  34274. useful for some other purpose too.
  34275. */
  34276. void setMouseMoveSelectsRows (bool shouldSelect);
  34277. /** Selects a row.
  34278. If the row is already selected, this won't do anything.
  34279. @param rowNumber the row to select
  34280. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  34281. the selected row is off-screen, it'll scroll to make
  34282. sure that row is on-screen
  34283. @param deselectOthersFirst if true and there are multiple selections, these will
  34284. first be deselected before this item is selected
  34285. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  34286. deselectAllRows, selectRangeOfRows
  34287. */
  34288. void selectRow (int rowNumber,
  34289. bool dontScrollToShowThisRow = false,
  34290. bool deselectOthersFirst = true);
  34291. /** Selects a set of rows.
  34292. This will add these rows to the current selection, so you might need to
  34293. clear the current selection first with deselectAllRows()
  34294. @param firstRow the first row to select (inclusive)
  34295. @param lastRow the last row to select (inclusive)
  34296. */
  34297. void selectRangeOfRows (int firstRow,
  34298. int lastRow);
  34299. /** Deselects a row.
  34300. If it's not currently selected, this will do nothing.
  34301. @see selectRow, deselectAllRows
  34302. */
  34303. void deselectRow (int rowNumber);
  34304. /** Deselects any currently selected rows.
  34305. @see deselectRow
  34306. */
  34307. void deselectAllRows();
  34308. /** Selects or deselects a row.
  34309. If the row's currently selected, this deselects it, and vice-versa.
  34310. */
  34311. void flipRowSelection (int rowNumber);
  34312. /** Returns a sparse set indicating the rows that are currently selected.
  34313. @see setSelectedRows
  34314. */
  34315. const SparseSet<int> getSelectedRows() const;
  34316. /** Sets the rows that should be selected, based on an explicit set of ranges.
  34317. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  34318. method will be called. If it's false, no notification will be sent to the model.
  34319. @see getSelectedRows
  34320. */
  34321. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  34322. bool sendNotificationEventToModel = true);
  34323. /** Checks whether a row is selected.
  34324. */
  34325. bool isRowSelected (int rowNumber) const;
  34326. /** Returns the number of rows that are currently selected.
  34327. @see getSelectedRow, isRowSelected, getLastRowSelected
  34328. */
  34329. int getNumSelectedRows() const;
  34330. /** Returns the row number of a selected row.
  34331. This will return the row number of the Nth selected row. The row numbers returned will
  34332. be sorted in order from low to high.
  34333. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  34334. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  34335. selected
  34336. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  34337. */
  34338. int getSelectedRow (int index = 0) const;
  34339. /** Returns the last row that the user selected.
  34340. This isn't the same as the highest row number that is currently selected - if the user
  34341. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  34342. If nothing is selected, it will return -1.
  34343. */
  34344. int getLastRowSelected() const;
  34345. /** Multiply-selects rows based on the modifier keys.
  34346. If no modifier keys are down, this will select the given row and
  34347. deselect any others.
  34348. If the ctrl (or command on the Mac) key is down, it'll flip the
  34349. state of the selected row.
  34350. If the shift key is down, it'll select up to the given row from the
  34351. last row selected.
  34352. @see selectRow
  34353. */
  34354. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  34355. const ModifierKeys& modifiers,
  34356. bool isMouseUpEvent);
  34357. /** Scrolls the list to a particular position.
  34358. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  34359. 1.0 scrolls to the bottom.
  34360. If the total number of rows all fit onto the screen at once, then this
  34361. method won't do anything.
  34362. @see getVerticalPosition
  34363. */
  34364. void setVerticalPosition (double newProportion);
  34365. /** Returns the current vertical position as a proportion of the total.
  34366. This can be used in conjunction with setVerticalPosition() to save and restore
  34367. the list's position. It returns a value in the range 0 to 1.
  34368. @see setVerticalPosition
  34369. */
  34370. double getVerticalPosition() const;
  34371. /** Scrolls if necessary to make sure that a particular row is visible.
  34372. */
  34373. void scrollToEnsureRowIsOnscreen (int row);
  34374. /** Returns a pointer to the scrollbar.
  34375. (Unlikely to be useful for most people).
  34376. */
  34377. ScrollBar* getVerticalScrollBar() const throw();
  34378. /** Returns a pointer to the scrollbar.
  34379. (Unlikely to be useful for most people).
  34380. */
  34381. ScrollBar* getHorizontalScrollBar() const throw();
  34382. /** Finds the row index that contains a given x,y position.
  34383. The position is relative to the ListBox's top-left.
  34384. If no row exists at this position, the method will return -1.
  34385. @see getComponentForRowNumber
  34386. */
  34387. int getRowContainingPosition (int x, int y) const throw();
  34388. /** Finds a row index that would be the most suitable place to insert a new
  34389. item for a given position.
  34390. This is useful when the user is e.g. dragging and dropping onto the listbox,
  34391. because it lets you easily choose the best position to insert the item that
  34392. they drop, based on where they drop it.
  34393. If the position is out of range, this will return -1. If the position is
  34394. beyond the end of the list, it will return getNumRows() to indicate the end
  34395. of the list.
  34396. @see getComponentForRowNumber
  34397. */
  34398. int getInsertionIndexForPosition (int x, int y) const throw();
  34399. /** Returns the position of one of the rows, relative to the top-left of
  34400. the listbox.
  34401. This may be off-screen, and the range of the row number that is passed-in is
  34402. not checked to see if it's a valid row.
  34403. */
  34404. const Rectangle<int> getRowPosition (int rowNumber,
  34405. bool relativeToComponentTopLeft) const throw();
  34406. /** Finds the row component for a given row in the list.
  34407. The component returned will have been created using createRowComponent().
  34408. If the component for this row is off-screen or if the row is out-of-range,
  34409. this will return 0.
  34410. @see getRowContainingPosition
  34411. */
  34412. Component* getComponentForRowNumber (int rowNumber) const throw();
  34413. /** Returns the row number that the given component represents.
  34414. If the component isn't one of the list's rows, this will return -1.
  34415. */
  34416. int getRowNumberOfComponent (Component* rowComponent) const throw();
  34417. /** Returns the width of a row (which may be less than the width of this component
  34418. if there's a scrollbar).
  34419. */
  34420. int getVisibleRowWidth() const throw();
  34421. /** Sets the height of each row in the list.
  34422. The default height is 22 pixels.
  34423. @see getRowHeight
  34424. */
  34425. void setRowHeight (int newHeight);
  34426. /** Returns the height of a row in the list.
  34427. @see setRowHeight
  34428. */
  34429. int getRowHeight() const throw() { return rowHeight; }
  34430. /** Returns the number of rows actually visible.
  34431. This is the number of whole rows which will fit on-screen, so the value might
  34432. be more than the actual number of rows in the list.
  34433. */
  34434. int getNumRowsOnScreen() const throw();
  34435. /** A set of colour IDs to use to change the colour of various aspects of the label.
  34436. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34437. methods.
  34438. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34439. */
  34440. enum ColourIds
  34441. {
  34442. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  34443. Make this transparent if you don't want the background to be filled. */
  34444. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  34445. Make this transparent to not have an outline. */
  34446. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  34447. };
  34448. /** Sets the thickness of a border that will be drawn around the box.
  34449. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  34450. @see outlineColourId
  34451. */
  34452. void setOutlineThickness (int outlineThickness);
  34453. /** Returns the thickness of outline that will be drawn around the listbox.
  34454. @see setOutlineColour
  34455. */
  34456. int getOutlineThickness() const throw() { return outlineThickness; }
  34457. /** Sets a component that the list should use as a header.
  34458. This will position the given component at the top of the list, maintaining the
  34459. height of the component passed-in, but rescaling it horizontally to match the
  34460. width of the items in the listbox.
  34461. The component will be deleted when setHeaderComponent() is called with a
  34462. different component, or when the listbox is deleted.
  34463. */
  34464. void setHeaderComponent (Component* newHeaderComponent);
  34465. /** Changes the width of the rows in the list.
  34466. This can be used to make the list's row components wider than the list itself - the
  34467. width of the rows will be either the width of the list or this value, whichever is
  34468. greater, and if the rows become wider than the list, a horizontal scrollbar will
  34469. appear.
  34470. The default value for this is 0, which means that the rows will always
  34471. be the same width as the list.
  34472. */
  34473. void setMinimumContentWidth (int newMinimumWidth);
  34474. /** Returns the space currently available for the row items, taking into account
  34475. borders, scrollbars, etc.
  34476. */
  34477. int getVisibleContentWidth() const throw();
  34478. /** Repaints one of the rows.
  34479. This is a lightweight alternative to calling updateContent, and just causes a
  34480. repaint of the row's area.
  34481. */
  34482. void repaintRow (int rowNumber) throw();
  34483. /** This fairly obscure method creates an image that just shows the currently
  34484. selected row components.
  34485. It's a handy method for doing drag-and-drop, as it can be passed to the
  34486. DragAndDropContainer for use as the drag image.
  34487. Note that it will make the row components temporarily invisible, so if you're
  34488. using custom components this could affect them if they're sensitive to that
  34489. sort of thing.
  34490. @see Component::createComponentSnapshot
  34491. */
  34492. virtual const Image createSnapshotOfSelectedRows (int& x, int& y);
  34493. /** Returns the viewport that this ListBox uses.
  34494. You may need to use this to change parameters such as whether scrollbars
  34495. are shown, etc.
  34496. */
  34497. Viewport* getViewport() const throw();
  34498. /** @internal */
  34499. bool keyPressed (const KeyPress& key);
  34500. /** @internal */
  34501. bool keyStateChanged (bool isKeyDown);
  34502. /** @internal */
  34503. void paint (Graphics& g);
  34504. /** @internal */
  34505. void paintOverChildren (Graphics& g);
  34506. /** @internal */
  34507. void resized();
  34508. /** @internal */
  34509. void visibilityChanged();
  34510. /** @internal */
  34511. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34512. /** @internal */
  34513. void mouseMove (const MouseEvent&);
  34514. /** @internal */
  34515. void mouseExit (const MouseEvent&);
  34516. /** @internal */
  34517. void mouseUp (const MouseEvent&);
  34518. /** @internal */
  34519. void colourChanged();
  34520. /** @internal */
  34521. void startDragAndDrop (const MouseEvent& e, const String& dragDescription);
  34522. private:
  34523. friend class ListViewport;
  34524. friend class TableListBox;
  34525. ListBoxModel* model;
  34526. ScopedPointer<ListViewport> viewport;
  34527. ScopedPointer<Component> headerComponent;
  34528. int totalItems, rowHeight, minimumRowWidth;
  34529. int outlineThickness;
  34530. int lastRowSelected;
  34531. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  34532. SparseSet <int> selected;
  34533. void selectRowInternal (int rowNumber,
  34534. bool dontScrollToShowThisRow,
  34535. bool deselectOthersFirst,
  34536. bool isMouseClick);
  34537. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBox);
  34538. };
  34539. #endif // __JUCE_LISTBOX_JUCEHEADER__
  34540. /*** End of inlined file: juce_ListBox.h ***/
  34541. /*** Start of inlined file: juce_TextButton.h ***/
  34542. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  34543. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  34544. /**
  34545. A button that uses the standard lozenge-shaped background with a line of
  34546. text on it.
  34547. @see Button, DrawableButton
  34548. */
  34549. class JUCE_API TextButton : public Button
  34550. {
  34551. public:
  34552. /** Creates a TextButton.
  34553. @param buttonName the text to put in the button (the component's name is also
  34554. initially set to this string, but these can be changed later
  34555. using the setName() and setButtonText() methods)
  34556. @param toolTip an optional string to use as a toolip
  34557. @see Button
  34558. */
  34559. TextButton (const String& buttonName = String::empty,
  34560. const String& toolTip = String::empty);
  34561. /** Destructor. */
  34562. ~TextButton();
  34563. /** A set of colour IDs to use to change the colour of various aspects of the button.
  34564. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34565. methods.
  34566. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34567. */
  34568. enum ColourIds
  34569. {
  34570. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  34571. 'off'). The look-and-feel class might re-interpret this to add
  34572. effects, etc. */
  34573. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  34574. 'on'). The look-and-feel class might re-interpret this to add
  34575. effects, etc. */
  34576. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  34577. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  34578. };
  34579. /** Resizes the button to fit neatly around its current text.
  34580. If newHeight is >= 0, the button's height will be changed to this
  34581. value. If it's less than zero, its height will be unaffected.
  34582. */
  34583. void changeWidthToFitText (int newHeight = -1);
  34584. /** This can be overridden to use different fonts than the default one.
  34585. Note that you'll need to set the font's size appropriately, too.
  34586. */
  34587. virtual const Font getFont();
  34588. protected:
  34589. /** @internal */
  34590. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  34591. /** @internal */
  34592. void colourChanged();
  34593. private:
  34594. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextButton);
  34595. };
  34596. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  34597. /*** End of inlined file: juce_TextButton.h ***/
  34598. /**
  34599. A component displaying a list of plugins, with options to scan for them,
  34600. add, remove and sort them.
  34601. */
  34602. class JUCE_API PluginListComponent : public Component,
  34603. public ListBoxModel,
  34604. public ChangeListener,
  34605. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  34606. public Timer
  34607. {
  34608. public:
  34609. /**
  34610. Creates the list component.
  34611. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  34612. The properties file, if supplied, is used to store the user's last search paths.
  34613. */
  34614. PluginListComponent (KnownPluginList& listToRepresent,
  34615. const File& deadMansPedalFile,
  34616. PropertiesFile* propertiesToUse);
  34617. /** Destructor. */
  34618. ~PluginListComponent();
  34619. /** @internal */
  34620. void resized();
  34621. /** @internal */
  34622. bool isInterestedInFileDrag (const StringArray& files);
  34623. /** @internal */
  34624. void filesDropped (const StringArray& files, int, int);
  34625. /** @internal */
  34626. int getNumRows();
  34627. /** @internal */
  34628. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  34629. /** @internal */
  34630. void deleteKeyPressed (int lastRowSelected);
  34631. /** @internal */
  34632. void buttonClicked (Button* b);
  34633. /** @internal */
  34634. void changeListenerCallback (ChangeBroadcaster*);
  34635. /** @internal */
  34636. void timerCallback();
  34637. private:
  34638. KnownPluginList& list;
  34639. File deadMansPedalFile;
  34640. ListBox listBox;
  34641. TextButton optionsButton;
  34642. PropertiesFile* propertiesToUse;
  34643. int typeToScan;
  34644. void scanFor (AudioPluginFormat* format);
  34645. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginListComponent);
  34646. };
  34647. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  34648. /*** End of inlined file: juce_PluginListComponent.h ***/
  34649. #endif
  34650. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  34651. #endif
  34652. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  34653. #endif
  34654. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  34655. #endif
  34656. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  34657. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  34658. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  34659. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  34660. /**
  34661. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  34662. Use one of these objects if you want to wire-up a set of AudioProcessors
  34663. and play back the result.
  34664. Processors can be added to the graph as "nodes" using addNode(), and once
  34665. added, you can connect any of their input or output channels to other
  34666. nodes using addConnection().
  34667. To play back a graph through an audio device, you might want to use an
  34668. AudioProcessorPlayer object.
  34669. */
  34670. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  34671. public AsyncUpdater
  34672. {
  34673. public:
  34674. /** Creates an empty graph.
  34675. */
  34676. AudioProcessorGraph();
  34677. /** Destructor.
  34678. Any processor objects that have been added to the graph will also be deleted.
  34679. */
  34680. ~AudioProcessorGraph();
  34681. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  34682. To create a node, call AudioProcessorGraph::addNode().
  34683. */
  34684. class JUCE_API Node : public ReferenceCountedObject
  34685. {
  34686. public:
  34687. /** The ID number assigned to this node.
  34688. This is assigned by the graph that owns it, and can't be changed.
  34689. */
  34690. const uint32 id;
  34691. /** The actual processor object that this node represents. */
  34692. AudioProcessor* getProcessor() const throw() { return processor; }
  34693. /** A set of user-definable properties that are associated with this node.
  34694. This can be used to attach values to the node for whatever purpose seems
  34695. useful. For example, you might store an x and y position if your application
  34696. is displaying the nodes on-screen.
  34697. */
  34698. NamedValueSet properties;
  34699. /** A convenient typedef for referring to a pointer to a node object.
  34700. */
  34701. typedef ReferenceCountedObjectPtr <Node> Ptr;
  34702. private:
  34703. friend class AudioProcessorGraph;
  34704. const ScopedPointer<AudioProcessor> processor;
  34705. bool isPrepared;
  34706. Node (uint32 id, AudioProcessor* processor);
  34707. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  34708. void unprepare();
  34709. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Node);
  34710. };
  34711. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  34712. To create a connection, use AudioProcessorGraph::addConnection().
  34713. */
  34714. struct JUCE_API Connection
  34715. {
  34716. public:
  34717. /** The ID number of the node which is the input source for this connection.
  34718. @see AudioProcessorGraph::getNodeForId
  34719. */
  34720. uint32 sourceNodeId;
  34721. /** The index of the output channel of the source node from which this
  34722. connection takes its data.
  34723. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  34724. it is referring to the source node's midi output. Otherwise, it is the zero-based
  34725. index of an audio output channel in the source node.
  34726. */
  34727. int sourceChannelIndex;
  34728. /** The ID number of the node which is the destination for this connection.
  34729. @see AudioProcessorGraph::getNodeForId
  34730. */
  34731. uint32 destNodeId;
  34732. /** The index of the input channel of the destination node to which this
  34733. connection delivers its data.
  34734. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  34735. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  34736. index of an audio input channel in the destination node.
  34737. */
  34738. int destChannelIndex;
  34739. private:
  34740. JUCE_LEAK_DETECTOR (Connection);
  34741. };
  34742. /** Deletes all nodes and connections from this graph.
  34743. Any processor objects in the graph will be deleted.
  34744. */
  34745. void clear();
  34746. /** Returns the number of nodes in the graph. */
  34747. int getNumNodes() const { return nodes.size(); }
  34748. /** Returns a pointer to one of the nodes in the graph.
  34749. This will return 0 if the index is out of range.
  34750. @see getNodeForId
  34751. */
  34752. Node* getNode (const int index) const { return nodes [index]; }
  34753. /** Searches the graph for a node with the given ID number and returns it.
  34754. If no such node was found, this returns 0.
  34755. @see getNode
  34756. */
  34757. Node* getNodeForId (const uint32 nodeId) const;
  34758. /** Adds a node to the graph.
  34759. This creates a new node in the graph, for the specified processor. Once you have
  34760. added a processor to the graph, the graph owns it and will delete it later when
  34761. it is no longer needed.
  34762. The optional nodeId parameter lets you specify an ID to use for the node, but
  34763. if the value is already in use, this new node will overwrite the old one.
  34764. If this succeeds, it returns a pointer to the newly-created node.
  34765. */
  34766. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  34767. /** Deletes a node within the graph which has the specified ID.
  34768. This will also delete any connections that are attached to this node.
  34769. */
  34770. bool removeNode (uint32 nodeId);
  34771. /** Returns the number of connections in the graph. */
  34772. int getNumConnections() const { return connections.size(); }
  34773. /** Returns a pointer to one of the connections in the graph. */
  34774. const Connection* getConnection (int index) const { return connections [index]; }
  34775. /** Searches for a connection between some specified channels.
  34776. If no such connection is found, this returns 0.
  34777. */
  34778. const Connection* getConnectionBetween (uint32 sourceNodeId,
  34779. int sourceChannelIndex,
  34780. uint32 destNodeId,
  34781. int destChannelIndex) const;
  34782. /** Returns true if there is a connection between any of the channels of
  34783. two specified nodes.
  34784. */
  34785. bool isConnected (uint32 possibleSourceNodeId,
  34786. uint32 possibleDestNodeId) const;
  34787. /** Returns true if it would be legal to connect the specified points.
  34788. */
  34789. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  34790. uint32 destNodeId, int destChannelIndex) const;
  34791. /** Attempts to connect two specified channels of two nodes.
  34792. If this isn't allowed (e.g. because you're trying to connect a midi channel
  34793. to an audio one or other such nonsense), then it'll return false.
  34794. */
  34795. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  34796. uint32 destNodeId, int destChannelIndex);
  34797. /** Deletes the connection with the specified index.
  34798. Returns true if a connection was actually deleted.
  34799. */
  34800. void removeConnection (int index);
  34801. /** Deletes any connection between two specified points.
  34802. Returns true if a connection was actually deleted.
  34803. */
  34804. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  34805. uint32 destNodeId, int destChannelIndex);
  34806. /** Removes all connections from the specified node.
  34807. */
  34808. bool disconnectNode (uint32 nodeId);
  34809. /** Performs a sanity checks of all the connections.
  34810. This might be useful if some of the processors are doing things like changing
  34811. their channel counts, which could render some connections obsolete.
  34812. */
  34813. bool removeIllegalConnections();
  34814. /** A special number that represents the midi channel of a node.
  34815. This is used as a channel index value if you want to refer to the midi input
  34816. or output instead of an audio channel.
  34817. */
  34818. static const int midiChannelIndex;
  34819. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  34820. in order to use the audio that comes into and out of the graph itself.
  34821. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  34822. node in the graph which delivers the audio that is coming into the parent
  34823. graph. This allows you to stream the data to other nodes and process the
  34824. incoming audio.
  34825. Likewise, one of these in "output" mode can be sent data which it will add to
  34826. the sum of data being sent to the graph's output.
  34827. @see AudioProcessorGraph
  34828. */
  34829. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  34830. {
  34831. public:
  34832. /** Specifies the mode in which this processor will operate.
  34833. */
  34834. enum IODeviceType
  34835. {
  34836. audioInputNode, /**< In this mode, the processor has output channels
  34837. representing all the audio input channels that are
  34838. coming into its parent audio graph. */
  34839. audioOutputNode, /**< In this mode, the processor has input channels
  34840. representing all the audio output channels that are
  34841. going out of its parent audio graph. */
  34842. midiInputNode, /**< In this mode, the processor has a midi output which
  34843. delivers the same midi data that is arriving at its
  34844. parent graph. */
  34845. midiOutputNode /**< In this mode, the processor has a midi input and
  34846. any data sent to it will be passed out of the parent
  34847. graph. */
  34848. };
  34849. /** Returns the mode of this processor. */
  34850. IODeviceType getType() const { return type; }
  34851. /** Returns the parent graph to which this processor belongs, or 0 if it
  34852. hasn't yet been added to one. */
  34853. AudioProcessorGraph* getParentGraph() const { return graph; }
  34854. /** True if this is an audio or midi input. */
  34855. bool isInput() const;
  34856. /** True if this is an audio or midi output. */
  34857. bool isOutput() const;
  34858. AudioGraphIOProcessor (const IODeviceType type);
  34859. ~AudioGraphIOProcessor();
  34860. const String getName() const;
  34861. void fillInPluginDescription (PluginDescription& d) const;
  34862. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  34863. void releaseResources();
  34864. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  34865. const String getInputChannelName (int channelIndex) const;
  34866. const String getOutputChannelName (int channelIndex) const;
  34867. bool isInputChannelStereoPair (int index) const;
  34868. bool isOutputChannelStereoPair (int index) const;
  34869. bool acceptsMidi() const;
  34870. bool producesMidi() const;
  34871. bool hasEditor() const;
  34872. AudioProcessorEditor* createEditor();
  34873. int getNumParameters();
  34874. const String getParameterName (int);
  34875. float getParameter (int);
  34876. const String getParameterText (int);
  34877. void setParameter (int, float);
  34878. int getNumPrograms();
  34879. int getCurrentProgram();
  34880. void setCurrentProgram (int);
  34881. const String getProgramName (int);
  34882. void changeProgramName (int, const String&);
  34883. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  34884. void setStateInformation (const void* data, int sizeInBytes);
  34885. /** @internal */
  34886. void setParentGraph (AudioProcessorGraph* graph);
  34887. private:
  34888. const IODeviceType type;
  34889. AudioProcessorGraph* graph;
  34890. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioGraphIOProcessor);
  34891. };
  34892. // AudioProcessor methods:
  34893. const String getName() const;
  34894. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  34895. void releaseResources();
  34896. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  34897. const String getInputChannelName (int channelIndex) const;
  34898. const String getOutputChannelName (int channelIndex) const;
  34899. bool isInputChannelStereoPair (int index) const;
  34900. bool isOutputChannelStereoPair (int index) const;
  34901. bool acceptsMidi() const;
  34902. bool producesMidi() const;
  34903. bool hasEditor() const { return false; }
  34904. AudioProcessorEditor* createEditor() { return 0; }
  34905. int getNumParameters() { return 0; }
  34906. const String getParameterName (int) { return String::empty; }
  34907. float getParameter (int) { return 0; }
  34908. const String getParameterText (int) { return String::empty; }
  34909. void setParameter (int, float) { }
  34910. int getNumPrograms() { return 0; }
  34911. int getCurrentProgram() { return 0; }
  34912. void setCurrentProgram (int) { }
  34913. const String getProgramName (int) { return String::empty; }
  34914. void changeProgramName (int, const String&) { }
  34915. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  34916. void setStateInformation (const void* data, int sizeInBytes);
  34917. /** @internal */
  34918. void handleAsyncUpdate();
  34919. private:
  34920. ReferenceCountedArray <Node> nodes;
  34921. OwnedArray <Connection> connections;
  34922. int lastNodeId;
  34923. AudioSampleBuffer renderingBuffers;
  34924. OwnedArray <MidiBuffer> midiBuffers;
  34925. CriticalSection renderLock;
  34926. Array<void*> renderingOps;
  34927. friend class AudioGraphIOProcessor;
  34928. AudioSampleBuffer* currentAudioInputBuffer;
  34929. AudioSampleBuffer currentAudioOutputBuffer;
  34930. MidiBuffer* currentMidiInputBuffer;
  34931. MidiBuffer currentMidiOutputBuffer;
  34932. void clearRenderingSequence();
  34933. void buildRenderingSequence();
  34934. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  34935. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorGraph);
  34936. };
  34937. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  34938. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  34939. #endif
  34940. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  34941. #endif
  34942. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  34943. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  34944. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  34945. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  34946. /**
  34947. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  34948. To use one of these, just make it the callback used by your AudioIODevice, and
  34949. give it a processor to use by calling setProcessor().
  34950. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  34951. input to send both streams through the processor.
  34952. @see AudioProcessor, AudioProcessorGraph
  34953. */
  34954. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  34955. public MidiInputCallback
  34956. {
  34957. public:
  34958. /**
  34959. */
  34960. AudioProcessorPlayer();
  34961. /** Destructor. */
  34962. virtual ~AudioProcessorPlayer();
  34963. /** Sets the processor that should be played.
  34964. The processor that is passed in will not be deleted or owned by this object.
  34965. To stop anything playing, pass in 0 to this method.
  34966. */
  34967. void setProcessor (AudioProcessor* processorToPlay);
  34968. /** Returns the current audio processor that is being played.
  34969. */
  34970. AudioProcessor* getCurrentProcessor() const { return processor; }
  34971. /** Returns a midi message collector that you can pass midi messages to if you
  34972. want them to be injected into the midi stream that is being sent to the
  34973. processor.
  34974. */
  34975. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  34976. /** @internal */
  34977. void audioDeviceIOCallback (const float** inputChannelData,
  34978. int totalNumInputChannels,
  34979. float** outputChannelData,
  34980. int totalNumOutputChannels,
  34981. int numSamples);
  34982. /** @internal */
  34983. void audioDeviceAboutToStart (AudioIODevice* device);
  34984. /** @internal */
  34985. void audioDeviceStopped();
  34986. /** @internal */
  34987. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  34988. private:
  34989. AudioProcessor* processor;
  34990. CriticalSection lock;
  34991. double sampleRate;
  34992. int blockSize;
  34993. bool isPrepared;
  34994. int numInputChans, numOutputChans;
  34995. float* channels [128];
  34996. AudioSampleBuffer tempBuffer;
  34997. MidiBuffer incomingMidi;
  34998. MidiMessageCollector messageCollector;
  34999. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorPlayer);
  35000. };
  35001. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  35002. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  35003. #endif
  35004. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35005. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  35006. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35007. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35008. /*** Start of inlined file: juce_PropertyPanel.h ***/
  35009. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  35010. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  35011. /*** Start of inlined file: juce_PropertyComponent.h ***/
  35012. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35013. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35014. class EditableProperty;
  35015. /**
  35016. A base class for a component that goes in a PropertyPanel and displays one of
  35017. an item's properties.
  35018. Subclasses of this are used to display a property in various forms, e.g. a
  35019. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  35020. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  35021. A subclass must implement the refresh() method which will be called to tell the
  35022. component to update itself, and is also responsible for calling this it when the
  35023. item that it refers to is changed.
  35024. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  35025. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  35026. */
  35027. class JUCE_API PropertyComponent : public Component,
  35028. public SettableTooltipClient
  35029. {
  35030. public:
  35031. /** Creates a PropertyComponent.
  35032. @param propertyName the name is stored as this component's name, and is
  35033. used as the name displayed next to this component in
  35034. a property panel
  35035. @param preferredHeight the height that the component should be given - some
  35036. items may need to be larger than a normal row height.
  35037. This value can also be set if a subclass changes the
  35038. preferredHeight member variable.
  35039. */
  35040. PropertyComponent (const String& propertyName,
  35041. int preferredHeight = 25);
  35042. /** Destructor. */
  35043. ~PropertyComponent();
  35044. /** Returns this item's preferred height.
  35045. This value is specified either in the constructor or by a subclass changing the
  35046. preferredHeight member variable.
  35047. */
  35048. int getPreferredHeight() const throw() { return preferredHeight; }
  35049. void setPreferredHeight (int newHeight) throw() { preferredHeight = newHeight; }
  35050. /** Updates the property component if the item it refers to has changed.
  35051. A subclass must implement this method, and other objects may call it to
  35052. force it to refresh itself.
  35053. The subclass should be economical in the amount of work is done, so for
  35054. example it should check whether it really needs to do a repaint rather than
  35055. just doing one every time this method is called, as it may be called when
  35056. the value being displayed hasn't actually changed.
  35057. */
  35058. virtual void refresh() = 0;
  35059. /** The default paint method fills the background and draws a label for the
  35060. item's name.
  35061. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  35062. */
  35063. void paint (Graphics& g);
  35064. /** The default resize method positions any child component to the right of this
  35065. one, based on the look and feel's default label size.
  35066. */
  35067. void resized();
  35068. /** By default, this just repaints the component. */
  35069. void enablementChanged();
  35070. protected:
  35071. /** Used by the PropertyPanel to determine how high this component needs to be.
  35072. A subclass can update this value in its constructor but shouldn't alter it later
  35073. as changes won't necessarily be picked up.
  35074. */
  35075. int preferredHeight;
  35076. private:
  35077. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyComponent);
  35078. };
  35079. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35080. /*** End of inlined file: juce_PropertyComponent.h ***/
  35081. /**
  35082. A panel that holds a list of PropertyComponent objects.
  35083. This panel displays a list of PropertyComponents, and allows them to be organised
  35084. into collapsible sections.
  35085. To use, simply create one of these and add your properties to it with addProperties()
  35086. or addSection().
  35087. @see PropertyComponent
  35088. */
  35089. class JUCE_API PropertyPanel : public Component
  35090. {
  35091. public:
  35092. /** Creates an empty property panel. */
  35093. PropertyPanel();
  35094. /** Destructor. */
  35095. ~PropertyPanel();
  35096. /** Deletes all property components from the panel.
  35097. */
  35098. void clear();
  35099. /** Adds a set of properties to the panel.
  35100. The components in the list will be owned by this object and will be automatically
  35101. deleted later on when no longer needed.
  35102. These properties are added without them being inside a named section. If you
  35103. want them to be kept together in a collapsible section, use addSection() instead.
  35104. */
  35105. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  35106. /** Adds a set of properties to the panel.
  35107. These properties are added at the bottom of the list, under a section heading with
  35108. a plus/minus button that allows it to be opened and closed.
  35109. The components in the list will be owned by this object and will be automatically
  35110. deleted later on when no longer needed.
  35111. To add properies without them being in a section, use addProperties().
  35112. */
  35113. void addSection (const String& sectionTitle,
  35114. const Array <PropertyComponent*>& newPropertyComponents,
  35115. bool shouldSectionInitiallyBeOpen = true);
  35116. /** Calls the refresh() method of all PropertyComponents in the panel */
  35117. void refreshAll() const;
  35118. /** Returns a list of all the names of sections in the panel.
  35119. These are the sections that have been added with addSection().
  35120. */
  35121. const StringArray getSectionNames() const;
  35122. /** Returns true if the section at this index is currently open.
  35123. The index is from 0 up to the number of items returned by getSectionNames().
  35124. */
  35125. bool isSectionOpen (int sectionIndex) const;
  35126. /** Opens or closes one of the sections.
  35127. The index is from 0 up to the number of items returned by getSectionNames().
  35128. */
  35129. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  35130. /** Enables or disables one of the sections.
  35131. The index is from 0 up to the number of items returned by getSectionNames().
  35132. */
  35133. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  35134. /** Saves the current state of open/closed sections so it can be restored later.
  35135. The caller is responsible for deleting the object that is returned.
  35136. To restore this state, use restoreOpennessState().
  35137. @see restoreOpennessState
  35138. */
  35139. XmlElement* getOpennessState() const;
  35140. /** Restores a previously saved arrangement of open/closed sections.
  35141. This will try to restore a snapshot of the panel's state that was created by
  35142. the getOpennessState() method. If any of the sections named in the original
  35143. XML aren't present, they will be ignored.
  35144. @see getOpennessState
  35145. */
  35146. void restoreOpennessState (const XmlElement& newState);
  35147. /** Sets a message to be displayed when there are no properties in the panel.
  35148. The default message is "nothing selected".
  35149. */
  35150. void setMessageWhenEmpty (const String& newMessage);
  35151. /** Returns the message that is displayed when there are no properties.
  35152. @see setMessageWhenEmpty
  35153. */
  35154. const String& getMessageWhenEmpty() const;
  35155. /** @internal */
  35156. void paint (Graphics& g);
  35157. /** @internal */
  35158. void resized();
  35159. private:
  35160. Viewport viewport;
  35161. class PropertyHolderComponent;
  35162. PropertyHolderComponent* propertyHolderComponent;
  35163. String messageWhenEmpty;
  35164. void updatePropHolderLayout() const;
  35165. void updatePropHolderLayout (int width) const;
  35166. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PropertyPanel);
  35167. };
  35168. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  35169. /*** End of inlined file: juce_PropertyPanel.h ***/
  35170. /**
  35171. A type of UI component that displays the parameters of an AudioProcessor as
  35172. a simple list of sliders.
  35173. This can be used for showing an editor for a processor that doesn't supply
  35174. its own custom editor.
  35175. @see AudioProcessor
  35176. */
  35177. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  35178. {
  35179. public:
  35180. GenericAudioProcessorEditor (AudioProcessor* owner);
  35181. ~GenericAudioProcessorEditor();
  35182. void paint (Graphics& g);
  35183. void resized();
  35184. private:
  35185. PropertyPanel panel;
  35186. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GenericAudioProcessorEditor);
  35187. };
  35188. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  35189. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  35190. #endif
  35191. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  35192. /*** Start of inlined file: juce_Sampler.h ***/
  35193. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  35194. #define __JUCE_SAMPLER_JUCEHEADER__
  35195. /*** Start of inlined file: juce_Synthesiser.h ***/
  35196. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  35197. #define __JUCE_SYNTHESISER_JUCEHEADER__
  35198. /**
  35199. Describes one of the sounds that a Synthesiser can play.
  35200. A synthesiser can contain one or more sounds, and a sound can choose which
  35201. midi notes and channels can trigger it.
  35202. The SynthesiserSound is a passive class that just describes what the sound is -
  35203. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  35204. more than one SynthesiserVoice to play the same sound at the same time.
  35205. @see Synthesiser, SynthesiserVoice
  35206. */
  35207. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  35208. {
  35209. protected:
  35210. SynthesiserSound();
  35211. public:
  35212. /** Destructor. */
  35213. virtual ~SynthesiserSound();
  35214. /** Returns true if this sound should be played when a given midi note is pressed.
  35215. The Synthesiser will use this information when deciding which sounds to trigger
  35216. for a given note.
  35217. */
  35218. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  35219. /** Returns true if the sound should be triggered by midi events on a given channel.
  35220. The Synthesiser will use this information when deciding which sounds to trigger
  35221. for a given note.
  35222. */
  35223. virtual bool appliesToChannel (const int midiChannel) = 0;
  35224. /**
  35225. */
  35226. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  35227. private:
  35228. JUCE_LEAK_DETECTOR (SynthesiserSound);
  35229. };
  35230. /**
  35231. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  35232. A voice plays a single sound at a time, and a synthesiser holds an array of
  35233. voices so that it can play polyphonically.
  35234. @see Synthesiser, SynthesiserSound
  35235. */
  35236. class JUCE_API SynthesiserVoice
  35237. {
  35238. public:
  35239. /** Creates a voice. */
  35240. SynthesiserVoice();
  35241. /** Destructor. */
  35242. virtual ~SynthesiserVoice();
  35243. /** Returns the midi note that this voice is currently playing.
  35244. Returns a value less than 0 if no note is playing.
  35245. */
  35246. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  35247. /** Returns the sound that this voice is currently playing.
  35248. Returns 0 if it's not playing.
  35249. */
  35250. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  35251. /** Must return true if this voice object is capable of playing the given sound.
  35252. If there are different classes of sound, and different classes of voice, a voice can
  35253. choose which ones it wants to take on.
  35254. A typical implementation of this method may just return true if there's only one type
  35255. of voice and sound, or it might check the type of the sound object passed-in and
  35256. see if it's one that it understands.
  35257. */
  35258. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  35259. /** Called to start a new note.
  35260. This will be called during the rendering callback, so must be fast and thread-safe.
  35261. */
  35262. virtual void startNote (const int midiNoteNumber,
  35263. const float velocity,
  35264. SynthesiserSound* sound,
  35265. const int currentPitchWheelPosition) = 0;
  35266. /** Called to stop a note.
  35267. This will be called during the rendering callback, so must be fast and thread-safe.
  35268. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  35269. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  35270. and allow the synth to reassign it another sound.
  35271. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  35272. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  35273. finishes playing (during the rendering callback), it must make sure that it calls
  35274. clearCurrentNote().
  35275. */
  35276. virtual void stopNote (const bool allowTailOff) = 0;
  35277. /** Called to let the voice know that the pitch wheel has been moved.
  35278. This will be called during the rendering callback, so must be fast and thread-safe.
  35279. */
  35280. virtual void pitchWheelMoved (const int newValue) = 0;
  35281. /** Called to let the voice know that a midi controller has been moved.
  35282. This will be called during the rendering callback, so must be fast and thread-safe.
  35283. */
  35284. virtual void controllerMoved (const int controllerNumber,
  35285. const int newValue) = 0;
  35286. /** Renders the next block of data for this voice.
  35287. The output audio data must be added to the current contents of the buffer provided.
  35288. Only the region of the buffer between startSample and (startSample + numSamples)
  35289. should be altered by this method.
  35290. If the voice is currently silent, it should just return without doing anything.
  35291. If the sound that the voice is playing finishes during the course of this rendered
  35292. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  35293. The size of the blocks that are rendered can change each time it is called, and may
  35294. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  35295. the voice's methods will be called to tell it about note and controller events.
  35296. */
  35297. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  35298. int startSample,
  35299. int numSamples) = 0;
  35300. /** Returns true if the voice is currently playing a sound which is mapped to the given
  35301. midi channel.
  35302. If it's not currently playing, this will return false.
  35303. */
  35304. bool isPlayingChannel (int midiChannel) const;
  35305. /** Changes the voice's reference sample rate.
  35306. The rate is set so that subclasses know the output rate and can set their pitch
  35307. accordingly.
  35308. This method is called by the synth, and subclasses can access the current rate with
  35309. the currentSampleRate member.
  35310. */
  35311. void setCurrentPlaybackSampleRate (double newRate);
  35312. protected:
  35313. /** Returns the current target sample rate at which rendering is being done.
  35314. This is available for subclasses so they can pitch things correctly.
  35315. */
  35316. double getSampleRate() const { return currentSampleRate; }
  35317. /** Resets the state of this voice after a sound has finished playing.
  35318. The subclass must call this when it finishes playing a note and becomes available
  35319. to play new ones.
  35320. It must either call it in the stopNote() method, or if the voice is tailing off,
  35321. then it should call it later during the renderNextBlock method, as soon as it
  35322. finishes its tail-off.
  35323. It can also be called at any time during the render callback if the sound happens
  35324. to have finished, e.g. if it's playing a sample and the sample finishes.
  35325. */
  35326. void clearCurrentNote();
  35327. private:
  35328. friend class Synthesiser;
  35329. double currentSampleRate;
  35330. int currentlyPlayingNote;
  35331. uint32 noteOnTime;
  35332. SynthesiserSound::Ptr currentlyPlayingSound;
  35333. JUCE_LEAK_DETECTOR (SynthesiserVoice);
  35334. };
  35335. /**
  35336. Base class for a musical device that can play sounds.
  35337. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  35338. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  35339. which can play back one of these sounds.
  35340. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  35341. set of sounds, and a set of voices it can use to play them. If you only give it
  35342. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  35343. have available.
  35344. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  35345. events that go in will be scanned for note on/off messages, and these are used to
  35346. start and stop the voices playing the appropriate sounds.
  35347. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  35348. noteOff() and other controller methods.
  35349. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  35350. what the target playback rate is. This value is passed on to the voices so that
  35351. they can pitch their output correctly.
  35352. */
  35353. class JUCE_API Synthesiser
  35354. {
  35355. public:
  35356. /** Creates a new synthesiser.
  35357. You'll need to add some sounds and voices before it'll make any sound..
  35358. */
  35359. Synthesiser();
  35360. /** Destructor. */
  35361. virtual ~Synthesiser();
  35362. /** Deletes all voices. */
  35363. void clearVoices();
  35364. /** Returns the number of voices that have been added. */
  35365. int getNumVoices() const { return voices.size(); }
  35366. /** Returns one of the voices that have been added. */
  35367. SynthesiserVoice* getVoice (int index) const;
  35368. /** Adds a new voice to the synth.
  35369. All the voices should be the same class of object and are treated equally.
  35370. The object passed in will be managed by the synthesiser, which will delete
  35371. it later on when no longer needed. The caller should not retain a pointer to the
  35372. voice.
  35373. */
  35374. void addVoice (SynthesiserVoice* newVoice);
  35375. /** Deletes one of the voices. */
  35376. void removeVoice (int index);
  35377. /** Deletes all sounds. */
  35378. void clearSounds();
  35379. /** Returns the number of sounds that have been added to the synth. */
  35380. int getNumSounds() const { return sounds.size(); }
  35381. /** Returns one of the sounds. */
  35382. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  35383. /** Adds a new sound to the synthesiser.
  35384. The object passed in is reference counted, so will be deleted when it is removed
  35385. from the synthesiser, and when no voices are still using it.
  35386. */
  35387. void addSound (const SynthesiserSound::Ptr& newSound);
  35388. /** Removes and deletes one of the sounds. */
  35389. void removeSound (int index);
  35390. /** If set to true, then the synth will try to take over an existing voice if
  35391. it runs out and needs to play another note.
  35392. The value of this boolean is passed into findFreeVoice(), so the result will
  35393. depend on the implementation of this method.
  35394. */
  35395. void setNoteStealingEnabled (bool shouldStealNotes);
  35396. /** Returns true if note-stealing is enabled.
  35397. @see setNoteStealingEnabled
  35398. */
  35399. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  35400. /** Triggers a note-on event.
  35401. The default method here will find all the sounds that want to be triggered by
  35402. this note/channel. For each sound, it'll try to find a free voice, and use the
  35403. voice to start playing the sound.
  35404. Subclasses might want to override this if they need a more complex algorithm.
  35405. This method will be called automatically according to the midi data passed into
  35406. renderNextBlock(), but may be called explicitly too.
  35407. */
  35408. virtual void noteOn (int midiChannel,
  35409. int midiNoteNumber,
  35410. float velocity);
  35411. /** Triggers a note-off event.
  35412. This will turn off any voices that are playing a sound for the given note/channel.
  35413. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  35414. (if they can do). If this is false, the notes will all be cut off immediately.
  35415. This method will be called automatically according to the midi data passed into
  35416. renderNextBlock(), but may be called explicitly too.
  35417. */
  35418. virtual void noteOff (int midiChannel,
  35419. int midiNoteNumber,
  35420. bool allowTailOff);
  35421. /** Turns off all notes.
  35422. This will turn off any voices that are playing a sound on the given midi channel.
  35423. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  35424. which channel they're playing.
  35425. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  35426. (if they can do). If this is false, the notes will all be cut off immediately.
  35427. This method will be called automatically according to the midi data passed into
  35428. renderNextBlock(), but may be called explicitly too.
  35429. */
  35430. virtual void allNotesOff (int midiChannel,
  35431. bool allowTailOff);
  35432. /** Sends a pitch-wheel message.
  35433. This will send a pitch-wheel message to any voices that are playing sounds on
  35434. the given midi channel.
  35435. This method will be called automatically according to the midi data passed into
  35436. renderNextBlock(), but may be called explicitly too.
  35437. @param midiChannel the midi channel for the event
  35438. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  35439. */
  35440. virtual void handlePitchWheel (int midiChannel,
  35441. int wheelValue);
  35442. /** Sends a midi controller message.
  35443. This will send a midi controller message to any voices that are playing sounds on
  35444. the given midi channel.
  35445. This method will be called automatically according to the midi data passed into
  35446. renderNextBlock(), but may be called explicitly too.
  35447. @param midiChannel the midi channel for the event
  35448. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  35449. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  35450. */
  35451. virtual void handleController (int midiChannel,
  35452. int controllerNumber,
  35453. int controllerValue);
  35454. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  35455. render.
  35456. This value is propagated to the voices so that they can use it to render the correct
  35457. pitches.
  35458. */
  35459. void setCurrentPlaybackSampleRate (double sampleRate);
  35460. /** Creates the next block of audio output.
  35461. This will process the next numSamples of data from all the voices, and add that output
  35462. to the audio block supplied, starting from the offset specified. Note that the
  35463. data will be added to the current contents of the buffer, so you should clear it
  35464. before calling this method if necessary.
  35465. The midi events in the inputMidi buffer are parsed for note and controller events,
  35466. and these are used to trigger the voices. Note that the startSample offset applies
  35467. both to the audio output buffer and the midi input buffer, so any midi events
  35468. with timestamps outside the specified region will be ignored.
  35469. */
  35470. void renderNextBlock (AudioSampleBuffer& outputAudio,
  35471. const MidiBuffer& inputMidi,
  35472. int startSample,
  35473. int numSamples);
  35474. protected:
  35475. /** This is used to control access to the rendering callback and the note trigger methods. */
  35476. CriticalSection lock;
  35477. OwnedArray <SynthesiserVoice> voices;
  35478. ReferenceCountedArray <SynthesiserSound> sounds;
  35479. /** The last pitch-wheel values for each midi channel. */
  35480. int lastPitchWheelValues [16];
  35481. /** Searches through the voices to find one that's not currently playing, and which
  35482. can play the given sound.
  35483. Returns 0 if all voices are busy and stealing isn't enabled.
  35484. This can be overridden to implement custom voice-stealing algorithms.
  35485. */
  35486. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  35487. const bool stealIfNoneAvailable) const;
  35488. /** Starts a specified voice playing a particular sound.
  35489. You'll probably never need to call this, it's used internally by noteOn(), but
  35490. may be needed by subclasses for custom behaviours.
  35491. */
  35492. void startVoice (SynthesiserVoice* voice,
  35493. SynthesiserSound* sound,
  35494. int midiChannel,
  35495. int midiNoteNumber,
  35496. float velocity);
  35497. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  35498. // Temporary method here to cause a compiler error - note the new parameters for this method.
  35499. int findFreeVoice (const bool) const { return 0; }
  35500. #endif
  35501. private:
  35502. double sampleRate;
  35503. uint32 lastNoteOnCounter;
  35504. bool shouldStealNotes;
  35505. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Synthesiser);
  35506. };
  35507. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  35508. /*** End of inlined file: juce_Synthesiser.h ***/
  35509. /**
  35510. A subclass of SynthesiserSound that represents a sampled audio clip.
  35511. This is a pretty basic sampler, and just attempts to load the whole audio stream
  35512. into memory.
  35513. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  35514. give it some SampledSound objects to play.
  35515. @see SamplerVoice, Synthesiser, SynthesiserSound
  35516. */
  35517. class JUCE_API SamplerSound : public SynthesiserSound
  35518. {
  35519. public:
  35520. /** Creates a sampled sound from an audio reader.
  35521. This will attempt to load the audio from the source into memory and store
  35522. it in this object.
  35523. @param name a name for the sample
  35524. @param source the audio to load. This object can be safely deleted by the
  35525. caller after this constructor returns
  35526. @param midiNotes the set of midi keys that this sound should be played on. This
  35527. is used by the SynthesiserSound::appliesToNote() method
  35528. @param midiNoteForNormalPitch the midi note at which the sample should be played
  35529. with its natural rate. All other notes will be pitched
  35530. up or down relative to this one
  35531. @param attackTimeSecs the attack (fade-in) time, in seconds
  35532. @param releaseTimeSecs the decay (fade-out) time, in seconds
  35533. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  35534. source, in seconds
  35535. */
  35536. SamplerSound (const String& name,
  35537. AudioFormatReader& source,
  35538. const BigInteger& midiNotes,
  35539. int midiNoteForNormalPitch,
  35540. double attackTimeSecs,
  35541. double releaseTimeSecs,
  35542. double maxSampleLengthSeconds);
  35543. /** Destructor. */
  35544. ~SamplerSound();
  35545. /** Returns the sample's name */
  35546. const String& getName() const { return name; }
  35547. /** Returns the audio sample data.
  35548. This could be 0 if there was a problem loading it.
  35549. */
  35550. AudioSampleBuffer* getAudioData() const { return data; }
  35551. bool appliesToNote (const int midiNoteNumber);
  35552. bool appliesToChannel (const int midiChannel);
  35553. private:
  35554. friend class SamplerVoice;
  35555. String name;
  35556. ScopedPointer <AudioSampleBuffer> data;
  35557. double sourceSampleRate;
  35558. BigInteger midiNotes;
  35559. int length, attackSamples, releaseSamples;
  35560. int midiRootNote;
  35561. JUCE_LEAK_DETECTOR (SamplerSound);
  35562. };
  35563. /**
  35564. A subclass of SynthesiserVoice that can play a SamplerSound.
  35565. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  35566. give it some SampledSound objects to play.
  35567. @see SamplerSound, Synthesiser, SynthesiserVoice
  35568. */
  35569. class JUCE_API SamplerVoice : public SynthesiserVoice
  35570. {
  35571. public:
  35572. /** Creates a SamplerVoice.
  35573. */
  35574. SamplerVoice();
  35575. /** Destructor. */
  35576. ~SamplerVoice();
  35577. bool canPlaySound (SynthesiserSound* sound);
  35578. void startNote (const int midiNoteNumber,
  35579. const float velocity,
  35580. SynthesiserSound* sound,
  35581. const int currentPitchWheelPosition);
  35582. void stopNote (const bool allowTailOff);
  35583. void pitchWheelMoved (const int newValue);
  35584. void controllerMoved (const int controllerNumber,
  35585. const int newValue);
  35586. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  35587. private:
  35588. double pitchRatio;
  35589. double sourceSamplePosition;
  35590. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  35591. bool isInAttack, isInRelease;
  35592. JUCE_LEAK_DETECTOR (SamplerVoice);
  35593. };
  35594. #endif // __JUCE_SAMPLER_JUCEHEADER__
  35595. /*** End of inlined file: juce_Sampler.h ***/
  35596. #endif
  35597. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  35598. #endif
  35599. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  35600. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  35601. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  35602. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  35603. /** Manages a list of ActionListeners, and can send them messages.
  35604. To quickly add methods to your class that can add/remove action
  35605. listeners and broadcast to them, you can derive from this.
  35606. @see ActionListener, ChangeListener
  35607. */
  35608. class JUCE_API ActionBroadcaster
  35609. {
  35610. public:
  35611. /** Creates an ActionBroadcaster. */
  35612. ActionBroadcaster();
  35613. /** Destructor. */
  35614. virtual ~ActionBroadcaster();
  35615. /** Adds a listener to the list.
  35616. Trying to add a listener that's already on the list will have no effect.
  35617. */
  35618. void addActionListener (ActionListener* listener);
  35619. /** Removes a listener from the list.
  35620. If the listener isn't on the list, this won't have any effect.
  35621. */
  35622. void removeActionListener (ActionListener* listener);
  35623. /** Removes all listeners from the list. */
  35624. void removeAllActionListeners();
  35625. /** Broadcasts a message to all the registered listeners.
  35626. @see ActionListener::actionListenerCallback
  35627. */
  35628. void sendActionMessage (const String& message) const;
  35629. private:
  35630. class CallbackReceiver : public MessageListener
  35631. {
  35632. public:
  35633. CallbackReceiver();
  35634. void handleMessage (const Message&);
  35635. ActionBroadcaster* owner;
  35636. };
  35637. friend class CallbackReceiver;
  35638. CallbackReceiver callback;
  35639. SortedSet <ActionListener*> actionListeners;
  35640. CriticalSection actionListenerLock;
  35641. JUCE_DECLARE_NON_COPYABLE (ActionBroadcaster);
  35642. };
  35643. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  35644. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  35645. #endif
  35646. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  35647. #endif
  35648. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  35649. #endif
  35650. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  35651. #endif
  35652. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  35653. #endif
  35654. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  35655. #endif
  35656. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  35657. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  35658. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  35659. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  35660. class InterprocessConnectionServer;
  35661. /**
  35662. Manages a simple two-way messaging connection to another process, using either
  35663. a socket or a named pipe as the transport medium.
  35664. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  35665. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  35666. and incoming messages will result in a callback via the messageReceived()
  35667. method.
  35668. To open a pipe and wait for another client to connect to it, use the createPipe()
  35669. method.
  35670. To act as a socket server and create connections for one or more client, see the
  35671. InterprocessConnectionServer class.
  35672. @see InterprocessConnectionServer, Socket, NamedPipe
  35673. */
  35674. class JUCE_API InterprocessConnection : public Thread,
  35675. private MessageListener
  35676. {
  35677. public:
  35678. /** Creates a connection.
  35679. Connections are created manually, connecting them with the connectToSocket()
  35680. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  35681. when a client wants to connect.
  35682. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  35683. connectionLost() and messageReceived() methods will
  35684. always be made using the message thread; if false,
  35685. these will be called immediately on the connection's
  35686. own thread.
  35687. @param magicMessageHeaderNumber a magic number to use in the header to check the
  35688. validity of the data blocks being sent and received. This
  35689. can be any number, but the sender and receiver must obviously
  35690. use matching values or they won't recognise each other.
  35691. */
  35692. InterprocessConnection (bool callbacksOnMessageThread = true,
  35693. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  35694. /** Destructor. */
  35695. ~InterprocessConnection();
  35696. /** Tries to connect this object to a socket.
  35697. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  35698. object waiting to receive client connections on this port number.
  35699. @param hostName the host computer, either a network address or name
  35700. @param portNumber the socket port number to try to connect to
  35701. @param timeOutMillisecs how long to keep trying before giving up
  35702. @returns true if the connection is established successfully
  35703. @see Socket
  35704. */
  35705. bool connectToSocket (const String& hostName,
  35706. int portNumber,
  35707. int timeOutMillisecs);
  35708. /** Tries to connect the object to an existing named pipe.
  35709. For this to work, another process on the same computer must already have opened
  35710. an InterprocessConnection object and used createPipe() to create a pipe for this
  35711. to connect to.
  35712. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  35713. @returns true if it connects successfully.
  35714. @see createPipe, NamedPipe
  35715. */
  35716. bool connectToPipe (const String& pipeName,
  35717. int pipeReceiveMessageTimeoutMs = -1);
  35718. /** Tries to create a new pipe for other processes to connect to.
  35719. This creates a pipe with the given name, so that other processes can use
  35720. connectToPipe() to connect to the other end.
  35721. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  35722. If another process is already using this pipe, this will fail and return false.
  35723. */
  35724. bool createPipe (const String& pipeName,
  35725. int pipeReceiveMessageTimeoutMs = -1);
  35726. /** Disconnects and closes any currently-open sockets or pipes. */
  35727. void disconnect();
  35728. /** True if a socket or pipe is currently active. */
  35729. bool isConnected() const;
  35730. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  35731. StreamingSocket* getSocket() const throw() { return socket; }
  35732. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  35733. NamedPipe* getPipe() const throw() { return pipe; }
  35734. /** Returns the name of the machine at the other end of this connection.
  35735. This will return an empty string if the other machine isn't known for
  35736. some reason.
  35737. */
  35738. const String getConnectedHostName() const;
  35739. /** Tries to send a message to the other end of this connection.
  35740. This will fail if it's not connected, or if there's some kind of write error. If
  35741. it succeeds, the connection object at the other end will receive the message by
  35742. a callback to its messageReceived() method.
  35743. @see messageReceived
  35744. */
  35745. bool sendMessage (const MemoryBlock& message);
  35746. /** Called when the connection is first connected.
  35747. If the connection was created with the callbacksOnMessageThread flag set, then
  35748. this will be called on the message thread; otherwise it will be called on a server
  35749. thread.
  35750. */
  35751. virtual void connectionMade() = 0;
  35752. /** Called when the connection is broken.
  35753. If the connection was created with the callbacksOnMessageThread flag set, then
  35754. this will be called on the message thread; otherwise it will be called on a server
  35755. thread.
  35756. */
  35757. virtual void connectionLost() = 0;
  35758. /** Called when a message arrives.
  35759. When the object at the other end of this connection sends us a message with sendMessage(),
  35760. this callback is used to deliver it to us.
  35761. If the connection was created with the callbacksOnMessageThread flag set, then
  35762. this will be called on the message thread; otherwise it will be called on a server
  35763. thread.
  35764. @see sendMessage
  35765. */
  35766. virtual void messageReceived (const MemoryBlock& message) = 0;
  35767. private:
  35768. CriticalSection pipeAndSocketLock;
  35769. ScopedPointer <StreamingSocket> socket;
  35770. ScopedPointer <NamedPipe> pipe;
  35771. bool callbackConnectionState;
  35772. const bool useMessageThread;
  35773. const uint32 magicMessageHeader;
  35774. int pipeReceiveMessageTimeout;
  35775. friend class InterprocessConnectionServer;
  35776. void initialiseWithSocket (StreamingSocket* socket_);
  35777. void initialiseWithPipe (NamedPipe* pipe_);
  35778. void handleMessage (const Message& message);
  35779. void connectionMadeInt();
  35780. void connectionLostInt();
  35781. void deliverDataInt (const MemoryBlock& data);
  35782. bool readNextMessageInt();
  35783. void run();
  35784. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnection);
  35785. };
  35786. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  35787. /*** End of inlined file: juce_InterprocessConnection.h ***/
  35788. #endif
  35789. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  35790. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  35791. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  35792. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  35793. /**
  35794. An object that waits for client sockets to connect to a port on this host, and
  35795. creates InterprocessConnection objects for each one.
  35796. To use this, create a class derived from it which implements the createConnectionObject()
  35797. method, so that it creates suitable connection objects for each client that tries
  35798. to connect.
  35799. @see InterprocessConnection
  35800. */
  35801. class JUCE_API InterprocessConnectionServer : private Thread
  35802. {
  35803. public:
  35804. /** Creates an uninitialised server object.
  35805. */
  35806. InterprocessConnectionServer();
  35807. /** Destructor. */
  35808. ~InterprocessConnectionServer();
  35809. /** Starts an internal thread which listens on the given port number.
  35810. While this is running, in another process tries to connect with the
  35811. InterprocessConnection::connectToSocket() method, this object will call
  35812. createConnectionObject() to create a connection to that client.
  35813. Use stop() to stop the thread running.
  35814. @see createConnectionObject, stop
  35815. */
  35816. bool beginWaitingForSocket (int portNumber);
  35817. /** Terminates the listener thread, if it's active.
  35818. @see beginWaitingForSocket
  35819. */
  35820. void stop();
  35821. protected:
  35822. /** Creates a suitable connection object for a client process that wants to
  35823. connect to this one.
  35824. This will be called by the listener thread when a client process tries
  35825. to connect, and must return a new InterprocessConnection object that will
  35826. then run as this end of the connection.
  35827. @see InterprocessConnection
  35828. */
  35829. virtual InterprocessConnection* createConnectionObject() = 0;
  35830. private:
  35831. ScopedPointer <StreamingSocket> socket;
  35832. void run();
  35833. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InterprocessConnectionServer);
  35834. };
  35835. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  35836. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  35837. #endif
  35838. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  35839. #endif
  35840. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  35841. #endif
  35842. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  35843. #endif
  35844. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  35845. /*** Start of inlined file: juce_MessageManager.h ***/
  35846. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  35847. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  35848. class Component;
  35849. class MessageManagerLock;
  35850. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  35851. */
  35852. typedef void* (MessageCallbackFunction) (void* userData);
  35853. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  35854. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  35855. */
  35856. class JUCE_API MessageManager
  35857. {
  35858. public:
  35859. /** Returns the global instance of the MessageManager. */
  35860. static MessageManager* getInstance() throw();
  35861. /** Runs the event dispatch loop until a stop message is posted.
  35862. This method is only intended to be run by the application's startup routine,
  35863. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  35864. @see stopDispatchLoop
  35865. */
  35866. void runDispatchLoop();
  35867. /** Sends a signal that the dispatch loop should terminate.
  35868. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  35869. will be interrupted and will return.
  35870. @see runDispatchLoop
  35871. */
  35872. void stopDispatchLoop();
  35873. /** Returns true if the stopDispatchLoop() method has been called.
  35874. */
  35875. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  35876. /** Synchronously dispatches messages until a given time has elapsed.
  35877. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  35878. otherwise returns true.
  35879. */
  35880. bool runDispatchLoopUntil (int millisecondsToRunFor);
  35881. /** Calls a function using the message-thread.
  35882. This can be used by any thread to cause this function to be called-back
  35883. by the message thread. If it's the message-thread that's calling this method,
  35884. then the function will just be called; if another thread is calling, a message
  35885. will be posted to the queue, and this method will block until that message
  35886. is delivered, the function is called, and the result is returned.
  35887. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  35888. thread has a critical section locked, which an unrelated message callback then tries to lock
  35889. before the message thread gets round to processing this callback.
  35890. @param callback the function to call - its signature must be @code
  35891. void* myCallbackFunction (void*) @endcode
  35892. @param userData a user-defined pointer that will be passed to the function that gets called
  35893. @returns the value that the callback function returns.
  35894. @see MessageManagerLock
  35895. */
  35896. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  35897. void* userData);
  35898. /** Returns true if the caller-thread is the message thread. */
  35899. bool isThisTheMessageThread() const throw();
  35900. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  35901. (Best to ignore this method unless you really know what you're doing..)
  35902. @see getCurrentMessageThread
  35903. */
  35904. void setCurrentThreadAsMessageThread();
  35905. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  35906. (Best to ignore this method unless you really know what you're doing..)
  35907. @see setCurrentMessageThread
  35908. */
  35909. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  35910. /** Returns true if the caller thread has currenltly got the message manager locked.
  35911. see the MessageManagerLock class for more info about this.
  35912. This will be true if the caller is the message thread, because that automatically
  35913. gains a lock while a message is being dispatched.
  35914. */
  35915. bool currentThreadHasLockedMessageManager() const throw();
  35916. /** Sends a message to all other JUCE applications that are running.
  35917. @param messageText the string that will be passed to the actionListenerCallback()
  35918. method of the broadcast listeners in the other app.
  35919. @see registerBroadcastListener, ActionListener
  35920. */
  35921. static void broadcastMessage (const String& messageText);
  35922. /** Registers a listener to get told about broadcast messages.
  35923. The actionListenerCallback() callback's string parameter
  35924. is the message passed into broadcastMessage().
  35925. @see broadcastMessage
  35926. */
  35927. void registerBroadcastListener (ActionListener* listener);
  35928. /** Deregisters a broadcast listener. */
  35929. void deregisterBroadcastListener (ActionListener* listener);
  35930. /** @internal */
  35931. void deliverMessage (Message*);
  35932. /** @internal */
  35933. void deliverBroadcastMessage (const String&);
  35934. /** @internal */
  35935. ~MessageManager() throw();
  35936. private:
  35937. MessageManager() throw();
  35938. friend class MessageListener;
  35939. friend class ChangeBroadcaster;
  35940. friend class ActionBroadcaster;
  35941. friend class CallbackMessage;
  35942. static MessageManager* instance;
  35943. SortedSet <const MessageListener*> messageListeners;
  35944. ScopedPointer <ActionBroadcaster> broadcaster;
  35945. friend class JUCEApplication;
  35946. bool quitMessagePosted, quitMessageReceived;
  35947. Thread::ThreadID messageThreadId;
  35948. static void* exitModalLoopCallback (void*);
  35949. void postMessageToQueue (Message* message);
  35950. static void doPlatformSpecificInitialisation();
  35951. static void doPlatformSpecificShutdown();
  35952. friend class MessageManagerLock;
  35953. Thread::ThreadID volatile threadWithLock;
  35954. CriticalSection lockingLock;
  35955. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager);
  35956. };
  35957. /** Used to make sure that the calling thread has exclusive access to the message loop.
  35958. Because it's not thread-safe to call any of the Component or other UI classes
  35959. from threads other than the message thread, one of these objects can be used to
  35960. lock the message loop and allow this to be done. The message thread will be
  35961. suspended for the lifetime of the MessageManagerLock object, so create one on
  35962. the stack like this: @code
  35963. void MyThread::run()
  35964. {
  35965. someData = 1234;
  35966. const MessageManagerLock mmLock;
  35967. // the event loop will now be locked so it's safe to make a few calls..
  35968. myComponent->setBounds (newBounds);
  35969. myComponent->repaint();
  35970. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  35971. }
  35972. @endcode
  35973. Obviously be careful not to create one of these and leave it lying around, or
  35974. your app will grind to a halt!
  35975. Another caveat is that using this in conjunction with other CriticalSections
  35976. can create lots of interesting ways of producing a deadlock! In particular, if
  35977. your message thread calls stopThread() for a thread that uses these locks,
  35978. you'll get an (occasional) deadlock..
  35979. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  35980. */
  35981. class JUCE_API MessageManagerLock
  35982. {
  35983. public:
  35984. /** Tries to acquire a lock on the message manager.
  35985. The constructor attempts to gain a lock on the message loop, and the lock will be
  35986. kept for the lifetime of this object.
  35987. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  35988. this method will keep checking whether the thread has been given the
  35989. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  35990. without gaining the lock. If you pass a thread, you must check whether the lock was
  35991. successful by calling lockWasGained(). If this is false, your thread is being told to
  35992. die, so you should take evasive action.
  35993. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  35994. careful when doing this, because it's very easy to deadlock if your message thread
  35995. attempts to call stopThread() on a thread just as that thread attempts to get the
  35996. message lock.
  35997. If the calling thread already has the lock, nothing will be done, so it's safe and
  35998. quick to use these locks recursively.
  35999. E.g.
  36000. @code
  36001. void run()
  36002. {
  36003. ...
  36004. while (! threadShouldExit())
  36005. {
  36006. MessageManagerLock mml (Thread::getCurrentThread());
  36007. if (! mml.lockWasGained())
  36008. return; // another thread is trying to kill us!
  36009. ..do some locked stuff here..
  36010. }
  36011. ..and now the MM is now unlocked..
  36012. }
  36013. @endcode
  36014. */
  36015. MessageManagerLock (Thread* threadToCheckForExitSignal = 0);
  36016. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  36017. instead of a thread.
  36018. See the MessageManagerLock (Thread*) constructor for details on how this works.
  36019. */
  36020. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  36021. /** Releases the current thread's lock on the message manager.
  36022. Make sure this object is created and deleted by the same thread,
  36023. otherwise there are no guarantees what will happen!
  36024. */
  36025. ~MessageManagerLock() throw();
  36026. /** Returns true if the lock was successfully acquired.
  36027. (See the constructor that takes a Thread for more info).
  36028. */
  36029. bool lockWasGained() const throw() { return locked; }
  36030. private:
  36031. class BlockingMessage;
  36032. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  36033. ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  36034. bool locked;
  36035. void init (Thread* thread, ThreadPoolJob* job);
  36036. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock);
  36037. };
  36038. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  36039. /*** End of inlined file: juce_MessageManager.h ***/
  36040. #endif
  36041. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  36042. /*** Start of inlined file: juce_MultiTimer.h ***/
  36043. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  36044. #define __JUCE_MULTITIMER_JUCEHEADER__
  36045. /**
  36046. A type of timer class that can run multiple timers with different frequencies,
  36047. all of which share a single callback.
  36048. This class is very similar to the Timer class, but allows you run multiple
  36049. separate timers, where each one has a unique ID number. The methods in this
  36050. class are exactly equivalent to those in Timer, but with the addition of
  36051. this ID number.
  36052. To use it, you need to create a subclass of MultiTimer, implementing the
  36053. timerCallback() method. Then you can start timers with startTimer(), and
  36054. each time the callback is triggered, it passes in the ID of the timer that
  36055. caused it.
  36056. @see Timer
  36057. */
  36058. class JUCE_API MultiTimer
  36059. {
  36060. protected:
  36061. /** Creates a MultiTimer.
  36062. When created, no timers are running, so use startTimer() to start things off.
  36063. */
  36064. MultiTimer() throw();
  36065. /** Creates a copy of another timer.
  36066. Note that this timer will not contain any running timers, even if the one you're
  36067. copying from was running.
  36068. */
  36069. MultiTimer (const MultiTimer& other) throw();
  36070. public:
  36071. /** Destructor. */
  36072. virtual ~MultiTimer();
  36073. /** The user-defined callback routine that actually gets called by each of the
  36074. timers that are running.
  36075. It's perfectly ok to call startTimer() or stopTimer() from within this
  36076. callback to change the subsequent intervals.
  36077. */
  36078. virtual void timerCallback (int timerId) = 0;
  36079. /** Starts a timer and sets the length of interval required.
  36080. If the timer is already started, this will reset it, so the
  36081. time between calling this method and the next timer callback
  36082. will not be less than the interval length passed in.
  36083. @param timerId a unique Id number that identifies the timer to
  36084. start. This is the id that will be passed back
  36085. to the timerCallback() method when this timer is
  36086. triggered
  36087. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  36088. rounded up to 1)
  36089. */
  36090. void startTimer (int timerId, int intervalInMilliseconds) throw();
  36091. /** Stops a timer.
  36092. If a timer has been started with the given ID number, it will be cancelled.
  36093. No more callbacks will be made for the specified timer after this method returns.
  36094. If this is called from a different thread, any callbacks that may
  36095. be currently executing may be allowed to finish before the method
  36096. returns.
  36097. */
  36098. void stopTimer (int timerId) throw();
  36099. /** Checks whether a timer has been started for a specified ID.
  36100. @returns true if a timer with the given ID is running.
  36101. */
  36102. bool isTimerRunning (int timerId) const throw();
  36103. /** Returns the interval for a specified timer ID.
  36104. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  36105. is running for the ID number specified.
  36106. */
  36107. int getTimerInterval (int timerId) const throw();
  36108. private:
  36109. class MultiTimerCallback;
  36110. CriticalSection timerListLock;
  36111. OwnedArray <MultiTimerCallback> timers;
  36112. MultiTimer& operator= (const MultiTimer&);
  36113. };
  36114. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  36115. /*** End of inlined file: juce_MultiTimer.h ***/
  36116. #endif
  36117. #ifndef __JUCE_TIMER_JUCEHEADER__
  36118. #endif
  36119. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  36120. /*** Start of inlined file: juce_ArrowButton.h ***/
  36121. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  36122. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  36123. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  36124. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36125. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36126. /**
  36127. An effect filter that adds a drop-shadow behind the image's content.
  36128. (This will only work on images/components that aren't opaque, of course).
  36129. When added to a component, this effect will draw a soft-edged
  36130. shadow based on what gets drawn inside it. The shadow will also
  36131. be applied to the component's children.
  36132. For speed, this doesn't use a proper gaussian blur, but cheats by
  36133. using a simple bilinear filter. If you need a really high-quality
  36134. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  36135. @see Component::setComponentEffect
  36136. */
  36137. class JUCE_API DropShadowEffect : public ImageEffectFilter
  36138. {
  36139. public:
  36140. /** Creates a default drop-shadow effect.
  36141. To customise the shadow's appearance, use the setShadowProperties()
  36142. method.
  36143. */
  36144. DropShadowEffect();
  36145. /** Destructor. */
  36146. ~DropShadowEffect();
  36147. /** Sets up parameters affecting the shadow's appearance.
  36148. @param newRadius the (approximate) radius of the blur used
  36149. @param newOpacity the opacity with which the shadow is rendered
  36150. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  36151. component's contents
  36152. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  36153. component's contents
  36154. */
  36155. void setShadowProperties (float newRadius,
  36156. float newOpacity,
  36157. int newShadowOffsetX,
  36158. int newShadowOffsetY);
  36159. /** @internal */
  36160. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  36161. private:
  36162. int offsetX, offsetY;
  36163. float radius, opacity;
  36164. JUCE_LEAK_DETECTOR (DropShadowEffect);
  36165. };
  36166. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  36167. /*** End of inlined file: juce_DropShadowEffect.h ***/
  36168. /**
  36169. A button with an arrow in it.
  36170. @see Button
  36171. */
  36172. class JUCE_API ArrowButton : public Button
  36173. {
  36174. public:
  36175. /** Creates an ArrowButton.
  36176. @param buttonName the name to give the button
  36177. @param arrowDirection the direction the arrow should point in, where 0.0 is
  36178. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  36179. @param arrowColour the colour to use for the arrow
  36180. */
  36181. ArrowButton (const String& buttonName,
  36182. float arrowDirection,
  36183. const Colour& arrowColour);
  36184. /** Destructor. */
  36185. ~ArrowButton();
  36186. protected:
  36187. /** @internal */
  36188. void paintButton (Graphics& g,
  36189. bool isMouseOverButton,
  36190. bool isButtonDown);
  36191. /** @internal */
  36192. void buttonStateChanged();
  36193. private:
  36194. Colour colour;
  36195. DropShadowEffect shadow;
  36196. Path path;
  36197. int offset;
  36198. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ArrowButton);
  36199. };
  36200. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  36201. /*** End of inlined file: juce_ArrowButton.h ***/
  36202. #endif
  36203. #ifndef __JUCE_BUTTON_JUCEHEADER__
  36204. #endif
  36205. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36206. /*** Start of inlined file: juce_DrawableButton.h ***/
  36207. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36208. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36209. /*** Start of inlined file: juce_Drawable.h ***/
  36210. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  36211. #define __JUCE_DRAWABLE_JUCEHEADER__
  36212. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  36213. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36214. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36215. /**
  36216. Expresses a coordinate as a dynamically evaluated expression.
  36217. @see RelativePoint, RelativeRectangle
  36218. */
  36219. class JUCE_API RelativeCoordinate
  36220. {
  36221. public:
  36222. /** Creates a zero coordinate. */
  36223. RelativeCoordinate();
  36224. RelativeCoordinate (const Expression& expression);
  36225. RelativeCoordinate (const RelativeCoordinate& other);
  36226. RelativeCoordinate& operator= (const RelativeCoordinate& other);
  36227. /** Creates an absolute position from the parent origin on either the X or Y axis.
  36228. @param absoluteDistanceFromOrigin the distance from the origin
  36229. */
  36230. RelativeCoordinate (double absoluteDistanceFromOrigin);
  36231. /** Recreates a coordinate from a string description.
  36232. The string will be parsed by ExpressionParser::parse().
  36233. @param stringVersion the expression to use
  36234. @see toString
  36235. */
  36236. RelativeCoordinate (const String& stringVersion);
  36237. /** Destructor. */
  36238. ~RelativeCoordinate();
  36239. bool operator== (const RelativeCoordinate& other) const throw();
  36240. bool operator!= (const RelativeCoordinate& other) const throw();
  36241. /** Calculates the absolute position of this coordinate.
  36242. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  36243. be needed to calculate the result.
  36244. */
  36245. double resolve (const Expression::Scope* evaluationScope) const;
  36246. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  36247. This will recursively check any coordinates upon which this one depends.
  36248. */
  36249. bool references (const String& coordName, const Expression::Scope* evaluationScope) const;
  36250. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  36251. bool isRecursive (const Expression::Scope* evaluationScope) const;
  36252. /** Returns true if this coordinate depends on any other coordinates for its position. */
  36253. bool isDynamic() const;
  36254. /** Changes the value of this coord to make it resolve to the specified position.
  36255. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  36256. or relative position to whatever value is necessary to make its resultant position
  36257. match the position that is provided.
  36258. */
  36259. void moveToAbsolute (double absoluteTargetPosition, const Expression::Scope* evaluationScope);
  36260. /** Returns the expression that defines this coordinate. */
  36261. const Expression& getExpression() const { return term; }
  36262. /** Returns a string which represents this coordinate.
  36263. For details of the string syntax, see the constructor notes.
  36264. */
  36265. const String toString() const;
  36266. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  36267. As well as avoiding using string literals in your code, using these preset values
  36268. has the advantage that all instances of the same string will share the same, reference-counted
  36269. String object, so if you have thousands of points which all refer to the same
  36270. anchor points, this can save a significant amount of memory allocation.
  36271. */
  36272. struct Strings
  36273. {
  36274. static const String parent; /**< "parent" */
  36275. static const String left; /**< "left" */
  36276. static const String right; /**< "right" */
  36277. static const String top; /**< "top" */
  36278. static const String bottom; /**< "bottom" */
  36279. static const String x; /**< "x" */
  36280. static const String y; /**< "y" */
  36281. static const String width; /**< "width" */
  36282. static const String height; /**< "height" */
  36283. };
  36284. struct StandardStrings
  36285. {
  36286. enum Type
  36287. {
  36288. left, right, top, bottom,
  36289. x, y, width, height,
  36290. parent,
  36291. unknown
  36292. };
  36293. static Type getTypeOf (const String& s) throw();
  36294. };
  36295. private:
  36296. Expression term;
  36297. };
  36298. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  36299. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  36300. /*** Start of inlined file: juce_RelativeCoordinatePositioner.h ***/
  36301. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  36302. #define __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  36303. /*** Start of inlined file: juce_RelativePoint.h ***/
  36304. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  36305. #define __JUCE_RELATIVEPOINT_JUCEHEADER__
  36306. /**
  36307. An X-Y position stored as a pair of RelativeCoordinate values.
  36308. @see RelativeCoordinate, RelativeRectangle
  36309. */
  36310. class JUCE_API RelativePoint
  36311. {
  36312. public:
  36313. /** Creates a point at the origin. */
  36314. RelativePoint();
  36315. /** Creates an absolute point, relative to the origin. */
  36316. RelativePoint (const Point<float>& absolutePoint);
  36317. /** Creates an absolute point, relative to the origin. */
  36318. RelativePoint (float absoluteX, float absoluteY);
  36319. /** Creates an absolute point from two coordinates. */
  36320. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  36321. /** Creates a point from a stringified representation.
  36322. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  36323. strings is explained in the RelativeCoordinate class.
  36324. @see toString
  36325. */
  36326. RelativePoint (const String& stringVersion);
  36327. bool operator== (const RelativePoint& other) const throw();
  36328. bool operator!= (const RelativePoint& other) const throw();
  36329. /** Calculates the absolute position of this point.
  36330. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  36331. be needed to calculate the result.
  36332. */
  36333. const Point<float> resolve (const Expression::Scope* evaluationContext) const;
  36334. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  36335. Calling this will leave any anchor points unchanged, but will set any absolute
  36336. or relative positions to whatever values are necessary to make the resultant position
  36337. match the position that is provided.
  36338. */
  36339. void moveToAbsolute (const Point<float>& newPos, const Expression::Scope* evaluationContext);
  36340. /** Returns a string which represents this point.
  36341. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  36342. coordinates, see the RelativeCoordinate constructor notes.
  36343. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  36344. */
  36345. const String toString() const;
  36346. /** Returns true if this point depends on any other coordinates for its position. */
  36347. bool isDynamic() const;
  36348. // The actual X and Y coords...
  36349. RelativeCoordinate x, y;
  36350. };
  36351. #endif // __JUCE_RELATIVEPOINT_JUCEHEADER__
  36352. /*** End of inlined file: juce_RelativePoint.h ***/
  36353. /*** Start of inlined file: juce_MarkerList.h ***/
  36354. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  36355. #define __JUCE_MARKERLIST_JUCEHEADER__
  36356. class Component;
  36357. /**
  36358. Holds a set of named marker points along a one-dimensional axis.
  36359. This class is used to store sets of X and Y marker points in components.
  36360. @see Component::getMarkers().
  36361. */
  36362. class JUCE_API MarkerList
  36363. {
  36364. public:
  36365. /** Creates an empty marker list. */
  36366. MarkerList();
  36367. /** Creates a copy of another marker list. */
  36368. MarkerList (const MarkerList& other);
  36369. /** Copies another marker list to this one. */
  36370. MarkerList& operator= (const MarkerList& other);
  36371. /** Destructor. */
  36372. ~MarkerList();
  36373. /** Represents a marker in a MarkerList. */
  36374. class JUCE_API Marker
  36375. {
  36376. public:
  36377. /** Creates a copy of another Marker. */
  36378. Marker (const Marker& other);
  36379. /** Creates a Marker with a given name and position. */
  36380. Marker (const String& name, const RelativeCoordinate& position);
  36381. /** The marker's name. */
  36382. String name;
  36383. /** The marker's position.
  36384. The expression used to define the coordinate may use the names of other
  36385. markers, so that markers can be linked in arbitrary ways, but be careful
  36386. not to create recursive loops of markers whose positions are based on each
  36387. other! It can also refer to "parent.right" and "parent.bottom" so that you
  36388. can set markers which are relative to the size of the component that contains
  36389. them.
  36390. To resolve the coordinate, you can use the MarkerList::getMarkerPosition() method.
  36391. */
  36392. RelativeCoordinate position;
  36393. /** Returns true if both the names and positions of these two markers match. */
  36394. bool operator== (const Marker&) const throw();
  36395. /** Returns true if either the name or position of these two markers differ. */
  36396. bool operator!= (const Marker&) const throw();
  36397. };
  36398. /** Returns the number of markers in the list. */
  36399. int getNumMarkers() const throw();
  36400. /** Returns one of the markers in the list, by its index. */
  36401. const Marker* getMarker (int index) const throw();
  36402. /** Returns a named marker, or 0 if no such name is found.
  36403. Note that name comparisons are case-sensitive.
  36404. */
  36405. const Marker* getMarker (const String& name) const throw();
  36406. /** Evaluates the given marker and returns its absolute position.
  36407. The parent component must be supplied in case the marker's expression refers to
  36408. the size of its parent component.
  36409. */
  36410. double getMarkerPosition (const Marker& marker, Component* parentComponent) const;
  36411. /** Sets the position of a marker.
  36412. If the name already exists, then the existing marker is moved; if it doesn't exist, then a
  36413. new marker is added.
  36414. */
  36415. void setMarker (const String& name, const RelativeCoordinate& position);
  36416. /** Deletes the marker at the given list index. */
  36417. void removeMarker (int index);
  36418. /** Deletes the marker with the given name. */
  36419. void removeMarker (const String& name);
  36420. /** Returns true if all the markers in these two lists match exactly. */
  36421. bool operator== (const MarkerList& other) const throw();
  36422. /** Returns true if not all the markers in these two lists match exactly. */
  36423. bool operator!= (const MarkerList& other) const throw();
  36424. /**
  36425. A class for receiving events when changes are made to a MarkerList.
  36426. You can register a MarkerList::Listener with a MarkerList using the MarkerList::addListener()
  36427. method, and it will be called when markers are moved, added, or deleted.
  36428. @see MarkerList::addListener, MarkerList::removeListener
  36429. */
  36430. class JUCE_API Listener
  36431. {
  36432. public:
  36433. /** Destructor. */
  36434. virtual ~Listener() {}
  36435. /** Called when something in the given marker list changes. */
  36436. virtual void markersChanged (MarkerList* markerList) = 0;
  36437. /** Called when the given marker list is being deleted. */
  36438. virtual void markerListBeingDeleted (MarkerList* markerList);
  36439. };
  36440. /** Registers a listener that will be called when the markers are changed. */
  36441. void addListener (Listener* listener);
  36442. /** Deregisters a previously-registered listener. */
  36443. void removeListener (Listener* listener);
  36444. /** Synchronously calls markersChanged() on all the registered listeners. */
  36445. void markersHaveChanged();
  36446. /** Forms a wrapper around a ValueTree that can be used for storing a MarkerList. */
  36447. class ValueTreeWrapper
  36448. {
  36449. public:
  36450. ValueTreeWrapper (const ValueTree& state);
  36451. ValueTree& getState() throw() { return state; }
  36452. int getNumMarkers() const;
  36453. const ValueTree getMarkerState (int index) const;
  36454. const ValueTree getMarkerState (const String& name) const;
  36455. bool containsMarker (const ValueTree& state) const;
  36456. const MarkerList::Marker getMarker (const ValueTree& state) const;
  36457. void setMarker (const MarkerList::Marker& marker, UndoManager* undoManager);
  36458. void removeMarker (const ValueTree& state, UndoManager* undoManager);
  36459. void applyTo (MarkerList& markerList);
  36460. void readFrom (const MarkerList& markerList, UndoManager* undoManager);
  36461. static const Identifier markerTag, nameProperty, posProperty;
  36462. private:
  36463. ValueTree state;
  36464. };
  36465. private:
  36466. OwnedArray<Marker> markers;
  36467. ListenerList<Listener> listeners;
  36468. JUCE_LEAK_DETECTOR (MarkerList);
  36469. };
  36470. #endif // __JUCE_MARKERLIST_JUCEHEADER__
  36471. /*** End of inlined file: juce_MarkerList.h ***/
  36472. /**
  36473. Base class for Component::Positioners that are based upon relative coordinates.
  36474. */
  36475. class JUCE_API RelativeCoordinatePositionerBase : public Component::Positioner,
  36476. public ComponentListener,
  36477. public MarkerList::Listener
  36478. {
  36479. public:
  36480. RelativeCoordinatePositionerBase (Component& component_);
  36481. ~RelativeCoordinatePositionerBase();
  36482. void componentMovedOrResized (Component&, bool, bool);
  36483. void componentParentHierarchyChanged (Component&);
  36484. void componentChildrenChanged (Component& component);
  36485. void componentBeingDeleted (Component& component);
  36486. void markersChanged (MarkerList*);
  36487. void markerListBeingDeleted (MarkerList* markerList);
  36488. void apply();
  36489. bool addCoordinate (const RelativeCoordinate& coord);
  36490. bool addPoint (const RelativePoint& point);
  36491. /** Used for resolving a RelativeCoordinate expression in the context of a component. */
  36492. class ComponentScope : public Expression::Scope
  36493. {
  36494. public:
  36495. ComponentScope (Component& component_);
  36496. const Expression getSymbolValue (const String& symbol) const;
  36497. void visitRelativeScope (const String& scopeName, Visitor& visitor) const;
  36498. const String getScopeUID() const;
  36499. protected:
  36500. Component& component;
  36501. Component* findSiblingComponent (const String& componentID) const;
  36502. const MarkerList::Marker* findMarker (const String& name, MarkerList*& list) const;
  36503. private:
  36504. JUCE_DECLARE_NON_COPYABLE (ComponentScope);
  36505. };
  36506. protected:
  36507. virtual bool registerCoordinates() = 0;
  36508. virtual void applyToComponentBounds() = 0;
  36509. private:
  36510. class DependencyFinderScope;
  36511. friend class DependencyFinderScope;
  36512. Array <Component*> sourceComponents;
  36513. Array <MarkerList*> sourceMarkerLists;
  36514. bool registeredOk;
  36515. void registerComponentListener (Component& comp);
  36516. void registerMarkerListListener (MarkerList* const list);
  36517. void unregisterListeners();
  36518. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeCoordinatePositionerBase);
  36519. };
  36520. #endif // __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  36521. /*** End of inlined file: juce_RelativeCoordinatePositioner.h ***/
  36522. /*** Start of inlined file: juce_ComponentBuilder.h ***/
  36523. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  36524. #define __JUCE_COMPONENTBUILDER_JUCEHEADER__
  36525. /**
  36526. Loads and maintains a tree of Components from a ValueTree that represents them.
  36527. To allow the state of a tree of components to be saved as a ValueTree and re-loaded,
  36528. this class lets you register a set of type-handlers for the different components that
  36529. are involved, and then uses these types to re-create a set of components from its
  36530. stored state.
  36531. Essentially, to use this, you need to create a ComponentBuilder with your ValueTree,
  36532. then use registerTypeHandler() to give it a set of type handlers that can cope with
  36533. all the items in your tree. Then you can call getComponent() to build the component.
  36534. Once you've got the component you can either take it and delete the ComponentBuilder
  36535. object, or if you keep the ComponentBuilder around, it'll monitor any changes in the
  36536. ValueTree and automatically update the component to reflect these changes.
  36537. */
  36538. class JUCE_API ComponentBuilder : public ValueTree::Listener
  36539. {
  36540. public:
  36541. /** Creates a ComponentBuilder that will use the given state.
  36542. Once you've created your builder, you should use registerTypeHandler() to register some
  36543. type handlers for it, and then you can call createComponent() or getManagedComponent()
  36544. to get the actual component.
  36545. */
  36546. explicit ComponentBuilder (const ValueTree& state);
  36547. /** Destructor. */
  36548. ~ComponentBuilder();
  36549. /** Returns the ValueTree that this builder is working with. */
  36550. ValueTree& getState() throw() { return state; }
  36551. /** Returns the ValueTree that this builder is working with. */
  36552. const ValueTree& getState() const throw() { return state; }
  36553. /** Returns the builder's component (creating it if necessary).
  36554. The first time that this method is called, the builder will attempt to create a component
  36555. from the ValueTree, so you must have registered some suitable type handlers before calling
  36556. this. If there's a problem and the component can't be created, this method returns 0.
  36557. The component that is returned is owned by this ComponentBuilder, so you can put it inside
  36558. your own parent components, but don't delete it! The ComponentBuilder will delete it automatically
  36559. when the builder is destroyed. If you want to get a component that you can delete yourself,
  36560. call createComponent() instead.
  36561. The ComponentBuilder will update this component if any changes are made to the ValueTree, so if
  36562. there's a chance that the tree might change, be careful not to keep any pointers to sub-components,
  36563. as they may be changed or removed.
  36564. */
  36565. Component* getManagedComponent();
  36566. /** Creates and returns a new instance of the component that the ValueTree represents.
  36567. The caller is responsible for using and deleting the object that is returned. Unlike
  36568. getManagedComponent(), the component that is returned will not be updated by the builder.
  36569. */
  36570. Component* createComponent();
  36571. /**
  36572. The class is a base class for objects that manage the loading of a type of component
  36573. from a ValueTree.
  36574. To store and re-load a tree of components as a ValueTree, each component type must have
  36575. a TypeHandler to represent it.
  36576. @see ComponentBuilder::registerTypeHandler(), Drawable::registerDrawableTypeHandlers()
  36577. */
  36578. class JUCE_API TypeHandler
  36579. {
  36580. public:
  36581. /** Creates a TypeHandler.
  36582. The valueTreeType must be the type name of the ValueTrees that this handler can parse.
  36583. */
  36584. explicit TypeHandler (const Identifier& valueTreeType);
  36585. /** Destructor. */
  36586. virtual ~TypeHandler();
  36587. /** Returns the type of the ValueTrees that this handler can parse. */
  36588. const Identifier& getType() const throw() { return valueTreeType; }
  36589. /** Returns the builder that this type is registered with. */
  36590. ComponentBuilder* getBuilder() const throw();
  36591. /** This method must create a new component from the given state, add it to the specified
  36592. parent component (which may be null), and return it.
  36593. The ValueTree will have been pre-checked to make sure that its type matches the type
  36594. that this handler supports.
  36595. There's no need to set the new Component's ID to match that of the state - the builder
  36596. will take care of that itself.
  36597. */
  36598. virtual Component* addNewComponentFromState (const ValueTree& state, Component* parent) = 0;
  36599. /** This method must update an existing component from a new ValueTree state.
  36600. A component that has been created with addNewComponentFromState() may need to be updated
  36601. if the ValueTree changes, so this method is used to do that. Your implementation must do
  36602. whatever's necessary to update the component from the new state provided.
  36603. The ValueTree will have been pre-checked to make sure that its type matches the type
  36604. that this handler supports, and the component will have been created by this type's
  36605. addNewComponentFromState() method.
  36606. */
  36607. virtual void updateComponentFromState (Component* component, const ValueTree& state) = 0;
  36608. private:
  36609. friend class ComponentBuilder;
  36610. ComponentBuilder* builder;
  36611. const Identifier valueTreeType;
  36612. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypeHandler);
  36613. };
  36614. /** Adds a type handler that the builder can use when trying to load components.
  36615. @see Drawable::registerDrawableTypeHandlers()
  36616. */
  36617. void registerTypeHandler (TypeHandler* type);
  36618. /** Tries to find a registered type handler that can load a component from the given ValueTree. */
  36619. TypeHandler* getHandlerForState (const ValueTree& state) const;
  36620. /** Returns the number of registered type handlers.
  36621. @see getHandler, registerTypeHandler
  36622. */
  36623. int getNumHandlers() const throw();
  36624. /** Returns one of the registered type handlers.
  36625. @see getNumHandlers, registerTypeHandler
  36626. */
  36627. TypeHandler* getHandler (int index) const throw();
  36628. /** This class is used when references to images need to be stored in ValueTrees.
  36629. An instance of an ImageProvider provides a mechanism for converting an Image to/from
  36630. a reference, which may be a file, URL, ID string, or whatever system is appropriate in
  36631. your app.
  36632. When you're loading components from a ValueTree that may need a way of loading images, you
  36633. should call ComponentBuilder::setImageProvider() to supply a suitable provider before
  36634. trying to load the component.
  36635. @see ComponentBuilder::setImageProvider()
  36636. */
  36637. class JUCE_API ImageProvider
  36638. {
  36639. public:
  36640. ImageProvider() {}
  36641. virtual ~ImageProvider() {}
  36642. /** Retrieves the image associated with this identifier, which could be any
  36643. kind of string, number, filename, etc.
  36644. The image that is returned will be owned by the caller, but it may come
  36645. from the ImageCache.
  36646. */
  36647. virtual const Image getImageForIdentifier (const var& imageIdentifier) = 0;
  36648. /** Returns an identifier to be used to refer to a given image.
  36649. This is used when a reference to an image is stored in a ValueTree.
  36650. */
  36651. virtual const var getIdentifierForImage (const Image& image) = 0;
  36652. };
  36653. /** Gives the builder an ImageProvider object that the type handlers can use when
  36654. loading images from stored references.
  36655. The object that is passed in is not owned by the builder, so the caller must delete
  36656. it when it is no longer needed, but not while the builder may still be using it. To
  36657. clear the image provider, just call setImageProvider (0).
  36658. */
  36659. void setImageProvider (ImageProvider* newImageProvider) throw();
  36660. /** Returns the current image provider that this builder is using, or 0 if none has been set. */
  36661. ImageProvider* getImageProvider() const throw();
  36662. /** Updates the children of a parent component by updating them from the children of
  36663. a given ValueTree.
  36664. */
  36665. void updateChildComponents (Component& parent, const ValueTree& children);
  36666. /** An identifier for the property of the ValueTrees that is used to store a unique ID
  36667. for that component.
  36668. */
  36669. static const Identifier idProperty;
  36670. /** @internal */
  36671. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& property);
  36672. /** @internal */
  36673. void valueTreeChildAdded (ValueTree& parentTree, ValueTree& childWhichHasBeenAdded);
  36674. /** @internal */
  36675. void valueTreeChildRemoved (ValueTree& parentTree, ValueTree& childWhichHasBeenRemoved);
  36676. /** @internal */
  36677. void valueTreeChildOrderChanged (ValueTree& parentTree);
  36678. /** @internal */
  36679. void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged);
  36680. private:
  36681. ValueTree state;
  36682. OwnedArray <TypeHandler> types;
  36683. ScopedPointer<Component> component;
  36684. ImageProvider* imageProvider;
  36685. #if JUCE_DEBUG
  36686. WeakReference<Component> componentRef;
  36687. #endif
  36688. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBuilder);
  36689. };
  36690. #endif // __JUCE_COMPONENTBUILDER_JUCEHEADER__
  36691. /*** End of inlined file: juce_ComponentBuilder.h ***/
  36692. class DrawableComposite;
  36693. /**
  36694. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  36695. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  36696. */
  36697. class JUCE_API Drawable : public Component
  36698. {
  36699. protected:
  36700. /** The base class can't be instantiated directly.
  36701. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  36702. */
  36703. Drawable();
  36704. public:
  36705. /** Destructor. */
  36706. virtual ~Drawable();
  36707. /** Creates a deep copy of this Drawable object.
  36708. Use this to create a new copy of this and any sub-objects in the tree.
  36709. */
  36710. virtual Drawable* createCopy() const = 0;
  36711. /** Renders this Drawable object.
  36712. Note that the preferred way to render a drawable in future is by using it
  36713. as a component and adding it to a parent, so you might want to consider that
  36714. before using this method.
  36715. @see drawWithin
  36716. */
  36717. void draw (Graphics& g, float opacity,
  36718. const AffineTransform& transform = AffineTransform::identity) const;
  36719. /** Renders the Drawable at a given offset within the Graphics context.
  36720. The co-ordinates passed-in are used to translate the object relative to its own
  36721. origin before drawing it - this is basically a quick way of saying:
  36722. @code
  36723. draw (g, AffineTransform::translation (x, y)).
  36724. @endcode
  36725. Note that the preferred way to render a drawable in future is by using it
  36726. as a component and adding it to a parent, so you might want to consider that
  36727. before using this method.
  36728. */
  36729. void drawAt (Graphics& g, float x, float y, float opacity) const;
  36730. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  36731. changing its aspect-ratio.
  36732. The object can placed arbitrarily within the rectangle based on a Justification type,
  36733. and can either be made as big as possible, or just reduced to fit.
  36734. Note that the preferred way to render a drawable in future is by using it
  36735. as a component and adding it to a parent, so you might want to consider that
  36736. before using this method.
  36737. @param g the graphics context to render onto
  36738. @param destArea the target rectangle to fit the drawable into
  36739. @param placement defines the alignment and rescaling to use to fit
  36740. this object within the target rectangle.
  36741. @param opacity the opacity to use, in the range 0 to 1.0
  36742. */
  36743. void drawWithin (Graphics& g,
  36744. const Rectangle<float>& destArea,
  36745. const RectanglePlacement& placement,
  36746. float opacity) const;
  36747. /** Resets any transformations on this drawable, and positions its origin within
  36748. its parent component.
  36749. */
  36750. void setOriginWithOriginalSize (const Point<float>& originWithinParent);
  36751. /** Sets a transform for this drawable that will position it within the specified
  36752. area of its parent component.
  36753. */
  36754. void setTransformToFit (const Rectangle<float>& areaInParent, const RectanglePlacement& placement);
  36755. /** Returns the DrawableComposite that contains this object, if there is one. */
  36756. DrawableComposite* getParent() const;
  36757. /** Tries to turn some kind of image file into a drawable.
  36758. The data could be an image that the ImageFileFormat class understands, or it
  36759. could be SVG.
  36760. */
  36761. static Drawable* createFromImageData (const void* data, size_t numBytes);
  36762. /** Tries to turn a stream containing some kind of image data into a drawable.
  36763. The data could be an image that the ImageFileFormat class understands, or it
  36764. could be SVG.
  36765. */
  36766. static Drawable* createFromImageDataStream (InputStream& dataSource);
  36767. /** Tries to turn a file containing some kind of image data into a drawable.
  36768. The data could be an image that the ImageFileFormat class understands, or it
  36769. could be SVG.
  36770. */
  36771. static Drawable* createFromImageFile (const File& file);
  36772. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  36773. into a Drawable tree.
  36774. The object returned must be deleted by the caller. If something goes wrong
  36775. while parsing, it may return 0.
  36776. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  36777. implementation, but it can return the basic vector objects.
  36778. */
  36779. static Drawable* createFromSVG (const XmlElement& svgDocument);
  36780. /** Tries to create a Drawable from a previously-saved ValueTree.
  36781. The ValueTree must have been created by the createValueTree() method.
  36782. If there are any images used within the drawable, you'll need to provide a valid
  36783. ImageProvider object that can be used to retrieve these images from whatever type
  36784. of identifier is used to represent them.
  36785. Internally, this uses a ComponentBuilder, and registerDrawableTypeHandlers().
  36786. */
  36787. static Drawable* createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider);
  36788. /** Creates a ValueTree to represent this Drawable.
  36789. The ValueTree that is returned can be turned back into a Drawable with createFromValueTree().
  36790. If there are any images used in this drawable, you'll need to provide a valid ImageProvider
  36791. object that can be used to create storable representations of them.
  36792. */
  36793. virtual const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const = 0;
  36794. /** Returns the area that this drawble covers.
  36795. The result is expressed in this drawable's own coordinate space, and does not take
  36796. into account any transforms that may be applied to the component.
  36797. */
  36798. virtual const Rectangle<float> getDrawableBounds() const = 0;
  36799. /** Internal class used to manage ValueTrees that represent Drawables. */
  36800. class ValueTreeWrapperBase
  36801. {
  36802. public:
  36803. ValueTreeWrapperBase (const ValueTree& state);
  36804. ValueTree& getState() throw() { return state; }
  36805. const String getID() const;
  36806. void setID (const String& newID);
  36807. ValueTree state;
  36808. };
  36809. /** Registers a set of ComponentBuilder::TypeHandler objects that can be used to
  36810. load all the different Drawable types from a saved state.
  36811. @see ComponentBuilder::registerTypeHandler()
  36812. */
  36813. static void registerDrawableTypeHandlers (ComponentBuilder& componentBuilder);
  36814. protected:
  36815. friend class DrawableComposite;
  36816. friend class DrawableShape;
  36817. /** @internal */
  36818. void transformContextToCorrectOrigin (Graphics& g);
  36819. /** @internal */
  36820. void parentHierarchyChanged();
  36821. /** @internal */
  36822. void setBoundsToEnclose (const Rectangle<float>& area);
  36823. Point<int> originRelativeToComponent;
  36824. #ifndef DOXYGEN
  36825. /** Internal utility class used by Drawables. */
  36826. template <class DrawableType>
  36827. class Positioner : public RelativeCoordinatePositionerBase
  36828. {
  36829. public:
  36830. Positioner (DrawableType& component_)
  36831. : RelativeCoordinatePositionerBase (component_),
  36832. owner (component_)
  36833. {}
  36834. bool registerCoordinates() { return owner.registerCoordinates (*this); }
  36835. void applyToComponentBounds()
  36836. {
  36837. ComponentScope scope (getComponent());
  36838. owner.recalculateCoordinates (&scope);
  36839. }
  36840. private:
  36841. DrawableType& owner;
  36842. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Positioner);
  36843. };
  36844. #endif
  36845. private:
  36846. void nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform);
  36847. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Drawable);
  36848. };
  36849. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  36850. /*** End of inlined file: juce_Drawable.h ***/
  36851. /**
  36852. A button that displays a Drawable.
  36853. Up to three Drawable objects can be given to this button, to represent the
  36854. 'normal', 'over' and 'down' states.
  36855. @see Button
  36856. */
  36857. class JUCE_API DrawableButton : public Button
  36858. {
  36859. public:
  36860. enum ButtonStyle
  36861. {
  36862. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  36863. ImageRaw, /**< The button will just display the images in their normal size and position.
  36864. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  36865. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  36866. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  36867. };
  36868. /** Creates a DrawableButton.
  36869. After creating one of these, use setImages() to specify the drawables to use.
  36870. @param buttonName the name to give the component
  36871. @param buttonStyle the layout to use
  36872. @see ButtonStyle, setButtonStyle, setImages
  36873. */
  36874. DrawableButton (const String& buttonName,
  36875. ButtonStyle buttonStyle);
  36876. /** Destructor. */
  36877. ~DrawableButton();
  36878. /** Sets up the images to draw for the various button states.
  36879. The button will keep its own internal copies of these drawables.
  36880. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  36881. will be made of the object passed-in if it is non-zero.
  36882. @param overImage the thing to draw for the button's 'over' state - if this is
  36883. zero, the button's normal image will be used when the mouse is
  36884. over it. An internal copy will be made of the object passed-in
  36885. if it is non-zero.
  36886. @param downImage the thing to draw for the button's 'down' state - if this is
  36887. zero, the 'over' image will be used instead (or the normal image
  36888. as a last resort). An internal copy will be made of the object
  36889. passed-in if it is non-zero.
  36890. @param disabledImage an image to draw when the button is disabled. If this is zero,
  36891. the normal image will be drawn with a reduced opacity instead.
  36892. An internal copy will be made of the object passed-in if it is
  36893. non-zero.
  36894. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  36895. state is 'on'. If this is 0, the normal image is used instead
  36896. @param overImageOn same as the overImage, but this is used when the button's toggle
  36897. state is 'on'. If this is 0, the normalImageOn is drawn instead
  36898. @param downImageOn same as the downImage, but this is used when the button's toggle
  36899. state is 'on'. If this is 0, the overImageOn is drawn instead
  36900. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  36901. state is 'on'. If this is 0, the normal image will be drawn instead
  36902. with a reduced opacity
  36903. */
  36904. void setImages (const Drawable* normalImage,
  36905. const Drawable* overImage = 0,
  36906. const Drawable* downImage = 0,
  36907. const Drawable* disabledImage = 0,
  36908. const Drawable* normalImageOn = 0,
  36909. const Drawable* overImageOn = 0,
  36910. const Drawable* downImageOn = 0,
  36911. const Drawable* disabledImageOn = 0);
  36912. /** Changes the button's style.
  36913. @see ButtonStyle
  36914. */
  36915. void setButtonStyle (ButtonStyle newStyle);
  36916. /** Changes the button's background colours.
  36917. The toggledOffColour is the colour to use when the button's toggle state
  36918. is off, and toggledOnColour when it's on.
  36919. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  36920. used to fill the background of the component.
  36921. For an ImageOnButtonBackground style, the colour is used to draw the
  36922. button's lozenge shape and exactly how the colour's used will depend
  36923. on the LookAndFeel.
  36924. */
  36925. void setBackgroundColours (const Colour& toggledOffColour,
  36926. const Colour& toggledOnColour);
  36927. /** Returns the current background colour being used.
  36928. @see setBackgroundColour
  36929. */
  36930. const Colour& getBackgroundColour() const throw();
  36931. /** Gives the button an optional amount of space around the edge of the drawable.
  36932. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  36933. ones on a button background. If the button is too small for the given gap, a
  36934. smaller gap will be used.
  36935. By default there's a gap of about 3 pixels.
  36936. */
  36937. void setEdgeIndent (int numPixelsIndent);
  36938. /** Returns the image that the button is currently displaying. */
  36939. Drawable* getCurrentImage() const throw();
  36940. Drawable* getNormalImage() const throw();
  36941. Drawable* getOverImage() const throw();
  36942. Drawable* getDownImage() const throw();
  36943. /** A set of colour IDs to use to change the colour of various aspects of the link.
  36944. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36945. methods.
  36946. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36947. */
  36948. enum ColourIds
  36949. {
  36950. textColourId = 0x1004010, /**< The colour to use for the URL text. */
  36951. };
  36952. protected:
  36953. /** @internal */
  36954. void paintButton (Graphics& g,
  36955. bool isMouseOverButton,
  36956. bool isButtonDown);
  36957. /** @internal */
  36958. void buttonStateChanged();
  36959. /** @internal */
  36960. void resized();
  36961. private:
  36962. ButtonStyle style;
  36963. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  36964. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  36965. Drawable* currentImage;
  36966. Colour backgroundOff, backgroundOn;
  36967. int edgeIndent;
  36968. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DrawableButton);
  36969. };
  36970. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  36971. /*** End of inlined file: juce_DrawableButton.h ***/
  36972. #endif
  36973. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  36974. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  36975. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  36976. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  36977. /**
  36978. A button showing an underlined weblink, that will launch the link
  36979. when it's clicked.
  36980. @see Button
  36981. */
  36982. class JUCE_API HyperlinkButton : public Button
  36983. {
  36984. public:
  36985. /** Creates a HyperlinkButton.
  36986. @param linkText the text that will be displayed in the button - this is
  36987. also set as the Component's name, but the text can be
  36988. changed later with the Button::getButtonText() method
  36989. @param linkURL the URL to launch when the user clicks the button
  36990. */
  36991. HyperlinkButton (const String& linkText,
  36992. const URL& linkURL);
  36993. /** Destructor. */
  36994. ~HyperlinkButton();
  36995. /** Changes the font to use for the text.
  36996. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  36997. to match the size of the component.
  36998. */
  36999. void setFont (const Font& newFont,
  37000. bool resizeToMatchComponentHeight,
  37001. const Justification& justificationType = Justification::horizontallyCentred);
  37002. /** A set of colour IDs to use to change the colour of various aspects of the link.
  37003. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37004. methods.
  37005. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37006. */
  37007. enum ColourIds
  37008. {
  37009. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  37010. };
  37011. /** Changes the URL that the button will trigger. */
  37012. void setURL (const URL& newURL) throw();
  37013. /** Returns the URL that the button will trigger. */
  37014. const URL& getURL() const throw() { return url; }
  37015. /** Resizes the button horizontally to fit snugly around the text.
  37016. This won't affect the button's height.
  37017. */
  37018. void changeWidthToFitText();
  37019. protected:
  37020. /** @internal */
  37021. void clicked();
  37022. /** @internal */
  37023. void colourChanged();
  37024. /** @internal */
  37025. void paintButton (Graphics& g,
  37026. bool isMouseOverButton,
  37027. bool isButtonDown);
  37028. private:
  37029. URL url;
  37030. Font font;
  37031. bool resizeFont;
  37032. Justification justification;
  37033. const Font getFontToUse() const;
  37034. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HyperlinkButton);
  37035. };
  37036. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  37037. /*** End of inlined file: juce_HyperlinkButton.h ***/
  37038. #endif
  37039. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  37040. /*** Start of inlined file: juce_ImageButton.h ***/
  37041. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  37042. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  37043. /**
  37044. As the title suggests, this is a button containing an image.
  37045. The colour and transparency of the image can be set to vary when the
  37046. button state changes.
  37047. @see Button, ShapeButton, TextButton
  37048. */
  37049. class JUCE_API ImageButton : public Button
  37050. {
  37051. public:
  37052. /** Creates an ImageButton.
  37053. Use setImage() to specify the image to use. The colours and opacities that
  37054. are specified here can be changed later using setDrawingOptions().
  37055. @param name the name to give the component
  37056. */
  37057. explicit ImageButton (const String& name);
  37058. /** Destructor. */
  37059. ~ImageButton();
  37060. /** Sets up the images to draw in various states.
  37061. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  37062. resized to the same dimensions as the normal image
  37063. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  37064. button when the button's size changes
  37065. @param preserveImageProportions if true then any rescaling of the image to fit
  37066. the button will keep the image's x and y proportions
  37067. correct - i.e. it won't distort its shape, although
  37068. this might create gaps around the edges
  37069. @param normalImage the image to use when the button is in its normal state.
  37070. button no longer needs it.
  37071. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  37072. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  37073. normal image - if this colour is transparent, no overlay
  37074. will be drawn. The overlay will be drawn over the top of the
  37075. image, so you can basically add a solid or semi-transparent
  37076. colour to the image to brighten or darken it
  37077. @param overImage the image to use when the mouse is over the button. If
  37078. you want to use the same image as was set in the normalImage
  37079. parameter, this value can be a null image.
  37080. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  37081. is over the button
  37082. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  37083. image when the mouse is over - if this colour is transparent,
  37084. no overlay will be drawn
  37085. @param downImage an image to use when the button is pressed down. If set
  37086. to a null image, the 'over' image will be drawn instead (or the
  37087. normal image if there isn't an 'over' image either).
  37088. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  37089. is pressed
  37090. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  37091. image when the button is pressed down - if this colour is
  37092. transparent, no overlay will be drawn
  37093. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  37094. whenever it's inside the button's bounding rectangle. If
  37095. set to values higher than 0, the mouse will only be
  37096. considered to be over the image when the value of the
  37097. image's alpha channel at that position is greater than
  37098. this level.
  37099. */
  37100. void setImages (bool resizeButtonNowToFitThisImage,
  37101. bool rescaleImagesWhenButtonSizeChanges,
  37102. bool preserveImageProportions,
  37103. const Image& normalImage,
  37104. float imageOpacityWhenNormal,
  37105. const Colour& overlayColourWhenNormal,
  37106. const Image& overImage,
  37107. float imageOpacityWhenOver,
  37108. const Colour& overlayColourWhenOver,
  37109. const Image& downImage,
  37110. float imageOpacityWhenDown,
  37111. const Colour& overlayColourWhenDown,
  37112. float hitTestAlphaThreshold = 0.0f);
  37113. /** Returns the currently set 'normal' image. */
  37114. const Image getNormalImage() const;
  37115. /** Returns the image that's drawn when the mouse is over the button.
  37116. If a valid 'over' image has been set, this will return it; otherwise it'll
  37117. just return the normal image.
  37118. */
  37119. const Image getOverImage() const;
  37120. /** Returns the image that's drawn when the button is held down.
  37121. If a valid 'down' image has been set, this will return it; otherwise it'll
  37122. return the 'over' image or normal image, depending on what's available.
  37123. */
  37124. const Image getDownImage() const;
  37125. protected:
  37126. /** @internal */
  37127. bool hitTest (int x, int y);
  37128. /** @internal */
  37129. void paintButton (Graphics& g,
  37130. bool isMouseOverButton,
  37131. bool isButtonDown);
  37132. private:
  37133. bool scaleImageToFit, preserveProportions;
  37134. unsigned char alphaThreshold;
  37135. int imageX, imageY, imageW, imageH;
  37136. Image normalImage, overImage, downImage;
  37137. float normalOpacity, overOpacity, downOpacity;
  37138. Colour normalOverlay, overOverlay, downOverlay;
  37139. const Image getCurrentImage() const;
  37140. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageButton);
  37141. };
  37142. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  37143. /*** End of inlined file: juce_ImageButton.h ***/
  37144. #endif
  37145. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  37146. /*** Start of inlined file: juce_ShapeButton.h ***/
  37147. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  37148. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  37149. /**
  37150. A button that contains a filled shape.
  37151. @see Button, ImageButton, TextButton, ArrowButton
  37152. */
  37153. class JUCE_API ShapeButton : public Button
  37154. {
  37155. public:
  37156. /** Creates a ShapeButton.
  37157. @param name a name to give the component - see Component::setName()
  37158. @param normalColour the colour to fill the shape with when the mouse isn't over
  37159. @param overColour the colour to use when the mouse is over the shape
  37160. @param downColour the colour to use when the button is in the pressed-down state
  37161. */
  37162. ShapeButton (const String& name,
  37163. const Colour& normalColour,
  37164. const Colour& overColour,
  37165. const Colour& downColour);
  37166. /** Destructor. */
  37167. ~ShapeButton();
  37168. /** Sets the shape to use.
  37169. @param newShape the shape to use
  37170. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  37171. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  37172. the button is resized
  37173. @param hasDropShadow if true, the button will be given a drop-shadow effect
  37174. */
  37175. void setShape (const Path& newShape,
  37176. bool resizeNowToFitThisShape,
  37177. bool maintainShapeProportions,
  37178. bool hasDropShadow);
  37179. /** Set the colours to use for drawing the shape.
  37180. @param normalColour the colour to fill the shape with when the mouse isn't over
  37181. @param overColour the colour to use when the mouse is over the shape
  37182. @param downColour the colour to use when the button is in the pressed-down state
  37183. */
  37184. void setColours (const Colour& normalColour,
  37185. const Colour& overColour,
  37186. const Colour& downColour);
  37187. /** Sets up an outline to draw around the shape.
  37188. @param outlineColour the colour to use
  37189. @param outlineStrokeWidth the thickness of line to draw
  37190. */
  37191. void setOutline (const Colour& outlineColour,
  37192. float outlineStrokeWidth);
  37193. protected:
  37194. /** @internal */
  37195. void paintButton (Graphics& g,
  37196. bool isMouseOverButton,
  37197. bool isButtonDown);
  37198. private:
  37199. Colour normalColour, overColour, downColour, outlineColour;
  37200. DropShadowEffect shadow;
  37201. Path shape;
  37202. bool maintainShapeProportions;
  37203. float outlineWidth;
  37204. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ShapeButton);
  37205. };
  37206. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  37207. /*** End of inlined file: juce_ShapeButton.h ***/
  37208. #endif
  37209. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  37210. #endif
  37211. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37212. /*** Start of inlined file: juce_ToggleButton.h ***/
  37213. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37214. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37215. /**
  37216. A button that can be toggled on/off.
  37217. All buttons can be toggle buttons, but this lets you create one of the
  37218. standard ones which has a tick-box and a text label next to it.
  37219. @see Button, DrawableButton, TextButton
  37220. */
  37221. class JUCE_API ToggleButton : public Button
  37222. {
  37223. public:
  37224. /** Creates a ToggleButton.
  37225. @param buttonText the text to put in the button (the component's name is also
  37226. initially set to this string, but these can be changed later
  37227. using the setName() and setButtonText() methods)
  37228. */
  37229. explicit ToggleButton (const String& buttonText = String::empty);
  37230. /** Destructor. */
  37231. ~ToggleButton();
  37232. /** Resizes the button to fit neatly around its current text.
  37233. The button's height won't be affected, only its width.
  37234. */
  37235. void changeWidthToFitText();
  37236. /** A set of colour IDs to use to change the colour of various aspects of the button.
  37237. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37238. methods.
  37239. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37240. */
  37241. enum ColourIds
  37242. {
  37243. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  37244. };
  37245. protected:
  37246. /** @internal */
  37247. void paintButton (Graphics& g,
  37248. bool isMouseOverButton,
  37249. bool isButtonDown);
  37250. /** @internal */
  37251. void colourChanged();
  37252. private:
  37253. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToggleButton);
  37254. };
  37255. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  37256. /*** End of inlined file: juce_ToggleButton.h ***/
  37257. #endif
  37258. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37259. /*** Start of inlined file: juce_ToolbarButton.h ***/
  37260. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37261. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37262. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  37263. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  37264. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  37265. /*** Start of inlined file: juce_Toolbar.h ***/
  37266. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  37267. #define __JUCE_TOOLBAR_JUCEHEADER__
  37268. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  37269. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  37270. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  37271. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  37272. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  37273. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  37274. /**
  37275. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  37276. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  37277. derive your component from this class, and make sure that it is somewhere inside a
  37278. DragAndDropContainer component.
  37279. Note: If all that you need to do is to respond to files being drag-and-dropped from
  37280. the operating system onto your component, you don't need any of these classes: instead
  37281. see the FileDragAndDropTarget class.
  37282. @see DragAndDropContainer, FileDragAndDropTarget
  37283. */
  37284. class JUCE_API DragAndDropTarget
  37285. {
  37286. public:
  37287. /** Destructor. */
  37288. virtual ~DragAndDropTarget() {}
  37289. /** Callback to check whether this target is interested in the type of object being
  37290. dragged.
  37291. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  37292. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  37293. @returns true if this component wants to receive the other callbacks regarging this
  37294. type of object; if it returns false, no other callbacks will be made.
  37295. */
  37296. virtual bool isInterestedInDragSource (const String& sourceDescription,
  37297. Component* sourceComponent) = 0;
  37298. /** Callback to indicate that something is being dragged over this component.
  37299. This gets called when the user moves the mouse into this component while dragging
  37300. something.
  37301. Use this callback as a trigger to make your component repaint itself to give the
  37302. user feedback about whether the item can be dropped here or not.
  37303. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  37304. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  37305. @param x the mouse x position, relative to this component
  37306. @param y the mouse y position, relative to this component
  37307. @see itemDragExit
  37308. */
  37309. virtual void itemDragEnter (const String& sourceDescription,
  37310. Component* sourceComponent,
  37311. int x, int y);
  37312. /** Callback to indicate that the user is dragging something over this component.
  37313. This gets called when the user moves the mouse over this component while dragging
  37314. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  37315. this lets you know what happens in-between.
  37316. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  37317. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  37318. @param x the mouse x position, relative to this component
  37319. @param y the mouse y position, relative to this component
  37320. */
  37321. virtual void itemDragMove (const String& sourceDescription,
  37322. Component* sourceComponent,
  37323. int x, int y);
  37324. /** Callback to indicate that something has been dragged off the edge of this component.
  37325. This gets called when the user moves the mouse out of this component while dragging
  37326. something.
  37327. If you've used itemDragEnter() to repaint your component and give feedback, use this
  37328. as a signal to repaint it in its normal state.
  37329. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  37330. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  37331. @see itemDragEnter
  37332. */
  37333. virtual void itemDragExit (const String& sourceDescription,
  37334. Component* sourceComponent);
  37335. /** Callback to indicate that the user has dropped something onto this component.
  37336. When the user drops an item this get called, and you can use the description to
  37337. work out whether your object wants to deal with it or not.
  37338. Note that after this is called, the itemDragExit method may not be called, so you should
  37339. clean up in here if there's anything you need to do when the drag finishes.
  37340. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  37341. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  37342. @param x the mouse x position, relative to this component
  37343. @param y the mouse y position, relative to this component
  37344. */
  37345. virtual void itemDropped (const String& sourceDescription,
  37346. Component* sourceComponent,
  37347. int x, int y) = 0;
  37348. /** Overriding this allows the target to tell the drag container whether to
  37349. draw the drag image while the cursor is over it.
  37350. By default it returns true, but if you return false, then the normal drag
  37351. image will not be shown when the cursor is over this target.
  37352. */
  37353. virtual bool shouldDrawDragImageWhenOver();
  37354. };
  37355. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  37356. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  37357. /**
  37358. Enables drag-and-drop behaviour for a component and all its sub-components.
  37359. For a component to be able to make or receive drag-and-drop events, one of its parent
  37360. components must derive from this class. It's probably best for the top-level
  37361. component to implement it.
  37362. Then to start a drag operation, any sub-component can just call the startDragging()
  37363. method, and this object will take over, tracking the mouse and sending appropriate
  37364. callbacks to any child components derived from DragAndDropTarget which the mouse
  37365. moves over.
  37366. Note: If all that you need to do is to respond to files being drag-and-dropped from
  37367. the operating system onto your component, you don't need any of these classes: you can do this
  37368. simply by overriding Component::filesDropped().
  37369. @see DragAndDropTarget
  37370. */
  37371. class JUCE_API DragAndDropContainer
  37372. {
  37373. public:
  37374. /** Creates a DragAndDropContainer.
  37375. The object that derives from this class must also be a Component.
  37376. */
  37377. DragAndDropContainer();
  37378. /** Destructor. */
  37379. virtual ~DragAndDropContainer();
  37380. /** Begins a drag-and-drop operation.
  37381. This starts a drag-and-drop operation - call it when the user drags the
  37382. mouse in your drag-source component, and this object will track mouse
  37383. movements until the user lets go of the mouse button, and will send
  37384. appropriate messages to DragAndDropTarget objects that the mouse moves
  37385. over.
  37386. findParentDragContainerFor() is a handy method to call to find the
  37387. drag container to use for a component.
  37388. @param sourceDescription a string to use as the description of the thing being
  37389. dragged - this will be passed to the objects that might be
  37390. dropped-onto so they can decide if they want to handle it or
  37391. not
  37392. @param sourceComponent the component that is being dragged
  37393. @param dragImage the image to drag around underneath the mouse. If this is a null image,
  37394. a snapshot of the sourceComponent will be used instead.
  37395. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  37396. window, and can be dragged to DragAndDropTargets that are the
  37397. children of components other than this one.
  37398. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  37399. at which the image should be drawn from the mouse. If it isn't
  37400. specified, then the image will be centred around the mouse. If
  37401. an image hasn't been passed-in, this will be ignored.
  37402. */
  37403. void startDragging (const String& sourceDescription,
  37404. Component* sourceComponent,
  37405. const Image& dragImage = Image::null,
  37406. bool allowDraggingToOtherJuceWindows = false,
  37407. const Point<int>* imageOffsetFromMouse = 0);
  37408. /** Returns true if something is currently being dragged. */
  37409. bool isDragAndDropActive() const;
  37410. /** Returns the description of the thing that's currently being dragged.
  37411. If nothing's being dragged, this will return an empty string, otherwise it's the
  37412. string that was passed into startDragging().
  37413. @see startDragging
  37414. */
  37415. const String getCurrentDragDescription() const;
  37416. /** Utility to find the DragAndDropContainer for a given Component.
  37417. This will search up this component's parent hierarchy looking for the first
  37418. parent component which is a DragAndDropContainer.
  37419. It's useful when a component wants to call startDragging but doesn't know
  37420. the DragAndDropContainer it should to use.
  37421. Obviously this may return 0 if it doesn't find a suitable component.
  37422. */
  37423. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  37424. /** This performs a synchronous drag-and-drop of a set of files to some external
  37425. application.
  37426. You can call this function in response to a mouseDrag callback, and it will
  37427. block, running its own internal message loop and tracking the mouse, while it
  37428. uses a native operating system drag-and-drop operation to move or copy some
  37429. files to another application.
  37430. @param files a list of filenames to drag
  37431. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  37432. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  37433. @returns true if the files were successfully dropped somewhere, or false if it
  37434. was interrupted
  37435. @see performExternalDragDropOfText
  37436. */
  37437. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  37438. /** This performs a synchronous drag-and-drop of a block of text to some external
  37439. application.
  37440. You can call this function in response to a mouseDrag callback, and it will
  37441. block, running its own internal message loop and tracking the mouse, while it
  37442. uses a native operating system drag-and-drop operation to move or copy some
  37443. text to another application.
  37444. @param text the text to copy
  37445. @returns true if the text was successfully dropped somewhere, or false if it
  37446. was interrupted
  37447. @see performExternalDragDropOfFiles
  37448. */
  37449. static bool performExternalDragDropOfText (const String& text);
  37450. protected:
  37451. /** Override this if you want to be able to perform an external drag a set of files
  37452. when the user drags outside of this container component.
  37453. This method will be called when a drag operation moves outside the Juce-based window,
  37454. and if you want it to then perform a file drag-and-drop, add the filenames you want
  37455. to the array passed in, and return true.
  37456. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  37457. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  37458. @param files on return, the filenames you want to drag
  37459. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  37460. it must make a copy of them (see the performExternalDragDropOfFiles()
  37461. method)
  37462. @see performExternalDragDropOfFiles
  37463. */
  37464. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  37465. Component* dragSourceComponent,
  37466. StringArray& files,
  37467. bool& canMoveFiles);
  37468. private:
  37469. friend class DragImageComponent;
  37470. ScopedPointer <Component> dragImageComponent;
  37471. String currentDragDesc;
  37472. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DragAndDropContainer);
  37473. };
  37474. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  37475. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  37476. class ToolbarItemComponent;
  37477. class ToolbarItemFactory;
  37478. /**
  37479. A toolbar component.
  37480. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  37481. and looks after their order and layout.
  37482. Items (icon buttons or other custom components) are added to a toolbar using a
  37483. ToolbarItemFactory - each type of item is given a unique ID number, and a
  37484. toolbar might contain more than one instance of a particular item type.
  37485. Toolbars can be interactively customised, allowing the user to drag the items
  37486. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  37487. component as a source of new items.
  37488. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  37489. */
  37490. class JUCE_API Toolbar : public Component,
  37491. public DragAndDropContainer,
  37492. public DragAndDropTarget,
  37493. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  37494. {
  37495. public:
  37496. /** Creates an empty toolbar component.
  37497. To add some icons or other components to your toolbar, you'll need to
  37498. create a ToolbarItemFactory class that can create a suitable set of
  37499. ToolbarItemComponents.
  37500. @see ToolbarItemFactory, ToolbarItemComponents
  37501. */
  37502. Toolbar();
  37503. /** Destructor.
  37504. Any items on the bar will be deleted when the toolbar is deleted.
  37505. */
  37506. ~Toolbar();
  37507. /** Changes the bar's orientation.
  37508. @see isVertical
  37509. */
  37510. void setVertical (bool shouldBeVertical);
  37511. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  37512. You can change the bar's orientation with setVertical().
  37513. */
  37514. bool isVertical() const throw() { return vertical; }
  37515. /** Returns the depth of the bar.
  37516. If the bar is horizontal, this will return its height; if it's vertical, it
  37517. will return its width.
  37518. @see getLength
  37519. */
  37520. int getThickness() const throw();
  37521. /** Returns the length of the bar.
  37522. If the bar is horizontal, this will return its width; if it's vertical, it
  37523. will return its height.
  37524. @see getThickness
  37525. */
  37526. int getLength() const throw();
  37527. /** Deletes all items from the bar.
  37528. */
  37529. void clear();
  37530. /** Adds an item to the toolbar.
  37531. The factory's ToolbarItemFactory::createItem() will be called by this method
  37532. to create the component that will actually be added to the bar.
  37533. The new item will be inserted at the specified index (if the index is -1, it
  37534. will be added to the right-hand or bottom end of the bar).
  37535. Once added, the component will be automatically deleted by this object when it
  37536. is no longer needed.
  37537. @see ToolbarItemFactory
  37538. */
  37539. void addItem (ToolbarItemFactory& factory,
  37540. int itemId,
  37541. int insertIndex = -1);
  37542. /** Deletes one of the items from the bar.
  37543. */
  37544. void removeToolbarItem (int itemIndex);
  37545. /** Returns the number of items currently on the toolbar.
  37546. @see getItemId, getItemComponent
  37547. */
  37548. int getNumItems() const throw();
  37549. /** Returns the ID of the item with the given index.
  37550. If the index is less than zero or greater than the number of items,
  37551. this will return 0.
  37552. @see getNumItems
  37553. */
  37554. int getItemId (int itemIndex) const throw();
  37555. /** Returns the component being used for the item with the given index.
  37556. If the index is less than zero or greater than the number of items,
  37557. this will return 0.
  37558. @see getNumItems
  37559. */
  37560. ToolbarItemComponent* getItemComponent (int itemIndex) const throw();
  37561. /** Clears this toolbar and adds to it the default set of items that the specified
  37562. factory creates.
  37563. @see ToolbarItemFactory::getDefaultItemSet
  37564. */
  37565. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  37566. /** Options for the way items should be displayed.
  37567. @see setStyle, getStyle
  37568. */
  37569. enum ToolbarItemStyle
  37570. {
  37571. iconsOnly, /**< Means that the toolbar should just contain icons. */
  37572. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  37573. textOnly /**< Means that the toolbar only display text labels for each item. */
  37574. };
  37575. /** Returns the toolbar's current style.
  37576. @see ToolbarItemStyle, setStyle
  37577. */
  37578. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  37579. /** Changes the toolbar's current style.
  37580. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  37581. */
  37582. void setStyle (const ToolbarItemStyle& newStyle);
  37583. /** Flags used by the showCustomisationDialog() method. */
  37584. enum CustomisationFlags
  37585. {
  37586. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  37587. show the "icons only" option on its choice of toolbar styles. */
  37588. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  37589. show the "icons with text" option on its choice of toolbar styles. */
  37590. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  37591. show the "text only" option on its choice of toolbar styles. */
  37592. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  37593. show a button to reset the toolbar to its default set of items. */
  37594. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  37595. };
  37596. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  37597. The dialog contains a ToolbarItemPalette and various controls for editing other
  37598. aspects of the toolbar. This method will block and run the dialog box modally,
  37599. returning when the user closes it.
  37600. The factory is used to determine the set of items that will be shown on the
  37601. palette.
  37602. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  37603. enum.
  37604. @see ToolbarItemPalette
  37605. */
  37606. void showCustomisationDialog (ToolbarItemFactory& factory,
  37607. int optionFlags = allCustomisationOptionsEnabled);
  37608. /** Turns on or off the toolbar's editing mode, in which its items can be
  37609. rearranged by the user.
  37610. (In most cases it's easier just to use showCustomisationDialog() instead of
  37611. trying to enable editing directly).
  37612. @see ToolbarItemPalette
  37613. */
  37614. void setEditingActive (bool editingEnabled);
  37615. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  37616. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37617. methods.
  37618. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37619. */
  37620. enum ColourIds
  37621. {
  37622. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  37623. more control over this, override LookAndFeel::paintToolbarBackground(). */
  37624. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  37625. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  37626. over them. */
  37627. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  37628. held down on them. */
  37629. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  37630. when the style is set to iconsWithText or textOnly. */
  37631. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  37632. the customisation dialog is active and the mouse moves over them. */
  37633. };
  37634. /** Returns a string that represents the toolbar's current set of items.
  37635. This lets you later restore the same item layout using restoreFromString().
  37636. @see restoreFromString
  37637. */
  37638. const String toString() const;
  37639. /** Restores a set of items that was previously stored in a string by the toString()
  37640. method.
  37641. The factory object is used to create any item components that are needed.
  37642. @see toString
  37643. */
  37644. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  37645. const String& savedVersion);
  37646. /** @internal */
  37647. void paint (Graphics& g);
  37648. /** @internal */
  37649. void resized();
  37650. /** @internal */
  37651. void buttonClicked (Button*);
  37652. /** @internal */
  37653. void mouseDown (const MouseEvent&);
  37654. /** @internal */
  37655. bool isInterestedInDragSource (const String&, Component*);
  37656. /** @internal */
  37657. void itemDragMove (const String&, Component*, int, int);
  37658. /** @internal */
  37659. void itemDragExit (const String&, Component*);
  37660. /** @internal */
  37661. void itemDropped (const String&, Component*, int, int);
  37662. /** @internal */
  37663. void updateAllItemPositions (bool animate);
  37664. /** @internal */
  37665. static ToolbarItemComponent* createItem (ToolbarItemFactory&, int itemId);
  37666. private:
  37667. ScopedPointer<Button> missingItemsButton;
  37668. bool vertical, isEditingActive;
  37669. ToolbarItemStyle toolbarStyle;
  37670. class MissingItemsComponent;
  37671. friend class MissingItemsComponent;
  37672. OwnedArray <ToolbarItemComponent> items;
  37673. friend class ItemDragAndDropOverlayComponent;
  37674. static const char* const toolbarDragDescriptor;
  37675. void addItemInternal (ToolbarItemFactory& factory, int itemId, int insertIndex);
  37676. ToolbarItemComponent* getNextActiveComponent (int index, int delta) const;
  37677. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Toolbar);
  37678. };
  37679. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  37680. /*** End of inlined file: juce_Toolbar.h ***/
  37681. class ItemDragAndDropOverlayComponent;
  37682. /**
  37683. A component that can be used as one of the items in a Toolbar.
  37684. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  37685. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  37686. class for further info about creating them.
  37687. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  37688. components too. To do this, set the value of isBeingUsedAsAButton to false when
  37689. calling the constructor, and override contentAreaChanged(), in which you can position
  37690. any sub-components you need to add.
  37691. To add basic buttons without writing a special subclass, have a look at the
  37692. ToolbarButton class.
  37693. @see ToolbarButton, Toolbar, ToolbarItemFactory
  37694. */
  37695. class JUCE_API ToolbarItemComponent : public Button
  37696. {
  37697. public:
  37698. /** Constructor.
  37699. @param itemId the ID of the type of toolbar item which this represents
  37700. @param labelText the text to display if the toolbar's style is set to
  37701. Toolbar::iconsWithText or Toolbar::textOnly
  37702. @param isBeingUsedAsAButton set this to false if you don't want the button
  37703. to draw itself with button over/down states when the mouse
  37704. moves over it or clicks
  37705. */
  37706. ToolbarItemComponent (int itemId,
  37707. const String& labelText,
  37708. bool isBeingUsedAsAButton);
  37709. /** Destructor. */
  37710. ~ToolbarItemComponent();
  37711. /** Returns the item type ID that this component represents.
  37712. This value is in the constructor.
  37713. */
  37714. int getItemId() const throw() { return itemId; }
  37715. /** Returns the toolbar that contains this component, or 0 if it's not currently
  37716. inside one.
  37717. */
  37718. Toolbar* getToolbar() const;
  37719. /** Returns true if this component is currently inside a toolbar which is vertical.
  37720. @see Toolbar::isVertical
  37721. */
  37722. bool isToolbarVertical() const;
  37723. /** Returns the current style setting of this item.
  37724. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  37725. @see setStyle, Toolbar::getStyle
  37726. */
  37727. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  37728. /** Changes the current style setting of this item.
  37729. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  37730. by the toolbar that holds this item.
  37731. @see setStyle, Toolbar::setStyle
  37732. */
  37733. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  37734. /** Returns the area of the component that should be used to display the button image or
  37735. other contents of the item.
  37736. This content area may change when the item's style changes, and may leave a space around the
  37737. edge of the component where the text label can be shown.
  37738. @see contentAreaChanged
  37739. */
  37740. const Rectangle<int> getContentArea() const throw() { return contentArea; }
  37741. /** This method must return the size criteria for this item, based on a given toolbar
  37742. size and orientation.
  37743. The preferredSize, minSize and maxSize values must all be set by your implementation
  37744. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  37745. toolbar, they refer to the item's height.
  37746. The preferredSize is the size that the component would like to be, and this must be
  37747. between the min and max sizes. For a fixed-size item, simply set all three variables to
  37748. the same value.
  37749. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  37750. Toolbar::getThickness().
  37751. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  37752. vertically.
  37753. */
  37754. virtual bool getToolbarItemSizes (int toolbarThickness,
  37755. bool isToolbarVertical,
  37756. int& preferredSize,
  37757. int& minSize,
  37758. int& maxSize) = 0;
  37759. /** Your subclass should use this method to draw its content area.
  37760. The graphics object that is passed-in will have been clipped and had its origin
  37761. moved to fit the content area as specified get getContentArea(). The width and height
  37762. parameters are the width and height of the content area.
  37763. If the component you're writing isn't a button, you can just do nothing in this method.
  37764. */
  37765. virtual void paintButtonArea (Graphics& g,
  37766. int width, int height,
  37767. bool isMouseOver, bool isMouseDown) = 0;
  37768. /** Callback to indicate that the content area of this item has changed.
  37769. This might be because the component was resized, or because the style changed and
  37770. the space needed for the text label is different.
  37771. See getContentArea() for a description of what the area is.
  37772. */
  37773. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  37774. /** Editing modes.
  37775. These are used by setEditingMode(), but will be rarely needed in user code.
  37776. */
  37777. enum ToolbarEditingMode
  37778. {
  37779. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  37780. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  37781. customisation mode, and the items can be dragged around. */
  37782. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  37783. dragged onto a toolbar to add it to that bar.*/
  37784. };
  37785. /** Changes the editing mode of this component.
  37786. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  37787. and is unlikely to be of much use in end-user-code.
  37788. */
  37789. void setEditingMode (const ToolbarEditingMode newMode);
  37790. /** Returns the current editing mode of this component.
  37791. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  37792. and is unlikely to be of much use in end-user-code.
  37793. */
  37794. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  37795. /** @internal */
  37796. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  37797. /** @internal */
  37798. void resized();
  37799. private:
  37800. friend class Toolbar;
  37801. friend class ItemDragAndDropOverlayComponent;
  37802. const int itemId;
  37803. ToolbarEditingMode mode;
  37804. Toolbar::ToolbarItemStyle toolbarStyle;
  37805. ScopedPointer <Component> overlayComp;
  37806. int dragOffsetX, dragOffsetY;
  37807. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  37808. Rectangle<int> contentArea;
  37809. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemComponent);
  37810. };
  37811. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  37812. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  37813. /**
  37814. A type of button designed to go on a toolbar.
  37815. This simple button can have two Drawable objects specified - one for normal
  37816. use and another one (optionally) for the button's "on" state if it's a
  37817. toggle button.
  37818. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  37819. */
  37820. class JUCE_API ToolbarButton : public ToolbarItemComponent
  37821. {
  37822. public:
  37823. /** Creates a ToolbarButton.
  37824. @param itemId the ID for this toolbar item type. This is passed through to the
  37825. ToolbarItemComponent constructor
  37826. @param labelText the text to display on the button (if the toolbar is using a style
  37827. that shows text labels). This is passed through to the
  37828. ToolbarItemComponent constructor
  37829. @param normalImage a drawable object that the button should use as its icon. The object
  37830. that is passed-in here will be kept by this object and will be
  37831. deleted when no longer needed or when this button is deleted.
  37832. @param toggledOnImage a drawable object that the button can use as its icon if the button
  37833. is in a toggled-on state (see the Button::getToggleState() method). If
  37834. 0 is passed-in here, then the normal image will be used instead, regardless
  37835. of the toggle state. The object that is passed-in here will be kept by
  37836. this object and will be deleted when no longer needed or when this button
  37837. is deleted.
  37838. */
  37839. ToolbarButton (int itemId,
  37840. const String& labelText,
  37841. Drawable* normalImage,
  37842. Drawable* toggledOnImage);
  37843. /** Destructor. */
  37844. ~ToolbarButton();
  37845. /** @internal */
  37846. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  37847. int& minSize, int& maxSize);
  37848. /** @internal */
  37849. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  37850. /** @internal */
  37851. void contentAreaChanged (const Rectangle<int>& newBounds);
  37852. /** @internal */
  37853. void buttonStateChanged();
  37854. /** @internal */
  37855. void resized();
  37856. /** @internal */
  37857. void enablementChanged();
  37858. private:
  37859. ScopedPointer<Drawable> normalImage, toggledOnImage;
  37860. Drawable* currentImage;
  37861. void updateDrawable();
  37862. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarButton);
  37863. };
  37864. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  37865. /*** End of inlined file: juce_ToolbarButton.h ***/
  37866. #endif
  37867. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  37868. /*** Start of inlined file: juce_CodeDocument.h ***/
  37869. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  37870. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  37871. class CodeDocumentLine;
  37872. /**
  37873. A class for storing and manipulating a source code file.
  37874. When using a CodeEditorComponent, it takes one of these as its source object.
  37875. The CodeDocument stores its content as an array of lines, which makes it
  37876. quick to insert and delete.
  37877. @see CodeEditorComponent
  37878. */
  37879. class JUCE_API CodeDocument
  37880. {
  37881. public:
  37882. /** Creates a new, empty document.
  37883. */
  37884. CodeDocument();
  37885. /** Destructor. */
  37886. ~CodeDocument();
  37887. /** A position in a code document.
  37888. Using this class you can find a position in a code document and quickly get its
  37889. character position, line, and index. By calling setPositionMaintained (true), the
  37890. position is automatically updated when text is inserted or deleted in the document,
  37891. so that it maintains its original place in the text.
  37892. */
  37893. class JUCE_API Position
  37894. {
  37895. public:
  37896. /** Creates an uninitialised postion.
  37897. Don't attempt to call any methods on this until you've given it an owner document
  37898. to refer to!
  37899. */
  37900. Position() throw();
  37901. /** Creates a position based on a line and index in a document.
  37902. Note that this index is NOT the column number, it's the number of characters from the
  37903. start of the line. The "column" number isn't quite the same, because if the line
  37904. contains any tab characters, the relationship of the index to its visual column depends on
  37905. the number of spaces per tab being used!
  37906. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  37907. they will be adjusted to keep them within its limits.
  37908. */
  37909. Position (const CodeDocument* ownerDocument,
  37910. int line, int indexInLine) throw();
  37911. /** Creates a position based on a character index in a document.
  37912. This position is placed at the specified number of characters from the start of the
  37913. document. The line and column are auto-calculated.
  37914. If the position is beyond the range of the document, it'll be adjusted to keep it
  37915. inside.
  37916. */
  37917. Position (const CodeDocument* ownerDocument,
  37918. int charactersFromStartOfDocument) throw();
  37919. /** Creates a copy of another position.
  37920. This will copy the position, but the new object will not be set to maintain its position,
  37921. even if the source object was set to do so.
  37922. */
  37923. Position (const Position& other) throw();
  37924. /** Destructor. */
  37925. ~Position();
  37926. Position& operator= (const Position& other);
  37927. bool operator== (const Position& other) const throw();
  37928. bool operator!= (const Position& other) const throw();
  37929. /** Points this object at a new position within the document.
  37930. If the position is beyond the range of the document, it'll be adjusted to keep it
  37931. inside.
  37932. @see getPosition, setLineAndIndex
  37933. */
  37934. void setPosition (int charactersFromStartOfDocument);
  37935. /** Returns the position as the number of characters from the start of the document.
  37936. @see setPosition, getLineNumber, getIndexInLine
  37937. */
  37938. int getPosition() const throw() { return characterPos; }
  37939. /** Moves the position to a new line and index within the line.
  37940. Note that the index is NOT the column at which the position appears in an editor.
  37941. If the line contains any tab characters, the relationship of the index to its
  37942. visual position depends on the number of spaces per tab being used!
  37943. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  37944. they will be adjusted to keep them within its limits.
  37945. */
  37946. void setLineAndIndex (int newLine, int newIndexInLine);
  37947. /** Returns the line number of this position.
  37948. The first line in the document is numbered zero, not one!
  37949. */
  37950. int getLineNumber() const throw() { return line; }
  37951. /** Returns the number of characters from the start of the line.
  37952. Note that this value is NOT the column at which the position appears in an editor.
  37953. If the line contains any tab characters, the relationship of the index to its
  37954. visual position depends on the number of spaces per tab being used!
  37955. */
  37956. int getIndexInLine() const throw() { return indexInLine; }
  37957. /** Allows the position to be automatically updated when the document changes.
  37958. If this is set to true, the positon will register with its document so that
  37959. when the document has text inserted or deleted, this position will be automatically
  37960. moved to keep it at the same position in the text.
  37961. */
  37962. void setPositionMaintained (bool isMaintained);
  37963. /** Moves the position forwards or backwards by the specified number of characters.
  37964. @see movedBy
  37965. */
  37966. void moveBy (int characterDelta);
  37967. /** Returns a position which is the same as this one, moved by the specified number of
  37968. characters.
  37969. @see moveBy
  37970. */
  37971. const Position movedBy (int characterDelta) const;
  37972. /** Returns a position which is the same as this one, moved up or down by the specified
  37973. number of lines.
  37974. @see movedBy
  37975. */
  37976. const Position movedByLines (int deltaLines) const;
  37977. /** Returns the character in the document at this position.
  37978. @see getLineText
  37979. */
  37980. const juce_wchar getCharacter() const;
  37981. /** Returns the line from the document that this position is within.
  37982. @see getCharacter, getLineNumber
  37983. */
  37984. const String getLineText() const;
  37985. private:
  37986. CodeDocument* owner;
  37987. int characterPos, line, indexInLine;
  37988. bool positionMaintained;
  37989. };
  37990. /** Returns the full text of the document. */
  37991. const String getAllContent() const;
  37992. /** Returns a section of the document's text. */
  37993. const String getTextBetween (const Position& start, const Position& end) const;
  37994. /** Returns a line from the document. */
  37995. const String getLine (int lineIndex) const throw();
  37996. /** Returns the number of characters in the document. */
  37997. int getNumCharacters() const throw();
  37998. /** Returns the number of lines in the document. */
  37999. int getNumLines() const throw() { return lines.size(); }
  38000. /** Returns the number of characters in the longest line of the document. */
  38001. int getMaximumLineLength() throw();
  38002. /** Deletes a section of the text.
  38003. This operation is undoable.
  38004. */
  38005. void deleteSection (const Position& startPosition, const Position& endPosition);
  38006. /** Inserts some text into the document at a given position.
  38007. This operation is undoable.
  38008. */
  38009. void insertText (const Position& position, const String& text);
  38010. /** Clears the document and replaces it with some new text.
  38011. This operation is undoable - if you're trying to completely reset the document, you
  38012. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  38013. */
  38014. void replaceAllContent (const String& newContent);
  38015. /** Replaces the editor's contents with the contents of a stream.
  38016. This will also reset the undo history and save point marker.
  38017. */
  38018. bool loadFromStream (InputStream& stream);
  38019. /** Writes the editor's current contents to a stream. */
  38020. bool writeToStream (OutputStream& stream);
  38021. /** Returns the preferred new-line characters for the document.
  38022. This will be either "\n", "\r\n", or (rarely) "\r".
  38023. @see setNewLineCharacters
  38024. */
  38025. const String getNewLineCharacters() const throw() { return newLineChars; }
  38026. /** Sets the new-line characters that the document should use.
  38027. The string must be either "\n", "\r\n", or (rarely) "\r".
  38028. @see getNewLineCharacters
  38029. */
  38030. void setNewLineCharacters (const String& newLine) throw();
  38031. /** Begins a new undo transaction.
  38032. The document itself will not call this internally, so relies on whatever is using the
  38033. document to periodically call this to break up the undo sequence into sensible chunks.
  38034. @see UndoManager::beginNewTransaction
  38035. */
  38036. void newTransaction();
  38037. /** Undo the last operation.
  38038. @see UndoManager::undo
  38039. */
  38040. void undo();
  38041. /** Redo the last operation.
  38042. @see UndoManager::redo
  38043. */
  38044. void redo();
  38045. /** Clears the undo history.
  38046. @see UndoManager::clearUndoHistory
  38047. */
  38048. void clearUndoHistory();
  38049. /** Returns the document's UndoManager */
  38050. UndoManager& getUndoManager() throw() { return undoManager; }
  38051. /** Makes a note that the document's current state matches the one that is saved.
  38052. After this has been called, hasChangedSinceSavePoint() will return false until
  38053. the document has been altered, and then it'll start returning true. If the document is
  38054. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  38055. will again return false.
  38056. @see hasChangedSinceSavePoint
  38057. */
  38058. void setSavePoint() throw();
  38059. /** Returns true if the state of the document differs from the state it was in when
  38060. setSavePoint() was last called.
  38061. @see setSavePoint
  38062. */
  38063. bool hasChangedSinceSavePoint() const throw();
  38064. /** Searches for a word-break. */
  38065. const Position findWordBreakAfter (const Position& position) const throw();
  38066. /** Searches for a word-break. */
  38067. const Position findWordBreakBefore (const Position& position) const throw();
  38068. /** An object that receives callbacks from the CodeDocument when its text changes.
  38069. @see CodeDocument::addListener, CodeDocument::removeListener
  38070. */
  38071. class JUCE_API Listener
  38072. {
  38073. public:
  38074. Listener() {}
  38075. virtual ~Listener() {}
  38076. /** Called by a CodeDocument when it is altered.
  38077. */
  38078. virtual void codeDocumentChanged (const Position& affectedTextStart,
  38079. const Position& affectedTextEnd) = 0;
  38080. };
  38081. /** Registers a listener object to receive callbacks when the document changes.
  38082. If the listener is already registered, this method has no effect.
  38083. @see removeListener
  38084. */
  38085. void addListener (Listener* listener) throw();
  38086. /** Deregisters a listener.
  38087. @see addListener
  38088. */
  38089. void removeListener (Listener* listener) throw();
  38090. /** Iterates the text in a CodeDocument.
  38091. This class lets you read characters from a CodeDocument. It's designed to be used
  38092. by a SyntaxAnalyser object.
  38093. @see CodeDocument, SyntaxAnalyser
  38094. */
  38095. class Iterator
  38096. {
  38097. public:
  38098. Iterator (CodeDocument* document);
  38099. Iterator (const Iterator& other);
  38100. Iterator& operator= (const Iterator& other) throw();
  38101. ~Iterator() throw();
  38102. /** Reads the next character and returns it.
  38103. @see peekNextChar
  38104. */
  38105. juce_wchar nextChar();
  38106. /** Reads the next character without advancing the current position. */
  38107. juce_wchar peekNextChar() const;
  38108. /** Advances the position by one character. */
  38109. void skip();
  38110. /** Returns the position of the next character as its position within the
  38111. whole document.
  38112. */
  38113. int getPosition() const throw() { return position; }
  38114. /** Skips over any whitespace characters until the next character is non-whitespace. */
  38115. void skipWhitespace();
  38116. /** Skips forward until the next character will be the first character on the next line */
  38117. void skipToEndOfLine();
  38118. /** Returns the line number of the next character. */
  38119. int getLine() const throw() { return line; }
  38120. /** Returns true if the iterator has reached the end of the document. */
  38121. bool isEOF() const throw();
  38122. private:
  38123. CodeDocument* document;
  38124. CodeDocumentLine* currentLine;
  38125. int line, position;
  38126. };
  38127. private:
  38128. friend class CodeDocumentInsertAction;
  38129. friend class CodeDocumentDeleteAction;
  38130. friend class Iterator;
  38131. friend class Position;
  38132. OwnedArray <CodeDocumentLine> lines;
  38133. Array <Position*> positionsToMaintain;
  38134. UndoManager undoManager;
  38135. int currentActionIndex, indexOfSavedState;
  38136. int maximumLineLength;
  38137. ListenerList <Listener> listeners;
  38138. String newLineChars;
  38139. void sendListenerChangeMessage (int startLine, int endLine);
  38140. void insert (const String& text, int insertPos, bool undoable);
  38141. void remove (int startPos, int endPos, bool undoable);
  38142. void checkLastLineStatus();
  38143. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeDocument);
  38144. };
  38145. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  38146. /*** End of inlined file: juce_CodeDocument.h ***/
  38147. #endif
  38148. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38149. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  38150. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38151. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38152. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  38153. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  38154. #define __JUCE_CODETOKENISER_JUCEHEADER__
  38155. /**
  38156. A base class for tokenising code so that the syntax can be displayed in a
  38157. code editor.
  38158. @see CodeDocument, CodeEditorComponent
  38159. */
  38160. class JUCE_API CodeTokeniser
  38161. {
  38162. public:
  38163. CodeTokeniser() {}
  38164. virtual ~CodeTokeniser() {}
  38165. /** Reads the next token from the source and returns its token type.
  38166. This must leave the source pointing to the first character in the
  38167. next token.
  38168. */
  38169. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  38170. /** Returns a list of the names of the token types this analyser uses.
  38171. The index in this list must match the token type numbers that are
  38172. returned by readNextToken().
  38173. */
  38174. virtual const StringArray getTokenTypes() = 0;
  38175. /** Returns a suggested syntax highlighting colour for a specified
  38176. token type.
  38177. */
  38178. virtual const Colour getDefaultColour (int tokenType) = 0;
  38179. private:
  38180. JUCE_LEAK_DETECTOR (CodeTokeniser);
  38181. };
  38182. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  38183. /*** End of inlined file: juce_CodeTokeniser.h ***/
  38184. /**
  38185. A text editor component designed specifically for source code.
  38186. This is designed to handle syntax highlighting and fast editing of very large
  38187. files.
  38188. */
  38189. class JUCE_API CodeEditorComponent : public Component,
  38190. public TextInputTarget,
  38191. public Timer,
  38192. public ScrollBar::Listener,
  38193. public CodeDocument::Listener,
  38194. public AsyncUpdater
  38195. {
  38196. public:
  38197. /** Creates an editor for a document.
  38198. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  38199. The object that you pass in is not owned or deleted by the editor - you must
  38200. make sure that it doesn't get deleted while this component is still using it.
  38201. @see CodeDocument
  38202. */
  38203. CodeEditorComponent (CodeDocument& document,
  38204. CodeTokeniser* codeTokeniser);
  38205. /** Destructor. */
  38206. ~CodeEditorComponent();
  38207. /** Returns the code document that this component is editing. */
  38208. CodeDocument& getDocument() const throw() { return document; }
  38209. /** Loads the given content into the document.
  38210. This will completely reset the CodeDocument object, clear its undo history,
  38211. and fill it with this text.
  38212. */
  38213. void loadContent (const String& newContent);
  38214. /** Returns the standard character width. */
  38215. float getCharWidth() const throw() { return charWidth; }
  38216. /** Returns the height of a line of text, in pixels. */
  38217. int getLineHeight() const throw() { return lineHeight; }
  38218. /** Returns the number of whole lines visible on the screen,
  38219. This doesn't include a cut-off line that might be visible at the bottom if the
  38220. component's height isn't an exact multiple of the line-height.
  38221. */
  38222. int getNumLinesOnScreen() const throw() { return linesOnScreen; }
  38223. /** Returns the number of whole columns visible on the screen.
  38224. This doesn't include any cut-off columns at the right-hand edge.
  38225. */
  38226. int getNumColumnsOnScreen() const throw() { return columnsOnScreen; }
  38227. /** Returns the current caret position. */
  38228. const CodeDocument::Position getCaretPos() const { return caretPos; }
  38229. /** Moves the caret.
  38230. If selecting is true, the section of the document between the current
  38231. caret position and the new one will become selected. If false, any currently
  38232. selected region will be deselected.
  38233. */
  38234. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  38235. /** Returns the on-screen position of a character in the document.
  38236. The rectangle returned is relative to this component's top-left origin.
  38237. */
  38238. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const;
  38239. /** Finds the character at a given on-screen position.
  38240. The co-ordinates are relative to this component's top-left origin.
  38241. */
  38242. const CodeDocument::Position getPositionAt (int x, int y);
  38243. void cursorLeft (bool moveInWholeWordSteps, bool selecting);
  38244. void cursorRight (bool moveInWholeWordSteps, bool selecting);
  38245. void cursorDown (bool selecting);
  38246. void cursorUp (bool selecting);
  38247. void pageDown (bool selecting);
  38248. void pageUp (bool selecting);
  38249. void scrollDown();
  38250. void scrollUp();
  38251. void scrollToLine (int newFirstLineOnScreen);
  38252. void scrollBy (int deltaLines);
  38253. void scrollToColumn (int newFirstColumnOnScreen);
  38254. void scrollToKeepCaretOnScreen();
  38255. void goToStartOfDocument (bool selecting);
  38256. void goToStartOfLine (bool selecting);
  38257. void goToEndOfDocument (bool selecting);
  38258. void goToEndOfLine (bool selecting);
  38259. void deselectAll();
  38260. void selectAll();
  38261. void insertTextAtCaret (const String& textToInsert);
  38262. void insertTabAtCaret();
  38263. void cut();
  38264. void copy();
  38265. void copyThenCut();
  38266. void paste();
  38267. void backspace (bool moveInWholeWordSteps);
  38268. void deleteForward (bool moveInWholeWordSteps);
  38269. void undo();
  38270. void redo();
  38271. const Range<int> getHighlightedRegion() const;
  38272. void setHighlightedRegion (const Range<int>& newRange);
  38273. const String getTextInRange (const Range<int>& range) const;
  38274. /** Changes the current tab settings.
  38275. This lets you change the tab size and whether pressing the tab key inserts a
  38276. tab character, or its equivalent number of spaces.
  38277. */
  38278. void setTabSize (int numSpacesPerTab, bool insertSpacesInsteadOfTabCharacters);
  38279. /** Returns the current number of spaces per tab.
  38280. @see setTabSize
  38281. */
  38282. int getTabSize() const throw() { return spacesPerTab; }
  38283. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  38284. @see setTabSize
  38285. */
  38286. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  38287. /** Changes the font.
  38288. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  38289. */
  38290. void setFont (const Font& newFont);
  38291. /** Returns the font that the editor is using. */
  38292. const Font& getFont() const throw() { return font; }
  38293. /** Resets the syntax highlighting colours to the default ones provided by the
  38294. code tokeniser.
  38295. @see CodeTokeniser::getDefaultColour
  38296. */
  38297. void resetToDefaultColours();
  38298. /** Changes one of the syntax highlighting colours.
  38299. The token type values are dependent on the tokeniser being used - use
  38300. CodeTokeniser::getTokenTypes() to get a list of the token types.
  38301. @see getColourForTokenType
  38302. */
  38303. void setColourForTokenType (int tokenType, const Colour& colour);
  38304. /** Returns one of the syntax highlighting colours.
  38305. The token type values are dependent on the tokeniser being used - use
  38306. CodeTokeniser::getTokenTypes() to get a list of the token types.
  38307. @see setColourForTokenType
  38308. */
  38309. const Colour getColourForTokenType (int tokenType) const;
  38310. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  38311. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38312. methods.
  38313. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38314. */
  38315. enum ColourIds
  38316. {
  38317. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  38318. caretColourId = 0x1004501, /**< The colour to draw the caret. */
  38319. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  38320. selected text. */
  38321. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  38322. enabled. */
  38323. };
  38324. /** Changes the size of the scrollbars. */
  38325. void setScrollbarThickness (int thickness);
  38326. /** Returns the thickness of the scrollbars. */
  38327. int getScrollbarThickness() const throw() { return scrollbarThickness; }
  38328. /** @internal */
  38329. void resized();
  38330. /** @internal */
  38331. void paint (Graphics& g);
  38332. /** @internal */
  38333. bool keyPressed (const KeyPress& key);
  38334. /** @internal */
  38335. void mouseDown (const MouseEvent& e);
  38336. /** @internal */
  38337. void mouseDrag (const MouseEvent& e);
  38338. /** @internal */
  38339. void mouseUp (const MouseEvent& e);
  38340. /** @internal */
  38341. void mouseDoubleClick (const MouseEvent& e);
  38342. /** @internal */
  38343. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  38344. /** @internal */
  38345. void focusGained (FocusChangeType cause);
  38346. /** @internal */
  38347. void focusLost (FocusChangeType cause);
  38348. /** @internal */
  38349. void timerCallback();
  38350. /** @internal */
  38351. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  38352. /** @internal */
  38353. void handleAsyncUpdate();
  38354. /** @internal */
  38355. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  38356. const CodeDocument::Position& affectedTextEnd);
  38357. /** @internal */
  38358. bool isTextInputActive() const;
  38359. private:
  38360. CodeDocument& document;
  38361. Font font;
  38362. int firstLineOnScreen, gutter, spacesPerTab;
  38363. float charWidth;
  38364. int lineHeight, linesOnScreen, columnsOnScreen;
  38365. int scrollbarThickness, columnToTryToMaintain;
  38366. bool useSpacesForTabs;
  38367. double xOffset;
  38368. CodeDocument::Position caretPos;
  38369. CodeDocument::Position selectionStart, selectionEnd;
  38370. class CaretComponent;
  38371. friend class ScopedPointer <CaretComponent>;
  38372. ScopedPointer<CaretComponent> caret;
  38373. ScrollBar verticalScrollBar, horizontalScrollBar;
  38374. enum DragType
  38375. {
  38376. notDragging,
  38377. draggingSelectionStart,
  38378. draggingSelectionEnd
  38379. };
  38380. DragType dragType;
  38381. CodeTokeniser* codeTokeniser;
  38382. Array <Colour> coloursForTokenCategories;
  38383. class CodeEditorLine;
  38384. OwnedArray <CodeEditorLine> lines;
  38385. void rebuildLineTokens();
  38386. OwnedArray <CodeDocument::Iterator> cachedIterators;
  38387. void clearCachedIterators (int firstLineToBeInvalid);
  38388. void updateCachedIterators (int maxLineNum);
  38389. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  38390. void moveLineDelta (int delta, bool selecting);
  38391. void updateScrollBars();
  38392. void scrollToLineInternal (int line);
  38393. void scrollToColumnInternal (double column);
  38394. void newTransaction();
  38395. int indexToColumn (int line, int index) const throw();
  38396. int columnToIndex (int line, int column) const throw();
  38397. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CodeEditorComponent);
  38398. };
  38399. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  38400. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  38401. #endif
  38402. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  38403. #endif
  38404. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  38405. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  38406. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  38407. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  38408. /**
  38409. A simple lexical analyser for syntax colouring of C++ code.
  38410. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  38411. */
  38412. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  38413. {
  38414. public:
  38415. CPlusPlusCodeTokeniser();
  38416. ~CPlusPlusCodeTokeniser();
  38417. enum TokenType
  38418. {
  38419. tokenType_error = 0,
  38420. tokenType_comment,
  38421. tokenType_builtInKeyword,
  38422. tokenType_identifier,
  38423. tokenType_integerLiteral,
  38424. tokenType_floatLiteral,
  38425. tokenType_stringLiteral,
  38426. tokenType_operator,
  38427. tokenType_bracket,
  38428. tokenType_punctuation,
  38429. tokenType_preprocessor
  38430. };
  38431. int readNextToken (CodeDocument::Iterator& source);
  38432. const StringArray getTokenTypes();
  38433. const Colour getDefaultColour (int tokenType);
  38434. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  38435. static bool isReservedKeyword (const String& token) throw();
  38436. private:
  38437. JUCE_LEAK_DETECTOR (CPlusPlusCodeTokeniser);
  38438. };
  38439. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  38440. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  38441. #endif
  38442. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  38443. #endif
  38444. #ifndef __JUCE_LABEL_JUCEHEADER__
  38445. #endif
  38446. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  38447. #endif
  38448. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  38449. /*** Start of inlined file: juce_ProgressBar.h ***/
  38450. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  38451. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  38452. /**
  38453. A progress bar component.
  38454. To use this, just create one and make it visible. It'll run its own timer
  38455. to keep an eye on a variable that you give it, and will automatically
  38456. redraw itself when the variable changes.
  38457. For an easy way of running a background task with a dialog box showing its
  38458. progress, see the ThreadWithProgressWindow class.
  38459. @see ThreadWithProgressWindow
  38460. */
  38461. class JUCE_API ProgressBar : public Component,
  38462. public SettableTooltipClient,
  38463. private Timer
  38464. {
  38465. public:
  38466. /** Creates a ProgressBar.
  38467. @param progress pass in a reference to a double that you're going to
  38468. update with your task's progress. The ProgressBar will
  38469. monitor the value of this variable and will redraw itself
  38470. when the value changes. The range is from 0 to 1.0. Obviously
  38471. you'd better be careful not to delete this variable while the
  38472. ProgressBar still exists!
  38473. */
  38474. explicit ProgressBar (double& progress);
  38475. /** Destructor. */
  38476. ~ProgressBar();
  38477. /** Turns the percentage display on or off.
  38478. By default this is on, and the progress bar will display a text string showing
  38479. its current percentage.
  38480. */
  38481. void setPercentageDisplay (bool shouldDisplayPercentage);
  38482. /** Gives the progress bar a string to display inside it.
  38483. If you call this, it will turn off the percentage display.
  38484. @see setPercentageDisplay
  38485. */
  38486. void setTextToDisplay (const String& text);
  38487. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  38488. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38489. methods.
  38490. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38491. */
  38492. enum ColourIds
  38493. {
  38494. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  38495. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  38496. classes will probably use variations on this colour. */
  38497. };
  38498. protected:
  38499. /** @internal */
  38500. void paint (Graphics& g);
  38501. /** @internal */
  38502. void lookAndFeelChanged();
  38503. /** @internal */
  38504. void visibilityChanged();
  38505. /** @internal */
  38506. void colourChanged();
  38507. private:
  38508. double& progress;
  38509. double currentValue;
  38510. bool displayPercentage;
  38511. String displayedMessage, currentMessage;
  38512. uint32 lastCallbackTime;
  38513. void timerCallback();
  38514. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProgressBar);
  38515. };
  38516. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  38517. /*** End of inlined file: juce_ProgressBar.h ***/
  38518. #endif
  38519. #ifndef __JUCE_SLIDER_JUCEHEADER__
  38520. /*** Start of inlined file: juce_Slider.h ***/
  38521. #ifndef __JUCE_SLIDER_JUCEHEADER__
  38522. #define __JUCE_SLIDER_JUCEHEADER__
  38523. #if JUCE_VC6
  38524. #define Listener LabelListener
  38525. #endif
  38526. /**
  38527. A slider control for changing a value.
  38528. The slider can be horizontal, vertical, or rotary, and can optionally have
  38529. a text-box inside it to show an editable display of the current value.
  38530. To use it, create a Slider object and use the setSliderStyle() method
  38531. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  38532. To define the values that it can be set to, see the setRange() and setValue() methods.
  38533. There are also lots of custom tweaks you can do by subclassing and overriding
  38534. some of the virtual methods, such as changing the scaling, changing the format of
  38535. the text display, custom ways of limiting the values, etc.
  38536. You can register Slider::Listener objects with a slider, and they'll be called when
  38537. the value changes.
  38538. @see Slider::Listener
  38539. */
  38540. class JUCE_API Slider : public Component,
  38541. public SettableTooltipClient,
  38542. public AsyncUpdater,
  38543. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  38544. public LabelListener,
  38545. public ValueListener
  38546. {
  38547. public:
  38548. /** Creates a slider.
  38549. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  38550. setRange(), etc.
  38551. */
  38552. explicit Slider (const String& componentName = String::empty);
  38553. /** Destructor. */
  38554. ~Slider();
  38555. /** The types of slider available.
  38556. @see setSliderStyle, setRotaryParameters
  38557. */
  38558. enum SliderStyle
  38559. {
  38560. LinearHorizontal, /**< A traditional horizontal slider. */
  38561. LinearVertical, /**< A traditional vertical slider. */
  38562. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  38563. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  38564. @see setRotaryParameters */
  38565. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  38566. @see setRotaryParameters */
  38567. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  38568. @see setRotaryParameters */
  38569. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  38570. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  38571. @see setMinValue, setMaxValue */
  38572. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  38573. @see setMinValue, setMaxValue */
  38574. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  38575. value, with the current value being somewhere between them.
  38576. @see setMinValue, setMaxValue */
  38577. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  38578. value, with the current value being somewhere between them.
  38579. @see setMinValue, setMaxValue */
  38580. };
  38581. /** Changes the type of slider interface being used.
  38582. @param newStyle the type of interface
  38583. @see setRotaryParameters, setVelocityBasedMode,
  38584. */
  38585. void setSliderStyle (SliderStyle newStyle);
  38586. /** Returns the slider's current style.
  38587. @see setSliderStyle
  38588. */
  38589. SliderStyle getSliderStyle() const throw() { return style; }
  38590. /** Changes the properties of a rotary slider.
  38591. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  38592. the slider's minimum value is represented
  38593. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  38594. the slider's maximum value is represented. This must be
  38595. greater than startAngleRadians
  38596. @param stopAtEnd if true, then when the slider is dragged around past the
  38597. minimum or maximum, it'll stop there; if false, it'll wrap
  38598. back to the opposite value
  38599. */
  38600. void setRotaryParameters (float startAngleRadians,
  38601. float endAngleRadians,
  38602. bool stopAtEnd);
  38603. /** Sets the distance the mouse has to move to drag the slider across
  38604. the full extent of its range.
  38605. This only applies when in modes like RotaryHorizontalDrag, where it's using
  38606. relative mouse movements to adjust the slider.
  38607. */
  38608. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  38609. /** Returns the current sensitivity value set by setMouseDragSensitivity(). */
  38610. int getMouseDragSensitivity() const throw() { return pixelsForFullDragExtent; }
  38611. /** Changes the way the the mouse is used when dragging the slider.
  38612. If true, this will turn on velocity-sensitive dragging, so that
  38613. the faster the mouse moves, the bigger the movement to the slider. This
  38614. helps when making accurate adjustments if the slider's range is quite large.
  38615. If false, the slider will just try to snap to wherever the mouse is.
  38616. */
  38617. void setVelocityBasedMode (bool isVelocityBased);
  38618. /** Returns true if velocity-based mode is active.
  38619. @see setVelocityBasedMode
  38620. */
  38621. bool getVelocityBasedMode() const throw() { return isVelocityBased; }
  38622. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  38623. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  38624. or if you're holding down ctrl.
  38625. @param sensitivity higher values than 1.0 increase the range of acceleration used
  38626. @param threshold the minimum number of pixels that the mouse needs to move for it
  38627. to be treated as a movement
  38628. @param offset values greater than 0.0 increase the minimum speed that will be used when
  38629. the threshold is reached
  38630. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  38631. key to toggle velocity-sensitive mode
  38632. */
  38633. void setVelocityModeParameters (double sensitivity = 1.0,
  38634. int threshold = 1,
  38635. double offset = 0.0,
  38636. bool userCanPressKeyToSwapMode = true);
  38637. /** Returns the velocity sensitivity setting.
  38638. @see setVelocityModeParameters
  38639. */
  38640. double getVelocitySensitivity() const throw() { return velocityModeSensitivity; }
  38641. /** Returns the velocity threshold setting.
  38642. @see setVelocityModeParameters
  38643. */
  38644. int getVelocityThreshold() const throw() { return velocityModeThreshold; }
  38645. /** Returns the velocity offset setting.
  38646. @see setVelocityModeParameters
  38647. */
  38648. double getVelocityOffset() const throw() { return velocityModeOffset; }
  38649. /** Returns the velocity user key setting.
  38650. @see setVelocityModeParameters
  38651. */
  38652. bool getVelocityModeIsSwappable() const throw() { return userKeyOverridesVelocity; }
  38653. /** Sets up a skew factor to alter the way values are distributed.
  38654. You may want to use a range of values on the slider where more accuracy
  38655. is required towards one end of the range, so this will logarithmically
  38656. spread the values across the length of the slider.
  38657. If the factor is < 1.0, the lower end of the range will fill more of the
  38658. slider's length; if the factor is > 1.0, the upper end of the range
  38659. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  38660. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  38661. method instead.
  38662. @see getSkewFactor, setSkewFactorFromMidPoint
  38663. */
  38664. void setSkewFactor (double factor);
  38665. /** Sets up a skew factor to alter the way values are distributed.
  38666. This allows you to specify the slider value that should appear in the
  38667. centre of the slider's visible range.
  38668. @see setSkewFactor, getSkewFactor
  38669. */
  38670. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  38671. /** Returns the current skew factor.
  38672. See setSkewFactor for more info.
  38673. @see setSkewFactor, setSkewFactorFromMidPoint
  38674. */
  38675. double getSkewFactor() const throw() { return skewFactor; }
  38676. /** Used by setIncDecButtonsMode().
  38677. */
  38678. enum IncDecButtonMode
  38679. {
  38680. incDecButtonsNotDraggable,
  38681. incDecButtonsDraggable_AutoDirection,
  38682. incDecButtonsDraggable_Horizontal,
  38683. incDecButtonsDraggable_Vertical
  38684. };
  38685. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  38686. can be dragged on the buttons to drag the values.
  38687. By default this is turned off. When enabled, clicking on the buttons still works
  38688. them as normal, but by holding down the mouse on a button and dragging it a little
  38689. distance, it flips into a mode where the value can be dragged. The drag direction can
  38690. either be set explicitly to be vertical or horizontal, or can be set to
  38691. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  38692. are side-by-side or above each other.
  38693. */
  38694. void setIncDecButtonsMode (IncDecButtonMode mode);
  38695. /** The position of the slider's text-entry box.
  38696. @see setTextBoxStyle
  38697. */
  38698. enum TextEntryBoxPosition
  38699. {
  38700. NoTextBox, /**< Doesn't display a text box. */
  38701. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  38702. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  38703. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  38704. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  38705. };
  38706. /** Changes the location and properties of the text-entry box.
  38707. @param newPosition where it should go (or NoTextBox to not have one at all)
  38708. @param isReadOnly if true, it's a read-only display
  38709. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  38710. room for the slider as well!
  38711. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  38712. room for the slider as well!
  38713. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  38714. */
  38715. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  38716. bool isReadOnly,
  38717. int textEntryBoxWidth,
  38718. int textEntryBoxHeight);
  38719. /** Returns the status of the text-box.
  38720. @see setTextBoxStyle
  38721. */
  38722. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  38723. /** Returns the width used for the text-box.
  38724. @see setTextBoxStyle
  38725. */
  38726. int getTextBoxWidth() const throw() { return textBoxWidth; }
  38727. /** Returns the height used for the text-box.
  38728. @see setTextBoxStyle
  38729. */
  38730. int getTextBoxHeight() const throw() { return textBoxHeight; }
  38731. /** Makes the text-box editable.
  38732. By default this is true, and the user can enter values into the textbox,
  38733. but it can be turned off if that's not suitable.
  38734. @see setTextBoxStyle, getValueFromText, getTextFromValue
  38735. */
  38736. void setTextBoxIsEditable (bool shouldBeEditable);
  38737. /** Returns true if the text-box is read-only.
  38738. @see setTextBoxStyle
  38739. */
  38740. bool isTextBoxEditable() const { return editableText; }
  38741. /** If the text-box is editable, this will give it the focus so that the user can
  38742. type directly into it.
  38743. This is basically the effect as the user clicking on it.
  38744. */
  38745. void showTextBox();
  38746. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  38747. focus away from it.
  38748. @param discardCurrentEditorContents if true, the slider's value will be left
  38749. unchanged; if false, the current contents of the
  38750. text editor will be used to set the slider position
  38751. before it is hidden.
  38752. */
  38753. void hideTextBox (bool discardCurrentEditorContents);
  38754. /** Changes the slider's current value.
  38755. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  38756. that are registered, and will synchronously call the valueChanged() method in case subclasses
  38757. want to handle it.
  38758. @param newValue the new value to set - this will be restricted by the
  38759. minimum and maximum range, and will be snapped to the
  38760. nearest interval if one has been set
  38761. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  38762. any Slider::Listeners or the valueChanged() method
  38763. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  38764. synchronously; if false, it will be asynchronous
  38765. */
  38766. void setValue (double newValue,
  38767. bool sendUpdateMessage = true,
  38768. bool sendMessageSynchronously = false);
  38769. /** Returns the slider's current value. */
  38770. double getValue() const;
  38771. /** Returns the Value object that represents the slider's current position.
  38772. You can use this Value object to connect the slider's position to external values or setters,
  38773. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  38774. your own Value object.
  38775. @see Value, getMaxValue, getMinValueObject
  38776. */
  38777. Value& getValueObject() { return currentValue; }
  38778. /** Sets the limits that the slider's value can take.
  38779. @param newMinimum the lowest value allowed
  38780. @param newMaximum the highest value allowed
  38781. @param newInterval the steps in which the value is allowed to increase - if this
  38782. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  38783. */
  38784. void setRange (double newMinimum,
  38785. double newMaximum,
  38786. double newInterval = 0);
  38787. /** Returns the current maximum value.
  38788. @see setRange
  38789. */
  38790. double getMaximum() const { return maximum; }
  38791. /** Returns the current minimum value.
  38792. @see setRange
  38793. */
  38794. double getMinimum() const { return minimum; }
  38795. /** Returns the current step-size for values.
  38796. @see setRange
  38797. */
  38798. double getInterval() const { return interval; }
  38799. /** For a slider with two or three thumbs, this returns the lower of its values.
  38800. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  38801. A slider with three values also uses the normal getValue() and setValue() methods to
  38802. control the middle value.
  38803. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  38804. */
  38805. double getMinValue() const;
  38806. /** For a slider with two or three thumbs, this returns the lower of its values.
  38807. You can use this Value object to connect the slider's position to external values or setters,
  38808. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  38809. your own Value object.
  38810. @see Value, getMinValue, getMaxValueObject
  38811. */
  38812. Value& getMinValueObject() throw() { return valueMin; }
  38813. /** For a slider with two or three thumbs, this sets the lower of its values.
  38814. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  38815. that are registered, and will synchronously call the valueChanged() method in case subclasses
  38816. want to handle it.
  38817. @param newValue the new value to set - this will be restricted by the
  38818. minimum and maximum range, and will be snapped to the nearest
  38819. interval if one has been set.
  38820. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  38821. any Slider::Listeners or the valueChanged() method
  38822. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  38823. synchronously; if false, it will be asynchronous
  38824. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  38825. max value (in a two-value slider) or the mid value (in a three-value
  38826. slider). If false, then if this value goes beyond those values,
  38827. it will push them along with it.
  38828. @see getMinValue, setMaxValue, setValue
  38829. */
  38830. void setMinValue (double newValue,
  38831. bool sendUpdateMessage = true,
  38832. bool sendMessageSynchronously = false,
  38833. bool allowNudgingOfOtherValues = false);
  38834. /** For a slider with two or three thumbs, this returns the higher of its values.
  38835. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  38836. A slider with three values also uses the normal getValue() and setValue() methods to
  38837. control the middle value.
  38838. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  38839. */
  38840. double getMaxValue() const;
  38841. /** For a slider with two or three thumbs, this returns the higher of its values.
  38842. You can use this Value object to connect the slider's position to external values or setters,
  38843. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  38844. your own Value object.
  38845. @see Value, getMaxValue, getMinValueObject
  38846. */
  38847. Value& getMaxValueObject() throw() { return valueMax; }
  38848. /** For a slider with two or three thumbs, this sets the lower of its values.
  38849. This will trigger a callback to Slider::Listener::sliderValueChanged() for any listeners
  38850. that are registered, and will synchronously call the valueChanged() method in case subclasses
  38851. want to handle it.
  38852. @param newValue the new value to set - this will be restricted by the
  38853. minimum and maximum range, and will be snapped to the nearest
  38854. interval if one has been set.
  38855. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  38856. any Slider::Listeners or the valueChanged() method
  38857. @param sendMessageSynchronously if true, then a call to the Slider::Listeners will be made
  38858. synchronously; if false, it will be asynchronous
  38859. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  38860. min value (in a two-value slider) or the mid value (in a three-value
  38861. slider). If false, then if this value goes beyond those values,
  38862. it will push them along with it.
  38863. @see getMaxValue, setMinValue, setValue
  38864. */
  38865. void setMaxValue (double newValue,
  38866. bool sendUpdateMessage = true,
  38867. bool sendMessageSynchronously = false,
  38868. bool allowNudgingOfOtherValues = false);
  38869. /** A class for receiving callbacks from a Slider.
  38870. To be told when a slider's value changes, you can register a Slider::Listener
  38871. object using Slider::addListener().
  38872. @see Slider::addListener, Slider::removeListener
  38873. */
  38874. class JUCE_API Listener
  38875. {
  38876. public:
  38877. /** Destructor. */
  38878. virtual ~Listener() {}
  38879. /** Called when the slider's value is changed.
  38880. This may be caused by dragging it, or by typing in its text entry box,
  38881. or by a call to Slider::setValue().
  38882. You can find out the new value using Slider::getValue().
  38883. @see Slider::valueChanged
  38884. */
  38885. virtual void sliderValueChanged (Slider* slider) = 0;
  38886. /** Called when the slider is about to be dragged.
  38887. This is called when a drag begins, then it's followed by multiple calls
  38888. to sliderValueChanged(), and then sliderDragEnded() is called after the
  38889. user lets go.
  38890. @see sliderDragEnded, Slider::startedDragging
  38891. */
  38892. virtual void sliderDragStarted (Slider* slider);
  38893. /** Called after a drag operation has finished.
  38894. @see sliderDragStarted, Slider::stoppedDragging
  38895. */
  38896. virtual void sliderDragEnded (Slider* slider);
  38897. };
  38898. /** Adds a listener to be called when this slider's value changes. */
  38899. void addListener (Listener* listener);
  38900. /** Removes a previously-registered listener. */
  38901. void removeListener (Listener* listener);
  38902. /** This lets you choose whether double-clicking moves the slider to a given position.
  38903. By default this is turned off, but it's handy if you want a double-click to act
  38904. as a quick way of resetting a slider. Just pass in the value you want it to
  38905. go to when double-clicked.
  38906. @see getDoubleClickReturnValue
  38907. */
  38908. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  38909. double valueToSetOnDoubleClick);
  38910. /** Returns the values last set by setDoubleClickReturnValue() method.
  38911. Sets isEnabled to true if double-click is enabled, and returns the value
  38912. that was set.
  38913. @see setDoubleClickReturnValue
  38914. */
  38915. double getDoubleClickReturnValue (bool& isEnabled) const;
  38916. /** Tells the slider whether to keep sending change messages while the user
  38917. is dragging the slider.
  38918. If set to true, a change message will only be sent when the user has
  38919. dragged the slider and let go. If set to false (the default), then messages
  38920. will be continuously sent as they drag it while the mouse button is still
  38921. held down.
  38922. */
  38923. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  38924. /** This lets you change whether the slider thumb jumps to the mouse position
  38925. when you click.
  38926. By default, this is true. If it's false, then the slider moves with relative
  38927. motion when you drag it.
  38928. This only applies to linear bars, and won't affect two- or three- value
  38929. sliders.
  38930. */
  38931. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  38932. /** If enabled, this gives the slider a pop-up bubble which appears while the
  38933. slider is being dragged.
  38934. This can be handy if your slider doesn't have a text-box, so that users can
  38935. see the value just when they're changing it.
  38936. If you pass a component as the parentComponentToUse parameter, the pop-up
  38937. bubble will be added as a child of that component when it's needed. If you
  38938. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  38939. transparent window, so if you're using an OS that can't do transparent windows
  38940. you'll have to add it to a parent component instead).
  38941. */
  38942. void setPopupDisplayEnabled (bool isEnabled,
  38943. Component* parentComponentToUse);
  38944. /** If this is set to true, then right-clicking on the slider will pop-up
  38945. a menu to let the user change the way it works.
  38946. By default this is turned off, but when turned on, the menu will include
  38947. things like velocity sensitivity, and for rotary sliders, whether they
  38948. use a linear or rotary mouse-drag to move them.
  38949. */
  38950. void setPopupMenuEnabled (bool menuEnabled);
  38951. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  38952. By default it's enabled.
  38953. */
  38954. void setScrollWheelEnabled (bool enabled);
  38955. /** Returns a number to indicate which thumb is currently being dragged by the
  38956. mouse.
  38957. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  38958. the maximum-value thumb, or -1 if none is currently down.
  38959. */
  38960. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  38961. /** Callback to indicate that the user is about to start dragging the slider.
  38962. @see Slider::Listener::sliderDragStarted
  38963. */
  38964. virtual void startedDragging();
  38965. /** Callback to indicate that the user has just stopped dragging the slider.
  38966. @see Slider::Listener::sliderDragEnded
  38967. */
  38968. virtual void stoppedDragging();
  38969. /** Callback to indicate that the user has just moved the slider.
  38970. @see Slider::Listener::sliderValueChanged
  38971. */
  38972. virtual void valueChanged();
  38973. /** Subclasses can override this to convert a text string to a value.
  38974. When the user enters something into the text-entry box, this method is
  38975. called to convert it to a value.
  38976. The default routine just tries to convert it to a double.
  38977. @see getTextFromValue
  38978. */
  38979. virtual double getValueFromText (const String& text);
  38980. /** Turns the slider's current value into a text string.
  38981. Subclasses can override this to customise the formatting of the text-entry box.
  38982. The default implementation just turns the value into a string, using
  38983. a number of decimal places based on the range interval. If a suffix string
  38984. has been set using setTextValueSuffix(), this will be appended to the text.
  38985. @see getValueFromText
  38986. */
  38987. virtual const String getTextFromValue (double value);
  38988. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  38989. a string.
  38990. This is used by the default implementation of getTextFromValue(), and is just
  38991. appended to the numeric value. For more advanced formatting, you can override
  38992. getTextFromValue() and do something else.
  38993. */
  38994. void setTextValueSuffix (const String& suffix);
  38995. /** Returns the suffix that was set by setTextValueSuffix(). */
  38996. const String getTextValueSuffix() const;
  38997. /** Allows a user-defined mapping of distance along the slider to its value.
  38998. The default implementation for this performs the skewing operation that
  38999. can be set up in the setSkewFactor() method. Override it if you need
  39000. some kind of custom mapping instead, but make sure you also implement the
  39001. inverse function in valueToProportionOfLength().
  39002. @param proportion a value 0 to 1.0, indicating a distance along the slider
  39003. @returns the slider value that is represented by this position
  39004. @see valueToProportionOfLength
  39005. */
  39006. virtual double proportionOfLengthToValue (double proportion);
  39007. /** Allows a user-defined mapping of value to the position of the slider along its length.
  39008. The default implementation for this performs the skewing operation that
  39009. can be set up in the setSkewFactor() method. Override it if you need
  39010. some kind of custom mapping instead, but make sure you also implement the
  39011. inverse function in proportionOfLengthToValue().
  39012. @param value a valid slider value, between the range of values specified in
  39013. setRange()
  39014. @returns a value 0 to 1.0 indicating the distance along the slider that
  39015. represents this value
  39016. @see proportionOfLengthToValue
  39017. */
  39018. virtual double valueToProportionOfLength (double value);
  39019. /** Returns the X or Y coordinate of a value along the slider's length.
  39020. If the slider is horizontal, this will be the X coordinate of the given
  39021. value, relative to the left of the slider. If it's vertical, then this will
  39022. be the Y coordinate, relative to the top of the slider.
  39023. If the slider is rotary, this will throw an assertion and return 0. If the
  39024. value is out-of-range, it will be constrained to the length of the slider.
  39025. */
  39026. float getPositionOfValue (double value);
  39027. /** This can be overridden to allow the slider to snap to user-definable values.
  39028. If overridden, it will be called when the user tries to move the slider to
  39029. a given position, and allows a subclass to sanity-check this value, possibly
  39030. returning a different value to use instead.
  39031. @param attemptedValue the value the user is trying to enter
  39032. @param userIsDragging true if the user is dragging with the mouse; false if
  39033. they are entering the value using the text box
  39034. @returns the value to use instead
  39035. */
  39036. virtual double snapValue (double attemptedValue, bool userIsDragging);
  39037. /** This can be called to force the text box to update its contents.
  39038. (Not normally needed, as this is done automatically).
  39039. */
  39040. void updateText();
  39041. /** True if the slider moves horizontally. */
  39042. bool isHorizontal() const;
  39043. /** True if the slider moves vertically. */
  39044. bool isVertical() const;
  39045. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  39046. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39047. methods.
  39048. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39049. */
  39050. enum ColourIds
  39051. {
  39052. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  39053. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  39054. and feel class how this is used. */
  39055. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  39056. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  39057. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  39058. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  39059. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  39060. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  39061. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  39062. };
  39063. protected:
  39064. /** @internal */
  39065. void labelTextChanged (Label*);
  39066. /** @internal */
  39067. void paint (Graphics& g);
  39068. /** @internal */
  39069. void resized();
  39070. /** @internal */
  39071. void mouseDown (const MouseEvent& e);
  39072. /** @internal */
  39073. void mouseUp (const MouseEvent& e);
  39074. /** @internal */
  39075. void mouseDrag (const MouseEvent& e);
  39076. /** @internal */
  39077. void mouseDoubleClick (const MouseEvent& e);
  39078. /** @internal */
  39079. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39080. /** @internal */
  39081. void modifierKeysChanged (const ModifierKeys& modifiers);
  39082. /** @internal */
  39083. void buttonClicked (Button* button);
  39084. /** @internal */
  39085. void lookAndFeelChanged();
  39086. /** @internal */
  39087. void enablementChanged();
  39088. /** @internal */
  39089. void focusOfChildComponentChanged (FocusChangeType cause);
  39090. /** @internal */
  39091. void handleAsyncUpdate();
  39092. /** @internal */
  39093. void colourChanged();
  39094. /** @internal */
  39095. void valueChanged (Value& value);
  39096. /** Returns the best number of decimal places to use when displaying numbers.
  39097. This is calculated from the slider's interval setting.
  39098. */
  39099. int getNumDecimalPlacesToDisplay() const throw() { return numDecimalPlaces; }
  39100. private:
  39101. ListenerList <Listener> listeners;
  39102. Value currentValue, valueMin, valueMax;
  39103. double lastCurrentValue, lastValueMin, lastValueMax;
  39104. double minimum, maximum, interval, doubleClickReturnValue;
  39105. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  39106. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  39107. int velocityModeThreshold;
  39108. float rotaryStart, rotaryEnd;
  39109. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  39110. int mouseDragStartX, mouseDragStartY;
  39111. int sliderRegionStart, sliderRegionSize;
  39112. int sliderBeingDragged;
  39113. int pixelsForFullDragExtent;
  39114. Rectangle<int> sliderRect;
  39115. String textSuffix;
  39116. SliderStyle style;
  39117. TextEntryBoxPosition textBoxPos;
  39118. int textBoxWidth, textBoxHeight;
  39119. IncDecButtonMode incDecButtonMode;
  39120. bool editableText : 1, doubleClickToValue : 1;
  39121. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  39122. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  39123. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  39124. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  39125. ScopedPointer<Label> valueBox;
  39126. ScopedPointer<Button> incButton, decButton;
  39127. ScopedPointer <Component> popupDisplay;
  39128. Component* parentForPopupDisplay;
  39129. float getLinearSliderPos (double value);
  39130. void restoreMouseIfHidden();
  39131. void sendDragStart();
  39132. void sendDragEnd();
  39133. double constrainedValue (double value) const;
  39134. void triggerChangeMessage (bool synchronous);
  39135. bool incDecDragDirectionIsHorizontal() const;
  39136. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Slider);
  39137. };
  39138. /** This typedef is just for compatibility with old code - newer code should use the Slider::Listener class directly. */
  39139. typedef Slider::Listener SliderListener;
  39140. #if JUCE_VC6
  39141. #undef Listener
  39142. #endif
  39143. #endif // __JUCE_SLIDER_JUCEHEADER__
  39144. /*** End of inlined file: juce_Slider.h ***/
  39145. #endif
  39146. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  39147. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  39148. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  39149. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  39150. /**
  39151. A component that displays a strip of column headings for a table, and allows these
  39152. to be resized, dragged around, etc.
  39153. This is just the component that goes at the top of a table. You can use it
  39154. directly for custom components, or to create a simple table, use the
  39155. TableListBox class.
  39156. To use one of these, create it and use addColumn() to add all the columns that you need.
  39157. Each column must be given a unique ID number that's used to refer to it.
  39158. @see TableListBox, TableHeaderComponent::Listener
  39159. */
  39160. class JUCE_API TableHeaderComponent : public Component,
  39161. private AsyncUpdater
  39162. {
  39163. public:
  39164. /** Creates an empty table header.
  39165. */
  39166. TableHeaderComponent();
  39167. /** Destructor. */
  39168. ~TableHeaderComponent();
  39169. /** A combination of these flags are passed into the addColumn() method to specify
  39170. the properties of a column.
  39171. */
  39172. enum ColumnPropertyFlags
  39173. {
  39174. 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. */
  39175. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  39176. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  39177. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  39178. 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. */
  39179. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  39180. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  39181. /** This set of default flags is used as the default parameter value in addColumn(). */
  39182. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  39183. /** A quick way of combining flags for a column that's not resizable. */
  39184. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  39185. /** A quick way of combining flags for a column that's not resizable or sortable. */
  39186. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  39187. /** A quick way of combining flags for a column that's not sortable. */
  39188. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  39189. };
  39190. /** Adds a column to the table.
  39191. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  39192. registered listeners.
  39193. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  39194. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  39195. a unique ID. This is used to identify the column later on, after the user may have
  39196. changed the order that they appear in
  39197. @param width the initial width of the column, in pixels
  39198. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  39199. if the 'resizable' flag is specified for this column
  39200. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  39201. if the 'resizable' flag is specified for this column
  39202. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  39203. properties of this column
  39204. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  39205. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  39206. all columns, not just the index amongst those that are currently visible
  39207. */
  39208. void addColumn (const String& columnName,
  39209. int columnId,
  39210. int width,
  39211. int minimumWidth = 30,
  39212. int maximumWidth = -1,
  39213. int propertyFlags = defaultFlags,
  39214. int insertIndex = -1);
  39215. /** Removes a column with the given ID.
  39216. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  39217. registered listeners.
  39218. */
  39219. void removeColumn (int columnIdToRemove);
  39220. /** Deletes all columns from the table.
  39221. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  39222. registered listeners.
  39223. */
  39224. void removeAllColumns();
  39225. /** Returns the number of columns in the table.
  39226. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  39227. return the total number of columns, including hidden ones.
  39228. @see isColumnVisible
  39229. */
  39230. int getNumColumns (bool onlyCountVisibleColumns) const;
  39231. /** Returns the name for a column.
  39232. @see setColumnName
  39233. */
  39234. const String getColumnName (int columnId) const;
  39235. /** Changes the name of a column. */
  39236. void setColumnName (int columnId, const String& newName);
  39237. /** Moves a column to a different index in the table.
  39238. @param columnId the column to move
  39239. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  39240. */
  39241. void moveColumn (int columnId, int newVisibleIndex);
  39242. /** Returns the width of one of the columns.
  39243. */
  39244. int getColumnWidth (int columnId) const;
  39245. /** Changes the width of a column.
  39246. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  39247. */
  39248. void setColumnWidth (int columnId, int newWidth);
  39249. /** Shows or hides a column.
  39250. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  39251. @see isColumnVisible
  39252. */
  39253. void setColumnVisible (int columnId, bool shouldBeVisible);
  39254. /** Returns true if this column is currently visible.
  39255. @see setColumnVisible
  39256. */
  39257. bool isColumnVisible (int columnId) const;
  39258. /** Changes the column which is the sort column.
  39259. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  39260. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  39261. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  39262. @see getSortColumnId, isSortedForwards, reSortTable
  39263. */
  39264. void setSortColumnId (int columnId, bool sortForwards);
  39265. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  39266. @see setSortColumnId, isSortedForwards
  39267. */
  39268. int getSortColumnId() const;
  39269. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  39270. @see setSortColumnId
  39271. */
  39272. bool isSortedForwards() const;
  39273. /** Triggers a re-sort of the table according to the current sort-column.
  39274. If you modifiy the table's contents, you can call this to signal that the table needs
  39275. to be re-sorted.
  39276. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  39277. tableSortOrderChanged() method of any listeners).
  39278. */
  39279. void reSortTable();
  39280. /** Returns the total width of all the visible columns in the table.
  39281. */
  39282. int getTotalWidth() const;
  39283. /** Returns the index of a given column.
  39284. If there's no such column ID, this will return -1.
  39285. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  39286. otherwise it'll return the index amongst all the columns, including any hidden ones.
  39287. */
  39288. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  39289. /** Returns the ID of the column at a given index.
  39290. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  39291. otherwise it'll count it amongst all the columns, including any hidden ones.
  39292. If the index is out-of-range, it'll return 0.
  39293. */
  39294. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  39295. /** Returns the rectangle containing of one of the columns.
  39296. The index is an index from 0 to the number of columns that are currently visible (hidden
  39297. ones are not counted). It returns a rectangle showing the position of the column relative
  39298. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  39299. */
  39300. const Rectangle<int> getColumnPosition (int index) const;
  39301. /** Finds the column ID at a given x-position in the component.
  39302. If there is a column at this point this returns its ID, or if not, it will return 0.
  39303. */
  39304. int getColumnIdAtX (int xToFind) const;
  39305. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  39306. entire width of the component.
  39307. By default this is disabled. Turning it on also means that when resizing a column, those
  39308. on the right will be squashed to fit.
  39309. */
  39310. void setStretchToFitActive (bool shouldStretchToFit);
  39311. /** Returns true if stretch-to-fit has been enabled.
  39312. @see setStretchToFitActive
  39313. */
  39314. bool isStretchToFitActive() const;
  39315. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  39316. specified width, keeping their relative proportions the same.
  39317. If the minimum widths of the columns are too wide to fit into this space, it may
  39318. actually end up wider.
  39319. */
  39320. void resizeAllColumnsToFit (int targetTotalWidth);
  39321. /** Enables or disables the pop-up menu.
  39322. The default menu allows the user to show or hide columns. You can add custom
  39323. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  39324. By default the menu is enabled.
  39325. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  39326. */
  39327. void setPopupMenuActive (bool hasMenu);
  39328. /** Returns true if the pop-up menu is enabled.
  39329. @see setPopupMenuActive
  39330. */
  39331. bool isPopupMenuActive() const;
  39332. /** Returns a string that encapsulates the table's current layout.
  39333. This can be restored later using restoreFromString(). It saves the order of
  39334. the columns, the currently-sorted column, and the widths.
  39335. @see restoreFromString
  39336. */
  39337. const String toString() const;
  39338. /** Restores the state of the table, based on a string previously created with
  39339. toString().
  39340. @see toString
  39341. */
  39342. void restoreFromString (const String& storedVersion);
  39343. /**
  39344. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  39345. You can register one of these objects for table events using TableHeaderComponent::addListener()
  39346. and TableHeaderComponent::removeListener().
  39347. @see TableHeaderComponent
  39348. */
  39349. class JUCE_API Listener
  39350. {
  39351. public:
  39352. Listener() {}
  39353. /** Destructor. */
  39354. virtual ~Listener() {}
  39355. /** This is called when some of the table's columns are added, removed, hidden,
  39356. or rearranged.
  39357. */
  39358. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  39359. /** This is called when one or more of the table's columns are resized.
  39360. */
  39361. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  39362. /** This is called when the column by which the table should be sorted is changed.
  39363. */
  39364. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  39365. /** This is called when the user begins or ends dragging one of the columns around.
  39366. When the user starts dragging a column, this is called with the ID of that
  39367. column. When they finish dragging, it is called again with 0 as the ID.
  39368. */
  39369. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  39370. int columnIdNowBeingDragged);
  39371. };
  39372. /** Adds a listener to be informed about things that happen to the header. */
  39373. void addListener (Listener* newListener);
  39374. /** Removes a previously-registered listener. */
  39375. void removeListener (Listener* listenerToRemove);
  39376. /** This can be overridden to handle a mouse-click on one of the column headers.
  39377. The default implementation will use this click to call getSortColumnId() and
  39378. change the sort order.
  39379. */
  39380. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  39381. /** This can be overridden to add custom items to the pop-up menu.
  39382. If you override this, you should call the superclass's method to add its
  39383. column show/hide items, if you want them on the menu as well.
  39384. Then to handle the result, override reactToMenuItem().
  39385. @see reactToMenuItem
  39386. */
  39387. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  39388. /** Override this to handle any custom items that you have added to the
  39389. pop-up menu with an addMenuItems() override.
  39390. If the menuReturnId isn't one of your own custom menu items, you'll need to
  39391. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  39392. handle the items that it had added.
  39393. @see addMenuItems
  39394. */
  39395. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  39396. /** @internal */
  39397. void paint (Graphics& g);
  39398. /** @internal */
  39399. void resized();
  39400. /** @internal */
  39401. void mouseMove (const MouseEvent&);
  39402. /** @internal */
  39403. void mouseEnter (const MouseEvent&);
  39404. /** @internal */
  39405. void mouseExit (const MouseEvent&);
  39406. /** @internal */
  39407. void mouseDown (const MouseEvent&);
  39408. /** @internal */
  39409. void mouseDrag (const MouseEvent&);
  39410. /** @internal */
  39411. void mouseUp (const MouseEvent&);
  39412. /** @internal */
  39413. const MouseCursor getMouseCursor();
  39414. /** Can be overridden for more control over the pop-up menu behaviour. */
  39415. virtual void showColumnChooserMenu (int columnIdClicked);
  39416. private:
  39417. struct ColumnInfo
  39418. {
  39419. String name;
  39420. int id, propertyFlags, width, minimumWidth, maximumWidth;
  39421. double lastDeliberateWidth;
  39422. bool isVisible() const;
  39423. };
  39424. OwnedArray <ColumnInfo> columns;
  39425. Array <Listener*> listeners;
  39426. ScopedPointer <Component> dragOverlayComp;
  39427. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  39428. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  39429. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  39430. ColumnInfo* getInfoForId (int columnId) const;
  39431. int visibleIndexToTotalIndex (int visibleIndex) const;
  39432. void sendColumnsChanged();
  39433. void handleAsyncUpdate();
  39434. void beginDrag (const MouseEvent&);
  39435. void endDrag (int finalIndex);
  39436. int getResizeDraggerAt (int mouseX) const;
  39437. void updateColumnUnderMouse (int x, int y);
  39438. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  39439. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableHeaderComponent);
  39440. };
  39441. /** This typedef is just for compatibility with old code - newer code should use the TableHeaderComponent::Listener class directly. */
  39442. typedef TableHeaderComponent::Listener TableHeaderListener;
  39443. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  39444. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  39445. #endif
  39446. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  39447. /*** Start of inlined file: juce_TableListBox.h ***/
  39448. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  39449. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  39450. /**
  39451. One of these is used by a TableListBox as the data model for the table's contents.
  39452. The virtual methods that you override in this class take care of drawing the
  39453. table cells, and reacting to events.
  39454. @see TableListBox
  39455. */
  39456. class JUCE_API TableListBoxModel
  39457. {
  39458. public:
  39459. TableListBoxModel() {}
  39460. /** Destructor. */
  39461. virtual ~TableListBoxModel() {}
  39462. /** This must return the number of rows currently in the table.
  39463. If the number of rows changes, you must call TableListBox::updateContent() to
  39464. cause it to refresh the list.
  39465. */
  39466. virtual int getNumRows() = 0;
  39467. /** This must draw the background behind one of the rows in the table.
  39468. The graphics context has its origin at the row's top-left, and your method
  39469. should fill the area specified by the width and height parameters.
  39470. */
  39471. virtual void paintRowBackground (Graphics& g,
  39472. int rowNumber,
  39473. int width, int height,
  39474. bool rowIsSelected) = 0;
  39475. /** This must draw one of the cells.
  39476. The graphics context's origin will already be set to the top-left of the cell,
  39477. whose size is specified by (width, height).
  39478. */
  39479. virtual void paintCell (Graphics& g,
  39480. int rowNumber,
  39481. int columnId,
  39482. int width, int height,
  39483. bool rowIsSelected) = 0;
  39484. /** This is used to create or update a custom component to go in a cell.
  39485. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  39486. and handle mouse clicks with cellClicked().
  39487. This method will be called whenever a custom component might need to be updated - e.g.
  39488. when the table is changed, or TableListBox::updateContent() is called.
  39489. If you don't need a custom component for the specified cell, then return 0.
  39490. If you do want a custom component, and the existingComponentToUpdate is null, then
  39491. this method must create a new component suitable for the cell, and return it.
  39492. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  39493. by this method. In this case, the method must either update it to make sure it's correctly representing
  39494. the given cell (which may be different from the one that the component was created for), or it can
  39495. delete this component and return a new one.
  39496. */
  39497. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  39498. Component* existingComponentToUpdate);
  39499. /** This callback is made when the user clicks on one of the cells in the table.
  39500. The mouse event's coordinates will be relative to the entire table row.
  39501. @see cellDoubleClicked, backgroundClicked
  39502. */
  39503. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  39504. /** This callback is made when the user clicks on one of the cells in the table.
  39505. The mouse event's coordinates will be relative to the entire table row.
  39506. @see cellClicked, backgroundClicked
  39507. */
  39508. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  39509. /** This can be overridden to react to the user double-clicking on a part of the list where
  39510. there are no rows.
  39511. @see cellClicked
  39512. */
  39513. virtual void backgroundClicked();
  39514. /** This callback is made when the table's sort order is changed.
  39515. This could be because the user has clicked a column header, or because the
  39516. TableHeaderComponent::setSortColumnId() method was called.
  39517. If you implement this, your method should re-sort the table using the given
  39518. column as the key.
  39519. */
  39520. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  39521. /** Returns the best width for one of the columns.
  39522. If you implement this method, you should measure the width of all the items
  39523. in this column, and return the best size.
  39524. Returning 0 means that the column shouldn't be changed.
  39525. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  39526. */
  39527. virtual int getColumnAutoSizeWidth (int columnId);
  39528. /** Returns a tooltip for a particular cell in the table.
  39529. */
  39530. virtual const String getCellTooltip (int rowNumber, int columnId);
  39531. /** Override this to be informed when rows are selected or deselected.
  39532. @see ListBox::selectedRowsChanged()
  39533. */
  39534. virtual void selectedRowsChanged (int lastRowSelected);
  39535. /** Override this to be informed when the delete key is pressed.
  39536. @see ListBox::deleteKeyPressed()
  39537. */
  39538. virtual void deleteKeyPressed (int lastRowSelected);
  39539. /** Override this to be informed when the return key is pressed.
  39540. @see ListBox::returnKeyPressed()
  39541. */
  39542. virtual void returnKeyPressed (int lastRowSelected);
  39543. /** Override this to be informed when the list is scrolled.
  39544. This might be caused by the user moving the scrollbar, or by programmatic changes
  39545. to the list position.
  39546. */
  39547. virtual void listWasScrolled();
  39548. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  39549. If this returns a non-empty name then when the user drags a row, the table will try to
  39550. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  39551. drag-and-drop operation, using this string as the source description, and the listbox
  39552. itself as the source component.
  39553. @see DragAndDropContainer::startDragging
  39554. */
  39555. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  39556. };
  39557. /**
  39558. A table of cells, using a TableHeaderComponent as its header.
  39559. This component makes it easy to create a table by providing a TableListBoxModel as
  39560. the data source.
  39561. @see TableListBoxModel, TableHeaderComponent
  39562. */
  39563. class JUCE_API TableListBox : public ListBox,
  39564. private ListBoxModel,
  39565. private TableHeaderComponent::Listener
  39566. {
  39567. public:
  39568. /** Creates a TableListBox.
  39569. The model pointer passed-in can be null, in which case you can set it later
  39570. with setModel().
  39571. */
  39572. TableListBox (const String& componentName = String::empty,
  39573. TableListBoxModel* model = 0);
  39574. /** Destructor. */
  39575. ~TableListBox();
  39576. /** Changes the TableListBoxModel that is being used for this table.
  39577. */
  39578. void setModel (TableListBoxModel* newModel);
  39579. /** Returns the model currently in use. */
  39580. TableListBoxModel* getModel() const { return model; }
  39581. /** Returns the header component being used in this table. */
  39582. TableHeaderComponent& getHeader() const { return *header; }
  39583. /** Sets the header component to use for the table.
  39584. The table will take ownership of the component that you pass in, and will delete it
  39585. when it's no longer needed.
  39586. */
  39587. void setHeader (TableHeaderComponent* newHeader);
  39588. /** Changes the height of the table header component.
  39589. @see getHeaderHeight
  39590. */
  39591. void setHeaderHeight (int newHeight);
  39592. /** Returns the height of the table header.
  39593. @see setHeaderHeight
  39594. */
  39595. int getHeaderHeight() const;
  39596. /** Resizes a column to fit its contents.
  39597. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  39598. and applies that to the column.
  39599. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  39600. */
  39601. void autoSizeColumn (int columnId);
  39602. /** Calls autoSizeColumn() for all columns in the table. */
  39603. void autoSizeAllColumns();
  39604. /** Enables or disables the auto size options on the popup menu.
  39605. By default, these are enabled.
  39606. */
  39607. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  39608. /** True if the auto-size options should be shown on the menu.
  39609. @see setAutoSizeMenuOptionsShown
  39610. */
  39611. bool isAutoSizeMenuOptionShown() const;
  39612. /** Returns the position of one of the cells in the table.
  39613. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  39614. the table component's top-left. The row number isn't checked to see if it's
  39615. in-range, but the column ID must exist or this will return an empty rectangle.
  39616. If relativeToComponentTopLeft is false, the co-ords are relative to the
  39617. top-left of the table's top-left cell.
  39618. */
  39619. const Rectangle<int> getCellPosition (int columnId, int rowNumber,
  39620. bool relativeToComponentTopLeft) const;
  39621. /** Returns the component that currently represents a given cell.
  39622. If the component for this cell is off-screen or if the position is out-of-range,
  39623. this may return 0.
  39624. @see getCellPosition
  39625. */
  39626. Component* getCellComponent (int columnId, int rowNumber) const;
  39627. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  39628. @see ListBox::scrollToEnsureRowIsOnscreen
  39629. */
  39630. void scrollToEnsureColumnIsOnscreen (int columnId);
  39631. /** @internal */
  39632. int getNumRows();
  39633. /** @internal */
  39634. void paintListBoxItem (int, Graphics&, int, int, bool);
  39635. /** @internal */
  39636. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  39637. /** @internal */
  39638. void selectedRowsChanged (int lastRowSelected);
  39639. /** @internal */
  39640. void deleteKeyPressed (int currentSelectedRow);
  39641. /** @internal */
  39642. void returnKeyPressed (int currentSelectedRow);
  39643. /** @internal */
  39644. void backgroundClicked();
  39645. /** @internal */
  39646. void listWasScrolled();
  39647. /** @internal */
  39648. void tableColumnsChanged (TableHeaderComponent*);
  39649. /** @internal */
  39650. void tableColumnsResized (TableHeaderComponent*);
  39651. /** @internal */
  39652. void tableSortOrderChanged (TableHeaderComponent*);
  39653. /** @internal */
  39654. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  39655. /** @internal */
  39656. void resized();
  39657. private:
  39658. TableHeaderComponent* header;
  39659. TableListBoxModel* model;
  39660. int columnIdNowBeingDragged;
  39661. bool autoSizeOptionsShown;
  39662. void updateColumnComponents() const;
  39663. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBox);
  39664. };
  39665. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  39666. /*** End of inlined file: juce_TableListBox.h ***/
  39667. #endif
  39668. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  39669. #endif
  39670. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  39671. #endif
  39672. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  39673. #endif
  39674. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  39675. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  39676. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  39677. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  39678. /**
  39679. A factory object which can create ToolbarItemComponent objects.
  39680. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  39681. that it can create.
  39682. Each type of item is identified by a unique ID, and multiple instances of an
  39683. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  39684. bars).
  39685. @see Toolbar, ToolbarItemComponent, ToolbarButton
  39686. */
  39687. class JUCE_API ToolbarItemFactory
  39688. {
  39689. public:
  39690. ToolbarItemFactory();
  39691. /** Destructor. */
  39692. virtual ~ToolbarItemFactory();
  39693. /** A set of reserved item ID values, used for the built-in item types.
  39694. */
  39695. enum SpecialItemIds
  39696. {
  39697. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  39698. can be placed between sets of items to break them into groups. */
  39699. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  39700. items.*/
  39701. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  39702. either side of it, filling any available space. */
  39703. };
  39704. /** Must return a list of the IDs for all the item types that this factory can create.
  39705. The ids should be added to the array that is passed-in.
  39706. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  39707. and the predefined IDs in the SpecialItemIds enum.
  39708. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  39709. to this list if you want your toolbar to be able to contain those items.
  39710. The list returned here is used by the ToolbarItemPalette class to obtain its list
  39711. of available items, and their order on the palette will reflect the order in which
  39712. they appear on this list.
  39713. @see ToolbarItemPalette
  39714. */
  39715. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  39716. /** Must return the set of items that should be added to a toolbar as its default set.
  39717. This method is used by Toolbar::addDefaultItems() to determine which items to
  39718. create.
  39719. The items that your method adds to the array that is passed-in will be added to the
  39720. toolbar in the same order. Items can appear in the list more than once.
  39721. */
  39722. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  39723. /** Must create an instance of one of the items that the factory lists in its
  39724. getAllToolbarItemIds() method.
  39725. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  39726. method, except for the built-in item types from the SpecialItemIds enum, which
  39727. are created internally by the toolbar code.
  39728. Try not to keep a pointer to the object that is returned, as it will be deleted
  39729. automatically by the toolbar, and remember that multiple instances of the same
  39730. item type are likely to exist at the same time.
  39731. */
  39732. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  39733. };
  39734. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  39735. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  39736. #endif
  39737. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  39738. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  39739. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  39740. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  39741. /**
  39742. A component containing a list of toolbar items, which the user can drag onto
  39743. a toolbar to add them.
  39744. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  39745. which automatically shows one of these in a dialog box with lots of extra controls.
  39746. @see Toolbar
  39747. */
  39748. class JUCE_API ToolbarItemPalette : public Component,
  39749. public DragAndDropContainer
  39750. {
  39751. public:
  39752. /** Creates a palette of items for a given factory, with the aim of adding them
  39753. to the specified toolbar.
  39754. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  39755. set of items that are shown in this palette.
  39756. The toolbar and factory must not be deleted while this object exists.
  39757. */
  39758. ToolbarItemPalette (ToolbarItemFactory& factory,
  39759. Toolbar* toolbar);
  39760. /** Destructor. */
  39761. ~ToolbarItemPalette();
  39762. /** @internal */
  39763. void resized();
  39764. private:
  39765. ToolbarItemFactory& factory;
  39766. Toolbar* toolbar;
  39767. Viewport viewport;
  39768. OwnedArray <ToolbarItemComponent> items;
  39769. friend class Toolbar;
  39770. void replaceComponent (ToolbarItemComponent* comp);
  39771. void addComponent (int itemId, int index);
  39772. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarItemPalette);
  39773. };
  39774. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  39775. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  39776. #endif
  39777. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  39778. /*** Start of inlined file: juce_TreeView.h ***/
  39779. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  39780. #define __JUCE_TREEVIEW_JUCEHEADER__
  39781. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  39782. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  39783. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  39784. /**
  39785. Components derived from this class can have files dropped onto them by an external application.
  39786. @see DragAndDropContainer
  39787. */
  39788. class JUCE_API FileDragAndDropTarget
  39789. {
  39790. public:
  39791. /** Destructor. */
  39792. virtual ~FileDragAndDropTarget() {}
  39793. /** Callback to check whether this target is interested in the set of files being offered.
  39794. Note that this will be called repeatedly when the user is dragging the mouse around over your
  39795. component, so don't do anything time-consuming in here, like opening the files to have a look
  39796. inside them!
  39797. @param files the set of (absolute) pathnames of the files that the user is dragging
  39798. @returns true if this component wants to receive the other callbacks regarging this
  39799. type of object; if it returns false, no other callbacks will be made.
  39800. */
  39801. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  39802. /** Callback to indicate that some files are being dragged over this component.
  39803. This gets called when the user moves the mouse into this component while dragging.
  39804. Use this callback as a trigger to make your component repaint itself to give the
  39805. user feedback about whether the files can be dropped here or not.
  39806. @param files the set of (absolute) pathnames of the files that the user is dragging
  39807. @param x the mouse x position, relative to this component
  39808. @param y the mouse y position, relative to this component
  39809. */
  39810. virtual void fileDragEnter (const StringArray& files, int x, int y);
  39811. /** Callback to indicate that the user is dragging some files over this component.
  39812. This gets called when the user moves the mouse over this component while dragging.
  39813. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  39814. this lets you know what happens in-between.
  39815. @param files the set of (absolute) pathnames of the files that the user is dragging
  39816. @param x the mouse x position, relative to this component
  39817. @param y the mouse y position, relative to this component
  39818. */
  39819. virtual void fileDragMove (const StringArray& files, int x, int y);
  39820. /** Callback to indicate that the mouse has moved away from this component.
  39821. This gets called when the user moves the mouse out of this component while dragging
  39822. the files.
  39823. If you've used fileDragEnter() to repaint your component and give feedback, use this
  39824. as a signal to repaint it in its normal state.
  39825. @param files the set of (absolute) pathnames of the files that the user is dragging
  39826. */
  39827. virtual void fileDragExit (const StringArray& files);
  39828. /** Callback to indicate that the user has dropped the files onto this component.
  39829. When the user drops the files, this get called, and you can use the files in whatever
  39830. way is appropriate.
  39831. Note that after this is called, the fileDragExit method may not be called, so you should
  39832. clean up in here if there's anything you need to do when the drag finishes.
  39833. @param files the set of (absolute) pathnames of the files that the user is dragging
  39834. @param x the mouse x position, relative to this component
  39835. @param y the mouse y position, relative to this component
  39836. */
  39837. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  39838. };
  39839. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  39840. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  39841. class TreeView;
  39842. /**
  39843. An item in a treeview.
  39844. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  39845. own sub-items.
  39846. To implement an item that contains sub-items, override the itemOpennessChanged()
  39847. method so that when it is opened, it adds the new sub-items to itself using the
  39848. addSubItem method. Depending on the nature of the item it might choose to only
  39849. do this the first time it's opened, or it might want to refresh itself each time.
  39850. It also has the option of deleting its sub-items when it is closed, or leaving them
  39851. in place.
  39852. */
  39853. class JUCE_API TreeViewItem
  39854. {
  39855. public:
  39856. /** Constructor. */
  39857. TreeViewItem();
  39858. /** Destructor. */
  39859. virtual ~TreeViewItem();
  39860. /** Returns the number of sub-items that have been added to this item.
  39861. Note that this doesn't mean much if the node isn't open.
  39862. @see getSubItem, mightContainSubItems, addSubItem
  39863. */
  39864. int getNumSubItems() const throw();
  39865. /** Returns one of the item's sub-items.
  39866. Remember that the object returned might get deleted at any time when its parent
  39867. item is closed or refreshed, depending on the nature of the items you're using.
  39868. @see getNumSubItems
  39869. */
  39870. TreeViewItem* getSubItem (int index) const throw();
  39871. /** Removes any sub-items. */
  39872. void clearSubItems();
  39873. /** Adds a sub-item.
  39874. @param newItem the object to add to the item's sub-item list. Once added, these can be
  39875. found using getSubItem(). When the items are later removed with
  39876. removeSubItem() (or when this item is deleted), they will be deleted.
  39877. @param insertPosition the index which the new item should have when it's added. If this
  39878. value is less than 0, the item will be added to the end of the list.
  39879. */
  39880. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  39881. /** Removes one of the sub-items.
  39882. @param index the item to remove
  39883. @param deleteItem if true, the item that is removed will also be deleted.
  39884. */
  39885. void removeSubItem (int index, bool deleteItem = true);
  39886. /** Returns the TreeView to which this item belongs. */
  39887. TreeView* getOwnerView() const throw() { return ownerView; }
  39888. /** Returns the item within which this item is contained. */
  39889. TreeViewItem* getParentItem() const throw() { return parentItem; }
  39890. /** True if this item is currently open in the treeview. */
  39891. bool isOpen() const throw();
  39892. /** Opens or closes the item.
  39893. When opened or closed, the item's itemOpennessChanged() method will be called,
  39894. and a subclass should use this callback to create and add any sub-items that
  39895. it needs to.
  39896. @see itemOpennessChanged, mightContainSubItems
  39897. */
  39898. void setOpen (bool shouldBeOpen);
  39899. /** True if this item is currently selected.
  39900. Use this when painting the node, to decide whether to draw it as selected or not.
  39901. */
  39902. bool isSelected() const throw();
  39903. /** Selects or deselects the item.
  39904. This will cause a callback to itemSelectionChanged()
  39905. */
  39906. void setSelected (bool shouldBeSelected,
  39907. bool deselectOtherItemsFirst);
  39908. /** Returns the rectangle that this item occupies.
  39909. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  39910. top-left of the TreeView comp, so this will depend on the scroll-position of
  39911. the tree. If false, it is relative to the top-left of the topmost item in the
  39912. tree (so this would be unaffected by scrolling the view).
  39913. */
  39914. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const throw();
  39915. /** Sends a signal to the treeview to make it refresh itself.
  39916. Call this if your items have changed and you want the tree to update to reflect
  39917. this.
  39918. */
  39919. void treeHasChanged() const throw();
  39920. /** Sends a repaint message to redraw just this item.
  39921. Note that you should only call this if you want to repaint a superficial change. If
  39922. you're altering the tree's nodes, you should instead call treeHasChanged().
  39923. */
  39924. void repaintItem() const;
  39925. /** Returns the row number of this item in the tree.
  39926. The row number of an item will change according to which items are open.
  39927. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  39928. */
  39929. int getRowNumberInTree() const throw();
  39930. /** Returns true if all the item's parent nodes are open.
  39931. This is useful to check whether the item might actually be visible or not.
  39932. */
  39933. bool areAllParentsOpen() const throw();
  39934. /** Changes whether lines are drawn to connect any sub-items to this item.
  39935. By default, line-drawing is turned on.
  39936. */
  39937. void setLinesDrawnForSubItems (bool shouldDrawLines) throw();
  39938. /** Tells the tree whether this item can potentially be opened.
  39939. If your item could contain sub-items, this should return true; if it returns
  39940. false then the tree will not try to open the item. This determines whether or
  39941. not the item will be drawn with a 'plus' button next to it.
  39942. */
  39943. virtual bool mightContainSubItems() = 0;
  39944. /** Returns a string to uniquely identify this item.
  39945. If you're planning on using the TreeView::getOpennessState() method, then
  39946. these strings will be used to identify which nodes are open. The string
  39947. should be unique amongst the item's sibling items, but it's ok for there
  39948. to be duplicates at other levels of the tree.
  39949. If you're not going to store the state, then it's ok not to bother implementing
  39950. this method.
  39951. */
  39952. virtual const String getUniqueName() const;
  39953. /** Called when an item is opened or closed.
  39954. When setOpen() is called and the item has specified that it might
  39955. have sub-items with the mightContainSubItems() method, this method
  39956. is called to let the item create or manage its sub-items.
  39957. So when this is called with isNowOpen set to true (i.e. when the item is being
  39958. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  39959. refresh its sub-item list.
  39960. When this is called with isNowOpen set to false, the subclass might want
  39961. to use clearSubItems() to save on space, or it might choose to leave them,
  39962. depending on the nature of the tree.
  39963. You could also use this callback as a trigger to start a background process
  39964. which asynchronously creates sub-items and adds them, if that's more
  39965. appropriate for the task in hand.
  39966. @see mightContainSubItems
  39967. */
  39968. virtual void itemOpennessChanged (bool isNowOpen);
  39969. /** Must return the width required by this item.
  39970. If your item needs to have a particular width in pixels, return that value; if
  39971. you'd rather have it just fill whatever space is available in the treeview,
  39972. return -1.
  39973. If all your items return -1, no horizontal scrollbar will be shown, but if any
  39974. items have fixed widths and extend beyond the width of the treeview, a
  39975. scrollbar will appear.
  39976. Each item can be a different width, but if they change width, you should call
  39977. treeHasChanged() to update the tree.
  39978. */
  39979. virtual int getItemWidth() const { return -1; }
  39980. /** Must return the height required by this item.
  39981. This is the height in pixels that the item will take up. Items in the tree
  39982. can be different heights, but if they change height, you should call
  39983. treeHasChanged() to update the tree.
  39984. */
  39985. virtual int getItemHeight() const { return 20; }
  39986. /** You can override this method to return false if you don't want to allow the
  39987. user to select this item.
  39988. */
  39989. virtual bool canBeSelected() const { return true; }
  39990. /** Creates a component that will be used to represent this item.
  39991. You don't have to implement this method - if it returns 0 then no component
  39992. will be used for the item, and you can just draw it using the paintItem()
  39993. callback. But if you do return a component, it will be positioned in the
  39994. treeview so that it can be used to represent this item.
  39995. The component returned will be managed by the treeview, so always return
  39996. a new component, and don't keep a reference to it, as the treeview will
  39997. delete it later when it goes off the screen or is no longer needed. Also
  39998. bear in mind that if the component keeps a reference to the item that
  39999. created it, that item could be deleted before the component. Its position
  40000. and size will be completely managed by the tree, so don't attempt to move it
  40001. around.
  40002. Something you may want to do with your component is to give it a pointer to
  40003. the TreeView that created it. This is perfectly safe, and there's no danger
  40004. of it becoming a dangling pointer because the TreeView will always delete
  40005. the component before it is itself deleted.
  40006. As long as you stick to these rules you can return whatever kind of
  40007. component you like. It's most useful if you're doing things like drag-and-drop
  40008. of items, or want to use a Label component to edit item names, etc.
  40009. */
  40010. virtual Component* createItemComponent() { return 0; }
  40011. /** Draws the item's contents.
  40012. You can choose to either implement this method and draw each item, or you
  40013. can use createItemComponent() to create a component that will represent the
  40014. item.
  40015. If all you need in your tree is to be able to draw the items and detect when
  40016. the user selects or double-clicks one of them, it's probably enough to
  40017. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  40018. complicated interactions, you may need to use createItemComponent() instead.
  40019. @param g the graphics context to draw into
  40020. @param width the width of the area available for drawing
  40021. @param height the height of the area available for drawing
  40022. */
  40023. virtual void paintItem (Graphics& g, int width, int height);
  40024. /** Draws the item's open/close button.
  40025. If you don't implement this method, the default behaviour is to
  40026. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  40027. it for custom effects.
  40028. */
  40029. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  40030. /** Called when the user clicks on this item.
  40031. If you're using createItemComponent() to create a custom component for the
  40032. item, the mouse-clicks might not make it through to the treeview, but this
  40033. is how you find out about clicks when just drawing each item individually.
  40034. The associated mouse-event details are passed in, so you can find out about
  40035. which button, where it was, etc.
  40036. @see itemDoubleClicked
  40037. */
  40038. virtual void itemClicked (const MouseEvent& e);
  40039. /** Called when the user double-clicks on this item.
  40040. If you're using createItemComponent() to create a custom component for the
  40041. item, the mouse-clicks might not make it through to the treeview, but this
  40042. is how you find out about clicks when just drawing each item individually.
  40043. The associated mouse-event details are passed in, so you can find out about
  40044. which button, where it was, etc.
  40045. If not overridden, the base class method here will open or close the item as
  40046. if the 'plus' button had been clicked.
  40047. @see itemClicked
  40048. */
  40049. virtual void itemDoubleClicked (const MouseEvent& e);
  40050. /** Called when the item is selected or deselected.
  40051. Use this if you want to do something special when the item's selectedness
  40052. changes. By default it'll get repainted when this happens.
  40053. */
  40054. virtual void itemSelectionChanged (bool isNowSelected);
  40055. /** The item can return a tool tip string here if it wants to.
  40056. @see TooltipClient
  40057. */
  40058. virtual const String getTooltip();
  40059. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  40060. If this returns a non-empty name then when the user drags an item, the treeview will
  40061. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  40062. a drag-and-drop operation, using this string as the source description, with the treeview
  40063. itself as the source component.
  40064. If you need more complex drag-and-drop behaviour, you can use custom components for
  40065. the items, and use those to trigger the drag.
  40066. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  40067. isInterestedInFileDrag(), etc.
  40068. @see DragAndDropContainer::startDragging
  40069. */
  40070. virtual const String getDragSourceDescription();
  40071. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  40072. method and return true.
  40073. If you return true and allow some files to be dropped, you'll also need to implement the
  40074. filesDropped() method to do something with them.
  40075. Note that this will be called often, so make your implementation very quick! There's
  40076. certainly no time to try opening the files and having a think about what's inside them!
  40077. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  40078. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  40079. */
  40080. virtual bool isInterestedInFileDrag (const StringArray& files);
  40081. /** When files are dropped into this item, this callback is invoked.
  40082. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  40083. The insertIndex value indicates where in the list of sub-items the files were dropped.
  40084. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  40085. */
  40086. virtual void filesDropped (const StringArray& files, int insertIndex);
  40087. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  40088. If you implement this method, you'll also need to implement itemDropped() in order to handle
  40089. the items when they are dropped.
  40090. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  40091. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  40092. */
  40093. virtual bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  40094. /** When a things are dropped into this item, this callback is invoked.
  40095. For this to work, you need to have also implemented isInterestedInDragSource().
  40096. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  40097. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  40098. */
  40099. virtual void itemDropped (const String& sourceDescription, Component* sourceComponent, int insertIndex);
  40100. /** Sets a flag to indicate that the item wants to be allowed
  40101. to draw all the way across to the left edge of the treeview.
  40102. By default this is false, which means that when the paintItem()
  40103. method is called, its graphics context is clipped to only allow
  40104. drawing within the item's rectangle. If this flag is set to true,
  40105. then the graphics context isn't clipped on its left side, so it
  40106. can draw all the way across to the left margin. Note that the
  40107. context will still have its origin in the same place though, so
  40108. the coordinates of anything to its left will be negative. It's
  40109. mostly useful if you want to draw a wider bar behind the
  40110. highlighted item.
  40111. */
  40112. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  40113. /** Saves the current state of open/closed nodes so it can be restored later.
  40114. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  40115. and records it as XML. To identify node objects it uses the
  40116. TreeViewItem::getUniqueName() method to create named paths. This
  40117. means that the same state of open/closed nodes can be restored to a
  40118. completely different instance of the tree, as long as it contains nodes
  40119. whose unique names are the same.
  40120. You'd normally want to use TreeView::getOpennessState() rather than call it
  40121. for a specific item, but this can be handy if you need to briefly save the state
  40122. for a section of the tree.
  40123. The caller is responsible for deleting the object that is returned.
  40124. @see TreeView::getOpennessState, restoreOpennessState
  40125. */
  40126. XmlElement* getOpennessState() const throw();
  40127. /** Restores the openness of this item and all its sub-items from a saved state.
  40128. See TreeView::restoreOpennessState for more details.
  40129. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  40130. for a specific item, but this can be handy if you need to briefly save the state
  40131. for a section of the tree.
  40132. @see TreeView::restoreOpennessState, getOpennessState
  40133. */
  40134. void restoreOpennessState (const XmlElement& xml) throw();
  40135. /** Returns the index of this item in its parent's sub-items. */
  40136. int getIndexInParent() const throw();
  40137. /** Returns true if this item is the last of its parent's sub-itens. */
  40138. bool isLastOfSiblings() const throw();
  40139. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  40140. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  40141. The string takes the form of a path, constructed from the getUniqueName() of this
  40142. item and all its parents, so these must all be correctly implemented for it to work.
  40143. @see TreeView::findItemFromIdentifierString, getUniqueName
  40144. */
  40145. const String getItemIdentifierString() const;
  40146. /**
  40147. This handy class takes a copy of a TreeViewItem's openness when you create it,
  40148. and restores that openness state when its destructor is called.
  40149. This can very handy when you're refreshing sub-items - e.g.
  40150. @code
  40151. void MyTreeViewItem::updateChildItems()
  40152. {
  40153. OpennessRestorer openness (*this); // saves the openness state here..
  40154. clearSubItems();
  40155. // add a bunch of sub-items here which may or may not be the same as the ones that
  40156. // were previously there
  40157. addSubItem (...
  40158. // ..and at this point, the old openness is restored, so any items that haven't
  40159. // changed will have their old openness retained.
  40160. }
  40161. @endcode
  40162. */
  40163. class OpennessRestorer
  40164. {
  40165. public:
  40166. OpennessRestorer (TreeViewItem& treeViewItem);
  40167. ~OpennessRestorer();
  40168. private:
  40169. TreeViewItem& treeViewItem;
  40170. ScopedPointer <XmlElement> oldOpenness;
  40171. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpennessRestorer);
  40172. };
  40173. private:
  40174. TreeView* ownerView;
  40175. TreeViewItem* parentItem;
  40176. OwnedArray <TreeViewItem> subItems;
  40177. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  40178. int uid;
  40179. bool selected : 1;
  40180. bool redrawNeeded : 1;
  40181. bool drawLinesInside : 1;
  40182. bool drawsInLeftMargin : 1;
  40183. unsigned int openness : 2;
  40184. friend class TreeView;
  40185. friend class TreeViewContentComponent;
  40186. void updatePositions (int newY);
  40187. int getIndentX() const throw();
  40188. void setOwnerView (TreeView* newOwner) throw();
  40189. void paintRecursively (Graphics& g, int width);
  40190. TreeViewItem* getTopLevelItem() throw();
  40191. TreeViewItem* findItemRecursively (int y) throw();
  40192. TreeViewItem* getDeepestOpenParentItem() throw();
  40193. int getNumRows() const throw();
  40194. TreeViewItem* getItemOnRow (int index) throw();
  40195. void deselectAllRecursively();
  40196. int countSelectedItemsRecursively (int depth) const throw();
  40197. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  40198. TreeViewItem* getNextVisibleItem (bool recurse) const throw();
  40199. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  40200. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewItem);
  40201. };
  40202. /**
  40203. A tree-view component.
  40204. Use one of these to hold and display a structure of TreeViewItem objects.
  40205. */
  40206. class JUCE_API TreeView : public Component,
  40207. public SettableTooltipClient,
  40208. public FileDragAndDropTarget,
  40209. public DragAndDropTarget,
  40210. private AsyncUpdater
  40211. {
  40212. public:
  40213. /** Creates an empty treeview.
  40214. Once you've got a treeview component, you'll need to give it something to
  40215. display, using the setRootItem() method.
  40216. */
  40217. TreeView (const String& componentName = String::empty);
  40218. /** Destructor. */
  40219. ~TreeView();
  40220. /** Sets the item that is displayed in the treeview.
  40221. A tree has a single root item which contains as many sub-items as it needs. If
  40222. you want the tree to contain a number of root items, you should still use a single
  40223. root item above these, but hide it using setRootItemVisible().
  40224. You can pass in 0 to this method to clear the tree and remove its current root item.
  40225. The object passed in will not be deleted by the treeview, it's up to the caller
  40226. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  40227. this item until you've removed it from the tree, either by calling setRootItem (0),
  40228. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  40229. to delete it.
  40230. */
  40231. void setRootItem (TreeViewItem* newRootItem);
  40232. /** Returns the tree's root item.
  40233. This will be the last object passed to setRootItem(), or 0 if none has been set.
  40234. */
  40235. TreeViewItem* getRootItem() const throw() { return rootItem; }
  40236. /** This will remove and delete the current root item.
  40237. It's a convenient way of deleting the item and calling setRootItem (0).
  40238. */
  40239. void deleteRootItem();
  40240. /** Changes whether the tree's root item is shown or not.
  40241. If the root item is hidden, only its sub-items will be shown in the treeview - this
  40242. lets you make the tree look as if it's got many root items. If it's hidden, this call
  40243. will also make sure the root item is open (otherwise the treeview would look empty).
  40244. */
  40245. void setRootItemVisible (bool shouldBeVisible);
  40246. /** Returns true if the root item is visible.
  40247. @see setRootItemVisible
  40248. */
  40249. bool isRootItemVisible() const throw() { return rootItemVisible; }
  40250. /** Sets whether items are open or closed by default.
  40251. Normally, items are closed until the user opens them, but you can use this
  40252. to make them default to being open until explicitly closed.
  40253. @see areItemsOpenByDefault
  40254. */
  40255. void setDefaultOpenness (bool isOpenByDefault);
  40256. /** Returns true if the tree's items default to being open.
  40257. @see setDefaultOpenness
  40258. */
  40259. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  40260. /** This sets a flag to indicate that the tree can be used for multi-selection.
  40261. You can always select multiple items internally by calling the
  40262. TreeViewItem::setSelected() method, but this flag indicates whether the user
  40263. is allowed to multi-select by clicking on the tree.
  40264. By default it is disabled.
  40265. @see isMultiSelectEnabled
  40266. */
  40267. void setMultiSelectEnabled (bool canMultiSelect);
  40268. /** Returns whether multi-select has been enabled for the tree.
  40269. @see setMultiSelectEnabled
  40270. */
  40271. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  40272. /** Sets a flag to indicate whether to hide the open/close buttons.
  40273. @see areOpenCloseButtonsVisible
  40274. */
  40275. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  40276. /** Returns whether open/close buttons are shown.
  40277. @see setOpenCloseButtonsVisible
  40278. */
  40279. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  40280. /** Deselects any items that are currently selected. */
  40281. void clearSelectedItems();
  40282. /** Returns the number of items that are currently selected.
  40283. If maximumDepthToSearchTo is >= 0, it lets you specify a maximum depth to which the
  40284. tree will be recursed.
  40285. @see getSelectedItem, clearSelectedItems
  40286. */
  40287. int getNumSelectedItems (int maximumDepthToSearchTo = -1) const throw();
  40288. /** Returns one of the selected items in the tree.
  40289. @param index the index, 0 to (getNumSelectedItems() - 1)
  40290. */
  40291. TreeViewItem* getSelectedItem (int index) const throw();
  40292. /** Returns the number of rows the tree is using.
  40293. This will depend on which items are open.
  40294. @see TreeViewItem::getRowNumberInTree()
  40295. */
  40296. int getNumRowsInTree() const;
  40297. /** Returns the item on a particular row of the tree.
  40298. If the index is out of range, this will return 0.
  40299. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  40300. */
  40301. TreeViewItem* getItemOnRow (int index) const;
  40302. /** Returns the item that contains a given y position.
  40303. The y is relative to the top of the TreeView component.
  40304. */
  40305. TreeViewItem* getItemAt (int yPosition) const throw();
  40306. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  40307. void scrollToKeepItemVisible (TreeViewItem* item);
  40308. /** Returns the treeview's Viewport object. */
  40309. Viewport* getViewport() const throw();
  40310. /** Returns the number of pixels by which each nested level of the tree is indented.
  40311. @see setIndentSize
  40312. */
  40313. int getIndentSize() const throw() { return indentSize; }
  40314. /** Changes the distance by which each nested level of the tree is indented.
  40315. @see getIndentSize
  40316. */
  40317. void setIndentSize (int newIndentSize);
  40318. /** Searches the tree for an item with the specified identifier.
  40319. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  40320. If no such item exists, this will return false. If the item is found, all of its items
  40321. will be automatically opened.
  40322. */
  40323. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  40324. /** Saves the current state of open/closed nodes so it can be restored later.
  40325. This takes a snapshot of which nodes have been explicitly opened or closed,
  40326. and records it as XML. To identify node objects it uses the
  40327. TreeViewItem::getUniqueName() method to create named paths. This
  40328. means that the same state of open/closed nodes can be restored to a
  40329. completely different instance of the tree, as long as it contains nodes
  40330. whose unique names are the same.
  40331. The caller is responsible for deleting the object that is returned.
  40332. @param alsoIncludeScrollPosition if this is true, the state will also
  40333. include information about where the
  40334. tree has been scrolled to vertically,
  40335. so this can also be restored
  40336. @see restoreOpennessState
  40337. */
  40338. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  40339. /** Restores a previously saved arrangement of open/closed nodes.
  40340. This will try to restore a snapshot of the tree's state that was created by
  40341. the getOpennessState() method. If any of the nodes named in the original
  40342. XML aren't present in this tree, they will be ignored.
  40343. @see getOpennessState
  40344. */
  40345. void restoreOpennessState (const XmlElement& newState);
  40346. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  40347. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40348. methods.
  40349. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40350. */
  40351. enum ColourIds
  40352. {
  40353. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  40354. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  40355. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  40356. };
  40357. /** @internal */
  40358. void paint (Graphics& g);
  40359. /** @internal */
  40360. void resized();
  40361. /** @internal */
  40362. bool keyPressed (const KeyPress& key);
  40363. /** @internal */
  40364. void colourChanged();
  40365. /** @internal */
  40366. void enablementChanged();
  40367. /** @internal */
  40368. bool isInterestedInFileDrag (const StringArray& files);
  40369. /** @internal */
  40370. void fileDragEnter (const StringArray& files, int x, int y);
  40371. /** @internal */
  40372. void fileDragMove (const StringArray& files, int x, int y);
  40373. /** @internal */
  40374. void fileDragExit (const StringArray& files);
  40375. /** @internal */
  40376. void filesDropped (const StringArray& files, int x, int y);
  40377. /** @internal */
  40378. bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  40379. /** @internal */
  40380. void itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y);
  40381. /** @internal */
  40382. void itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y);
  40383. /** @internal */
  40384. void itemDragExit (const String& sourceDescription, Component* sourceComponent);
  40385. /** @internal */
  40386. void itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y);
  40387. private:
  40388. friend class TreeViewItem;
  40389. friend class TreeViewContentComponent;
  40390. class TreeViewport;
  40391. class InsertPointHighlight;
  40392. class TargetGroupHighlight;
  40393. friend class ScopedPointer<TreeViewport>;
  40394. friend class ScopedPointer<InsertPointHighlight>;
  40395. friend class ScopedPointer<TargetGroupHighlight>;
  40396. ScopedPointer<TreeViewport> viewport;
  40397. CriticalSection nodeAlterationLock;
  40398. TreeViewItem* rootItem;
  40399. ScopedPointer<InsertPointHighlight> dragInsertPointHighlight;
  40400. ScopedPointer<TargetGroupHighlight> dragTargetGroupHighlight;
  40401. int indentSize;
  40402. bool defaultOpenness : 1;
  40403. bool needsRecalculating : 1;
  40404. bool rootItemVisible : 1;
  40405. bool multiSelectEnabled : 1;
  40406. bool openCloseButtonsVisible : 1;
  40407. void itemsChanged() throw();
  40408. void handleAsyncUpdate();
  40409. void moveSelectedRow (int delta);
  40410. void updateButtonUnderMouse (const MouseEvent& e);
  40411. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw();
  40412. void hideDragHighlight() throw();
  40413. void handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  40414. void handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  40415. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  40416. const StringArray& files, const String& sourceDescription,
  40417. Component* sourceComponent) const throw();
  40418. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeView);
  40419. };
  40420. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  40421. /*** End of inlined file: juce_TreeView.h ***/
  40422. #endif
  40423. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  40424. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  40425. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  40426. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  40427. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  40428. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  40429. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  40430. /*** Start of inlined file: juce_FileFilter.h ***/
  40431. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  40432. #define __JUCE_FILEFILTER_JUCEHEADER__
  40433. /**
  40434. Interface for deciding which files are suitable for something.
  40435. For example, this is used by DirectoryContentsList to select which files
  40436. go into the list.
  40437. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  40438. */
  40439. class JUCE_API FileFilter
  40440. {
  40441. public:
  40442. /** Creates a filter with the given description.
  40443. The description can be returned later with the getDescription() method.
  40444. */
  40445. FileFilter (const String& filterDescription);
  40446. /** Destructor. */
  40447. virtual ~FileFilter();
  40448. /** Returns the description that the filter was created with. */
  40449. const String& getDescription() const throw();
  40450. /** Should return true if this file is suitable for inclusion in whatever context
  40451. the object is being used.
  40452. */
  40453. virtual bool isFileSuitable (const File& file) const = 0;
  40454. /** Should return true if this directory is suitable for inclusion in whatever context
  40455. the object is being used.
  40456. */
  40457. virtual bool isDirectorySuitable (const File& file) const = 0;
  40458. protected:
  40459. String description;
  40460. };
  40461. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  40462. /*** End of inlined file: juce_FileFilter.h ***/
  40463. /**
  40464. A class to asynchronously scan for details about the files in a directory.
  40465. This keeps a list of files and some information about them, using a background
  40466. thread to scan for more files. As files are found, it broadcasts change messages
  40467. to tell any listeners.
  40468. @see FileListComponent, FileBrowserComponent
  40469. */
  40470. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  40471. public TimeSliceClient
  40472. {
  40473. public:
  40474. /** Creates a directory list.
  40475. To set the directory it should point to, use setDirectory(), which will
  40476. also start it scanning for files on the background thread.
  40477. When the background thread finds and adds new files to this list, the
  40478. ChangeBroadcaster class will send a change message, so you can register
  40479. listeners and update them when the list changes.
  40480. @param fileFilter an optional filter to select which files are
  40481. included in the list. If this is 0, then all files
  40482. and directories are included. Make sure that the
  40483. filter doesn't get deleted during the lifetime of this
  40484. object
  40485. @param threadToUse a thread object that this list can use
  40486. to scan for files as a background task. Make sure
  40487. that the thread you give it has been started, or you
  40488. won't get any files!
  40489. */
  40490. DirectoryContentsList (const FileFilter* fileFilter,
  40491. TimeSliceThread& threadToUse);
  40492. /** Destructor. */
  40493. ~DirectoryContentsList();
  40494. /** Sets the directory to look in for files.
  40495. If the directory that's passed in is different to the current one, this will
  40496. also start the background thread scanning it for files.
  40497. */
  40498. void setDirectory (const File& directory,
  40499. bool includeDirectories,
  40500. bool includeFiles);
  40501. /** Returns the directory that's currently being used. */
  40502. const File& getDirectory() const;
  40503. /** Clears the list, and stops the thread scanning for files. */
  40504. void clear();
  40505. /** Clears the list and restarts scanning the directory for files. */
  40506. void refresh();
  40507. /** True if the background thread hasn't yet finished scanning for files. */
  40508. bool isStillLoading() const;
  40509. /** Tells the list whether or not to ignore hidden files.
  40510. By default these are ignored.
  40511. */
  40512. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  40513. /** Returns true if hidden files are ignored.
  40514. @see setIgnoresHiddenFiles
  40515. */
  40516. bool ignoresHiddenFiles() const;
  40517. /** Contains cached information about one of the files in a DirectoryContentsList.
  40518. */
  40519. struct FileInfo
  40520. {
  40521. /** The filename.
  40522. This isn't a full pathname, it's just the last part of the path, same as you'd
  40523. get from File::getFileName().
  40524. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  40525. */
  40526. String filename;
  40527. /** File size in bytes. */
  40528. int64 fileSize;
  40529. /** File modification time.
  40530. As supplied by File::getLastModificationTime().
  40531. */
  40532. Time modificationTime;
  40533. /** File creation time.
  40534. As supplied by File::getCreationTime().
  40535. */
  40536. Time creationTime;
  40537. /** True if the file is a directory. */
  40538. bool isDirectory;
  40539. /** True if the file is read-only. */
  40540. bool isReadOnly;
  40541. };
  40542. /** Returns the number of files currently available in the list.
  40543. The info about one of these files can be retrieved with getFileInfo() or
  40544. getFile().
  40545. Obviously as the background thread runs and scans the directory for files, this
  40546. number will change.
  40547. @see getFileInfo, getFile
  40548. */
  40549. int getNumFiles() const;
  40550. /** Returns the cached information about one of the files in the list.
  40551. If the index is in-range, this will return true and will copy the file's details
  40552. to the structure that is passed-in.
  40553. If it returns false, then the index wasn't in range, and the structure won't
  40554. be affected.
  40555. @see getNumFiles, getFile
  40556. */
  40557. bool getFileInfo (int index, FileInfo& resultInfo) const;
  40558. /** Returns one of the files in the list.
  40559. @param index should be less than getNumFiles(). If this is out-of-range, the
  40560. return value will be File::nonexistent
  40561. @see getNumFiles, getFileInfo
  40562. */
  40563. const File getFile (int index) const;
  40564. /** Returns the file filter being used.
  40565. The filter is specified in the constructor.
  40566. */
  40567. const FileFilter* getFilter() const { return fileFilter; }
  40568. /** @internal */
  40569. int useTimeSlice();
  40570. /** @internal */
  40571. TimeSliceThread& getTimeSliceThread() { return thread; }
  40572. /** @internal */
  40573. static int compareElements (const DirectoryContentsList::FileInfo* first,
  40574. const DirectoryContentsList::FileInfo* second);
  40575. private:
  40576. File root;
  40577. const FileFilter* fileFilter;
  40578. TimeSliceThread& thread;
  40579. int fileTypeFlags;
  40580. CriticalSection fileListLock;
  40581. OwnedArray <FileInfo> files;
  40582. ScopedPointer <DirectoryIterator> fileFindHandle;
  40583. bool volatile shouldStop;
  40584. void changed();
  40585. bool checkNextFile (bool& hasChanged);
  40586. bool addFile (const File& file, bool isDir,
  40587. const int64 fileSize, const Time& modTime,
  40588. const Time& creationTime, bool isReadOnly);
  40589. void setTypeFlags (int newFlags);
  40590. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsList);
  40591. };
  40592. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  40593. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  40594. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  40595. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  40596. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  40597. /**
  40598. A listener for user selection events in a file browser.
  40599. This is used by a FileBrowserComponent or FileListComponent.
  40600. */
  40601. class JUCE_API FileBrowserListener
  40602. {
  40603. public:
  40604. /** Destructor. */
  40605. virtual ~FileBrowserListener();
  40606. /** Callback when the user selects a different file in the browser. */
  40607. virtual void selectionChanged() = 0;
  40608. /** Callback when the user clicks on a file in the browser. */
  40609. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  40610. /** Callback when the user double-clicks on a file in the browser. */
  40611. virtual void fileDoubleClicked (const File& file) = 0;
  40612. };
  40613. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  40614. /*** End of inlined file: juce_FileBrowserListener.h ***/
  40615. /**
  40616. A base class for components that display a list of the files in a directory.
  40617. @see DirectoryContentsList
  40618. */
  40619. class JUCE_API DirectoryContentsDisplayComponent
  40620. {
  40621. public:
  40622. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  40623. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  40624. /** Destructor. */
  40625. virtual ~DirectoryContentsDisplayComponent();
  40626. /** Returns the number of files the user has got selected.
  40627. @see getSelectedFile
  40628. */
  40629. virtual int getNumSelectedFiles() const = 0;
  40630. /** Returns one of the files that the user has currently selected.
  40631. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  40632. @see getNumSelectedFiles
  40633. */
  40634. virtual const File getSelectedFile (int index) const = 0;
  40635. /** Deselects any selected files. */
  40636. virtual void deselectAllFiles() = 0;
  40637. /** Scrolls this view to the top. */
  40638. virtual void scrollToTop() = 0;
  40639. /** Adds a listener to be told when files are selected or clicked.
  40640. @see removeListener
  40641. */
  40642. void addListener (FileBrowserListener* listener);
  40643. /** Removes a listener.
  40644. @see addListener
  40645. */
  40646. void removeListener (FileBrowserListener* listener);
  40647. /** A set of colour IDs to use to change the colour of various aspects of the list.
  40648. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40649. methods.
  40650. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40651. */
  40652. enum ColourIds
  40653. {
  40654. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  40655. textColourId = 0x1000541, /**< The colour for the text. */
  40656. };
  40657. /** @internal */
  40658. void sendSelectionChangeMessage();
  40659. /** @internal */
  40660. void sendDoubleClickMessage (const File& file);
  40661. /** @internal */
  40662. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  40663. protected:
  40664. DirectoryContentsList& fileList;
  40665. ListenerList <FileBrowserListener> listeners;
  40666. private:
  40667. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DirectoryContentsDisplayComponent);
  40668. };
  40669. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  40670. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  40671. #endif
  40672. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  40673. #endif
  40674. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  40675. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  40676. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  40677. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  40678. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  40679. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  40680. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  40681. /**
  40682. Base class for components that live inside a file chooser dialog box and
  40683. show previews of the files that get selected.
  40684. One of these allows special extra information to be displayed for files
  40685. in a dialog box as the user selects them. Each time the current file or
  40686. directory is changed, the selectedFileChanged() method will be called
  40687. to allow it to update itself appropriately.
  40688. @see FileChooser, ImagePreviewComponent
  40689. */
  40690. class JUCE_API FilePreviewComponent : public Component
  40691. {
  40692. public:
  40693. /** Creates a FilePreviewComponent. */
  40694. FilePreviewComponent();
  40695. /** Destructor. */
  40696. ~FilePreviewComponent();
  40697. /** Called to indicate that the user's currently selected file has changed.
  40698. @param newSelectedFile the newly selected file or directory, which may be
  40699. File::nonexistent if none is selected.
  40700. */
  40701. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  40702. private:
  40703. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilePreviewComponent);
  40704. };
  40705. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  40706. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  40707. /**
  40708. A component for browsing and selecting a file or directory to open or save.
  40709. This contains a FileListComponent and adds various boxes and controls for
  40710. navigating and selecting a file. It can work in different modes so that it can
  40711. be used for loading or saving a file, or for choosing a directory.
  40712. @see FileChooserDialogBox, FileChooser, FileListComponent
  40713. */
  40714. class JUCE_API FileBrowserComponent : public Component,
  40715. public ChangeBroadcaster,
  40716. private FileBrowserListener,
  40717. private TextEditorListener,
  40718. private ButtonListener,
  40719. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  40720. private FileFilter
  40721. {
  40722. public:
  40723. /** Various options for the browser.
  40724. A combination of these is passed into the FileBrowserComponent constructor.
  40725. */
  40726. enum FileChooserFlags
  40727. {
  40728. openMode = 1, /**< specifies that the component should allow the user to
  40729. choose an existing file with the intention of opening it. */
  40730. saveMode = 2, /**< specifies that the component should allow the user to specify
  40731. the name of a file that will be used to save something. */
  40732. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  40733. conjunction with canSelectDirectories). */
  40734. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  40735. conjuction with canSelectFiles). */
  40736. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  40737. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  40738. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  40739. };
  40740. /** Creates a FileBrowserComponent.
  40741. @param flags A combination of flags from the FileChooserFlags enumeration,
  40742. used to specify the component's behaviour. The flags must contain
  40743. either openMode or saveMode, and canSelectFiles and/or
  40744. canSelectDirectories.
  40745. @param initialFileOrDirectory The file or directory that should be selected when
  40746. the component begins. If this is File::nonexistent,
  40747. a default directory will be chosen.
  40748. @param fileFilter an optional filter to use to determine which files
  40749. are shown. If this is 0 then all files are displayed. Note
  40750. that a pointer is kept internally to this object, so
  40751. make sure that it is not deleted before the browser object
  40752. is deleted.
  40753. @param previewComp an optional preview component that will be used to
  40754. show previews of files that the user selects
  40755. */
  40756. FileBrowserComponent (int flags,
  40757. const File& initialFileOrDirectory,
  40758. const FileFilter* fileFilter,
  40759. FilePreviewComponent* previewComp);
  40760. /** Destructor. */
  40761. ~FileBrowserComponent();
  40762. /** Returns the number of files that the user has got selected.
  40763. If multiple select isn't active, this will only be 0 or 1. To get the complete
  40764. list of files they've chosen, pass an index to getCurrentFile().
  40765. */
  40766. int getNumSelectedFiles() const throw();
  40767. /** Returns one of the files that the user has chosen.
  40768. If the box has multi-select enabled, the index lets you specify which of the files
  40769. to get - see getNumSelectedFiles() to find out how many files were chosen.
  40770. @see getHighlightedFile
  40771. */
  40772. const File getSelectedFile (int index) const throw();
  40773. /** Deselects any files that are currently selected.
  40774. */
  40775. void deselectAllFiles();
  40776. /** Returns true if the currently selected file(s) are usable.
  40777. This can be used to decide whether the user can press "ok" for the
  40778. current file. What it does depends on the mode, so for example in an "open"
  40779. mode, this only returns true if a file has been selected and if it exists.
  40780. In a "save" mode, a non-existent file would also be valid.
  40781. */
  40782. bool currentFileIsValid() const;
  40783. /** This returns the last item in the view that the user has highlighted.
  40784. This may be different from getCurrentFile(), which returns the value
  40785. that is shown in the filename box, and if there are multiple selections,
  40786. this will only return one of them.
  40787. @see getSelectedFile
  40788. */
  40789. const File getHighlightedFile() const throw();
  40790. /** Returns the directory whose contents are currently being shown in the listbox. */
  40791. const File getRoot() const;
  40792. /** Changes the directory that's being shown in the listbox. */
  40793. void setRoot (const File& newRootDirectory);
  40794. /** Equivalent to pressing the "up" button to browse the parent directory. */
  40795. void goUp();
  40796. /** Refreshes the directory that's currently being listed. */
  40797. void refresh();
  40798. /** Changes the filter that's being used to sift the files. */
  40799. void setFileFilter (const FileFilter* newFileFilter);
  40800. /** Returns a verb to describe what should happen when the file is accepted.
  40801. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  40802. mode, it'll be "Save", etc.
  40803. */
  40804. virtual const String getActionVerb() const;
  40805. /** Returns true if the saveMode flag was set when this component was created.
  40806. */
  40807. bool isSaveMode() const throw();
  40808. /** Adds a listener to be told when the user selects and clicks on files.
  40809. @see removeListener
  40810. */
  40811. void addListener (FileBrowserListener* listener);
  40812. /** Removes a listener.
  40813. @see addListener
  40814. */
  40815. void removeListener (FileBrowserListener* listener);
  40816. /** @internal */
  40817. void resized();
  40818. /** @internal */
  40819. void buttonClicked (Button* b);
  40820. /** @internal */
  40821. void comboBoxChanged (ComboBox*);
  40822. /** @internal */
  40823. void textEditorTextChanged (TextEditor& editor);
  40824. /** @internal */
  40825. void textEditorReturnKeyPressed (TextEditor& editor);
  40826. /** @internal */
  40827. void textEditorEscapeKeyPressed (TextEditor& editor);
  40828. /** @internal */
  40829. void textEditorFocusLost (TextEditor& editor);
  40830. /** @internal */
  40831. bool keyPressed (const KeyPress& key);
  40832. /** @internal */
  40833. void selectionChanged();
  40834. /** @internal */
  40835. void fileClicked (const File& f, const MouseEvent& e);
  40836. /** @internal */
  40837. void fileDoubleClicked (const File& f);
  40838. /** @internal */
  40839. bool isFileSuitable (const File& file) const;
  40840. /** @internal */
  40841. bool isDirectorySuitable (const File&) const;
  40842. /** @internal */
  40843. FilePreviewComponent* getPreviewComponent() const throw();
  40844. protected:
  40845. /** Returns a list of names and paths for the default places the user might want to look.
  40846. Use an empty string to indicate a section break.
  40847. */
  40848. virtual void getRoots (StringArray& rootNames, StringArray& rootPaths);
  40849. private:
  40850. ScopedPointer <DirectoryContentsList> fileList;
  40851. const FileFilter* fileFilter;
  40852. int flags;
  40853. File currentRoot;
  40854. Array<File> chosenFiles;
  40855. ListenerList <FileBrowserListener> listeners;
  40856. ScopedPointer<DirectoryContentsDisplayComponent> fileListComponent;
  40857. FilePreviewComponent* previewComp;
  40858. ComboBox currentPathBox;
  40859. TextEditor filenameBox;
  40860. Label fileLabel;
  40861. ScopedPointer<Button> goUpButton;
  40862. TimeSliceThread thread;
  40863. void sendListenerChangeMessage();
  40864. bool isFileOrDirSuitable (const File& f) const;
  40865. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBrowserComponent);
  40866. };
  40867. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  40868. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  40869. #endif
  40870. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  40871. #endif
  40872. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  40873. /*** Start of inlined file: juce_FileChooser.h ***/
  40874. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  40875. #define __JUCE_FILECHOOSER_JUCEHEADER__
  40876. /**
  40877. Creates a dialog box to choose a file or directory to load or save.
  40878. To use a FileChooser:
  40879. - create one (as a local stack variable is the neatest way)
  40880. - call one of its browseFor.. methods
  40881. - if this returns true, the user has selected a file, so you can retrieve it
  40882. with the getResult() method.
  40883. e.g. @code
  40884. void loadMooseFile()
  40885. {
  40886. FileChooser myChooser ("Please select the moose you want to load...",
  40887. File::getSpecialLocation (File::userHomeDirectory),
  40888. "*.moose");
  40889. if (myChooser.browseForFileToOpen())
  40890. {
  40891. File mooseFile (myChooser.getResult());
  40892. loadMoose (mooseFile);
  40893. }
  40894. }
  40895. @endcode
  40896. */
  40897. class JUCE_API FileChooser
  40898. {
  40899. public:
  40900. /** Creates a FileChooser.
  40901. After creating one of these, use one of the browseFor... methods to display it.
  40902. @param dialogBoxTitle a text string to display in the dialog box to
  40903. tell the user what's going on
  40904. @param initialFileOrDirectory the file or directory that should be selected when
  40905. the dialog box opens. If this parameter is set to
  40906. File::nonexistent, a sensible default directory
  40907. will be used instead.
  40908. @param filePatternsAllowed a set of file patterns to specify which files can be
  40909. selected - each pattern should be separated by a
  40910. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  40911. empty string means that all files are allowed
  40912. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  40913. possible; if false, then a Juce-based browser dialog
  40914. box will always be used
  40915. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  40916. */
  40917. FileChooser (const String& dialogBoxTitle,
  40918. const File& initialFileOrDirectory = File::nonexistent,
  40919. const String& filePatternsAllowed = String::empty,
  40920. bool useOSNativeDialogBox = true);
  40921. /** Destructor. */
  40922. ~FileChooser();
  40923. /** Shows a dialog box to choose a file to open.
  40924. This will display the dialog box modally, using an "open file" mode, so that
  40925. it won't allow non-existent files or directories to be chosen.
  40926. @param previewComponent an optional component to display inside the dialog
  40927. box to show special info about the files that the user
  40928. is browsing. The component will not be deleted by this
  40929. object, so the caller must take care of it.
  40930. @returns true if the user selected a file, in which case, use the getResult()
  40931. method to find out what it was. Returns false if they cancelled instead.
  40932. @see browseForFileToSave, browseForDirectory
  40933. */
  40934. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  40935. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  40936. The files that are returned can be obtained by calling getResults(). See
  40937. browseForFileToOpen() for more info about the behaviour of this method.
  40938. */
  40939. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  40940. /** Shows a dialog box to choose a file to save.
  40941. This will display the dialog box modally, using an "save file" mode, so it
  40942. will allow non-existent files to be chosen, but not directories.
  40943. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  40944. the user if they're sure they want to overwrite a file that already
  40945. exists
  40946. @returns true if the user chose a file and pressed 'ok', in which case, use
  40947. the getResult() method to find out what the file was. Returns false
  40948. if they cancelled instead.
  40949. @see browseForFileToOpen, browseForDirectory
  40950. */
  40951. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  40952. /** Shows a dialog box to choose a directory.
  40953. This will display the dialog box modally, using an "open directory" mode, so it
  40954. will only allow directories to be returned, not files.
  40955. @returns true if the user chose a directory and pressed 'ok', in which case, use
  40956. the getResult() method to find out what they chose. Returns false
  40957. if they cancelled instead.
  40958. @see browseForFileToOpen, browseForFileToSave
  40959. */
  40960. bool browseForDirectory();
  40961. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  40962. The files that are returned can be obtained by calling getResults(). See
  40963. browseForFileToOpen() for more info about the behaviour of this method.
  40964. */
  40965. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  40966. /** Returns the last file that was chosen by one of the browseFor methods.
  40967. After calling the appropriate browseFor... method, this method lets you
  40968. find out what file or directory they chose.
  40969. Note that the file returned is only valid if the browse method returned true (i.e.
  40970. if the user pressed 'ok' rather than cancelling).
  40971. If you're using a multiple-file select, then use the getResults() method instead,
  40972. to obtain the list of all files chosen.
  40973. @see getResults
  40974. */
  40975. const File getResult() const;
  40976. /** Returns a list of all the files that were chosen during the last call to a
  40977. browse method.
  40978. This array may be empty if no files were chosen, or can contain multiple entries
  40979. if multiple files were chosen.
  40980. @see getResult
  40981. */
  40982. const Array<File>& getResults() const;
  40983. private:
  40984. String title, filters;
  40985. File startingFile;
  40986. Array<File> results;
  40987. bool useNativeDialogBox;
  40988. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  40989. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  40990. FilePreviewComponent* previewComponent);
  40991. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  40992. const String& filters, bool selectsDirectories, bool selectsFiles,
  40993. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  40994. FilePreviewComponent* previewComponent);
  40995. JUCE_LEAK_DETECTOR (FileChooser);
  40996. };
  40997. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  40998. /*** End of inlined file: juce_FileChooser.h ***/
  40999. #endif
  41000. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  41001. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  41002. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  41003. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  41004. /*** Start of inlined file: juce_ResizableWindow.h ***/
  41005. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  41006. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  41007. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  41008. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  41009. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  41010. /*** Start of inlined file: juce_DropShadower.h ***/
  41011. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  41012. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  41013. /**
  41014. Adds a drop-shadow to a component.
  41015. This object creates and manages a set of components which sit around a
  41016. component, creating a gaussian shadow around it. The components will track
  41017. the position of the component and if it's brought to the front they'll also
  41018. follow this.
  41019. For desktop windows you don't need to use this class directly - just
  41020. set the Component::windowHasDropShadow flag when calling
  41021. Component::addToDesktop(), and the system will create one of these if it's
  41022. needed (which it obviously isn't on the Mac, for example).
  41023. */
  41024. class JUCE_API DropShadower : public ComponentListener
  41025. {
  41026. public:
  41027. /** Creates a DropShadower.
  41028. @param alpha the opacity of the shadows, from 0 to 1.0
  41029. @param xOffset the horizontal displacement of the shadow, in pixels
  41030. @param yOffset the vertical displacement of the shadow, in pixels
  41031. @param blurRadius the radius of the blur to use for creating the shadow
  41032. */
  41033. DropShadower (float alpha = 0.5f,
  41034. int xOffset = 1,
  41035. int yOffset = 5,
  41036. float blurRadius = 10.0f);
  41037. /** Destructor. */
  41038. virtual ~DropShadower();
  41039. /** Attaches the DropShadower to the component you want to shadow. */
  41040. void setOwner (Component* componentToFollow);
  41041. /** @internal */
  41042. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  41043. /** @internal */
  41044. void componentBroughtToFront (Component& component);
  41045. /** @internal */
  41046. void componentParentHierarchyChanged (Component& component);
  41047. /** @internal */
  41048. void componentVisibilityChanged (Component& component);
  41049. private:
  41050. Component* owner;
  41051. OwnedArray<Component> shadowWindows;
  41052. Image shadowImageSections[12];
  41053. const int xOffset, yOffset;
  41054. const float alpha, blurRadius;
  41055. bool reentrant;
  41056. void updateShadows();
  41057. void setShadowImage (const Image& src, int num, int w, int h, int sx, int sy);
  41058. void bringShadowWindowsToFront();
  41059. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DropShadower);
  41060. };
  41061. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  41062. /*** End of inlined file: juce_DropShadower.h ***/
  41063. /**
  41064. A base class for top-level windows.
  41065. This class is used for components that are considered a major part of your
  41066. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  41067. etc. Things like menus that pop up briefly aren't derived from it.
  41068. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  41069. could itself be the child of another component.
  41070. The class manages a list of all instances of top-level windows that are in use,
  41071. and each one is also given the concept of being "active". The active window is
  41072. one that is actively being used by the user. This isn't quite the same as the
  41073. component with the keyboard focus, because there may be a popup menu or other
  41074. temporary window which gets keyboard focus while the active top level window is
  41075. unchanged.
  41076. A top-level window also has an optional drop-shadow.
  41077. @see ResizableWindow, DocumentWindow, DialogWindow
  41078. */
  41079. class JUCE_API TopLevelWindow : public Component
  41080. {
  41081. public:
  41082. /** Creates a TopLevelWindow.
  41083. @param name the name to give the component
  41084. @param addToDesktop if true, the window will be automatically added to the
  41085. desktop; if false, you can use it as a child component
  41086. */
  41087. TopLevelWindow (const String& name, bool addToDesktop);
  41088. /** Destructor. */
  41089. ~TopLevelWindow();
  41090. /** True if this is currently the TopLevelWindow that is actively being used.
  41091. This isn't quite the same as having keyboard focus, because the focus may be
  41092. on a child component or a temporary pop-up menu, etc, while this window is
  41093. still considered to be active.
  41094. @see activeWindowStatusChanged
  41095. */
  41096. bool isActiveWindow() const throw() { return windowIsActive_; }
  41097. /** This will set the bounds of the window so that it's centred in front of another
  41098. window.
  41099. If your app has a few windows open and want to pop up a dialog box for one of
  41100. them, you can use this to show it in front of the relevent parent window, which
  41101. is a bit neater than just having it appear in the middle of the screen.
  41102. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  41103. be used instead. If no window is focused, it'll just default to the middle of the
  41104. screen.
  41105. */
  41106. void centreAroundComponent (Component* componentToCentreAround,
  41107. int width, int height);
  41108. /** Turns the drop-shadow on and off. */
  41109. void setDropShadowEnabled (bool useShadow);
  41110. /** Sets whether an OS-native title bar will be used, or a Juce one.
  41111. @see isUsingNativeTitleBar
  41112. */
  41113. void setUsingNativeTitleBar (bool useNativeTitleBar);
  41114. /** Returns true if the window is currently using an OS-native title bar.
  41115. @see setUsingNativeTitleBar
  41116. */
  41117. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  41118. /** Returns the number of TopLevelWindow objects currently in use.
  41119. @see getTopLevelWindow
  41120. */
  41121. static int getNumTopLevelWindows() throw();
  41122. /** Returns one of the TopLevelWindow objects currently in use.
  41123. The index is 0 to (getNumTopLevelWindows() - 1).
  41124. */
  41125. static TopLevelWindow* getTopLevelWindow (int index) throw();
  41126. /** Returns the currently-active top level window.
  41127. There might not be one, of course, so this can return 0.
  41128. */
  41129. static TopLevelWindow* getActiveTopLevelWindow() throw();
  41130. /** @internal */
  41131. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  41132. protected:
  41133. /** This callback happens when this window becomes active or inactive.
  41134. @see isActiveWindow
  41135. */
  41136. virtual void activeWindowStatusChanged();
  41137. /** @internal */
  41138. void focusOfChildComponentChanged (FocusChangeType cause);
  41139. /** @internal */
  41140. void parentHierarchyChanged();
  41141. /** @internal */
  41142. virtual int getDesktopWindowStyleFlags() const;
  41143. /** @internal */
  41144. void recreateDesktopWindow();
  41145. /** @internal */
  41146. void visibilityChanged();
  41147. private:
  41148. friend class TopLevelWindowManager;
  41149. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  41150. ScopedPointer <DropShadower> shadower;
  41151. void setWindowActive (bool isNowActive);
  41152. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TopLevelWindow);
  41153. };
  41154. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  41155. /*** End of inlined file: juce_TopLevelWindow.h ***/
  41156. /*** Start of inlined file: juce_ComponentDragger.h ***/
  41157. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  41158. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  41159. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  41160. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  41161. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  41162. /**
  41163. A class that imposes restrictions on a Component's size or position.
  41164. This is used by classes such as ResizableCornerComponent,
  41165. ResizableBorderComponent and ResizableWindow.
  41166. The base class can impose some basic size and position limits, but you can
  41167. also subclass this for custom uses.
  41168. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  41169. */
  41170. class JUCE_API ComponentBoundsConstrainer
  41171. {
  41172. public:
  41173. /** When first created, the object will not impose any restrictions on the components. */
  41174. ComponentBoundsConstrainer() throw();
  41175. /** Destructor. */
  41176. virtual ~ComponentBoundsConstrainer();
  41177. /** Imposes a minimum width limit. */
  41178. void setMinimumWidth (int minimumWidth) throw();
  41179. /** Returns the current minimum width. */
  41180. int getMinimumWidth() const throw() { return minW; }
  41181. /** Imposes a maximum width limit. */
  41182. void setMaximumWidth (int maximumWidth) throw();
  41183. /** Returns the current maximum width. */
  41184. int getMaximumWidth() const throw() { return maxW; }
  41185. /** Imposes a minimum height limit. */
  41186. void setMinimumHeight (int minimumHeight) throw();
  41187. /** Returns the current minimum height. */
  41188. int getMinimumHeight() const throw() { return minH; }
  41189. /** Imposes a maximum height limit. */
  41190. void setMaximumHeight (int maximumHeight) throw();
  41191. /** Returns the current maximum height. */
  41192. int getMaximumHeight() const throw() { return maxH; }
  41193. /** Imposes a minimum width and height limit. */
  41194. void setMinimumSize (int minimumWidth,
  41195. int minimumHeight) throw();
  41196. /** Imposes a maximum width and height limit. */
  41197. void setMaximumSize (int maximumWidth,
  41198. int maximumHeight) throw();
  41199. /** Set all the maximum and minimum dimensions. */
  41200. void setSizeLimits (int minimumWidth,
  41201. int minimumHeight,
  41202. int maximumWidth,
  41203. int maximumHeight) throw();
  41204. /** Sets the amount by which the component is allowed to go off-screen.
  41205. The values indicate how many pixels must remain on-screen when dragged off
  41206. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  41207. when the component goes off the top of the screen, its y-position will be
  41208. clipped so that there are always at least 10 pixels on-screen. In other words,
  41209. the lowest y-position it can take would be (10 - the component's height).
  41210. If you pass 0 or less for one of these amounts, the component is allowed
  41211. to move beyond that edge completely, with no restrictions at all.
  41212. If you pass a very large number (i.e. larger that the dimensions of the
  41213. component itself), then the component won't be allowed to overlap that
  41214. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  41215. the component will bump into the left side of the screen and go no further.
  41216. */
  41217. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  41218. int minimumWhenOffTheLeft,
  41219. int minimumWhenOffTheBottom,
  41220. int minimumWhenOffTheRight) throw();
  41221. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  41222. int getMinimumWhenOffTheTop() const throw() { return minOffTop; }
  41223. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  41224. int getMinimumWhenOffTheLeft() const throw() { return minOffLeft; }
  41225. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  41226. int getMinimumWhenOffTheBottom() const throw() { return minOffBottom; }
  41227. /** Returns the minimum distance the bounds can be off-screen. @see setMinimumOnscreenAmounts */
  41228. int getMinimumWhenOffTheRight() const throw() { return minOffRight; }
  41229. /** Specifies a width-to-height ratio that the resizer should always maintain.
  41230. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  41231. will always be maintained as this multiple of the height.
  41232. @see setResizeLimits
  41233. */
  41234. void setFixedAspectRatio (double widthOverHeight) throw();
  41235. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  41236. If no aspect ratio is being enforced, this will return 0.
  41237. */
  41238. double getFixedAspectRatio() const throw();
  41239. /** This callback changes the given co-ordinates to impose whatever the current
  41240. constraints are set to be.
  41241. @param bounds the target position that should be examined and adjusted
  41242. @param previousBounds the component's current size
  41243. @param limits the region in which the component can be positioned
  41244. @param isStretchingTop whether the top edge of the component is being resized
  41245. @param isStretchingLeft whether the left edge of the component is being resized
  41246. @param isStretchingBottom whether the bottom edge of the component is being resized
  41247. @param isStretchingRight whether the right edge of the component is being resized
  41248. */
  41249. virtual void checkBounds (Rectangle<int>& bounds,
  41250. const Rectangle<int>& previousBounds,
  41251. const Rectangle<int>& limits,
  41252. bool isStretchingTop,
  41253. bool isStretchingLeft,
  41254. bool isStretchingBottom,
  41255. bool isStretchingRight);
  41256. /** This callback happens when the resizer is about to start dragging. */
  41257. virtual void resizeStart();
  41258. /** This callback happens when the resizer has finished dragging. */
  41259. virtual void resizeEnd();
  41260. /** Checks the given bounds, and then sets the component to the corrected size. */
  41261. void setBoundsForComponent (Component* component,
  41262. const Rectangle<int>& bounds,
  41263. bool isStretchingTop,
  41264. bool isStretchingLeft,
  41265. bool isStretchingBottom,
  41266. bool isStretchingRight);
  41267. /** Performs a check on the current size of a component, and moves or resizes
  41268. it if it fails the constraints.
  41269. */
  41270. void checkComponentBounds (Component* component);
  41271. /** Called by setBoundsForComponent() to apply a new constrained size to a
  41272. component.
  41273. By default this just calls setBounds(), but it virtual in case it's needed for
  41274. extremely cunning purposes.
  41275. */
  41276. virtual void applyBoundsToComponent (Component* component,
  41277. const Rectangle<int>& bounds);
  41278. private:
  41279. int minW, maxW, minH, maxH;
  41280. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  41281. double aspectRatio;
  41282. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentBoundsConstrainer);
  41283. };
  41284. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  41285. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  41286. /**
  41287. An object to take care of the logic for dragging components around with the mouse.
  41288. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  41289. then in your mouseDrag() callback, call dragComponent().
  41290. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  41291. to limit the component's position and keep it on-screen.
  41292. e.g. @code
  41293. class MyDraggableComp
  41294. {
  41295. ComponentDragger myDragger;
  41296. void mouseDown (const MouseEvent& e)
  41297. {
  41298. myDragger.startDraggingComponent (this, e);
  41299. }
  41300. void mouseDrag (const MouseEvent& e)
  41301. {
  41302. myDragger.dragComponent (this, e, 0);
  41303. }
  41304. };
  41305. @endcode
  41306. */
  41307. class JUCE_API ComponentDragger
  41308. {
  41309. public:
  41310. /** Creates a ComponentDragger. */
  41311. ComponentDragger();
  41312. /** Destructor. */
  41313. virtual ~ComponentDragger();
  41314. /** Call this from your component's mouseDown() method, to prepare for dragging.
  41315. @param componentToDrag the component that you want to drag
  41316. @param e the mouse event that is triggering the drag
  41317. @see dragComponent
  41318. */
  41319. void startDraggingComponent (Component* componentToDrag,
  41320. const MouseEvent& e);
  41321. /** Call this from your mouseDrag() callback to move the component.
  41322. This will move the component, but will first check the validity of the
  41323. component's new position using the checkPosition() method, which you
  41324. can override if you need to enforce special positioning limits on the
  41325. component.
  41326. @param componentToDrag the component that you want to drag
  41327. @param e the current mouse-drag event
  41328. @param constrainer an optional constrainer object that should be used
  41329. to apply limits to the component's position. Pass
  41330. null if you don't want to contrain the movement.
  41331. @see startDraggingComponent
  41332. */
  41333. void dragComponent (Component* componentToDrag,
  41334. const MouseEvent& e,
  41335. ComponentBoundsConstrainer* constrainer);
  41336. private:
  41337. Point<int> mouseDownWithinTarget;
  41338. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentDragger);
  41339. };
  41340. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  41341. /*** End of inlined file: juce_ComponentDragger.h ***/
  41342. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  41343. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  41344. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  41345. /**
  41346. A component that resizes its parent window when dragged.
  41347. This component forms a frame around the edge of a component, allowing it to
  41348. be dragged by the edges or corners to resize it - like the way windows are
  41349. resized in MSWindows or Linux.
  41350. To use it, just add it to your component, making it fill the entire parent component
  41351. (there's a mouse hit-test that only traps mouse-events which land around the
  41352. edge of the component, so it's even ok to put it on top of any other components
  41353. you're using). Make sure you rescale the resizer component to fill the parent
  41354. each time the parent's size changes.
  41355. @see ResizableCornerComponent
  41356. */
  41357. class JUCE_API ResizableBorderComponent : public Component
  41358. {
  41359. public:
  41360. /** Creates a resizer.
  41361. Pass in the target component which you want to be resized when this one is
  41362. dragged.
  41363. The target component will usually be a parent of the resizer component, but this
  41364. isn't mandatory.
  41365. Remember that when the target component is resized, it'll need to move and
  41366. resize this component to keep it in place, as this won't happen automatically.
  41367. If the constrainer parameter is non-zero, then this object will be used to enforce
  41368. limits on the size and position that the component can be stretched to. Make sure
  41369. that the constrainer isn't deleted while still in use by this object.
  41370. @see ComponentBoundsConstrainer
  41371. */
  41372. ResizableBorderComponent (Component* componentToResize,
  41373. ComponentBoundsConstrainer* constrainer);
  41374. /** Destructor. */
  41375. ~ResizableBorderComponent();
  41376. /** Specifies how many pixels wide the draggable edges of this component are.
  41377. @see getBorderThickness
  41378. */
  41379. void setBorderThickness (const BorderSize<int>& newBorderSize);
  41380. /** Returns the number of pixels wide that the draggable edges of this component are.
  41381. @see setBorderThickness
  41382. */
  41383. const BorderSize<int> getBorderThickness() const;
  41384. /** Represents the different sections of a resizable border, which allow it to
  41385. resized in different ways.
  41386. */
  41387. class Zone
  41388. {
  41389. public:
  41390. enum Zones
  41391. {
  41392. centre = 0,
  41393. left = 1,
  41394. top = 2,
  41395. right = 4,
  41396. bottom = 8
  41397. };
  41398. /** Creates a Zone from a combination of the flags in \enum Zones. */
  41399. explicit Zone (int zoneFlags = 0) throw();
  41400. Zone (const Zone& other) throw();
  41401. Zone& operator= (const Zone& other) throw();
  41402. bool operator== (const Zone& other) const throw();
  41403. bool operator!= (const Zone& other) const throw();
  41404. /** Given a point within a rectangle with a resizable border, this returns the
  41405. zone that the point lies within.
  41406. */
  41407. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  41408. const BorderSize<int>& border,
  41409. const Point<int>& position);
  41410. /** Returns an appropriate mouse-cursor for this resize zone. */
  41411. const MouseCursor getMouseCursor() const throw();
  41412. /** Returns true if dragging this zone will move the enire object without resizing it. */
  41413. bool isDraggingWholeObject() const throw() { return zone == centre; }
  41414. /** Returns true if dragging this zone will move the object's left edge. */
  41415. bool isDraggingLeftEdge() const throw() { return (zone & left) != 0; }
  41416. /** Returns true if dragging this zone will move the object's right edge. */
  41417. bool isDraggingRightEdge() const throw() { return (zone & right) != 0; }
  41418. /** Returns true if dragging this zone will move the object's top edge. */
  41419. bool isDraggingTopEdge() const throw() { return (zone & top) != 0; }
  41420. /** Returns true if dragging this zone will move the object's bottom edge. */
  41421. bool isDraggingBottomEdge() const throw() { return (zone & bottom) != 0; }
  41422. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  41423. applies to.
  41424. */
  41425. template <typename ValueType>
  41426. const Rectangle<ValueType> resizeRectangleBy (Rectangle<ValueType> original,
  41427. const Point<ValueType>& distance) const throw()
  41428. {
  41429. if (isDraggingWholeObject())
  41430. return original + distance;
  41431. if (isDraggingLeftEdge())
  41432. original.setLeft (jmin (original.getRight(), original.getX() + distance.getX()));
  41433. if (isDraggingRightEdge())
  41434. original.setWidth (jmax (ValueType(), original.getWidth() + distance.getX()));
  41435. if (isDraggingTopEdge())
  41436. original.setTop (jmin (original.getBottom(), original.getY() + distance.getY()));
  41437. if (isDraggingBottomEdge())
  41438. original.setHeight (jmax (ValueType(), original.getHeight() + distance.getY()));
  41439. return original;
  41440. }
  41441. /** Returns the raw flags for this zone. */
  41442. int getZoneFlags() const throw() { return zone; }
  41443. private:
  41444. int zone;
  41445. };
  41446. protected:
  41447. /** @internal */
  41448. void paint (Graphics& g);
  41449. /** @internal */
  41450. void mouseEnter (const MouseEvent& e);
  41451. /** @internal */
  41452. void mouseMove (const MouseEvent& e);
  41453. /** @internal */
  41454. void mouseDown (const MouseEvent& e);
  41455. /** @internal */
  41456. void mouseDrag (const MouseEvent& e);
  41457. /** @internal */
  41458. void mouseUp (const MouseEvent& e);
  41459. /** @internal */
  41460. bool hitTest (int x, int y);
  41461. private:
  41462. WeakReference<Component> component;
  41463. ComponentBoundsConstrainer* constrainer;
  41464. BorderSize<int> borderSize;
  41465. Rectangle<int> originalBounds;
  41466. Zone mouseZone;
  41467. void updateMouseZone (const MouseEvent& e);
  41468. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableBorderComponent);
  41469. };
  41470. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  41471. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  41472. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  41473. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  41474. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  41475. /** A component that resizes a parent window when dragged.
  41476. This is the small triangular stripey resizer component you get in the bottom-right
  41477. of windows (more commonly on the Mac than Windows). Put one in the corner of
  41478. a larger component and it will automatically resize its parent when it gets dragged
  41479. around.
  41480. @see ResizableFrameComponent
  41481. */
  41482. class JUCE_API ResizableCornerComponent : public Component
  41483. {
  41484. public:
  41485. /** Creates a resizer.
  41486. Pass in the target component which you want to be resized when this one is
  41487. dragged.
  41488. The target component will usually be a parent of the resizer component, but this
  41489. isn't mandatory.
  41490. Remember that when the target component is resized, it'll need to move and
  41491. resize this component to keep it in place, as this won't happen automatically.
  41492. If the constrainer parameter is non-zero, then this object will be used to enforce
  41493. limits on the size and position that the component can be stretched to. Make sure
  41494. that the constrainer isn't deleted while still in use by this object. If you
  41495. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  41496. @see ComponentBoundsConstrainer
  41497. */
  41498. ResizableCornerComponent (Component* componentToResize,
  41499. ComponentBoundsConstrainer* constrainer);
  41500. /** Destructor. */
  41501. ~ResizableCornerComponent();
  41502. protected:
  41503. /** @internal */
  41504. void paint (Graphics& g);
  41505. /** @internal */
  41506. void mouseDown (const MouseEvent& e);
  41507. /** @internal */
  41508. void mouseDrag (const MouseEvent& e);
  41509. /** @internal */
  41510. void mouseUp (const MouseEvent& e);
  41511. /** @internal */
  41512. bool hitTest (int x, int y);
  41513. private:
  41514. WeakReference<Component> component;
  41515. ComponentBoundsConstrainer* constrainer;
  41516. Rectangle<int> originalBounds;
  41517. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableCornerComponent);
  41518. };
  41519. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  41520. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  41521. /**
  41522. A base class for top-level windows that can be dragged around and resized.
  41523. To add content to the window, use its setContentComponent() method to
  41524. give it a component that will remain positioned inside it (leaving a gap around
  41525. the edges for a border).
  41526. It's not advisable to add child components directly to a ResizableWindow: put them
  41527. inside your content component instead. And overriding methods like resized(), moved(), etc
  41528. is also not recommended - instead override these methods for your content component.
  41529. (If for some obscure reason you do need to override these methods, always remember to
  41530. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  41531. decorations correctly).
  41532. By default resizing isn't enabled - use the setResizable() method to enable it and
  41533. to choose the style of resizing to use.
  41534. @see TopLevelWindow
  41535. */
  41536. class JUCE_API ResizableWindow : public TopLevelWindow
  41537. {
  41538. public:
  41539. /** Creates a ResizableWindow.
  41540. This constructor doesn't specify a background colour, so the LookAndFeel's default
  41541. background colour will be used.
  41542. @param name the name to give the component
  41543. @param addToDesktop if true, the window will be automatically added to the
  41544. desktop; if false, you can use it as a child component
  41545. */
  41546. ResizableWindow (const String& name,
  41547. bool addToDesktop);
  41548. /** Creates a ResizableWindow.
  41549. @param name the name to give the component
  41550. @param backgroundColour the colour to use for filling the window's background.
  41551. @param addToDesktop if true, the window will be automatically added to the
  41552. desktop; if false, you can use it as a child component
  41553. */
  41554. ResizableWindow (const String& name,
  41555. const Colour& backgroundColour,
  41556. bool addToDesktop);
  41557. /** Destructor.
  41558. If a content component has been set with setContentComponent(), it
  41559. will be deleted.
  41560. */
  41561. ~ResizableWindow();
  41562. /** Returns the colour currently being used for the window's background.
  41563. As a convenience the window will fill itself with this colour, but you
  41564. can override the paint() method if you need more customised behaviour.
  41565. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  41566. @see setBackgroundColour
  41567. */
  41568. const Colour getBackgroundColour() const throw();
  41569. /** Changes the colour currently being used for the window's background.
  41570. As a convenience the window will fill itself with this colour, but you
  41571. can override the paint() method if you need more customised behaviour.
  41572. Note that the opaque state of this window is altered by this call to reflect
  41573. the opacity of the colour passed-in. On window systems which can't support
  41574. semi-transparent windows this might cause problems, (though it's unlikely you'll
  41575. be using this class as a base for a semi-transparent component anyway).
  41576. You can also use the ResizableWindow::backgroundColourId colour id to set
  41577. this colour.
  41578. @see getBackgroundColour
  41579. */
  41580. void setBackgroundColour (const Colour& newColour);
  41581. /** Make the window resizable or fixed.
  41582. @param shouldBeResizable whether it's resizable at all
  41583. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  41584. bottom-right; if false, it'll use a ResizableBorderComponent
  41585. around the edge
  41586. @see setResizeLimits, isResizable
  41587. */
  41588. void setResizable (bool shouldBeResizable,
  41589. bool useBottomRightCornerResizer);
  41590. /** True if resizing is enabled.
  41591. @see setResizable
  41592. */
  41593. bool isResizable() const throw();
  41594. /** This sets the maximum and minimum sizes for the window.
  41595. If the window's current size is outside these limits, it will be resized to
  41596. make sure it's within them.
  41597. Calling setBounds() on the component will bypass any size checking - it's only when
  41598. the window is being resized by the user that these values are enforced.
  41599. @see setResizable, setFixedAspectRatio
  41600. */
  41601. void setResizeLimits (int newMinimumWidth,
  41602. int newMinimumHeight,
  41603. int newMaximumWidth,
  41604. int newMaximumHeight) throw();
  41605. /** Returns the bounds constrainer object that this window is using.
  41606. You can access this to change its properties.
  41607. */
  41608. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  41609. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  41610. A pointer to the object you pass in will be kept, but it won't be deleted
  41611. by this object, so it's the caller's responsiblity to manage it.
  41612. If you pass 0, then no contraints will be placed on the positioning of the window.
  41613. */
  41614. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  41615. /** Calls the window's setBounds method, after first checking these bounds
  41616. with the current constrainer.
  41617. @see setConstrainer
  41618. */
  41619. void setBoundsConstrained (const Rectangle<int>& bounds);
  41620. /** Returns true if the window is currently in full-screen mode.
  41621. @see setFullScreen
  41622. */
  41623. bool isFullScreen() const;
  41624. /** Puts the window into full-screen mode, or restores it to its normal size.
  41625. If true, the window will become full-screen; if false, it will return to the
  41626. last size it was before being made full-screen.
  41627. @see isFullScreen
  41628. */
  41629. void setFullScreen (bool shouldBeFullScreen);
  41630. /** Returns true if the window is currently minimised.
  41631. @see setMinimised
  41632. */
  41633. bool isMinimised() const;
  41634. /** Minimises the window, or restores it to its previous position and size.
  41635. When being un-minimised, it'll return to the last position and size it
  41636. was in before being minimised.
  41637. @see isMinimised
  41638. */
  41639. void setMinimised (bool shouldMinimise);
  41640. /** Returns a string which encodes the window's current size and position.
  41641. This string will encapsulate the window's size, position, and whether it's
  41642. in full-screen mode. It's intended for letting your application save and
  41643. restore a window's position.
  41644. Use the restoreWindowStateFromString() to restore from a saved state.
  41645. @see restoreWindowStateFromString
  41646. */
  41647. const String getWindowStateAsString();
  41648. /** Restores the window to a previously-saved size and position.
  41649. This restores the window's size, positon and full-screen status from an
  41650. string that was previously created with the getWindowStateAsString()
  41651. method.
  41652. @returns false if the string wasn't a valid window state
  41653. @see getWindowStateAsString
  41654. */
  41655. bool restoreWindowStateFromString (const String& previousState);
  41656. /** Returns the current content component.
  41657. This will be the component set by setContentComponent(), or 0 if none
  41658. has yet been specified.
  41659. @see setContentComponent
  41660. */
  41661. Component* getContentComponent() const throw() { return contentComponent; }
  41662. /** Changes the current content component.
  41663. This sets a component that will be placed in the centre of the ResizableWindow,
  41664. (leaving a space around the edge for the border).
  41665. You should never add components directly to a ResizableWindow (or any of its subclasses)
  41666. with addChildComponent(). Instead, add them to the content component.
  41667. @param newContentComponent the new component to use (or null to not use one) - this
  41668. component will be deleted either when replaced by another call
  41669. to this method, or when the ResizableWindow is deleted.
  41670. To remove a content component without deleting it, use
  41671. setContentComponent (0, false).
  41672. @param deleteOldOne if true, the previous content component will be deleted; if
  41673. false, the previous component will just be removed without
  41674. deleting it.
  41675. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  41676. it always fits around the size of the content component. If false, the
  41677. new content will be resized to fit the current space available.
  41678. */
  41679. void setContentComponent (Component* newContentComponent,
  41680. bool deleteOldOne = true,
  41681. bool resizeToFit = false);
  41682. /** Changes the window so that the content component ends up with the specified size.
  41683. This is basically a setSize call on the window, but which adds on the borders,
  41684. so you can specify the content component's target size.
  41685. */
  41686. void setContentComponentSize (int width, int height);
  41687. /** Returns the width of the frame to use around the window.
  41688. @see getContentComponentBorder
  41689. */
  41690. virtual const BorderSize<int> getBorderThickness();
  41691. /** Returns the insets to use when positioning the content component.
  41692. @see getBorderThickness
  41693. */
  41694. virtual const BorderSize<int> getContentComponentBorder();
  41695. /** A set of colour IDs to use to change the colour of various aspects of the window.
  41696. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41697. methods.
  41698. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41699. */
  41700. enum ColourIds
  41701. {
  41702. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  41703. };
  41704. protected:
  41705. /** @internal */
  41706. void paint (Graphics& g);
  41707. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  41708. void moved();
  41709. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  41710. void resized();
  41711. /** @internal */
  41712. void mouseDown (const MouseEvent& e);
  41713. /** @internal */
  41714. void mouseDrag (const MouseEvent& e);
  41715. /** @internal */
  41716. void lookAndFeelChanged();
  41717. /** @internal */
  41718. void childBoundsChanged (Component* child);
  41719. /** @internal */
  41720. void parentSizeChanged();
  41721. /** @internal */
  41722. void visibilityChanged();
  41723. /** @internal */
  41724. void activeWindowStatusChanged();
  41725. /** @internal */
  41726. int getDesktopWindowStyleFlags() const;
  41727. #if JUCE_DEBUG
  41728. /** Overridden to warn people about adding components directly to this component
  41729. instead of using setContentComponent().
  41730. If you know what you're doing and are sure you really want to add a component, specify
  41731. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  41732. */
  41733. void addChildComponent (Component* child, int zOrder = -1);
  41734. /** Overridden to warn people about adding components directly to this component
  41735. instead of using setContentComponent().
  41736. If you know what you're doing and are sure you really want to add a component, specify
  41737. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  41738. */
  41739. void addAndMakeVisible (Component* child, int zOrder = -1);
  41740. #endif
  41741. ScopedPointer <ResizableCornerComponent> resizableCorner;
  41742. ScopedPointer <ResizableBorderComponent> resizableBorder;
  41743. private:
  41744. Component::SafePointer <Component> contentComponent;
  41745. bool resizeToFitContent, fullscreen;
  41746. ComponentDragger dragger;
  41747. Rectangle<int> lastNonFullScreenPos;
  41748. ComponentBoundsConstrainer defaultConstrainer;
  41749. ComponentBoundsConstrainer* constrainer;
  41750. #if JUCE_DEBUG
  41751. bool hasBeenResized;
  41752. #endif
  41753. void updateLastPos();
  41754. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  41755. // The parameters for these methods have changed - please update your code!
  41756. JUCE_DEPRECATED (void getBorderThickness (int& left, int& top, int& right, int& bottom));
  41757. JUCE_DEPRECATED (void getContentComponentBorder (int& left, int& top, int& right, int& bottom));
  41758. #endif
  41759. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ResizableWindow);
  41760. };
  41761. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  41762. /*** End of inlined file: juce_ResizableWindow.h ***/
  41763. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  41764. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  41765. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  41766. /**
  41767. A glyph from a particular font, with a particular size, style,
  41768. typeface and position.
  41769. @see GlyphArrangement, Font
  41770. */
  41771. class JUCE_API PositionedGlyph
  41772. {
  41773. public:
  41774. PositionedGlyph (const PositionedGlyph& other);
  41775. /** Returns the character the glyph represents. */
  41776. juce_wchar getCharacter() const { return character; }
  41777. /** Checks whether the glyph is actually empty. */
  41778. bool isWhitespace() const { return CharacterFunctions::isWhitespace (character); }
  41779. /** Returns the position of the glyph's left-hand edge. */
  41780. float getLeft() const { return x; }
  41781. /** Returns the position of the glyph's right-hand edge. */
  41782. float getRight() const { return x + w; }
  41783. /** Returns the y position of the glyph's baseline. */
  41784. float getBaselineY() const { return y; }
  41785. /** Returns the y position of the top of the glyph. */
  41786. float getTop() const { return y - font.getAscent(); }
  41787. /** Returns the y position of the bottom of the glyph. */
  41788. float getBottom() const { return y + font.getDescent(); }
  41789. /** Returns the bounds of the glyph. */
  41790. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  41791. /** Shifts the glyph's position by a relative amount. */
  41792. void moveBy (float deltaX, float deltaY);
  41793. /** Draws the glyph into a graphics context. */
  41794. void draw (const Graphics& g) const;
  41795. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  41796. void draw (const Graphics& g, const AffineTransform& transform) const;
  41797. /** Returns the path for this glyph.
  41798. @param path the glyph's outline will be appended to this path
  41799. */
  41800. void createPath (Path& path) const;
  41801. /** Checks to see if a point lies within this glyph. */
  41802. bool hitTest (float x, float y) const;
  41803. private:
  41804. friend class GlyphArrangement;
  41805. float x, y, w;
  41806. Font font;
  41807. juce_wchar character;
  41808. int glyph;
  41809. PositionedGlyph (float x, float y, float w, const Font& font, juce_wchar character, int glyph);
  41810. JUCE_LEAK_DETECTOR (PositionedGlyph);
  41811. };
  41812. /**
  41813. A set of glyphs, each with a position.
  41814. You can create a GlyphArrangement, text to it and then draw it onto a
  41815. graphics context. It's used internally by the text methods in the
  41816. Graphics class, but can be used directly if more control is needed.
  41817. @see Font, PositionedGlyph
  41818. */
  41819. class JUCE_API GlyphArrangement
  41820. {
  41821. public:
  41822. /** Creates an empty arrangement. */
  41823. GlyphArrangement();
  41824. /** Takes a copy of another arrangement. */
  41825. GlyphArrangement (const GlyphArrangement& other);
  41826. /** Copies another arrangement onto this one.
  41827. To add another arrangement without clearing this one, use addGlyphArrangement().
  41828. */
  41829. GlyphArrangement& operator= (const GlyphArrangement& other);
  41830. /** Destructor. */
  41831. ~GlyphArrangement();
  41832. /** Returns the total number of glyphs in the arrangement. */
  41833. int getNumGlyphs() const throw() { return glyphs.size(); }
  41834. /** Returns one of the glyphs from the arrangement.
  41835. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  41836. careful not to pass an out-of-range index here, as it
  41837. doesn't do any bounds-checking.
  41838. */
  41839. PositionedGlyph& getGlyph (int index) const;
  41840. /** Clears all text from the arrangement and resets it.
  41841. */
  41842. void clear();
  41843. /** Appends a line of text to the arrangement.
  41844. This will add the text as a single line, where x is the left-hand edge of the
  41845. first character, and y is the position for the text's baseline.
  41846. If the text contains new-lines or carriage-returns, this will ignore them - use
  41847. addJustifiedText() to add multi-line arrangements.
  41848. */
  41849. void addLineOfText (const Font& font,
  41850. const String& text,
  41851. float x, float y);
  41852. /** Adds a line of text, truncating it if it's wider than a specified size.
  41853. This is the same as addLineOfText(), but if the line's width exceeds the value
  41854. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  41855. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  41856. */
  41857. void addCurtailedLineOfText (const Font& font,
  41858. const String& text,
  41859. float x, float y,
  41860. float maxWidthPixels,
  41861. bool useEllipsis);
  41862. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  41863. This will add text to the arrangement, breaking it into new lines either where there
  41864. is a new-line or carriage-return character in the text, or where a line's width
  41865. exceeds the value set in maxLineWidth.
  41866. Each line that is added will be laid out using the flags set in horizontalLayout, so
  41867. the lines can be left- or right-justified, or centred horizontally in the space
  41868. between x and (x + maxLineWidth).
  41869. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  41870. lines will be placed below it, separated by a distance of font.getHeight().
  41871. */
  41872. void addJustifiedText (const Font& font,
  41873. const String& text,
  41874. float x, float y,
  41875. float maxLineWidth,
  41876. const Justification& horizontalLayout);
  41877. /** Tries to fit some text withing a given space.
  41878. This does its best to make the given text readable within the specified rectangle,
  41879. so it useful for labelling things.
  41880. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  41881. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  41882. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  41883. it's been truncated.
  41884. A Justification parameter lets you specify how the text is laid out within the rectangle,
  41885. both horizontally and vertically.
  41886. @see Graphics::drawFittedText
  41887. */
  41888. void addFittedText (const Font& font,
  41889. const String& text,
  41890. float x, float y, float width, float height,
  41891. const Justification& layout,
  41892. int maximumLinesToUse,
  41893. float minimumHorizontalScale = 0.7f);
  41894. /** Appends another glyph arrangement to this one. */
  41895. void addGlyphArrangement (const GlyphArrangement& other);
  41896. /** Draws this glyph arrangement to a graphics context.
  41897. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  41898. method, which renders the glyphs as filled vectors.
  41899. */
  41900. void draw (const Graphics& g) const;
  41901. /** Draws this glyph arrangement to a graphics context.
  41902. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  41903. method for non-transformed arrangements.
  41904. */
  41905. void draw (const Graphics& g, const AffineTransform& transform) const;
  41906. /** Converts the set of glyphs into a path.
  41907. @param path the glyphs' outlines will be appended to this path
  41908. */
  41909. void createPath (Path& path) const;
  41910. /** Looks for a glyph that contains the given co-ordinate.
  41911. @returns the index of the glyph, or -1 if none were found.
  41912. */
  41913. int findGlyphIndexAt (float x, float y) const;
  41914. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  41915. @param startIndex the first glyph to test
  41916. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  41917. startIndex will be included
  41918. @param includeWhitespace if true, the extent of any whitespace characters will also
  41919. be taken into account
  41920. */
  41921. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  41922. /** Shifts a set of glyphs by a given amount.
  41923. @param startIndex the first glyph to transform
  41924. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  41925. startIndex will be used
  41926. @param deltaX the amount to add to their x-positions
  41927. @param deltaY the amount to add to their y-positions
  41928. */
  41929. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  41930. float deltaX, float deltaY);
  41931. /** Removes a set of glyphs from the arrangement.
  41932. @param startIndex the first glyph to remove
  41933. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  41934. startIndex will be deleted
  41935. */
  41936. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  41937. /** Expands or compresses a set of glyphs horizontally.
  41938. @param startIndex the first glyph to transform
  41939. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  41940. startIndex will be used
  41941. @param horizontalScaleFactor how much to scale their horizontal width by
  41942. */
  41943. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  41944. float horizontalScaleFactor);
  41945. /** Justifies a set of glyphs within a given space.
  41946. This moves the glyphs as a block so that the whole thing is located within the
  41947. given rectangle with the specified layout.
  41948. If the Justification::horizontallyJustified flag is specified, each line will
  41949. be stretched out to fill the specified width.
  41950. */
  41951. void justifyGlyphs (int startIndex, int numGlyphs,
  41952. float x, float y, float width, float height,
  41953. const Justification& justification);
  41954. private:
  41955. OwnedArray <PositionedGlyph> glyphs;
  41956. int insertEllipsis (const Font& font, float maxXPos, int startIndex, int endIndex);
  41957. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  41958. const Justification& justification, float minimumHorizontalScale);
  41959. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  41960. JUCE_LEAK_DETECTOR (GlyphArrangement);
  41961. };
  41962. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  41963. /*** End of inlined file: juce_GlyphArrangement.h ***/
  41964. /**
  41965. A file open/save dialog box.
  41966. This is a Juce-based file dialog box; to use a native file chooser, see the
  41967. FileChooser class.
  41968. To use one of these, create it and call its show() method. e.g.
  41969. @code
  41970. {
  41971. WildcardFileFilter wildcardFilter ("*.foo", "Foo files");
  41972. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  41973. File::nonexistent,
  41974. &wildcardFilter,
  41975. 0);
  41976. FileChooserDialogBox dialogBox ("Open some kind of file",
  41977. "Please choose some kind of file that you want to open...",
  41978. browser,
  41979. getLookAndFeel().alertWindowBackground);
  41980. if (dialogBox.show())
  41981. {
  41982. File selectedFile = browser.getCurrentFile();
  41983. ...
  41984. }
  41985. }
  41986. @endcode
  41987. @see FileChooser
  41988. */
  41989. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  41990. public ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  41991. public FileBrowserListener
  41992. {
  41993. public:
  41994. /** Creates a file chooser box.
  41995. @param title the main title to show at the top of the box
  41996. @param instructions an optional longer piece of text to show below the title in
  41997. a smaller font, describing in more detail what's required.
  41998. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  41999. box. Make sure you delete this after (but not before!) the
  42000. dialog box has been deleted.
  42001. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  42002. if they try to select a file that already exists. (This
  42003. flag is only used when saving files)
  42004. @param backgroundColour the background colour for the top level window
  42005. @see FileBrowserComponent, FilePreviewComponent
  42006. */
  42007. FileChooserDialogBox (const String& title,
  42008. const String& instructions,
  42009. FileBrowserComponent& browserComponent,
  42010. bool warnAboutOverwritingExistingFiles,
  42011. const Colour& backgroundColour);
  42012. /** Destructor. */
  42013. ~FileChooserDialogBox();
  42014. /** Displays and runs the dialog box modally.
  42015. This will show the box with the specified size, returning true if the user
  42016. pressed 'ok', or false if they cancelled.
  42017. Leave the width or height as 0 to use the default size
  42018. */
  42019. bool show (int width = 0, int height = 0);
  42020. /** Displays and runs the dialog box modally.
  42021. This will show the box with the specified size at the specified location,
  42022. returning true if the user pressed 'ok', or false if they cancelled.
  42023. Leave the width or height as 0 to use the default size.
  42024. */
  42025. bool showAt (int x, int y, int width, int height);
  42026. /** A set of colour IDs to use to change the colour of various aspects of the box.
  42027. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42028. methods.
  42029. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42030. */
  42031. enum ColourIds
  42032. {
  42033. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  42034. };
  42035. /** @internal */
  42036. void buttonClicked (Button* button);
  42037. /** @internal */
  42038. void closeButtonPressed();
  42039. /** @internal */
  42040. void selectionChanged();
  42041. /** @internal */
  42042. void fileClicked (const File& file, const MouseEvent& e);
  42043. /** @internal */
  42044. void fileDoubleClicked (const File& file);
  42045. private:
  42046. class ContentComponent : public Component
  42047. {
  42048. public:
  42049. ContentComponent (const String& name, const String& instructions, FileBrowserComponent& chooserComponent);
  42050. void paint (Graphics& g);
  42051. void resized();
  42052. String instructions;
  42053. GlyphArrangement text;
  42054. FileBrowserComponent& chooserComponent;
  42055. TextButton okButton, cancelButton, newFolderButton;
  42056. };
  42057. ContentComponent* content;
  42058. const bool warnAboutOverwritingExistingFiles;
  42059. void okButtonPressed();
  42060. void createNewFolder();
  42061. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileChooserDialogBox);
  42062. };
  42063. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  42064. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  42065. #endif
  42066. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  42067. #endif
  42068. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  42069. /*** Start of inlined file: juce_FileListComponent.h ***/
  42070. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  42071. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  42072. /**
  42073. A component that displays the files in a directory as a listbox.
  42074. This implements the DirectoryContentsDisplayComponent base class so that
  42075. it can be used in a FileBrowserComponent.
  42076. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  42077. class and the FileBrowserListener class.
  42078. @see DirectoryContentsList, FileTreeComponent
  42079. */
  42080. class JUCE_API FileListComponent : public ListBox,
  42081. public DirectoryContentsDisplayComponent,
  42082. private ListBoxModel,
  42083. private ChangeListener
  42084. {
  42085. public:
  42086. /** Creates a listbox to show the contents of a specified directory.
  42087. */
  42088. FileListComponent (DirectoryContentsList& listToShow);
  42089. /** Destructor. */
  42090. ~FileListComponent();
  42091. /** Returns the number of files the user has got selected.
  42092. @see getSelectedFile
  42093. */
  42094. int getNumSelectedFiles() const;
  42095. /** Returns one of the files that the user has currently selected.
  42096. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  42097. @see getNumSelectedFiles
  42098. */
  42099. const File getSelectedFile (int index = 0) const;
  42100. /** Deselects any files that are currently selected. */
  42101. void deselectAllFiles();
  42102. /** Scrolls to the top of the list. */
  42103. void scrollToTop();
  42104. /** @internal */
  42105. void changeListenerCallback (ChangeBroadcaster*);
  42106. /** @internal */
  42107. int getNumRows();
  42108. /** @internal */
  42109. void paintListBoxItem (int, Graphics&, int, int, bool);
  42110. /** @internal */
  42111. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  42112. /** @internal */
  42113. void selectedRowsChanged (int lastRowSelected);
  42114. /** @internal */
  42115. void deleteKeyPressed (int currentSelectedRow);
  42116. /** @internal */
  42117. void returnKeyPressed (int currentSelectedRow);
  42118. private:
  42119. File lastDirectory;
  42120. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListComponent);
  42121. };
  42122. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  42123. /*** End of inlined file: juce_FileListComponent.h ***/
  42124. #endif
  42125. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  42126. /*** Start of inlined file: juce_FilenameComponent.h ***/
  42127. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  42128. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  42129. class FilenameComponent;
  42130. /**
  42131. Listens for events happening to a FilenameComponent.
  42132. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  42133. register one of these objects for event callbacks when the filename is changed.
  42134. @see FilenameComponent
  42135. */
  42136. class JUCE_API FilenameComponentListener
  42137. {
  42138. public:
  42139. /** Destructor. */
  42140. virtual ~FilenameComponentListener() {}
  42141. /** This method is called after the FilenameComponent's file has been changed. */
  42142. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  42143. };
  42144. /**
  42145. Shows a filename as an editable text box, with a 'browse' button and a
  42146. drop-down list for recently selected files.
  42147. A handy component for dialogue boxes where you want the user to be able to
  42148. select a file or directory.
  42149. Attach an FilenameComponentListener using the addListener() method, and it will
  42150. get called each time the user changes the filename, either by browsing for a file
  42151. and clicking 'ok', or by typing a new filename into the box and pressing return.
  42152. @see FileChooser, ComboBox
  42153. */
  42154. class JUCE_API FilenameComponent : public Component,
  42155. public SettableTooltipClient,
  42156. public FileDragAndDropTarget,
  42157. private AsyncUpdater,
  42158. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  42159. private ComboBoxListener
  42160. {
  42161. public:
  42162. /** Creates a FilenameComponent.
  42163. @param name the name for this component.
  42164. @param currentFile the file to initially show in the box
  42165. @param canEditFilename if true, the user can manually edit the filename; if false,
  42166. they can only change it by browsing for a new file
  42167. @param isDirectory if true, the file will be treated as a directory, and
  42168. an appropriate directory browser used
  42169. @param isForSaving if true, the file browser will allow non-existent files to
  42170. be picked, as the file is assumed to be used for saving rather
  42171. than loading
  42172. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  42173. If an empty string is passed in, then the pattern is assumed to be "*"
  42174. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  42175. to any filenames that are entered or chosen
  42176. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  42177. will only appear if the initial file isn't valid)
  42178. */
  42179. FilenameComponent (const String& name,
  42180. const File& currentFile,
  42181. bool canEditFilename,
  42182. bool isDirectory,
  42183. bool isForSaving,
  42184. const String& fileBrowserWildcard,
  42185. const String& enforcedSuffix,
  42186. const String& textWhenNothingSelected);
  42187. /** Destructor. */
  42188. ~FilenameComponent();
  42189. /** Returns the currently displayed filename. */
  42190. const File getCurrentFile() const;
  42191. /** Changes the current filename.
  42192. If addToRecentlyUsedList is true, the filename will also be added to the
  42193. drop-down list of recent files.
  42194. If sendChangeNotification is false, then the listeners won't be told of the
  42195. change.
  42196. */
  42197. void setCurrentFile (File newFile,
  42198. bool addToRecentlyUsedList,
  42199. bool sendChangeNotification = true);
  42200. /** Changes whether the use can type into the filename box.
  42201. */
  42202. void setFilenameIsEditable (bool shouldBeEditable);
  42203. /** Sets a file or directory to be the default starting point for the browser to show.
  42204. This is only used if the current file hasn't been set.
  42205. */
  42206. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  42207. /** Returns all the entries on the recent files list.
  42208. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  42209. state of this list.
  42210. @see setRecentlyUsedFilenames
  42211. */
  42212. const StringArray getRecentlyUsedFilenames() const;
  42213. /** Sets all the entries on the recent files list.
  42214. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  42215. state of this list.
  42216. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  42217. */
  42218. void setRecentlyUsedFilenames (const StringArray& filenames);
  42219. /** Adds an entry to the recently-used files dropdown list.
  42220. If the file is already in the list, it will be moved to the top. A limit
  42221. is also placed on the number of items that are kept in the list.
  42222. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  42223. */
  42224. void addRecentlyUsedFile (const File& file);
  42225. /** Changes the limit for the number of files that will be stored in the recent-file list.
  42226. */
  42227. void setMaxNumberOfRecentFiles (int newMaximum);
  42228. /** Changes the text shown on the 'browse' button.
  42229. By default this button just says "..." but you can change it. The button itself
  42230. can be changed using the look-and-feel classes, so it might not actually have any
  42231. text on it.
  42232. */
  42233. void setBrowseButtonText (const String& browseButtonText);
  42234. /** Adds a listener that will be called when the selected file is changed. */
  42235. void addListener (FilenameComponentListener* listener);
  42236. /** Removes a previously-registered listener. */
  42237. void removeListener (FilenameComponentListener* listener);
  42238. /** Gives the component a tooltip. */
  42239. void setTooltip (const String& newTooltip);
  42240. /** @internal */
  42241. void paintOverChildren (Graphics& g);
  42242. /** @internal */
  42243. void resized();
  42244. /** @internal */
  42245. void lookAndFeelChanged();
  42246. /** @internal */
  42247. bool isInterestedInFileDrag (const StringArray& files);
  42248. /** @internal */
  42249. void filesDropped (const StringArray& files, int, int);
  42250. /** @internal */
  42251. void fileDragEnter (const StringArray& files, int, int);
  42252. /** @internal */
  42253. void fileDragExit (const StringArray& files);
  42254. private:
  42255. ComboBox filenameBox;
  42256. String lastFilename;
  42257. ScopedPointer<Button> browseButton;
  42258. int maxRecentFiles;
  42259. bool isDir, isSaving, isFileDragOver;
  42260. String wildcard, enforcedSuffix, browseButtonText;
  42261. ListenerList <FilenameComponentListener> listeners;
  42262. File defaultBrowseFile;
  42263. void comboBoxChanged (ComboBox*);
  42264. void buttonClicked (Button* button);
  42265. void handleAsyncUpdate();
  42266. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FilenameComponent);
  42267. };
  42268. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  42269. /*** End of inlined file: juce_FilenameComponent.h ***/
  42270. #endif
  42271. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  42272. #endif
  42273. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  42274. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  42275. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  42276. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  42277. /**
  42278. Shows a set of file paths in a list, allowing them to be added, removed or
  42279. re-ordered.
  42280. @see FileSearchPath
  42281. */
  42282. class JUCE_API FileSearchPathListComponent : public Component,
  42283. public SettableTooltipClient,
  42284. public FileDragAndDropTarget,
  42285. private ButtonListener, // (can't use Button::Listener due to idiotic VC2005 bug)
  42286. private ListBoxModel
  42287. {
  42288. public:
  42289. /** Creates an empty FileSearchPathListComponent. */
  42290. FileSearchPathListComponent();
  42291. /** Destructor. */
  42292. ~FileSearchPathListComponent();
  42293. /** Returns the path as it is currently shown. */
  42294. const FileSearchPath& getPath() const throw() { return path; }
  42295. /** Changes the current path. */
  42296. void setPath (const FileSearchPath& newPath);
  42297. /** Sets a file or directory to be the default starting point for the browser to show.
  42298. This is only used if the current file hasn't been set.
  42299. */
  42300. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  42301. /** A set of colour IDs to use to change the colour of various aspects of the label.
  42302. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42303. methods.
  42304. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42305. */
  42306. enum ColourIds
  42307. {
  42308. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  42309. Make this transparent if you don't want the background to be filled. */
  42310. };
  42311. /** @internal */
  42312. int getNumRows();
  42313. /** @internal */
  42314. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  42315. /** @internal */
  42316. void deleteKeyPressed (int lastRowSelected);
  42317. /** @internal */
  42318. void returnKeyPressed (int lastRowSelected);
  42319. /** @internal */
  42320. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  42321. /** @internal */
  42322. void selectedRowsChanged (int lastRowSelected);
  42323. /** @internal */
  42324. void resized();
  42325. /** @internal */
  42326. void paint (Graphics& g);
  42327. /** @internal */
  42328. bool isInterestedInFileDrag (const StringArray& files);
  42329. /** @internal */
  42330. void filesDropped (const StringArray& files, int, int);
  42331. /** @internal */
  42332. void buttonClicked (Button* button);
  42333. private:
  42334. FileSearchPath path;
  42335. File defaultBrowseTarget;
  42336. ListBox listBox;
  42337. TextButton addButton, removeButton, changeButton;
  42338. DrawableButton upButton, downButton;
  42339. void changed();
  42340. void updateButtons();
  42341. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileSearchPathListComponent);
  42342. };
  42343. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  42344. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  42345. #endif
  42346. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  42347. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  42348. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  42349. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  42350. /**
  42351. A component that displays the files in a directory as a treeview.
  42352. This implements the DirectoryContentsDisplayComponent base class so that
  42353. it can be used in a FileBrowserComponent.
  42354. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  42355. class and the FileBrowserListener class.
  42356. @see DirectoryContentsList, FileListComponent
  42357. */
  42358. class JUCE_API FileTreeComponent : public TreeView,
  42359. public DirectoryContentsDisplayComponent
  42360. {
  42361. public:
  42362. /** Creates a listbox to show the contents of a specified directory.
  42363. */
  42364. FileTreeComponent (DirectoryContentsList& listToShow);
  42365. /** Destructor. */
  42366. ~FileTreeComponent();
  42367. /** Returns the number of files the user has got selected.
  42368. @see getSelectedFile
  42369. */
  42370. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  42371. /** Returns one of the files that the user has currently selected.
  42372. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  42373. @see getNumSelectedFiles
  42374. */
  42375. const File getSelectedFile (int index = 0) const;
  42376. /** Deselects any files that are currently selected. */
  42377. void deselectAllFiles();
  42378. /** Scrolls the list to the top. */
  42379. void scrollToTop();
  42380. /** Setting a name for this allows tree items to be dragged.
  42381. The string that you pass in here will be returned by the getDragSourceDescription()
  42382. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  42383. */
  42384. void setDragAndDropDescription (const String& description);
  42385. /** Returns the last value that was set by setDragAndDropDescription().
  42386. */
  42387. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  42388. private:
  42389. String dragAndDropDescription;
  42390. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileTreeComponent);
  42391. };
  42392. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  42393. /*** End of inlined file: juce_FileTreeComponent.h ***/
  42394. #endif
  42395. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  42396. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  42397. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  42398. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  42399. /**
  42400. A simple preview component that shows thumbnails of image files.
  42401. @see FileChooserDialogBox, FilePreviewComponent
  42402. */
  42403. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  42404. private Timer
  42405. {
  42406. public:
  42407. /** Creates an ImagePreviewComponent. */
  42408. ImagePreviewComponent();
  42409. /** Destructor. */
  42410. ~ImagePreviewComponent();
  42411. /** @internal */
  42412. void selectedFileChanged (const File& newSelectedFile);
  42413. /** @internal */
  42414. void paint (Graphics& g);
  42415. /** @internal */
  42416. void timerCallback();
  42417. private:
  42418. File fileToLoad;
  42419. Image currentThumbnail;
  42420. String currentDetails;
  42421. void getThumbSize (int& w, int& h) const;
  42422. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImagePreviewComponent);
  42423. };
  42424. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  42425. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  42426. #endif
  42427. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  42428. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  42429. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  42430. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  42431. /**
  42432. A type of FileFilter that works by wildcard pattern matching.
  42433. This filter only allows files that match one of the specified patterns, but
  42434. allows all directories through.
  42435. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  42436. */
  42437. class JUCE_API WildcardFileFilter : public FileFilter
  42438. {
  42439. public:
  42440. /**
  42441. Creates a wildcard filter for one or more patterns.
  42442. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  42443. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  42444. or .aiff.
  42445. The description is a name to show the user in a list of possible patterns, so
  42446. for the wav/aiff example, your description might be "audio files".
  42447. */
  42448. WildcardFileFilter (const String& fileWildcardPatterns,
  42449. const String& directoryWildcardPatterns,
  42450. const String& description);
  42451. /** Destructor. */
  42452. ~WildcardFileFilter();
  42453. /** Returns true if the filename matches one of the patterns specified. */
  42454. bool isFileSuitable (const File& file) const;
  42455. /** This always returns true. */
  42456. bool isDirectorySuitable (const File& file) const;
  42457. private:
  42458. StringArray fileWildcards, directoryWildcards;
  42459. static void parse (const String& pattern, StringArray& result);
  42460. static bool match (const File& file, const StringArray& wildcards);
  42461. JUCE_LEAK_DETECTOR (WildcardFileFilter);
  42462. };
  42463. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  42464. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  42465. #endif
  42466. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  42467. #endif
  42468. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  42469. #endif
  42470. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  42471. #endif
  42472. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  42473. #endif
  42474. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  42475. #endif
  42476. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  42477. #endif
  42478. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  42479. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  42480. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  42481. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  42482. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  42483. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  42484. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  42485. /**
  42486. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  42487. command in a ApplicationCommandManager.
  42488. Normally, you won't actually create a KeyPressMappingSet directly, because
  42489. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  42490. you'd create yourself an ApplicationCommandManager, and call its
  42491. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  42492. KeyPressMappingSet.
  42493. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  42494. to the top-level component for which you want to handle keystrokes. So for example:
  42495. @code
  42496. class MyMainWindow : public Component
  42497. {
  42498. ApplicationCommandManager* myCommandManager;
  42499. public:
  42500. MyMainWindow()
  42501. {
  42502. myCommandManager = new ApplicationCommandManager();
  42503. // first, make sure the command manager has registered all the commands that its
  42504. // targets can perform..
  42505. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  42506. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  42507. // this will use the command manager to initialise the KeyPressMappingSet with
  42508. // the default keypresses that were specified when the targets added their commands
  42509. // to the manager.
  42510. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  42511. // having set up the default key-mappings, you might now want to load the last set
  42512. // of mappings that the user configured.
  42513. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  42514. // Now tell our top-level window to send any keypresses that arrive to the
  42515. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  42516. addKeyListener (myCommandManager->getKeyMappings());
  42517. }
  42518. ...
  42519. }
  42520. @endcode
  42521. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  42522. register to be told when a command or mapping is added, removed, etc.
  42523. There's also a UI component called KeyMappingEditorComponent that can be used
  42524. to easily edit the key mappings.
  42525. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  42526. */
  42527. class JUCE_API KeyPressMappingSet : public KeyListener,
  42528. public ChangeBroadcaster,
  42529. public FocusChangeListener
  42530. {
  42531. public:
  42532. /** Creates a KeyPressMappingSet for a given command manager.
  42533. Normally, you won't actually create a KeyPressMappingSet directly, because
  42534. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  42535. best thing to do is to create your ApplicationCommandManager, and use the
  42536. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  42537. When a suitable keypress happens, the manager's invoke() method will be
  42538. used to invoke the appropriate command.
  42539. @see ApplicationCommandManager
  42540. */
  42541. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  42542. /** Creates an copy of a KeyPressMappingSet. */
  42543. KeyPressMappingSet (const KeyPressMappingSet& other);
  42544. /** Destructor. */
  42545. ~KeyPressMappingSet();
  42546. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  42547. /** Returns a list of keypresses that are assigned to a particular command.
  42548. @param commandID the command's ID
  42549. */
  42550. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  42551. /** Assigns a keypress to a command.
  42552. If the keypress is already assigned to a different command, it will first be
  42553. removed from that command, to avoid it triggering multiple functions.
  42554. @param commandID the ID of the command that you want to add a keypress to. If
  42555. this is 0, the keypress will be removed from anything that it
  42556. was previously assigned to, but not re-assigned
  42557. @param newKeyPress the new key-press
  42558. @param insertIndex if this is less than zero, the key will be appended to the
  42559. end of the list of keypresses; otherwise the new keypress will
  42560. be inserted into the existing list at this index
  42561. */
  42562. void addKeyPress (CommandID commandID,
  42563. const KeyPress& newKeyPress,
  42564. int insertIndex = -1);
  42565. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  42566. @see resetToDefaultMapping
  42567. */
  42568. void resetToDefaultMappings();
  42569. /** Resets all key-mappings to the defaults for a particular command.
  42570. @see resetToDefaultMappings
  42571. */
  42572. void resetToDefaultMapping (CommandID commandID);
  42573. /** Removes all keypresses that are assigned to any commands. */
  42574. void clearAllKeyPresses();
  42575. /** Removes all keypresses that are assigned to a particular command. */
  42576. void clearAllKeyPresses (CommandID commandID);
  42577. /** Removes one of the keypresses that are assigned to a command.
  42578. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  42579. which the keyPressIndex refers.
  42580. */
  42581. void removeKeyPress (CommandID commandID, int keyPressIndex);
  42582. /** Removes a keypress from any command that it may be assigned to.
  42583. */
  42584. void removeKeyPress (const KeyPress& keypress);
  42585. /** Returns true if the given command is linked to this key. */
  42586. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const throw();
  42587. /** Looks for a command that corresponds to a keypress.
  42588. @returns the UID of the command or 0 if none was found
  42589. */
  42590. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  42591. /** Tries to recreate the mappings from a previously stored state.
  42592. The XML passed in must have been created by the createXml() method.
  42593. If the stored state makes any reference to commands that aren't
  42594. currently available, these will be ignored.
  42595. If the set of mappings being loaded was a set of differences (using createXml (true)),
  42596. then this will call resetToDefaultMappings() and then merge the saved mappings
  42597. on top. If the saved set was created with createXml (false), then this method
  42598. will first clear all existing mappings and load the saved ones as a complete set.
  42599. @returns true if it manages to load the XML correctly
  42600. @see createXml
  42601. */
  42602. bool restoreFromXml (const XmlElement& xmlVersion);
  42603. /** Creates an XML representation of the current mappings.
  42604. This will produce a lump of XML that can be later reloaded using
  42605. restoreFromXml() to recreate the current mapping state.
  42606. The object that is returned must be deleted by the caller.
  42607. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  42608. will be saved into the XML. If it's true, then the XML will
  42609. only store the differences between the current mappings and
  42610. the default mappings you'd get from calling resetToDefaultMappings().
  42611. The advantage of saving a set of differences from the default is that
  42612. if you change the default mappings (in a new version of your app, for
  42613. example), then these will be merged into a user's saved preferences.
  42614. @see restoreFromXml
  42615. */
  42616. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  42617. /** @internal */
  42618. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  42619. /** @internal */
  42620. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  42621. /** @internal */
  42622. void globalFocusChanged (Component* focusedComponent);
  42623. private:
  42624. ApplicationCommandManager* commandManager;
  42625. struct CommandMapping
  42626. {
  42627. CommandID commandID;
  42628. Array <KeyPress> keypresses;
  42629. bool wantsKeyUpDownCallbacks;
  42630. };
  42631. OwnedArray <CommandMapping> mappings;
  42632. struct KeyPressTime
  42633. {
  42634. KeyPress key;
  42635. uint32 timeWhenPressed;
  42636. };
  42637. OwnedArray <KeyPressTime> keysDown;
  42638. void handleMessage (const Message& message);
  42639. void invokeCommand (const CommandID commandID,
  42640. const KeyPress& keyPress,
  42641. const bool isKeyDown,
  42642. const int millisecsSinceKeyPressed,
  42643. Component* const originatingComponent) const;
  42644. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  42645. JUCE_LEAK_DETECTOR (KeyPressMappingSet);
  42646. };
  42647. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  42648. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  42649. /**
  42650. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  42651. object.
  42652. @see KeyPressMappingSet
  42653. */
  42654. class JUCE_API KeyMappingEditorComponent : public Component
  42655. {
  42656. public:
  42657. /** Creates a KeyMappingEditorComponent.
  42658. @param mappingSet this is the set of mappings to display and edit. Make sure the
  42659. mappings object is not deleted before this component!
  42660. @param showResetToDefaultButton if true, then at the bottom of the list, the
  42661. component will include a 'reset to defaults' button.
  42662. */
  42663. KeyMappingEditorComponent (KeyPressMappingSet& mappingSet,
  42664. bool showResetToDefaultButton);
  42665. /** Destructor. */
  42666. virtual ~KeyMappingEditorComponent();
  42667. /** Sets up the colours to use for parts of the component.
  42668. @param mainBackground colour to use for most of the background
  42669. @param textColour colour to use for the text
  42670. */
  42671. void setColours (const Colour& mainBackground,
  42672. const Colour& textColour);
  42673. /** Returns the KeyPressMappingSet that this component is acting upon. */
  42674. KeyPressMappingSet& getMappings() const throw() { return mappings; }
  42675. /** Can be overridden if some commands need to be excluded from the list.
  42676. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  42677. method to decide what to return, but you can override it to handle special cases.
  42678. */
  42679. virtual bool shouldCommandBeIncluded (CommandID commandID);
  42680. /** Can be overridden to indicate that some commands are shown as read-only.
  42681. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  42682. method to decide what to return, but you can override it to handle special cases.
  42683. */
  42684. virtual bool isCommandReadOnly (CommandID commandID);
  42685. /** This can be overridden to let you change the format of the string used
  42686. to describe a keypress.
  42687. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  42688. keys that are triggered by something else externally. If you override the
  42689. method, be sure to let the base class's method handle keys you're not
  42690. interested in.
  42691. */
  42692. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  42693. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  42694. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42695. methods.
  42696. To change the colours of the menu that pops up
  42697. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42698. */
  42699. enum ColourIds
  42700. {
  42701. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  42702. textColourId = 0x100ad01, /**< The colour for the text. */
  42703. };
  42704. /** @internal */
  42705. void parentHierarchyChanged();
  42706. /** @internal */
  42707. void resized();
  42708. private:
  42709. KeyPressMappingSet& mappings;
  42710. TreeView tree;
  42711. TextButton resetButton;
  42712. class TopLevelItem;
  42713. class ChangeKeyButton;
  42714. class MappingItem;
  42715. class CategoryItem;
  42716. class ItemComponent;
  42717. friend class TopLevelItem;
  42718. friend class OwnedArray <ChangeKeyButton>;
  42719. friend class ScopedPointer<TopLevelItem>;
  42720. ScopedPointer<TopLevelItem> treeItem;
  42721. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KeyMappingEditorComponent);
  42722. };
  42723. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  42724. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  42725. #endif
  42726. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  42727. #endif
  42728. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  42729. #endif
  42730. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  42731. #endif
  42732. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  42733. #endif
  42734. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  42735. #endif
  42736. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  42737. #endif
  42738. #ifndef __JUCE_COMPONENTBUILDER_JUCEHEADER__
  42739. #endif
  42740. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  42741. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  42742. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  42743. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  42744. /** An object that watches for any movement of a component or any of its parent components.
  42745. This makes it easy to check when a component is moved relative to its top-level
  42746. peer window. The normal Component::moved() method is only called when a component
  42747. moves relative to its immediate parent, and sometimes you want to know if any of
  42748. components higher up the tree have moved (which of course will affect the overall
  42749. position of all their sub-components).
  42750. It also includes a callback that lets you know when the top-level peer is changed.
  42751. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  42752. because they need to keep their custom windows in the right place and respond to
  42753. changes in the peer.
  42754. */
  42755. class JUCE_API ComponentMovementWatcher : public ComponentListener
  42756. {
  42757. public:
  42758. /** Creates a ComponentMovementWatcher to watch a given target component. */
  42759. ComponentMovementWatcher (Component* component);
  42760. /** Destructor. */
  42761. ~ComponentMovementWatcher();
  42762. /** This callback happens when the component that is being watched is moved
  42763. relative to its top-level peer window, or when it is resized. */
  42764. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  42765. /** This callback happens when the component's top-level peer is changed. */
  42766. virtual void componentPeerChanged() = 0;
  42767. /** This callback happens when the component's visibility state changes, possibly due to
  42768. one of its parents being made visible or invisible.
  42769. */
  42770. virtual void componentVisibilityChanged() = 0;
  42771. /** @internal */
  42772. void componentParentHierarchyChanged (Component& component);
  42773. /** @internal */
  42774. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  42775. /** @internal */
  42776. void componentBeingDeleted (Component& component);
  42777. /** @internal */
  42778. void componentVisibilityChanged (Component& component);
  42779. private:
  42780. WeakReference<Component> component;
  42781. ComponentPeer* lastPeer;
  42782. Array <Component*> registeredParentComps;
  42783. bool reentrant, wasShowing;
  42784. Rectangle<int> lastBounds;
  42785. void unregister();
  42786. void registerWithParentComps();
  42787. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentMovementWatcher);
  42788. };
  42789. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  42790. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  42791. #endif
  42792. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  42793. /*** Start of inlined file: juce_GroupComponent.h ***/
  42794. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  42795. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  42796. /**
  42797. A component that draws an outline around itself and has an optional title at
  42798. the top, for drawing an outline around a group of controls.
  42799. */
  42800. class JUCE_API GroupComponent : public Component
  42801. {
  42802. public:
  42803. /** Creates a GroupComponent.
  42804. @param componentName the name to give the component
  42805. @param labelText the text to show at the top of the outline
  42806. */
  42807. GroupComponent (const String& componentName = String::empty,
  42808. const String& labelText = String::empty);
  42809. /** Destructor. */
  42810. ~GroupComponent();
  42811. /** Changes the text that's shown at the top of the component. */
  42812. void setText (const String& newText);
  42813. /** Returns the currently displayed text label. */
  42814. const String getText() const;
  42815. /** Sets the positioning of the text label.
  42816. (The default is Justification::left)
  42817. @see getTextLabelPosition
  42818. */
  42819. void setTextLabelPosition (const Justification& justification);
  42820. /** Returns the current text label position.
  42821. @see setTextLabelPosition
  42822. */
  42823. const Justification getTextLabelPosition() const throw() { return justification; }
  42824. /** A set of colour IDs to use to change the colour of various aspects of the component.
  42825. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42826. methods.
  42827. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42828. */
  42829. enum ColourIds
  42830. {
  42831. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  42832. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  42833. };
  42834. /** @internal */
  42835. void paint (Graphics& g);
  42836. /** @internal */
  42837. void enablementChanged();
  42838. /** @internal */
  42839. void colourChanged();
  42840. private:
  42841. String text;
  42842. Justification justification;
  42843. JUCE_DECLARE_NON_COPYABLE (GroupComponent);
  42844. };
  42845. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  42846. /*** End of inlined file: juce_GroupComponent.h ***/
  42847. #endif
  42848. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  42849. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  42850. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  42851. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  42852. /*** Start of inlined file: juce_TabbedComponent.h ***/
  42853. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  42854. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  42855. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  42856. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  42857. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  42858. class TabbedButtonBar;
  42859. /** In a TabbedButtonBar, this component is used for each of the buttons.
  42860. If you want to create a TabbedButtonBar with custom tab components, derive
  42861. your component from this class, and override the TabbedButtonBar::createTabButton()
  42862. method to create it instead of the default one.
  42863. @see TabbedButtonBar
  42864. */
  42865. class JUCE_API TabBarButton : public Button
  42866. {
  42867. public:
  42868. /** Creates the tab button. */
  42869. TabBarButton (const String& name, TabbedButtonBar& ownerBar);
  42870. /** Destructor. */
  42871. ~TabBarButton();
  42872. /** Chooses the best length for the tab, given the specified depth.
  42873. If the tab is horizontal, this should return its width, and the depth
  42874. specifies its height. If it's vertical, it should return the height, and
  42875. the depth is actually its width.
  42876. */
  42877. virtual int getBestTabLength (int depth);
  42878. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  42879. void clicked (const ModifierKeys& mods);
  42880. bool hitTest (int x, int y);
  42881. protected:
  42882. friend class TabbedButtonBar;
  42883. TabbedButtonBar& owner;
  42884. int overlapPixels;
  42885. DropShadowEffect shadow;
  42886. /** Returns an area of the component that's safe to draw in.
  42887. This deals with the orientation of the tabs, which affects which side is
  42888. touching the tabbed box's content component.
  42889. */
  42890. const Rectangle<int> getActiveArea();
  42891. /** Returns this tab's index in its tab bar. */
  42892. int getIndex() const;
  42893. private:
  42894. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabBarButton);
  42895. };
  42896. /**
  42897. A vertical or horizontal bar containing tabs that you can select.
  42898. You can use one of these to generate things like a dialog box that has
  42899. tabbed pages you can flip between. Attach a ChangeListener to the
  42900. button bar to be told when the user changes the page.
  42901. An easier method than doing this is to use a TabbedComponent, which
  42902. contains its own TabbedButtonBar and which takes care of the layout
  42903. and other housekeeping.
  42904. @see TabbedComponent
  42905. */
  42906. class JUCE_API TabbedButtonBar : public Component,
  42907. public ChangeBroadcaster
  42908. {
  42909. public:
  42910. /** The placement of the tab-bar
  42911. @see setOrientation, getOrientation
  42912. */
  42913. enum Orientation
  42914. {
  42915. TabsAtTop,
  42916. TabsAtBottom,
  42917. TabsAtLeft,
  42918. TabsAtRight
  42919. };
  42920. /** Creates a TabbedButtonBar with a given placement.
  42921. You can change the orientation later if you need to.
  42922. */
  42923. TabbedButtonBar (Orientation orientation);
  42924. /** Destructor. */
  42925. ~TabbedButtonBar();
  42926. /** Changes the bar's orientation.
  42927. This won't change the bar's actual size - you'll need to do that yourself,
  42928. but this determines which direction the tabs go in, and which side they're
  42929. stuck to.
  42930. */
  42931. void setOrientation (Orientation orientation);
  42932. /** Returns the current orientation.
  42933. @see setOrientation
  42934. */
  42935. Orientation getOrientation() const throw() { return orientation; }
  42936. /** Changes the minimum scale factor to which the tabs can be compressed when trying to
  42937. fit a lot of tabs on-screen.
  42938. */
  42939. void setMinimumTabScaleFactor (double newMinimumScale);
  42940. /** Deletes all the tabs from the bar.
  42941. @see addTab
  42942. */
  42943. void clearTabs();
  42944. /** Adds a tab to the bar.
  42945. Tabs are added in left-to-right reading order.
  42946. If this is the first tab added, it'll also be automatically selected.
  42947. */
  42948. void addTab (const String& tabName,
  42949. const Colour& tabBackgroundColour,
  42950. int insertIndex = -1);
  42951. /** Changes the name of one of the tabs. */
  42952. void setTabName (int tabIndex,
  42953. const String& newName);
  42954. /** Gets rid of one of the tabs. */
  42955. void removeTab (int tabIndex);
  42956. /** Moves a tab to a new index in the list.
  42957. Pass -1 as the index to move it to the end of the list.
  42958. */
  42959. void moveTab (int currentIndex, int newIndex);
  42960. /** Returns the number of tabs in the bar. */
  42961. int getNumTabs() const;
  42962. /** Returns a list of all the tab names in the bar. */
  42963. const StringArray getTabNames() const;
  42964. /** Changes the currently selected tab.
  42965. This will send a change message and cause a synchronous callback to
  42966. the currentTabChanged() method. (But if the given tab is already selected,
  42967. nothing will be done).
  42968. To deselect all the tabs, use an index of -1.
  42969. */
  42970. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  42971. /** Returns the name of the currently selected tab.
  42972. This could be an empty string if none are selected.
  42973. */
  42974. const String getCurrentTabName() const;
  42975. /** Returns the index of the currently selected tab.
  42976. This could return -1 if none are selected.
  42977. */
  42978. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  42979. /** Returns the button for a specific tab.
  42980. The button that is returned may be deleted later by this component, so don't hang
  42981. on to the pointer that is returned. A null pointer may be returned if the index is
  42982. out of range.
  42983. */
  42984. TabBarButton* getTabButton (int index) const;
  42985. /** Returns the index of a TabBarButton if it belongs to this bar. */
  42986. int indexOfTabButton (const TabBarButton* button) const;
  42987. /** Callback method to indicate the selected tab has been changed.
  42988. @see setCurrentTabIndex
  42989. */
  42990. virtual void currentTabChanged (int newCurrentTabIndex,
  42991. const String& newCurrentTabName);
  42992. /** Callback method to indicate that the user has right-clicked on a tab.
  42993. (Or ctrl-clicked on the Mac)
  42994. */
  42995. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  42996. /** Returns the colour of a tab.
  42997. This is the colour that was specified in addTab().
  42998. */
  42999. const Colour getTabBackgroundColour (int tabIndex);
  43000. /** Changes the background colour of a tab.
  43001. @see addTab, getTabBackgroundColour
  43002. */
  43003. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  43004. /** A set of colour IDs to use to change the colour of various aspects of the component.
  43005. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43006. methods.
  43007. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43008. */
  43009. enum ColourIds
  43010. {
  43011. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  43012. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  43013. the look and feel will choose an appropriate colour. */
  43014. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  43015. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  43016. this isn't specified, the look and feel will choose an appropriate
  43017. colour. */
  43018. };
  43019. /** @internal */
  43020. void resized();
  43021. /** @internal */
  43022. void lookAndFeelChanged();
  43023. protected:
  43024. /** This creates one of the tabs.
  43025. If you need to use custom tab components, you can override this method and
  43026. return your own class instead of the default.
  43027. */
  43028. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  43029. private:
  43030. Orientation orientation;
  43031. struct TabInfo
  43032. {
  43033. ScopedPointer<TabBarButton> component;
  43034. String name;
  43035. Colour colour;
  43036. };
  43037. OwnedArray <TabInfo> tabs;
  43038. double minimumScale;
  43039. int currentTabIndex;
  43040. class BehindFrontTabComp;
  43041. friend class BehindFrontTabComp;
  43042. friend class ScopedPointer<BehindFrontTabComp>;
  43043. ScopedPointer<BehindFrontTabComp> behindFrontTab;
  43044. ScopedPointer<Button> extraTabsButton;
  43045. void showExtraItemsMenu();
  43046. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedButtonBar);
  43047. };
  43048. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  43049. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  43050. /**
  43051. A component with a TabbedButtonBar along one of its sides.
  43052. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  43053. with addTab(), and this will take care of showing the pages for you when the
  43054. user clicks on a different tab.
  43055. @see TabbedButtonBar
  43056. */
  43057. class JUCE_API TabbedComponent : public Component
  43058. {
  43059. public:
  43060. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  43061. Once created, add some tabs with the addTab() method.
  43062. */
  43063. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  43064. /** Destructor. */
  43065. ~TabbedComponent();
  43066. /** Changes the placement of the tabs.
  43067. This will rearrange the layout to place the tabs along the appropriate
  43068. side of this component, and will shift the content component accordingly.
  43069. @see TabbedButtonBar::setOrientation
  43070. */
  43071. void setOrientation (TabbedButtonBar::Orientation orientation);
  43072. /** Returns the current tab placement.
  43073. @see setOrientation, TabbedButtonBar::getOrientation
  43074. */
  43075. TabbedButtonBar::Orientation getOrientation() const throw();
  43076. /** Specifies how many pixels wide or high the tab-bar should be.
  43077. If the tabs are placed along the top or bottom, this specified the height
  43078. of the bar; if they're along the left or right edges, it'll be the width
  43079. of the bar.
  43080. */
  43081. void setTabBarDepth (int newDepth);
  43082. /** Returns the current thickness of the tab bar.
  43083. @see setTabBarDepth
  43084. */
  43085. int getTabBarDepth() const throw() { return tabDepth; }
  43086. /** Specifies the thickness of an outline that should be drawn around the content component.
  43087. If this thickness is > 0, a line will be drawn around the three sides of the content
  43088. component which don't touch the tab-bar, and the content component will be inset by this amount.
  43089. To set the colour of the line, use setColour (outlineColourId, ...).
  43090. */
  43091. void setOutline (int newThickness);
  43092. /** Specifies a gap to leave around the edge of the content component.
  43093. Each edge of the content component will be indented by the given number of pixels.
  43094. */
  43095. void setIndent (int indentThickness);
  43096. /** Removes all the tabs from the bar.
  43097. @see TabbedButtonBar::clearTabs
  43098. */
  43099. void clearTabs();
  43100. /** Adds a tab to the tab-bar.
  43101. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  43102. is true, it will be deleted when the tab is removed or when this object is
  43103. deleted.
  43104. @see TabbedButtonBar::addTab
  43105. */
  43106. void addTab (const String& tabName,
  43107. const Colour& tabBackgroundColour,
  43108. Component* contentComponent,
  43109. bool deleteComponentWhenNotNeeded,
  43110. int insertIndex = -1);
  43111. /** Changes the name of one of the tabs. */
  43112. void setTabName (int tabIndex, const String& newName);
  43113. /** Gets rid of one of the tabs. */
  43114. void removeTab (int tabIndex);
  43115. /** Returns the number of tabs in the bar. */
  43116. int getNumTabs() const;
  43117. /** Returns a list of all the tab names in the bar. */
  43118. const StringArray getTabNames() const;
  43119. /** Returns the content component that was added for the given index.
  43120. Be sure not to use or delete the components that are returned, as this may interfere
  43121. with the TabbedComponent's use of them.
  43122. */
  43123. Component* getTabContentComponent (int tabIndex) const throw();
  43124. /** Returns the colour of one of the tabs. */
  43125. const Colour getTabBackgroundColour (int tabIndex) const throw();
  43126. /** Changes the background colour of one of the tabs. */
  43127. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  43128. /** Changes the currently-selected tab.
  43129. To deselect all the tabs, pass -1 as the index.
  43130. @see TabbedButtonBar::setCurrentTabIndex
  43131. */
  43132. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  43133. /** Returns the index of the currently selected tab.
  43134. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  43135. */
  43136. int getCurrentTabIndex() const;
  43137. /** Returns the name of the currently selected tab.
  43138. @see addTab, TabbedButtonBar::getCurrentTabName()
  43139. */
  43140. const String getCurrentTabName() const;
  43141. /** Returns the current component that's filling the panel.
  43142. This will return 0 if there isn't one.
  43143. */
  43144. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  43145. /** Callback method to indicate the selected tab has been changed.
  43146. @see setCurrentTabIndex
  43147. */
  43148. virtual void currentTabChanged (int newCurrentTabIndex,
  43149. const String& newCurrentTabName);
  43150. /** Callback method to indicate that the user has right-clicked on a tab.
  43151. (Or ctrl-clicked on the Mac)
  43152. */
  43153. virtual void popupMenuClickOnTab (int tabIndex,
  43154. const String& tabName);
  43155. /** Returns the tab button bar component that is being used.
  43156. */
  43157. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  43158. /** A set of colour IDs to use to change the colour of various aspects of the component.
  43159. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43160. methods.
  43161. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43162. */
  43163. enum ColourIds
  43164. {
  43165. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  43166. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  43167. (See setOutline) */
  43168. };
  43169. /** @internal */
  43170. void paint (Graphics& g);
  43171. /** @internal */
  43172. void resized();
  43173. /** @internal */
  43174. void lookAndFeelChanged();
  43175. protected:
  43176. /** This creates one of the tab buttons.
  43177. If you need to use custom tab components, you can override this method and
  43178. return your own class instead of the default.
  43179. */
  43180. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  43181. /** @internal */
  43182. ScopedPointer<TabbedButtonBar> tabs;
  43183. private:
  43184. Array <WeakReference<Component> > contentComponents;
  43185. WeakReference<Component> panelComponent;
  43186. int tabDepth;
  43187. int outlineThickness, edgeIndent;
  43188. class ButtonBar;
  43189. friend class ButtonBar;
  43190. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  43191. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TabbedComponent);
  43192. };
  43193. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  43194. /*** End of inlined file: juce_TabbedComponent.h ***/
  43195. /*** Start of inlined file: juce_DocumentWindow.h ***/
  43196. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  43197. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  43198. /*** Start of inlined file: juce_MenuBarModel.h ***/
  43199. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  43200. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  43201. /**
  43202. A class for controlling MenuBar components.
  43203. This class is used to tell a MenuBar what menus to show, and to respond
  43204. to a menu being selected.
  43205. @see MenuBarModel::Listener, MenuBarComponent, PopupMenu
  43206. */
  43207. class JUCE_API MenuBarModel : private AsyncUpdater,
  43208. private ApplicationCommandManagerListener
  43209. {
  43210. public:
  43211. MenuBarModel() throw();
  43212. /** Destructor. */
  43213. virtual ~MenuBarModel();
  43214. /** Call this when some of your menu items have changed.
  43215. This method will cause a callback to any MenuBarListener objects that
  43216. are registered with this model.
  43217. If this model is displaying items from an ApplicationCommandManager, you
  43218. can use the setApplicationCommandManagerToWatch() method to cause
  43219. change messages to be sent automatically when the ApplicationCommandManager
  43220. is changed.
  43221. @see addListener, removeListener, MenuBarListener
  43222. */
  43223. void menuItemsChanged();
  43224. /** Tells the menu bar to listen to the specified command manager, and to update
  43225. itself when the commands change.
  43226. This will also allow it to flash a menu name when a command from that menu
  43227. is invoked using a keystroke.
  43228. */
  43229. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) throw();
  43230. /** A class to receive callbacks when a MenuBarModel changes.
  43231. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  43232. */
  43233. class JUCE_API Listener
  43234. {
  43235. public:
  43236. /** Destructor. */
  43237. virtual ~Listener() {}
  43238. /** This callback is made when items are changed in the menu bar model.
  43239. */
  43240. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  43241. /** This callback is made when an application command is invoked that
  43242. is represented by one of the items in the menu bar model.
  43243. */
  43244. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  43245. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  43246. };
  43247. /** Registers a listener for callbacks when the menu items in this model change.
  43248. The listener object will get callbacks when this object's menuItemsChanged()
  43249. method is called.
  43250. @see removeListener
  43251. */
  43252. void addListener (Listener* listenerToAdd) throw();
  43253. /** Removes a listener.
  43254. @see addListener
  43255. */
  43256. void removeListener (Listener* listenerToRemove) throw();
  43257. /** This method must return a list of the names of the menus. */
  43258. virtual const StringArray getMenuBarNames() = 0;
  43259. /** This should return the popup menu to display for a given top-level menu.
  43260. @param topLevelMenuIndex the index of the top-level menu to show
  43261. @param menuName the name of the top-level menu item to show
  43262. */
  43263. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  43264. const String& menuName) = 0;
  43265. /** This is called when a menu item has been clicked on.
  43266. @param menuItemID the item ID of the PopupMenu item that was selected
  43267. @param topLevelMenuIndex the index of the top-level menu from which the item was
  43268. chosen (just in case you've used duplicate ID numbers
  43269. on more than one of the popup menus)
  43270. */
  43271. virtual void menuItemSelected (int menuItemID,
  43272. int topLevelMenuIndex) = 0;
  43273. #if JUCE_MAC || DOXYGEN
  43274. /** MAC ONLY - Sets the model that is currently being shown as the main
  43275. menu bar at the top of the screen on the Mac.
  43276. You can pass 0 to stop the current model being displayed. Be careful
  43277. not to delete a model while it is being used.
  43278. An optional extra menu can be specified, containing items to add to the top of
  43279. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  43280. an apple, it's the one next to it, with your application's name at the top
  43281. and the services menu etc on it). When one of these items is selected, the
  43282. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  43283. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  43284. object then newMenuBarModel must be non-null.
  43285. */
  43286. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  43287. const PopupMenu* extraAppleMenuItems = 0);
  43288. /** MAC ONLY - Returns the menu model that is currently being shown as
  43289. the main menu bar.
  43290. */
  43291. static MenuBarModel* getMacMainMenu();
  43292. #endif
  43293. /** @internal */
  43294. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  43295. /** @internal */
  43296. void applicationCommandListChanged();
  43297. /** @internal */
  43298. void handleAsyncUpdate();
  43299. private:
  43300. ApplicationCommandManager* manager;
  43301. ListenerList <Listener> listeners;
  43302. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarModel);
  43303. };
  43304. /** This typedef is just for compatibility with old code - newer code should use the MenuBarModel::Listener class directly. */
  43305. typedef MenuBarModel::Listener MenuBarModelListener;
  43306. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  43307. /*** End of inlined file: juce_MenuBarModel.h ***/
  43308. /**
  43309. A resizable window with a title bar and maximise, minimise and close buttons.
  43310. This subclass of ResizableWindow creates a fairly standard type of window with
  43311. a title bar and various buttons. The name of the component is shown in the
  43312. title bar, and an icon can optionally be specified with setIcon().
  43313. All the methods available to a ResizableWindow are also available to this,
  43314. so it can easily be made resizable, minimised, maximised, etc.
  43315. It's not advisable to add child components directly to a DocumentWindow: put them
  43316. inside your content component instead. And overriding methods like resized(), moved(), etc
  43317. is also not recommended - instead override these methods for your content component.
  43318. (If for some obscure reason you do need to override these methods, always remember to
  43319. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  43320. decorations correctly).
  43321. You can also automatically add a menu bar to the window, using the setMenuBar()
  43322. method.
  43323. @see ResizableWindow, DialogWindow
  43324. */
  43325. class JUCE_API DocumentWindow : public ResizableWindow
  43326. {
  43327. public:
  43328. /** The set of available button-types that can be put on the title bar.
  43329. @see setTitleBarButtonsRequired
  43330. */
  43331. enum TitleBarButtons
  43332. {
  43333. minimiseButton = 1,
  43334. maximiseButton = 2,
  43335. closeButton = 4,
  43336. /** A combination of all the buttons above. */
  43337. allButtons = 7
  43338. };
  43339. /** Creates a DocumentWindow.
  43340. @param name the name to give the component - this is also
  43341. the title shown at the top of the window. To change
  43342. this later, use setName()
  43343. @param backgroundColour the colour to use for filling the window's background.
  43344. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  43345. should be shown on the title bar. This value is a bitwise
  43346. combination of values from the TitleBarButtons enum. Note
  43347. that it can be "allButtons" to get them all. You
  43348. can change this later with the setTitleBarButtonsRequired()
  43349. method, which can also specify where they are positioned.
  43350. @param addToDesktop if true, the window will be automatically added to the
  43351. desktop; if false, you can use it as a child component
  43352. @see TitleBarButtons
  43353. */
  43354. DocumentWindow (const String& name,
  43355. const Colour& backgroundColour,
  43356. int requiredButtons,
  43357. bool addToDesktop = true);
  43358. /** Destructor.
  43359. If a content component has been set with setContentComponent(), it
  43360. will be deleted.
  43361. */
  43362. ~DocumentWindow();
  43363. /** Changes the component's name.
  43364. (This is overridden from Component::setName() to cause a repaint, as
  43365. the name is what gets drawn across the window's title bar).
  43366. */
  43367. void setName (const String& newName);
  43368. /** Sets an icon to show in the title bar, next to the title.
  43369. A copy is made internally of the image, so the caller can delete the
  43370. image after calling this. If 0 is passed-in, any existing icon will be
  43371. removed.
  43372. */
  43373. void setIcon (const Image& imageToUse);
  43374. /** Changes the height of the title-bar. */
  43375. void setTitleBarHeight (int newHeight);
  43376. /** Returns the current title bar height. */
  43377. int getTitleBarHeight() const;
  43378. /** Changes the set of title-bar buttons being shown.
  43379. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  43380. should be shown on the title bar. This value is a bitwise
  43381. combination of values from the TitleBarButtons enum. Note
  43382. that it can be "allButtons" to get them all.
  43383. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  43384. left side of the bar; if false, they'll be placed at the right
  43385. */
  43386. void setTitleBarButtonsRequired (int requiredButtons,
  43387. bool positionTitleBarButtonsOnLeft);
  43388. /** Sets whether the title should be centred within the window.
  43389. If true, the title text is shown in the middle of the title-bar; if false,
  43390. it'll be shown at the left of the bar.
  43391. */
  43392. void setTitleBarTextCentred (bool textShouldBeCentred);
  43393. /** Creates a menu inside this window.
  43394. @param menuBarModel this specifies a MenuBarModel that should be used to
  43395. generate the contents of a menu bar that will be placed
  43396. just below the title bar, and just above any content
  43397. component. If this value is zero, any existing menu bar
  43398. will be removed from the component; if non-zero, one will
  43399. be added if it's required.
  43400. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  43401. or less to use the look-and-feel's default size.
  43402. */
  43403. void setMenuBar (MenuBarModel* menuBarModel,
  43404. int menuBarHeight = 0);
  43405. /** Returns the current menu bar component, or null if there isn't one.
  43406. This is probably a MenuBarComponent, unless a custom one has been set using
  43407. setMenuBarComponent().
  43408. */
  43409. Component* getMenuBarComponent() const throw();
  43410. /** Replaces the current menu bar with a custom component.
  43411. The component will be owned and deleted by the document window.
  43412. */
  43413. void setMenuBarComponent (Component* newMenuBarComponent);
  43414. /** This method is called when the user tries to close the window.
  43415. This is triggered by the user clicking the close button, or using some other
  43416. OS-specific key shortcut or OS menu for getting rid of a window.
  43417. If the window is just a pop-up, you should override this closeButtonPressed()
  43418. method and make it delete the window in whatever way is appropriate for your
  43419. app. E.g. you might just want to call "delete this".
  43420. If your app is centred around this window such that the whole app should quit when
  43421. the window is closed, then you will probably want to use this method as an opportunity
  43422. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  43423. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  43424. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  43425. or closing it via the taskbar icon on Windows).
  43426. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  43427. redirects it to call this method, so any methods of closing the window that are
  43428. caught by userTriedToCloseWindow() will also end up here).
  43429. */
  43430. virtual void closeButtonPressed();
  43431. /** Callback that is triggered when the minimise button is pressed.
  43432. The default implementation of this calls ResizableWindow::setMinimised(), but
  43433. you can override it to do more customised behaviour.
  43434. */
  43435. virtual void minimiseButtonPressed();
  43436. /** Callback that is triggered when the maximise button is pressed, or when the
  43437. title-bar is double-clicked.
  43438. The default implementation of this calls ResizableWindow::setFullScreen(), but
  43439. you can override it to do more customised behaviour.
  43440. */
  43441. virtual void maximiseButtonPressed();
  43442. /** Returns the close button, (or 0 if there isn't one). */
  43443. Button* getCloseButton() const throw();
  43444. /** Returns the minimise button, (or 0 if there isn't one). */
  43445. Button* getMinimiseButton() const throw();
  43446. /** Returns the maximise button, (or 0 if there isn't one). */
  43447. Button* getMaximiseButton() const throw();
  43448. /** A set of colour IDs to use to change the colour of various aspects of the window.
  43449. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  43450. methods.
  43451. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  43452. */
  43453. enum ColourIds
  43454. {
  43455. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  43456. and feel class how this is used. */
  43457. };
  43458. /** @internal */
  43459. void paint (Graphics& g);
  43460. /** @internal */
  43461. void resized();
  43462. /** @internal */
  43463. void lookAndFeelChanged();
  43464. /** @internal */
  43465. const BorderSize<int> getBorderThickness();
  43466. /** @internal */
  43467. const BorderSize<int> getContentComponentBorder();
  43468. /** @internal */
  43469. void mouseDoubleClick (const MouseEvent& e);
  43470. /** @internal */
  43471. void userTriedToCloseWindow();
  43472. /** @internal */
  43473. void activeWindowStatusChanged();
  43474. /** @internal */
  43475. int getDesktopWindowStyleFlags() const;
  43476. /** @internal */
  43477. void parentHierarchyChanged();
  43478. /** @internal */
  43479. const Rectangle<int> getTitleBarArea();
  43480. private:
  43481. int titleBarHeight, menuBarHeight, requiredButtons;
  43482. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  43483. ScopedPointer <Button> titleBarButtons [3];
  43484. Image titleBarIcon;
  43485. ScopedPointer <Component> menuBar;
  43486. MenuBarModel* menuBarModel;
  43487. class ButtonListenerProxy;
  43488. friend class ScopedPointer <ButtonListenerProxy>;
  43489. ScopedPointer <ButtonListenerProxy> buttonListener;
  43490. void repaintTitleBar();
  43491. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DocumentWindow);
  43492. };
  43493. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  43494. /*** End of inlined file: juce_DocumentWindow.h ***/
  43495. class MultiDocumentPanel;
  43496. class MDITabbedComponentInternal;
  43497. /**
  43498. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  43499. component.
  43500. It's like a normal DocumentWindow but has some extra functionality to make sure
  43501. everything works nicely inside a MultiDocumentPanel.
  43502. @see MultiDocumentPanel
  43503. */
  43504. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  43505. {
  43506. public:
  43507. /**
  43508. */
  43509. MultiDocumentPanelWindow (const Colour& backgroundColour);
  43510. /** Destructor. */
  43511. ~MultiDocumentPanelWindow();
  43512. /** @internal */
  43513. void maximiseButtonPressed();
  43514. /** @internal */
  43515. void closeButtonPressed();
  43516. /** @internal */
  43517. void activeWindowStatusChanged();
  43518. /** @internal */
  43519. void broughtToFront();
  43520. private:
  43521. void updateOrder();
  43522. MultiDocumentPanel* getOwner() const throw();
  43523. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanelWindow);
  43524. };
  43525. /**
  43526. A component that contains a set of other components either in floating windows
  43527. or tabs.
  43528. This acts as a panel that can be used to hold a set of open document windows, with
  43529. different layout modes.
  43530. Use addDocument() and closeDocument() to add or remove components from the
  43531. panel - never use any of the Component methods to access the panel's child
  43532. components directly, as these are managed internally.
  43533. */
  43534. class JUCE_API MultiDocumentPanel : public Component,
  43535. private ComponentListener
  43536. {
  43537. public:
  43538. /** Creates an empty panel.
  43539. Use addDocument() and closeDocument() to add or remove components from the
  43540. panel - never use any of the Component methods to access the panel's child
  43541. components directly, as these are managed internally.
  43542. */
  43543. MultiDocumentPanel();
  43544. /** Destructor.
  43545. When deleted, this will call closeAllDocuments (false) to make sure all its
  43546. components are deleted. If you need to make sure all documents are saved
  43547. before closing, then you should call closeAllDocuments (true) and check that
  43548. it returns true before deleting the panel.
  43549. */
  43550. ~MultiDocumentPanel();
  43551. /** Tries to close all the documents.
  43552. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  43553. be called for each open document, and any of these calls fails, this method
  43554. will stop and return false, leaving some documents still open.
  43555. If checkItsOkToCloseFirst is false, then all documents will be closed
  43556. unconditionally.
  43557. @see closeDocument
  43558. */
  43559. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  43560. /** Adds a document component to the panel.
  43561. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  43562. this will fail and return false. (If it does fail, the component passed-in will not be
  43563. deleted, even if deleteWhenRemoved was set to true).
  43564. The MultiDocumentPanel will deal with creating a window border to go around your component,
  43565. so just pass in the bare content component here, no need to give it a ResizableWindow
  43566. or DocumentWindow.
  43567. @param component the component to add
  43568. @param backgroundColour the background colour to use to fill the component's
  43569. window or tab
  43570. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  43571. or closeAllDocuments(), then it will be deleted. If false, then
  43572. the caller must handle the component's deletion
  43573. */
  43574. bool addDocument (Component* component,
  43575. const Colour& backgroundColour,
  43576. bool deleteWhenRemoved);
  43577. /** Closes one of the documents.
  43578. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  43579. be called, and if it fails, this method will return false without closing the
  43580. document.
  43581. If checkItsOkToCloseFirst is false, then the documents will be closed
  43582. unconditionally.
  43583. The component will be deleted if the deleteWhenRemoved parameter was set to
  43584. true when it was added with addDocument.
  43585. @see addDocument, closeAllDocuments
  43586. */
  43587. bool closeDocument (Component* component,
  43588. bool checkItsOkToCloseFirst);
  43589. /** Returns the number of open document windows.
  43590. @see getDocument
  43591. */
  43592. int getNumDocuments() const throw();
  43593. /** Returns one of the open documents.
  43594. The order of the documents in this array may change when they are added, removed
  43595. or moved around.
  43596. @see getNumDocuments
  43597. */
  43598. Component* getDocument (int index) const throw();
  43599. /** Returns the document component that is currently focused or on top.
  43600. If currently using floating windows, then this will be the component in the currently
  43601. active window, or the top component if none are active.
  43602. If it's currently in tabbed mode, then it'll return the component in the active tab.
  43603. @see setActiveDocument
  43604. */
  43605. Component* getActiveDocument() const throw();
  43606. /** Makes one of the components active and brings it to the top.
  43607. @see getActiveDocument
  43608. */
  43609. void setActiveDocument (Component* component);
  43610. /** Callback which gets invoked when the currently-active document changes. */
  43611. virtual void activeDocumentChanged();
  43612. /** Sets a limit on how many windows can be open at once.
  43613. If this is zero or less there's no limit (the default). addDocument() will fail
  43614. if this number is exceeded.
  43615. */
  43616. void setMaximumNumDocuments (int maximumNumDocuments);
  43617. /** Sets an option to make the document fullscreen if there's only one document open.
  43618. If set to true, then if there's only one document, it'll fill the whole of this
  43619. component without tabs or a window border. If false, then tabs or a window
  43620. will always be shown, even if there's only one document. If there's more than
  43621. one document open, then this option makes no difference.
  43622. */
  43623. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  43624. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  43625. */
  43626. bool isFullscreenWhenOneDocument() const throw();
  43627. /** The different layout modes available. */
  43628. enum LayoutMode
  43629. {
  43630. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  43631. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  43632. };
  43633. /** Changes the panel's mode.
  43634. @see LayoutMode, getLayoutMode
  43635. */
  43636. void setLayoutMode (LayoutMode newLayoutMode);
  43637. /** Returns the current layout mode. */
  43638. LayoutMode getLayoutMode() const throw() { return mode; }
  43639. /** Sets the background colour for the whole panel.
  43640. Each document has its own background colour, but this is the one used to fill the areas
  43641. behind them.
  43642. */
  43643. void setBackgroundColour (const Colour& newBackgroundColour);
  43644. /** Returns the current background colour.
  43645. @see setBackgroundColour
  43646. */
  43647. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  43648. /** A subclass must override this to say whether its currently ok for a document
  43649. to be closed.
  43650. This method is called by closeDocument() and closeAllDocuments() to indicate that
  43651. a document should be saved if possible, ready for it to be closed.
  43652. If this method returns true, then it means the document is ok and can be closed.
  43653. If it returns false, then it means that the closeDocument() method should stop
  43654. and not close.
  43655. Normally, you'd use this method to ask the user if they want to save any changes,
  43656. then return true if the save operation went ok. If the user cancelled the save
  43657. operation you could return false here to abort the close operation.
  43658. If your component is based on the FileBasedDocument class, then you'd probably want
  43659. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  43660. FileBasedDocument::savedOk
  43661. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  43662. */
  43663. virtual bool tryToCloseDocument (Component* component) = 0;
  43664. /** Creates a new window to be used for a document.
  43665. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  43666. but you might want to override it to return a custom component.
  43667. */
  43668. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  43669. /** @internal */
  43670. void paint (Graphics& g);
  43671. /** @internal */
  43672. void resized();
  43673. /** @internal */
  43674. void componentNameChanged (Component&);
  43675. private:
  43676. LayoutMode mode;
  43677. Array <Component*> components;
  43678. ScopedPointer<TabbedComponent> tabComponent;
  43679. Colour backgroundColour;
  43680. int maximumNumDocuments, numDocsBeforeTabsUsed;
  43681. friend class MultiDocumentPanelWindow;
  43682. friend class MDITabbedComponentInternal;
  43683. Component* getContainerComp (Component* c) const;
  43684. void updateOrder();
  43685. void addWindow (Component* component);
  43686. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiDocumentPanel);
  43687. };
  43688. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  43689. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  43690. #endif
  43691. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  43692. #endif
  43693. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  43694. #endif
  43695. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  43696. #endif
  43697. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  43698. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  43699. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  43700. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  43701. /**
  43702. For laying out a set of components, where the components have preferred sizes
  43703. and size limits, but where they are allowed to stretch to fill the available
  43704. space.
  43705. For example, if you have a component containing several other components, and
  43706. each one should be given a share of the total size, you could use one of these
  43707. to resize the child components when the parent component is resized. Then
  43708. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  43709. A StretchableLayoutManager operates only in one dimension, so if you have a set
  43710. of components stacked vertically on top of each other, you'd use one to manage their
  43711. heights. To build up complex arrangements of components, e.g. for applications
  43712. with multiple nested panels, you would use more than one StretchableLayoutManager.
  43713. E.g. by using two (one vertical, one horizontal), you could create a resizable
  43714. spreadsheet-style table.
  43715. E.g.
  43716. @code
  43717. class MyComp : public Component
  43718. {
  43719. StretchableLayoutManager myLayout;
  43720. MyComp()
  43721. {
  43722. myLayout.setItemLayout (0, // for item 0
  43723. 50, 100, // must be between 50 and 100 pixels in size
  43724. -0.6); // and its preferred size is 60% of the total available space
  43725. myLayout.setItemLayout (1, // for item 1
  43726. -0.2, -0.6, // size must be between 20% and 60% of the available space
  43727. 50); // and its preferred size is 50 pixels
  43728. }
  43729. void resized()
  43730. {
  43731. // make a list of two of our child components that we want to reposition
  43732. Component* comps[] = { myComp1, myComp2 };
  43733. // this will position the 2 components, one above the other, to fit
  43734. // vertically into the rectangle provided.
  43735. myLayout.layOutComponents (comps, 2,
  43736. 0, 0, getWidth(), getHeight(),
  43737. true);
  43738. }
  43739. };
  43740. @endcode
  43741. @see StretchableLayoutResizerBar
  43742. */
  43743. class JUCE_API StretchableLayoutManager
  43744. {
  43745. public:
  43746. /** Creates an empty layout.
  43747. You'll need to add some item properties to the layout before it can be used
  43748. to resize things - see setItemLayout().
  43749. */
  43750. StretchableLayoutManager();
  43751. /** Destructor. */
  43752. ~StretchableLayoutManager();
  43753. /** For a numbered item, this sets its size limits and preferred size.
  43754. @param itemIndex the index of the item to change.
  43755. @param minimumSize the minimum size that this item is allowed to be - a positive number
  43756. indicates an absolute size in pixels. A negative number indicates a
  43757. proportion of the available space (e.g -0.5 is 50%)
  43758. @param maximumSize the maximum size that this item is allowed to be - a positive number
  43759. indicates an absolute size in pixels. A negative number indicates a
  43760. proportion of the available space
  43761. @param preferredSize the size that this item would like to be, if there's enough room. A
  43762. positive number indicates an absolute size in pixels. A negative number
  43763. indicates a proportion of the available space
  43764. @see getItemLayout
  43765. */
  43766. void setItemLayout (int itemIndex,
  43767. double minimumSize,
  43768. double maximumSize,
  43769. double preferredSize);
  43770. /** For a numbered item, this returns its size limits and preferred size.
  43771. @param itemIndex the index of the item.
  43772. @param minimumSize the minimum size that this item is allowed to be - a positive number
  43773. indicates an absolute size in pixels. A negative number indicates a
  43774. proportion of the available space (e.g -0.5 is 50%)
  43775. @param maximumSize the maximum size that this item is allowed to be - a positive number
  43776. indicates an absolute size in pixels. A negative number indicates a
  43777. proportion of the available space
  43778. @param preferredSize the size that this item would like to be, if there's enough room. A
  43779. positive number indicates an absolute size in pixels. A negative number
  43780. indicates a proportion of the available space
  43781. @returns false if the item's properties hadn't been set
  43782. @see setItemLayout
  43783. */
  43784. bool getItemLayout (int itemIndex,
  43785. double& minimumSize,
  43786. double& maximumSize,
  43787. double& preferredSize) const;
  43788. /** Clears all the properties that have been set with setItemLayout() and resets
  43789. this object to its initial state.
  43790. */
  43791. void clearAllItems();
  43792. /** Takes a set of components that correspond to the layout's items, and positions
  43793. them to fill a space.
  43794. This will try to give each item its preferred size, whether that's a relative size
  43795. or an absolute one.
  43796. @param components an array of components that correspond to each of the
  43797. numbered items that the StretchableLayoutManager object
  43798. has been told about with setItemLayout()
  43799. @param numComponents the number of components in the array that is passed-in. This
  43800. should be the same as the number of items this object has been
  43801. told about.
  43802. @param x the left of the rectangle in which the components should
  43803. be laid out
  43804. @param y the top of the rectangle in which the components should
  43805. be laid out
  43806. @param width the width of the rectangle in which the components should
  43807. be laid out
  43808. @param height the height of the rectangle in which the components should
  43809. be laid out
  43810. @param vertically if true, the components will be positioned in a vertical stack,
  43811. so that they fill the height of the rectangle. If false, they
  43812. will be placed side-by-side in a horizontal line, filling the
  43813. available width
  43814. @param resizeOtherDimension if true, this means that the components will have their
  43815. other dimension resized to fit the space - i.e. if the 'vertically'
  43816. parameter is true, their x-positions and widths are adjusted to fit
  43817. the x and width parameters; if 'vertically' is false, their y-positions
  43818. and heights are adjusted to fit the y and height parameters.
  43819. */
  43820. void layOutComponents (Component** components,
  43821. int numComponents,
  43822. int x, int y, int width, int height,
  43823. bool vertically,
  43824. bool resizeOtherDimension);
  43825. /** Returns the current position of one of the items.
  43826. This is only a valid call after layOutComponents() has been called, as it
  43827. returns the last position that this item was placed at. If the layout was
  43828. vertical, the value returned will be the y position of the top of the item,
  43829. relative to the top of the rectangle in which the items were placed (so for
  43830. example, item 0 will always have position of 0, even in the rectangle passed
  43831. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  43832. the position returned is the item's left-hand position, again relative to the
  43833. x position of the rectangle used.
  43834. @see getItemCurrentSize, setItemPosition
  43835. */
  43836. int getItemCurrentPosition (int itemIndex) const;
  43837. /** Returns the current size of one of the items.
  43838. This is only meaningful after layOutComponents() has been called, as it
  43839. returns the last size that this item was given. If the layout was done
  43840. vertically, it'll return the item's height in pixels; if it was horizontal,
  43841. it'll return its width.
  43842. @see getItemCurrentRelativeSize
  43843. */
  43844. int getItemCurrentAbsoluteSize (int itemIndex) const;
  43845. /** Returns the current size of one of the items.
  43846. This is only meaningful after layOutComponents() has been called, as it
  43847. returns the last size that this item was given. If the layout was done
  43848. vertically, it'll return a negative value representing the item's height relative
  43849. to the last size used for laying the components out; if the layout was done
  43850. horizontally it'll be the proportion of its width.
  43851. @see getItemCurrentAbsoluteSize
  43852. */
  43853. double getItemCurrentRelativeSize (int itemIndex) const;
  43854. /** Moves one of the items, shifting along any other items as necessary in
  43855. order to get it to the desired position.
  43856. Calling this method will also update the preferred sizes of the items it
  43857. shuffles along, so that they reflect their new positions.
  43858. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  43859. about when it's dragged).
  43860. @param itemIndex the item to move
  43861. @param newPosition the absolute position that you'd like this item to move
  43862. to. The item might not be able to always reach exactly this position,
  43863. because other items may have minimum sizes that constrain how
  43864. far it can go
  43865. */
  43866. void setItemPosition (int itemIndex,
  43867. int newPosition);
  43868. private:
  43869. struct ItemLayoutProperties
  43870. {
  43871. int itemIndex;
  43872. int currentSize;
  43873. double minSize, maxSize, preferredSize;
  43874. };
  43875. OwnedArray <ItemLayoutProperties> items;
  43876. int totalSize;
  43877. static int sizeToRealSize (double size, int totalSpace);
  43878. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  43879. void setTotalSize (int newTotalSize);
  43880. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  43881. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  43882. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  43883. void updatePrefSizesToMatchCurrentPositions();
  43884. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutManager);
  43885. };
  43886. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  43887. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  43888. #endif
  43889. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  43890. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  43891. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  43892. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  43893. /**
  43894. A component that acts as one of the vertical or horizontal bars you see being
  43895. used to resize panels in a window.
  43896. One of these acts with a StretchableLayoutManager to resize the other components.
  43897. @see StretchableLayoutManager
  43898. */
  43899. class JUCE_API StretchableLayoutResizerBar : public Component
  43900. {
  43901. public:
  43902. /** Creates a resizer bar for use on a specified layout.
  43903. @param layoutToUse the layout that will be affected when this bar
  43904. is dragged
  43905. @param itemIndexInLayout the item index in the layout that corresponds to
  43906. this bar component. You'll need to set up the item
  43907. properties in a suitable way for a divider bar, e.g.
  43908. for an 8-pixel wide bar which, you could call
  43909. myLayout->setItemLayout (barIndex, 8, 8, 8)
  43910. @param isBarVertical true if it's an upright bar that you drag left and
  43911. right; false for a horizontal one that you drag up and
  43912. down
  43913. */
  43914. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  43915. int itemIndexInLayout,
  43916. bool isBarVertical);
  43917. /** Destructor. */
  43918. ~StretchableLayoutResizerBar();
  43919. /** This is called when the bar is dragged.
  43920. This method must update the positions of any components whose position is
  43921. determined by the StretchableLayoutManager, because they might have just
  43922. moved.
  43923. The default implementation calls the resized() method of this component's
  43924. parent component, because that's often where you're likely to apply the
  43925. layout, but it can be overridden for more specific needs.
  43926. */
  43927. virtual void hasBeenMoved();
  43928. /** @internal */
  43929. void paint (Graphics& g);
  43930. /** @internal */
  43931. void mouseDown (const MouseEvent& e);
  43932. /** @internal */
  43933. void mouseDrag (const MouseEvent& e);
  43934. private:
  43935. StretchableLayoutManager* layout;
  43936. int itemIndex, mouseDownPos;
  43937. bool isVertical;
  43938. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableLayoutResizerBar);
  43939. };
  43940. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  43941. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  43942. #endif
  43943. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  43944. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  43945. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  43946. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  43947. /**
  43948. A utility class for fitting a set of objects whose sizes can vary between
  43949. a minimum and maximum size, into a space.
  43950. This is a trickier algorithm than it would first seem, so I've put it in this
  43951. class to allow it to be shared by various bits of code.
  43952. To use it, create one of these objects, call addItem() to add the list of items
  43953. you need, then call resizeToFit(), which will change all their sizes. You can
  43954. then retrieve the new sizes with getItemSize() and getNumItems().
  43955. It's currently used by the TableHeaderComponent for stretching out the table
  43956. headings to fill the table's width.
  43957. */
  43958. class StretchableObjectResizer
  43959. {
  43960. public:
  43961. /** Creates an empty object resizer. */
  43962. StretchableObjectResizer();
  43963. /** Destructor. */
  43964. ~StretchableObjectResizer();
  43965. /** Adds an item to the list.
  43966. The order parameter lets you specify groups of items that are resized first when some
  43967. space needs to be found. Those items with an order of 0 will be the first ones to be
  43968. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  43969. will then try resizing the items with an order of 1, then 2, and so on.
  43970. */
  43971. void addItem (double currentSize,
  43972. double minSize,
  43973. double maxSize,
  43974. int order = 0);
  43975. /** Resizes all the items to fit this amount of space.
  43976. This will attempt to fit them in without exceeding each item's miniumum and
  43977. maximum sizes. In cases where none of the items can be expanded or enlarged any
  43978. further, the final size may be greater or less than the size passed in.
  43979. After calling this method, you can retrieve the new sizes with the getItemSize()
  43980. method.
  43981. */
  43982. void resizeToFit (double targetSize);
  43983. /** Returns the number of items that have been added. */
  43984. int getNumItems() const throw() { return items.size(); }
  43985. /** Returns the size of one of the items. */
  43986. double getItemSize (int index) const throw();
  43987. private:
  43988. struct Item
  43989. {
  43990. double size;
  43991. double minSize;
  43992. double maxSize;
  43993. int order;
  43994. };
  43995. OwnedArray <Item> items;
  43996. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StretchableObjectResizer);
  43997. };
  43998. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  43999. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  44000. #endif
  44001. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  44002. #endif
  44003. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  44004. #endif
  44005. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  44006. #endif
  44007. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  44008. /*** Start of inlined file: juce_LookAndFeel.h ***/
  44009. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  44010. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  44011. /*** Start of inlined file: juce_AlertWindow.h ***/
  44012. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  44013. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  44014. /*** Start of inlined file: juce_TextLayout.h ***/
  44015. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  44016. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  44017. class Graphics;
  44018. /**
  44019. A laid-out arrangement of text.
  44020. You can add text in different fonts to a TextLayout object, then call its
  44021. layout() method to word-wrap it into lines. The layout can then be drawn
  44022. using a graphics context.
  44023. It's handy if you've got a message to display, because you can format it,
  44024. measure the extent of the layout, and then create a suitably-sized window
  44025. to show it in.
  44026. @see Font, Graphics::drawFittedText, GlyphArrangement
  44027. */
  44028. class JUCE_API TextLayout
  44029. {
  44030. public:
  44031. /** Creates an empty text layout.
  44032. Text can then be appended using the appendText() method.
  44033. */
  44034. TextLayout();
  44035. /** Creates a copy of another layout object. */
  44036. TextLayout (const TextLayout& other);
  44037. /** Creates a text layout from an initial string and font. */
  44038. TextLayout (const String& text, const Font& font);
  44039. /** Destructor. */
  44040. ~TextLayout();
  44041. /** Copies another layout onto this one. */
  44042. TextLayout& operator= (const TextLayout& layoutToCopy);
  44043. /** Clears the layout, removing all its text. */
  44044. void clear();
  44045. /** Adds a string to the end of the arrangement.
  44046. The string will be broken onto new lines wherever it contains
  44047. carriage-returns or linefeeds. After adding it, you can call layout()
  44048. to wrap long lines into a paragraph and justify it.
  44049. */
  44050. void appendText (const String& textToAppend,
  44051. const Font& fontToUse);
  44052. /** Replaces all the text with a new string.
  44053. This is equivalent to calling clear() followed by appendText().
  44054. */
  44055. void setText (const String& newText,
  44056. const Font& fontToUse);
  44057. /** Returns true if the layout has not had any text added yet. */
  44058. bool isEmpty() const;
  44059. /** Breaks the text up to form a paragraph with the given width.
  44060. @param maximumWidth any text wider than this will be split
  44061. across multiple lines
  44062. @param justification how the lines are to be laid-out horizontally
  44063. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  44064. width that keeps all the lines of text at a
  44065. similar length - this is good when you're displaying
  44066. a short message and don't want it to get split
  44067. onto two lines with only a couple of words on
  44068. the second line, which looks untidy.
  44069. */
  44070. void layout (int maximumWidth,
  44071. const Justification& justification,
  44072. bool attemptToBalanceLineLengths);
  44073. /** Returns the overall width of the entire text layout. */
  44074. int getWidth() const;
  44075. /** Returns the overall height of the entire text layout. */
  44076. int getHeight() const;
  44077. /** Returns the total number of lines of text. */
  44078. int getNumLines() const { return totalLines; }
  44079. /** Returns the width of a particular line of text.
  44080. @param lineNumber the line, from 0 to (getNumLines() - 1)
  44081. */
  44082. int getLineWidth (int lineNumber) const;
  44083. /** Renders the text at a specified position using a graphics context.
  44084. */
  44085. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  44086. /** Renders the text within a specified rectangle using a graphics context.
  44087. The justification flags dictate how the block of text should be positioned
  44088. within the rectangle.
  44089. */
  44090. void drawWithin (Graphics& g,
  44091. int x, int y, int w, int h,
  44092. const Justification& layoutFlags) const;
  44093. private:
  44094. class Token;
  44095. friend class OwnedArray <Token>;
  44096. OwnedArray <Token> tokens;
  44097. int totalLines;
  44098. JUCE_LEAK_DETECTOR (TextLayout);
  44099. };
  44100. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  44101. /*** End of inlined file: juce_TextLayout.h ***/
  44102. /** A window that displays a message and has buttons for the user to react to it.
  44103. For simple dialog boxes with just a couple of buttons on them, there are
  44104. some static methods for running these.
  44105. For more complex dialogs, an AlertWindow can be created, then it can have some
  44106. buttons and components added to it, and its runModalLoop() method is then used to
  44107. show it. The value returned by runModalLoop() shows which button the
  44108. user pressed to dismiss the box.
  44109. @see ThreadWithProgressWindow
  44110. */
  44111. class JUCE_API AlertWindow : public TopLevelWindow,
  44112. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  44113. {
  44114. public:
  44115. /** The type of icon to show in the dialog box. */
  44116. enum AlertIconType
  44117. {
  44118. NoIcon, /**< No icon will be shown on the dialog box. */
  44119. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  44120. user to answer a question. */
  44121. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  44122. warning about something and shouldn't be ignored. */
  44123. InfoIcon /**< An icon that indicates that the dialog box is just
  44124. giving the user some information, which doesn't require
  44125. a response from them. */
  44126. };
  44127. /** Creates an AlertWindow.
  44128. @param title the headline to show at the top of the dialog box
  44129. @param message a longer, more descriptive message to show underneath the
  44130. headline
  44131. @param iconType the type of icon to display
  44132. @param associatedComponent if this is non-zero, it specifies the component that the
  44133. alert window should be associated with. Depending on the look
  44134. and feel, this might be used for positioning of the alert window.
  44135. */
  44136. AlertWindow (const String& title,
  44137. const String& message,
  44138. AlertIconType iconType,
  44139. Component* associatedComponent = 0);
  44140. /** Destroys the AlertWindow */
  44141. ~AlertWindow();
  44142. /** Returns the type of alert icon that was specified when the window
  44143. was created. */
  44144. AlertIconType getAlertType() const throw() { return alertIconType; }
  44145. /** Changes the dialog box's message.
  44146. This will also resize the window to fit the new message if required.
  44147. */
  44148. void setMessage (const String& message);
  44149. /** Adds a button to the window.
  44150. @param name the text to show on the button
  44151. @param returnValue the value that should be returned from runModalLoop()
  44152. if this is the button that the user presses.
  44153. @param shortcutKey1 an optional key that can be pressed to trigger this button
  44154. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  44155. */
  44156. void addButton (const String& name,
  44157. int returnValue,
  44158. const KeyPress& shortcutKey1 = KeyPress(),
  44159. const KeyPress& shortcutKey2 = KeyPress());
  44160. /** Returns the number of buttons that the window currently has. */
  44161. int getNumButtons() const;
  44162. /** Invokes a click of one of the buttons. */
  44163. void triggerButtonClick (const String& buttonName);
  44164. /** Adds a textbox to the window for entering strings.
  44165. @param name an internal name for the text-box. This is the name to pass to
  44166. the getTextEditorContents() method to find out what the
  44167. user typed-in.
  44168. @param initialContents a string to show in the text box when it's first shown
  44169. @param onScreenLabel if this is non-empty, it will be displayed next to the
  44170. text-box to label it.
  44171. @param isPasswordBox if true, the text editor will display asterisks instead of
  44172. the actual text
  44173. @see getTextEditorContents
  44174. */
  44175. void addTextEditor (const String& name,
  44176. const String& initialContents,
  44177. const String& onScreenLabel = String::empty,
  44178. bool isPasswordBox = false);
  44179. /** Returns the contents of a named textbox.
  44180. After showing an AlertWindow that contains a text editor, this can be
  44181. used to find out what the user has typed into it.
  44182. @param nameOfTextEditor the name of the text box that you're interested in
  44183. @see addTextEditor
  44184. */
  44185. const String getTextEditorContents (const String& nameOfTextEditor) const;
  44186. /** Returns a pointer to a textbox that was added with addTextEditor(). */
  44187. TextEditor* getTextEditor (const String& nameOfTextEditor) const;
  44188. /** Adds a drop-down list of choices to the box.
  44189. After the box has been shown, the getComboBoxComponent() method can
  44190. be used to find out which item the user picked.
  44191. @param name the label to use for the drop-down list
  44192. @param items the list of items to show in it
  44193. @param onScreenLabel if this is non-empty, it will be displayed next to the
  44194. combo-box to label it.
  44195. @see getComboBoxComponent
  44196. */
  44197. void addComboBox (const String& name,
  44198. const StringArray& items,
  44199. const String& onScreenLabel = String::empty);
  44200. /** Returns a drop-down list that was added to the AlertWindow.
  44201. @param nameOfList the name that was passed into the addComboBox() method
  44202. when creating the drop-down
  44203. @returns the ComboBox component, or 0 if none was found for the given name.
  44204. */
  44205. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  44206. /** Adds a block of text.
  44207. This is handy for adding a multi-line note next to a textbox or combo-box,
  44208. to provide more details about what's going on.
  44209. */
  44210. void addTextBlock (const String& text);
  44211. /** Adds a progress-bar to the window.
  44212. @param progressValue a variable that will be repeatedly checked while the
  44213. dialog box is visible, to see how far the process has
  44214. got. The value should be in the range 0 to 1.0
  44215. */
  44216. void addProgressBarComponent (double& progressValue);
  44217. /** Adds a user-defined component to the dialog box.
  44218. @param component the component to add - its size should be set up correctly
  44219. before it is passed in. The caller is responsible for deleting
  44220. the component later on - the AlertWindow won't delete it.
  44221. */
  44222. void addCustomComponent (Component* component);
  44223. /** Returns the number of custom components in the dialog box.
  44224. @see getCustomComponent, addCustomComponent
  44225. */
  44226. int getNumCustomComponents() const;
  44227. /** Returns one of the custom components in the dialog box.
  44228. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  44229. will return 0
  44230. @see getNumCustomComponents, addCustomComponent
  44231. */
  44232. Component* getCustomComponent (int index) const;
  44233. /** Removes one of the custom components in the dialog box.
  44234. Note that this won't delete it, it just removes the component from the window
  44235. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  44236. will return 0
  44237. @returns the component that was removed (or zero)
  44238. @see getNumCustomComponents, addCustomComponent
  44239. */
  44240. Component* removeCustomComponent (int index);
  44241. /** Returns true if the window contains any components other than just buttons.*/
  44242. bool containsAnyExtraComponents() const;
  44243. // easy-to-use message box functions:
  44244. /** Shows a dialog box that just has a message and a single button to get rid of it.
  44245. The box is shown modally, and the method returns after the user
  44246. has clicked the button (or pressed the escape or return keys).
  44247. @param iconType the type of icon to show
  44248. @param title the headline to show at the top of the box
  44249. @param message a longer, more descriptive message to show underneath the
  44250. headline
  44251. @param buttonText the text to show in the button - if this string is empty, the
  44252. default string "ok" (or a localised version) will be used.
  44253. @param associatedComponent if this is non-zero, it specifies the component that the
  44254. alert window should be associated with. Depending on the look
  44255. and feel, this might be used for positioning of the alert window.
  44256. */
  44257. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  44258. const String& title,
  44259. const String& message,
  44260. const String& buttonText = String::empty,
  44261. Component* associatedComponent = 0);
  44262. /** Shows a dialog box with two buttons.
  44263. Ideal for ok/cancel or yes/no choices. The return key can also be used
  44264. to trigger the first button, and the escape key for the second button.
  44265. @param iconType the type of icon to show
  44266. @param title the headline to show at the top of the box
  44267. @param message a longer, more descriptive message to show underneath the
  44268. headline
  44269. @param button1Text the text to show in the first button - if this string is
  44270. empty, the default string "ok" (or a localised version of it)
  44271. will be used.
  44272. @param button2Text the text to show in the second button - if this string is
  44273. empty, the default string "cancel" (or a localised version of it)
  44274. will be used.
  44275. @param associatedComponent if this is non-zero, it specifies the component that the
  44276. alert window should be associated with. Depending on the look
  44277. and feel, this might be used for positioning of the alert window.
  44278. @returns true if button 1 was clicked, false if it was button 2
  44279. */
  44280. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  44281. const String& title,
  44282. const String& message,
  44283. const String& button1Text = String::empty,
  44284. const String& button2Text = String::empty,
  44285. Component* associatedComponent = 0);
  44286. /** Shows a dialog box with three buttons.
  44287. Ideal for yes/no/cancel boxes.
  44288. The escape key can be used to trigger the third button.
  44289. @param iconType the type of icon to show
  44290. @param title the headline to show at the top of the box
  44291. @param message a longer, more descriptive message to show underneath the
  44292. headline
  44293. @param button1Text the text to show in the first button - if an empty string, then
  44294. "yes" will be used (or a localised version of it)
  44295. @param button2Text the text to show in the first button - if an empty string, then
  44296. "no" will be used (or a localised version of it)
  44297. @param button3Text the text to show in the first button - if an empty string, then
  44298. "cancel" will be used (or a localised version of it)
  44299. @param associatedComponent if this is non-zero, it specifies the component that the
  44300. alert window should be associated with. Depending on the look
  44301. and feel, this might be used for positioning of the alert window.
  44302. @returns one of the following values:
  44303. - 0 if the third button was pressed (normally used for 'cancel')
  44304. - 1 if the first button was pressed (normally used for 'yes')
  44305. - 2 if the middle button was pressed (normally used for 'no')
  44306. */
  44307. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  44308. const String& title,
  44309. const String& message,
  44310. const String& button1Text = String::empty,
  44311. const String& button2Text = String::empty,
  44312. const String& button3Text = String::empty,
  44313. Component* associatedComponent = 0);
  44314. /** Shows an operating-system native dialog box.
  44315. @param title the title to use at the top
  44316. @param bodyText the longer message to show
  44317. @param isOkCancel if true, this will show an ok/cancel box, if false,
  44318. it'll show a box with just an ok button
  44319. @returns true if the ok button was pressed, false if they pressed cancel.
  44320. */
  44321. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  44322. const String& bodyText,
  44323. bool isOkCancel);
  44324. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  44325. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  44326. methods.
  44327. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  44328. */
  44329. enum ColourIds
  44330. {
  44331. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  44332. textColourId = 0x1001810, /**< The colour for the text. */
  44333. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  44334. };
  44335. protected:
  44336. /** @internal */
  44337. void paint (Graphics& g);
  44338. /** @internal */
  44339. void mouseDown (const MouseEvent& e);
  44340. /** @internal */
  44341. void mouseDrag (const MouseEvent& e);
  44342. /** @internal */
  44343. bool keyPressed (const KeyPress& key);
  44344. /** @internal */
  44345. void buttonClicked (Button* button);
  44346. /** @internal */
  44347. void lookAndFeelChanged();
  44348. /** @internal */
  44349. void userTriedToCloseWindow();
  44350. /** @internal */
  44351. int getDesktopWindowStyleFlags() const;
  44352. private:
  44353. String text;
  44354. TextLayout textLayout;
  44355. AlertIconType alertIconType;
  44356. ComponentBoundsConstrainer constrainer;
  44357. ComponentDragger dragger;
  44358. Rectangle<int> textArea;
  44359. OwnedArray<TextButton> buttons;
  44360. OwnedArray<TextEditor> textBoxes;
  44361. OwnedArray<ComboBox> comboBoxes;
  44362. OwnedArray<ProgressBar> progressBars;
  44363. Array<Component*> customComps;
  44364. OwnedArray<Component> textBlocks;
  44365. Array<Component*> allComps;
  44366. StringArray textboxNames, comboBoxNames;
  44367. Font font;
  44368. Component* associatedComponent;
  44369. void updateLayout (bool onlyIncreaseSize);
  44370. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AlertWindow);
  44371. };
  44372. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  44373. /*** End of inlined file: juce_AlertWindow.h ***/
  44374. class ToggleButton;
  44375. class TextButton;
  44376. class AlertWindow;
  44377. class TextLayout;
  44378. class ScrollBar;
  44379. class BubbleComponent;
  44380. class ComboBox;
  44381. class Button;
  44382. class FilenameComponent;
  44383. class DocumentWindow;
  44384. class ResizableWindow;
  44385. class GroupComponent;
  44386. class MenuBarComponent;
  44387. class DropShadower;
  44388. class GlyphArrangement;
  44389. class PropertyComponent;
  44390. class TableHeaderComponent;
  44391. class Toolbar;
  44392. class ToolbarItemComponent;
  44393. class PopupMenu;
  44394. class ProgressBar;
  44395. class FileBrowserComponent;
  44396. class DirectoryContentsDisplayComponent;
  44397. class FilePreviewComponent;
  44398. class ImageButton;
  44399. class CallOutBox;
  44400. class Drawable;
  44401. /**
  44402. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  44403. can be used to apply different 'skins' to the application.
  44404. */
  44405. class JUCE_API LookAndFeel
  44406. {
  44407. public:
  44408. /** Creates the default JUCE look and feel. */
  44409. LookAndFeel();
  44410. /** Destructor. */
  44411. virtual ~LookAndFeel();
  44412. /** Returns the current default look-and-feel for a component to use when it
  44413. hasn't got one explicitly set.
  44414. @see setDefaultLookAndFeel
  44415. */
  44416. static LookAndFeel& getDefaultLookAndFeel() throw();
  44417. /** Changes the default look-and-feel.
  44418. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  44419. set to 0, it will revert to using the default one. The
  44420. object passed-in must be deleted by the caller when
  44421. it's no longer needed.
  44422. @see getDefaultLookAndFeel
  44423. */
  44424. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  44425. /** Looks for a colour that has been registered with the given colour ID number.
  44426. If a colour has been set for this ID number using setColour(), then it is
  44427. returned. If none has been set, it will just return Colours::black.
  44428. The colour IDs for various purposes are stored as enums in the components that
  44429. they are relevent to - for an example, see Slider::ColourIds,
  44430. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  44431. If you're looking up a colour for use in drawing a component, it's usually
  44432. best not to call this directly, but to use the Component::findColour() method
  44433. instead. That will first check whether a suitable colour has been registered
  44434. directly with the component, and will fall-back on calling the component's
  44435. LookAndFeel's findColour() method if none is found.
  44436. @see setColour, Component::findColour, Component::setColour
  44437. */
  44438. const Colour findColour (int colourId) const throw();
  44439. /** Registers a colour to be used for a particular purpose.
  44440. For more details, see the comments for findColour().
  44441. @see findColour, Component::findColour, Component::setColour
  44442. */
  44443. void setColour (int colourId, const Colour& colour) throw();
  44444. /** Returns true if the specified colour ID has been explicitly set using the
  44445. setColour() method.
  44446. */
  44447. bool isColourSpecified (int colourId) const throw();
  44448. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  44449. /** Allows you to change the default sans-serif font.
  44450. If you need to supply your own Typeface object for any of the default fonts, rather
  44451. than just supplying the name (e.g. if you want to use an embedded font), then
  44452. you should instead override getTypefaceForFont() to create and return the typeface.
  44453. */
  44454. void setDefaultSansSerifTypefaceName (const String& newName);
  44455. /** Override this to get the chance to swap a component's mouse cursor for a
  44456. customised one.
  44457. */
  44458. virtual const MouseCursor getMouseCursorFor (Component& component);
  44459. /** Draws the lozenge-shaped background for a standard button. */
  44460. virtual void drawButtonBackground (Graphics& g,
  44461. Button& button,
  44462. const Colour& backgroundColour,
  44463. bool isMouseOverButton,
  44464. bool isButtonDown);
  44465. virtual const Font getFontForTextButton (TextButton& button);
  44466. /** Draws the text for a TextButton. */
  44467. virtual void drawButtonText (Graphics& g,
  44468. TextButton& button,
  44469. bool isMouseOverButton,
  44470. bool isButtonDown);
  44471. /** Draws the contents of a standard ToggleButton. */
  44472. virtual void drawToggleButton (Graphics& g,
  44473. ToggleButton& button,
  44474. bool isMouseOverButton,
  44475. bool isButtonDown);
  44476. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  44477. virtual void drawTickBox (Graphics& g,
  44478. Component& component,
  44479. float x, float y, float w, float h,
  44480. bool ticked,
  44481. bool isEnabled,
  44482. bool isMouseOverButton,
  44483. bool isButtonDown);
  44484. /* AlertWindow handling..
  44485. */
  44486. virtual AlertWindow* createAlertWindow (const String& title,
  44487. const String& message,
  44488. const String& button1,
  44489. const String& button2,
  44490. const String& button3,
  44491. AlertWindow::AlertIconType iconType,
  44492. int numButtons,
  44493. Component* associatedComponent);
  44494. virtual void drawAlertBox (Graphics& g,
  44495. AlertWindow& alert,
  44496. const Rectangle<int>& textArea,
  44497. TextLayout& textLayout);
  44498. virtual int getAlertBoxWindowFlags();
  44499. virtual int getAlertWindowButtonHeight();
  44500. virtual const Font getAlertWindowMessageFont();
  44501. virtual const Font getAlertWindowFont();
  44502. /** Draws a progress bar.
  44503. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  44504. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  44505. isn't known). It can use the current time as a basis for playing an animation.
  44506. (Used by progress bars in AlertWindow).
  44507. */
  44508. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  44509. int width, int height,
  44510. double progress, const String& textToShow);
  44511. // Draws a small image that spins to indicate that something's happening..
  44512. // This method should use the current time to animate itself, so just keep
  44513. // repainting it every so often.
  44514. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  44515. int x, int y, int w, int h);
  44516. /** Draws one of the buttons on a scrollbar.
  44517. @param g the context to draw into
  44518. @param scrollbar the bar itself
  44519. @param width the width of the button
  44520. @param height the height of the button
  44521. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  44522. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  44523. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  44524. @param isButtonDown whether the mouse button's held down
  44525. */
  44526. virtual void drawScrollbarButton (Graphics& g,
  44527. ScrollBar& scrollbar,
  44528. int width, int height,
  44529. int buttonDirection,
  44530. bool isScrollbarVertical,
  44531. bool isMouseOverButton,
  44532. bool isButtonDown);
  44533. /** Draws the thumb area of a scrollbar.
  44534. @param g the context to draw into
  44535. @param scrollbar the bar itself
  44536. @param x the x position of the left edge of the thumb area to draw in
  44537. @param y the y position of the top edge of the thumb area to draw in
  44538. @param width the width of the thumb area to draw in
  44539. @param height the height of the thumb area to draw in
  44540. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  44541. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  44542. thumb, or its x position for horizontal bars
  44543. @param thumbSize for vertical bars, the height of the thumb, or its width for
  44544. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  44545. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  44546. currently dragging the thumb
  44547. @param isMouseDown whether the mouse is currently dragging the scrollbar
  44548. */
  44549. virtual void drawScrollbar (Graphics& g,
  44550. ScrollBar& scrollbar,
  44551. int x, int y,
  44552. int width, int height,
  44553. bool isScrollbarVertical,
  44554. int thumbStartPosition,
  44555. int thumbSize,
  44556. bool isMouseOver,
  44557. bool isMouseDown);
  44558. /** Returns the component effect to use for a scrollbar */
  44559. virtual ImageEffectFilter* getScrollbarEffect();
  44560. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  44561. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  44562. /** Returns the default thickness to use for a scrollbar. */
  44563. virtual int getDefaultScrollbarWidth();
  44564. /** Returns the length in pixels to use for a scrollbar button. */
  44565. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  44566. /** Returns a tick shape for use in yes/no boxes, etc. */
  44567. virtual const Path getTickShape (float height);
  44568. /** Returns a cross shape for use in yes/no boxes, etc. */
  44569. virtual const Path getCrossShape (float height);
  44570. /** Draws the + or - box in a treeview. */
  44571. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  44572. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  44573. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  44574. // These return a pointer to an internally cached drawable - make sure you don't keep
  44575. // a copy of this pointer anywhere, as it may become invalid in the future.
  44576. virtual const Drawable* getDefaultFolderImage();
  44577. virtual const Drawable* getDefaultDocumentFileImage();
  44578. virtual void createFileChooserHeaderText (const String& title,
  44579. const String& instructions,
  44580. GlyphArrangement& destArrangement,
  44581. int width);
  44582. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  44583. const String& filename, Image* icon,
  44584. const String& fileSizeDescription,
  44585. const String& fileTimeDescription,
  44586. bool isDirectory,
  44587. bool isItemSelected,
  44588. int itemIndex,
  44589. DirectoryContentsDisplayComponent& component);
  44590. virtual Button* createFileBrowserGoUpButton();
  44591. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  44592. DirectoryContentsDisplayComponent* fileListComponent,
  44593. FilePreviewComponent* previewComp,
  44594. ComboBox* currentPathBox,
  44595. TextEditor* filenameBox,
  44596. Button* goUpButton);
  44597. virtual void drawBubble (Graphics& g,
  44598. float tipX, float tipY,
  44599. float boxX, float boxY, float boxW, float boxH);
  44600. /** Fills the background of a popup menu component. */
  44601. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  44602. /** Draws one of the items in a popup menu. */
  44603. virtual void drawPopupMenuItem (Graphics& g,
  44604. int width, int height,
  44605. bool isSeparator,
  44606. bool isActive,
  44607. bool isHighlighted,
  44608. bool isTicked,
  44609. bool hasSubMenu,
  44610. const String& text,
  44611. const String& shortcutKeyText,
  44612. Image* image,
  44613. const Colour* const textColour);
  44614. /** Returns the size and style of font to use in popup menus. */
  44615. virtual const Font getPopupMenuFont();
  44616. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  44617. int width, int height,
  44618. bool isScrollUpArrow);
  44619. /** Finds the best size for an item in a popup menu. */
  44620. virtual void getIdealPopupMenuItemSize (const String& text,
  44621. bool isSeparator,
  44622. int standardMenuItemHeight,
  44623. int& idealWidth,
  44624. int& idealHeight);
  44625. virtual int getMenuWindowFlags();
  44626. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  44627. bool isMouseOverBar,
  44628. MenuBarComponent& menuBar);
  44629. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  44630. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  44631. virtual void drawMenuBarItem (Graphics& g,
  44632. int width, int height,
  44633. int itemIndex,
  44634. const String& itemText,
  44635. bool isMouseOverItem,
  44636. bool isMenuOpen,
  44637. bool isMouseOverBar,
  44638. MenuBarComponent& menuBar);
  44639. virtual void drawComboBox (Graphics& g, int width, int height,
  44640. bool isButtonDown,
  44641. int buttonX, int buttonY,
  44642. int buttonW, int buttonH,
  44643. ComboBox& box);
  44644. virtual const Font getComboBoxFont (ComboBox& box);
  44645. virtual Label* createComboBoxTextBox (ComboBox& box);
  44646. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  44647. virtual void drawLabel (Graphics& g, Label& label);
  44648. virtual void drawLinearSlider (Graphics& g,
  44649. int x, int y,
  44650. int width, int height,
  44651. float sliderPos,
  44652. float minSliderPos,
  44653. float maxSliderPos,
  44654. const Slider::SliderStyle style,
  44655. Slider& slider);
  44656. virtual void drawLinearSliderBackground (Graphics& g,
  44657. int x, int y,
  44658. int width, int height,
  44659. float sliderPos,
  44660. float minSliderPos,
  44661. float maxSliderPos,
  44662. const Slider::SliderStyle style,
  44663. Slider& slider);
  44664. virtual void drawLinearSliderThumb (Graphics& g,
  44665. int x, int y,
  44666. int width, int height,
  44667. float sliderPos,
  44668. float minSliderPos,
  44669. float maxSliderPos,
  44670. const Slider::SliderStyle style,
  44671. Slider& slider);
  44672. virtual int getSliderThumbRadius (Slider& slider);
  44673. virtual void drawRotarySlider (Graphics& g,
  44674. int x, int y,
  44675. int width, int height,
  44676. float sliderPosProportional,
  44677. float rotaryStartAngle,
  44678. float rotaryEndAngle,
  44679. Slider& slider);
  44680. virtual Button* createSliderButton (bool isIncrement);
  44681. virtual Label* createSliderTextBox (Slider& slider);
  44682. virtual ImageEffectFilter* getSliderEffect();
  44683. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  44684. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  44685. virtual Button* createFilenameComponentBrowseButton (const String& text);
  44686. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  44687. ComboBox* filenameBox, Button* browseButton);
  44688. virtual void drawCornerResizer (Graphics& g,
  44689. int w, int h,
  44690. bool isMouseOver,
  44691. bool isMouseDragging);
  44692. virtual void drawResizableFrame (Graphics& g,
  44693. int w, int h,
  44694. const BorderSize<int>& borders);
  44695. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  44696. const BorderSize<int>& border,
  44697. ResizableWindow& window);
  44698. virtual void drawResizableWindowBorder (Graphics& g,
  44699. int w, int h,
  44700. const BorderSize<int>& border,
  44701. ResizableWindow& window);
  44702. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  44703. Graphics& g, int w, int h,
  44704. int titleSpaceX, int titleSpaceW,
  44705. const Image* icon,
  44706. bool drawTitleTextOnLeft);
  44707. virtual Button* createDocumentWindowButton (int buttonType);
  44708. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  44709. int titleBarX, int titleBarY,
  44710. int titleBarW, int titleBarH,
  44711. Button* minimiseButton,
  44712. Button* maximiseButton,
  44713. Button* closeButton,
  44714. bool positionTitleBarButtonsOnLeft);
  44715. virtual int getDefaultMenuBarHeight();
  44716. virtual DropShadower* createDropShadowerForComponent (Component* component);
  44717. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  44718. int w, int h,
  44719. bool isVerticalBar,
  44720. bool isMouseOver,
  44721. bool isMouseDragging);
  44722. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  44723. const String& text,
  44724. const Justification& position,
  44725. GroupComponent& group);
  44726. virtual void createTabButtonShape (Path& p,
  44727. int width, int height,
  44728. int tabIndex,
  44729. const String& text,
  44730. Button& button,
  44731. TabbedButtonBar::Orientation orientation,
  44732. bool isMouseOver,
  44733. bool isMouseDown,
  44734. bool isFrontTab);
  44735. virtual void fillTabButtonShape (Graphics& g,
  44736. const Path& path,
  44737. const Colour& preferredBackgroundColour,
  44738. int tabIndex,
  44739. const String& text,
  44740. Button& button,
  44741. TabbedButtonBar::Orientation orientation,
  44742. bool isMouseOver,
  44743. bool isMouseDown,
  44744. bool isFrontTab);
  44745. virtual void drawTabButtonText (Graphics& g,
  44746. int x, int y, int w, int h,
  44747. const Colour& preferredBackgroundColour,
  44748. int tabIndex,
  44749. const String& text,
  44750. Button& button,
  44751. TabbedButtonBar::Orientation orientation,
  44752. bool isMouseOver,
  44753. bool isMouseDown,
  44754. bool isFrontTab);
  44755. virtual int getTabButtonOverlap (int tabDepth);
  44756. virtual int getTabButtonSpaceAroundImage();
  44757. virtual int getTabButtonBestWidth (int tabIndex,
  44758. const String& text,
  44759. int tabDepth,
  44760. Button& button);
  44761. virtual void drawTabButton (Graphics& g,
  44762. int w, int h,
  44763. const Colour& preferredColour,
  44764. int tabIndex,
  44765. const String& text,
  44766. Button& button,
  44767. TabbedButtonBar::Orientation orientation,
  44768. bool isMouseOver,
  44769. bool isMouseDown,
  44770. bool isFrontTab);
  44771. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  44772. int w, int h,
  44773. TabbedButtonBar& tabBar,
  44774. TabbedButtonBar::Orientation orientation);
  44775. virtual Button* createTabBarExtrasButton();
  44776. virtual void drawImageButton (Graphics& g, Image* image,
  44777. int imageX, int imageY, int imageW, int imageH,
  44778. const Colour& overlayColour,
  44779. float imageOpacity,
  44780. ImageButton& button);
  44781. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  44782. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  44783. int width, int height,
  44784. bool isMouseOver, bool isMouseDown,
  44785. int columnFlags);
  44786. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  44787. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  44788. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  44789. bool isMouseOver, bool isMouseDown,
  44790. ToolbarItemComponent& component);
  44791. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  44792. const String& text, ToolbarItemComponent& component);
  44793. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  44794. bool isOpen, int width, int height);
  44795. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  44796. PropertyComponent& component);
  44797. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  44798. PropertyComponent& component);
  44799. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  44800. void drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path);
  44801. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  44802. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  44803. /**
  44804. */
  44805. virtual void playAlertSound();
  44806. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  44807. static void drawGlassSphere (Graphics& g,
  44808. float x, float y,
  44809. float diameter,
  44810. const Colour& colour,
  44811. float outlineThickness) throw();
  44812. static void drawGlassPointer (Graphics& g,
  44813. float x, float y,
  44814. float diameter,
  44815. const Colour& colour, float outlineThickness,
  44816. int direction) throw();
  44817. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  44818. static void drawGlassLozenge (Graphics& g,
  44819. float x, float y,
  44820. float width, float height,
  44821. const Colour& colour,
  44822. float outlineThickness,
  44823. float cornerSize,
  44824. bool flatOnLeft, bool flatOnRight,
  44825. bool flatOnTop, bool flatOnBottom) throw();
  44826. static Drawable* loadDrawableFromData (const void* data, size_t numBytes);
  44827. private:
  44828. friend JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  44829. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  44830. Array <int> colourIds;
  44831. Array <Colour> colours;
  44832. // default typeface names
  44833. String defaultSans, defaultSerif, defaultFixed;
  44834. ScopedPointer<Drawable> folderImage, documentImage;
  44835. void drawShinyButtonShape (Graphics& g,
  44836. float x, float y, float w, float h, float maxCornerSize,
  44837. const Colour& baseColour,
  44838. float strokeWidth,
  44839. bool flatOnLeft,
  44840. bool flatOnRight,
  44841. bool flatOnTop,
  44842. bool flatOnBottom) throw();
  44843. // This has been deprecated - see the new parameter list..
  44844. virtual int drawFileBrowserRow (Graphics&, int, int, const String&, Image*, const String&, const String&, bool, bool, int) { return 0; }
  44845. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LookAndFeel);
  44846. };
  44847. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  44848. /*** End of inlined file: juce_LookAndFeel.h ***/
  44849. #endif
  44850. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  44851. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  44852. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  44853. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  44854. /**
  44855. The original Juce look-and-feel.
  44856. */
  44857. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  44858. {
  44859. public:
  44860. /** Creates the default JUCE look and feel. */
  44861. OldSchoolLookAndFeel();
  44862. /** Destructor. */
  44863. virtual ~OldSchoolLookAndFeel();
  44864. /** Draws the lozenge-shaped background for a standard button. */
  44865. virtual void drawButtonBackground (Graphics& g,
  44866. Button& button,
  44867. const Colour& backgroundColour,
  44868. bool isMouseOverButton,
  44869. bool isButtonDown);
  44870. /** Draws the contents of a standard ToggleButton. */
  44871. virtual void drawToggleButton (Graphics& g,
  44872. ToggleButton& button,
  44873. bool isMouseOverButton,
  44874. bool isButtonDown);
  44875. virtual void drawTickBox (Graphics& g,
  44876. Component& component,
  44877. float x, float y, float w, float h,
  44878. bool ticked,
  44879. bool isEnabled,
  44880. bool isMouseOverButton,
  44881. bool isButtonDown);
  44882. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  44883. int width, int height,
  44884. double progress, const String& textToShow);
  44885. virtual void drawScrollbarButton (Graphics& g,
  44886. ScrollBar& scrollbar,
  44887. int width, int height,
  44888. int buttonDirection,
  44889. bool isScrollbarVertical,
  44890. bool isMouseOverButton,
  44891. bool isButtonDown);
  44892. virtual void drawScrollbar (Graphics& g,
  44893. ScrollBar& scrollbar,
  44894. int x, int y,
  44895. int width, int height,
  44896. bool isScrollbarVertical,
  44897. int thumbStartPosition,
  44898. int thumbSize,
  44899. bool isMouseOver,
  44900. bool isMouseDown);
  44901. virtual ImageEffectFilter* getScrollbarEffect();
  44902. virtual void drawTextEditorOutline (Graphics& g,
  44903. int width, int height,
  44904. TextEditor& textEditor);
  44905. /** Fills the background of a popup menu component. */
  44906. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  44907. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  44908. bool isMouseOverBar,
  44909. MenuBarComponent& menuBar);
  44910. virtual void drawComboBox (Graphics& g, int width, int height,
  44911. bool isButtonDown,
  44912. int buttonX, int buttonY,
  44913. int buttonW, int buttonH,
  44914. ComboBox& box);
  44915. virtual const Font getComboBoxFont (ComboBox& box);
  44916. virtual void drawLinearSlider (Graphics& g,
  44917. int x, int y,
  44918. int width, int height,
  44919. float sliderPos,
  44920. float minSliderPos,
  44921. float maxSliderPos,
  44922. const Slider::SliderStyle style,
  44923. Slider& slider);
  44924. virtual int getSliderThumbRadius (Slider& slider);
  44925. virtual Button* createSliderButton (bool isIncrement);
  44926. virtual ImageEffectFilter* getSliderEffect();
  44927. virtual void drawCornerResizer (Graphics& g,
  44928. int w, int h,
  44929. bool isMouseOver,
  44930. bool isMouseDragging);
  44931. virtual Button* createDocumentWindowButton (int buttonType);
  44932. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  44933. int titleBarX, int titleBarY,
  44934. int titleBarW, int titleBarH,
  44935. Button* minimiseButton,
  44936. Button* maximiseButton,
  44937. Button* closeButton,
  44938. bool positionTitleBarButtonsOnLeft);
  44939. private:
  44940. DropShadowEffect scrollbarShadow;
  44941. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OldSchoolLookAndFeel);
  44942. };
  44943. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  44944. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  44945. #endif
  44946. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  44947. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  44948. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  44949. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  44950. /**
  44951. A menu bar component.
  44952. @see MenuBarModel
  44953. */
  44954. class JUCE_API MenuBarComponent : public Component,
  44955. private MenuBarModel::Listener,
  44956. private Timer
  44957. {
  44958. public:
  44959. /** Creates a menu bar.
  44960. @param model the model object to use to control this bar. You can
  44961. pass 0 into this if you like, and set the model later
  44962. using the setModel() method
  44963. */
  44964. MenuBarComponent (MenuBarModel* model);
  44965. /** Destructor. */
  44966. ~MenuBarComponent();
  44967. /** Changes the model object to use to control the bar.
  44968. This can be 0, in which case the bar will be empty. Don't delete the object
  44969. that is passed-in while it's still being used by this MenuBar.
  44970. */
  44971. void setModel (MenuBarModel* newModel);
  44972. /** Returns the current menu bar model being used.
  44973. */
  44974. MenuBarModel* getModel() const throw();
  44975. /** Pops up one of the menu items.
  44976. This lets you manually open one of the menus - it could be triggered by a
  44977. key shortcut, for example.
  44978. */
  44979. void showMenu (int menuIndex);
  44980. /** @internal */
  44981. void paint (Graphics& g);
  44982. /** @internal */
  44983. void resized();
  44984. /** @internal */
  44985. void mouseEnter (const MouseEvent& e);
  44986. /** @internal */
  44987. void mouseExit (const MouseEvent& e);
  44988. /** @internal */
  44989. void mouseDown (const MouseEvent& e);
  44990. /** @internal */
  44991. void mouseDrag (const MouseEvent& e);
  44992. /** @internal */
  44993. void mouseUp (const MouseEvent& e);
  44994. /** @internal */
  44995. void mouseMove (const MouseEvent& e);
  44996. /** @internal */
  44997. void handleCommandMessage (int commandId);
  44998. /** @internal */
  44999. bool keyPressed (const KeyPress& key);
  45000. /** @internal */
  45001. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  45002. /** @internal */
  45003. void menuCommandInvoked (MenuBarModel* menuBarModel,
  45004. const ApplicationCommandTarget::InvocationInfo& info);
  45005. private:
  45006. class AsyncCallback;
  45007. friend class AsyncCallback;
  45008. MenuBarModel* model;
  45009. StringArray menuNames;
  45010. Array <int> xPositions;
  45011. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked;
  45012. int lastMouseX, lastMouseY;
  45013. int getItemAt (int x, int y);
  45014. void setItemUnderMouse (int index);
  45015. void setOpenItem (int index);
  45016. void updateItemUnderMouse (int x, int y);
  45017. void timerCallback();
  45018. void repaintMenuItem (int index);
  45019. void menuDismissed (int topLevelIndex, int itemId);
  45020. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MenuBarComponent);
  45021. };
  45022. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  45023. /*** End of inlined file: juce_MenuBarComponent.h ***/
  45024. #endif
  45025. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  45026. #endif
  45027. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  45028. #endif
  45029. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  45030. #endif
  45031. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  45032. #endif
  45033. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  45034. #endif
  45035. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  45036. #endif
  45037. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  45038. /*** Start of inlined file: juce_LassoComponent.h ***/
  45039. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  45040. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  45041. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  45042. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  45043. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  45044. /** Manages a list of selectable items.
  45045. Use one of these to keep a track of things that the user has highlighted, like
  45046. icons or things in a list.
  45047. The class is templated so that you can use it to hold either a set of pointers
  45048. to objects, or a set of ID numbers or handles, for cases where each item may
  45049. not always have a corresponding object.
  45050. To be informed when items are selected/deselected, register a ChangeListener with
  45051. this object.
  45052. @see SelectableObject
  45053. */
  45054. template <class SelectableItemType>
  45055. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  45056. {
  45057. public:
  45058. typedef SelectableItemType ItemType;
  45059. typedef PARAMETER_TYPE (SelectableItemType) ParameterType;
  45060. /** Creates an empty set. */
  45061. SelectedItemSet()
  45062. {
  45063. }
  45064. /** Creates a set based on an array of items. */
  45065. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  45066. : selectedItems (items)
  45067. {
  45068. }
  45069. /** Creates a copy of another set. */
  45070. SelectedItemSet (const SelectedItemSet& other)
  45071. : selectedItems (other.selectedItems)
  45072. {
  45073. }
  45074. /** Creates a copy of another set. */
  45075. SelectedItemSet& operator= (const SelectedItemSet& other)
  45076. {
  45077. if (selectedItems != other.selectedItems)
  45078. {
  45079. selectedItems = other.selectedItems;
  45080. changed();
  45081. }
  45082. return *this;
  45083. }
  45084. /** Clears any other currently selected items, and selects this item.
  45085. If this item is already the only thing selected, no change notification
  45086. will be sent out.
  45087. @see addToSelection, addToSelectionBasedOnModifiers
  45088. */
  45089. void selectOnly (ParameterType item)
  45090. {
  45091. if (isSelected (item))
  45092. {
  45093. for (int i = selectedItems.size(); --i >= 0;)
  45094. {
  45095. if (selectedItems.getUnchecked(i) != item)
  45096. {
  45097. deselect (selectedItems.getUnchecked(i));
  45098. i = jmin (i, selectedItems.size());
  45099. }
  45100. }
  45101. }
  45102. else
  45103. {
  45104. deselectAll();
  45105. changed();
  45106. selectedItems.add (item);
  45107. itemSelected (item);
  45108. }
  45109. }
  45110. /** Selects an item.
  45111. If the item is already selected, no change notification will be sent out.
  45112. @see selectOnly, addToSelectionBasedOnModifiers
  45113. */
  45114. void addToSelection (ParameterType item)
  45115. {
  45116. if (! isSelected (item))
  45117. {
  45118. changed();
  45119. selectedItems.add (item);
  45120. itemSelected (item);
  45121. }
  45122. }
  45123. /** Selects or deselects an item.
  45124. This will use the modifier keys to decide whether to deselect other items
  45125. first.
  45126. So if the shift key is held down, the item will be added without deselecting
  45127. anything (same as calling addToSelection() )
  45128. If no modifiers are down, the current selection will be cleared first (same
  45129. as calling selectOnly() )
  45130. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  45131. so it'll be added to the set unless it's already there, in which case it'll be
  45132. deselected.
  45133. If the items that you're selecting can also be dragged, you may need to use the
  45134. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  45135. subtleties of this kind of usage.
  45136. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  45137. */
  45138. void addToSelectionBasedOnModifiers (ParameterType item,
  45139. const ModifierKeys& modifiers)
  45140. {
  45141. if (modifiers.isShiftDown())
  45142. {
  45143. addToSelection (item);
  45144. }
  45145. else if (modifiers.isCommandDown())
  45146. {
  45147. if (isSelected (item))
  45148. deselect (item);
  45149. else
  45150. addToSelection (item);
  45151. }
  45152. else
  45153. {
  45154. selectOnly (item);
  45155. }
  45156. }
  45157. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  45158. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  45159. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  45160. makes it easy to handle multiple-selection of sets of objects that can also
  45161. be dragged.
  45162. For example, if you have several items already selected, and you click on
  45163. one of them (without dragging), then you'd expect this to deselect the other, and
  45164. just select the item you clicked on. But if you had clicked on this item and
  45165. dragged it, you'd have expected them all to stay selected.
  45166. When you call this method, you'll need to store the boolean result, because the
  45167. addToSelectionOnMouseUp() method will need to be know this value.
  45168. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  45169. */
  45170. bool addToSelectionOnMouseDown (ParameterType item,
  45171. const ModifierKeys& modifiers)
  45172. {
  45173. if (isSelected (item))
  45174. {
  45175. return ! modifiers.isPopupMenu();
  45176. }
  45177. else
  45178. {
  45179. addToSelectionBasedOnModifiers (item, modifiers);
  45180. return false;
  45181. }
  45182. }
  45183. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  45184. Call this during a mouseUp callback, when you have previously called the
  45185. addToSelectionOnMouseDown() method during your mouseDown event.
  45186. See addToSelectionOnMouseDown() for more info
  45187. @param item the item to select (or deselect)
  45188. @param modifiers the modifiers from the mouse-up event
  45189. @param wasItemDragged true if your item was dragged during the mouse click
  45190. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  45191. back from the addToSelectionOnMouseDown() call that you
  45192. should have made during the matching mouseDown event
  45193. */
  45194. void addToSelectionOnMouseUp (ParameterType item,
  45195. const ModifierKeys& modifiers,
  45196. const bool wasItemDragged,
  45197. const bool resultOfMouseDownSelectMethod)
  45198. {
  45199. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  45200. addToSelectionBasedOnModifiers (item, modifiers);
  45201. }
  45202. /** Deselects an item. */
  45203. void deselect (ParameterType item)
  45204. {
  45205. const int i = selectedItems.indexOf (item);
  45206. if (i >= 0)
  45207. {
  45208. changed();
  45209. itemDeselected (selectedItems.remove (i));
  45210. }
  45211. }
  45212. /** Deselects all items. */
  45213. void deselectAll()
  45214. {
  45215. if (selectedItems.size() > 0)
  45216. {
  45217. changed();
  45218. for (int i = selectedItems.size(); --i >= 0;)
  45219. {
  45220. itemDeselected (selectedItems.remove (i));
  45221. i = jmin (i, selectedItems.size());
  45222. }
  45223. }
  45224. }
  45225. /** Returns the number of currently selected items.
  45226. @see getSelectedItem
  45227. */
  45228. int getNumSelected() const throw()
  45229. {
  45230. return selectedItems.size();
  45231. }
  45232. /** Returns one of the currently selected items.
  45233. Returns 0 if the index is out-of-range.
  45234. @see getNumSelected
  45235. */
  45236. SelectableItemType getSelectedItem (const int index) const throw()
  45237. {
  45238. return selectedItems [index];
  45239. }
  45240. /** True if this item is currently selected. */
  45241. bool isSelected (ParameterType item) const throw()
  45242. {
  45243. return selectedItems.contains (item);
  45244. }
  45245. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  45246. /** Can be overridden to do special handling when an item is selected.
  45247. For example, if the item is an object, you might want to call it and tell
  45248. it that it's being selected.
  45249. */
  45250. virtual void itemSelected (SelectableItemType item) { (void) item; }
  45251. /** Can be overridden to do special handling when an item is deselected.
  45252. For example, if the item is an object, you might want to call it and tell
  45253. it that it's being deselected.
  45254. */
  45255. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  45256. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  45257. */
  45258. void changed (const bool synchronous = false)
  45259. {
  45260. if (synchronous)
  45261. sendSynchronousChangeMessage();
  45262. else
  45263. sendChangeMessage();
  45264. }
  45265. private:
  45266. Array <SelectableItemType> selectedItems;
  45267. JUCE_LEAK_DETECTOR (SelectedItemSet <SelectableItemType>);
  45268. };
  45269. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  45270. /*** End of inlined file: juce_SelectedItemSet.h ***/
  45271. /**
  45272. A class used by the LassoComponent to manage the things that it selects.
  45273. This allows the LassoComponent to find out which items are within the lasso,
  45274. and to change the list of selected items.
  45275. @see LassoComponent, SelectedItemSet
  45276. */
  45277. template <class SelectableItemType>
  45278. class LassoSource
  45279. {
  45280. public:
  45281. /** Destructor. */
  45282. virtual ~LassoSource() {}
  45283. /** Returns the set of items that lie within a given lassoable region.
  45284. Your implementation of this method must find all the relevent items that lie
  45285. within the given rectangle. and add them to the itemsFound array.
  45286. The co-ordinates are relative to the top-left of the lasso component's parent
  45287. component. (i.e. they are the same as the size and position of the lasso
  45288. component itself).
  45289. */
  45290. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  45291. const Rectangle<int>& area) = 0;
  45292. /** Returns the SelectedItemSet that the lasso should update.
  45293. This set will be continuously updated by the LassoComponent as it gets
  45294. dragged around, so make sure that you've got a ChangeListener attached to
  45295. the set so that your UI objects will know when the selection changes and
  45296. be able to update themselves appropriately.
  45297. */
  45298. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  45299. };
  45300. /**
  45301. A component that acts as a rectangular selection region, which you drag with
  45302. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  45303. To use one of these:
  45304. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  45305. component, and call its beginLasso() method, giving it a
  45306. suitable LassoSource object that it can use to find out which items are in
  45307. the active area.
  45308. - Each time your parent component gets a mouseDrag event, call dragLasso()
  45309. to update the lasso's position - it will use its LassoSource to calculate and
  45310. update the current selection.
  45311. - After the drag has finished and you get a mouseUp callback, you should call
  45312. endLasso() to clean up. This will make the lasso component invisible, and you
  45313. can remove it from the parent component, or delete it.
  45314. The class takes into account the modifier keys that are being held down while
  45315. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  45316. be added to the original selection; if ctrl or command is pressed, they will be
  45317. xor'ed with any previously selected items.
  45318. @see LassoSource, SelectedItemSet
  45319. */
  45320. template <class SelectableItemType>
  45321. class LassoComponent : public Component
  45322. {
  45323. public:
  45324. /** Creates a Lasso component.
  45325. The fill colour is used to fill the lasso'ed rectangle, and the outline
  45326. colour is used to draw a line around its edge.
  45327. */
  45328. explicit LassoComponent (const int outlineThickness_ = 1)
  45329. : source (0),
  45330. outlineThickness (outlineThickness_)
  45331. {
  45332. }
  45333. /** Destructor. */
  45334. ~LassoComponent()
  45335. {
  45336. }
  45337. /** Call this in your mouseDown event, to initialise a drag.
  45338. Pass in a suitable LassoSource object which the lasso will use to find
  45339. the items and change the selection.
  45340. After using this method to initialise the lasso, repeatedly call dragLasso()
  45341. in your component's mouseDrag callback.
  45342. @see dragLasso, endLasso, LassoSource
  45343. */
  45344. void beginLasso (const MouseEvent& e,
  45345. LassoSource <SelectableItemType>* const lassoSource)
  45346. {
  45347. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  45348. jassert (lassoSource != 0); // the source can't be null!
  45349. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  45350. source = lassoSource;
  45351. if (lassoSource != 0)
  45352. originalSelection = lassoSource->getLassoSelection().getItemArray();
  45353. setSize (0, 0);
  45354. dragStartPos = e.getMouseDownPosition();
  45355. }
  45356. /** Call this in your mouseDrag event, to update the lasso's position.
  45357. This must be repeatedly calling when the mouse is dragged, after you've
  45358. first initialised the lasso with beginLasso().
  45359. This method takes into account the modifier keys that are being held down, so
  45360. if shift is pressed, then the lassoed items will be added to any that were
  45361. previously selected; if ctrl or command is pressed, then they will be xor'ed
  45362. with previously selected items.
  45363. @see beginLasso, endLasso
  45364. */
  45365. void dragLasso (const MouseEvent& e)
  45366. {
  45367. if (source != 0)
  45368. {
  45369. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  45370. setVisible (true);
  45371. Array <SelectableItemType> itemsInLasso;
  45372. source->findLassoItemsInArea (itemsInLasso, getBounds());
  45373. if (e.mods.isShiftDown())
  45374. {
  45375. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  45376. itemsInLasso.addArray (originalSelection);
  45377. }
  45378. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  45379. {
  45380. Array <SelectableItemType> originalMinusNew (originalSelection);
  45381. originalMinusNew.removeValuesIn (itemsInLasso);
  45382. itemsInLasso.removeValuesIn (originalSelection);
  45383. itemsInLasso.addArray (originalMinusNew);
  45384. }
  45385. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  45386. }
  45387. }
  45388. /** Call this in your mouseUp event, after the lasso has been dragged.
  45389. @see beginLasso, dragLasso
  45390. */
  45391. void endLasso()
  45392. {
  45393. source = 0;
  45394. originalSelection.clear();
  45395. setVisible (false);
  45396. }
  45397. /** A set of colour IDs to use to change the colour of various aspects of the label.
  45398. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  45399. methods.
  45400. Note that you can also use the constants from TextEditor::ColourIds to change the
  45401. colour of the text editor that is opened when a label is editable.
  45402. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  45403. */
  45404. enum ColourIds
  45405. {
  45406. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  45407. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  45408. };
  45409. /** @internal */
  45410. void paint (Graphics& g)
  45411. {
  45412. g.fillAll (findColour (lassoFillColourId));
  45413. g.setColour (findColour (lassoOutlineColourId));
  45414. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  45415. // this suggests that you've left a lasso comp lying around after the
  45416. // mouse drag has finished.. Be careful to call endLasso() when you get a
  45417. // mouse-up event.
  45418. jassert (isMouseButtonDownAnywhere());
  45419. }
  45420. /** @internal */
  45421. bool hitTest (int, int) { return false; }
  45422. private:
  45423. Array <SelectableItemType> originalSelection;
  45424. LassoSource <SelectableItemType>* source;
  45425. int outlineThickness;
  45426. Point<int> dragStartPos;
  45427. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LassoComponent);
  45428. };
  45429. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  45430. /*** End of inlined file: juce_LassoComponent.h ***/
  45431. #endif
  45432. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  45433. #endif
  45434. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  45435. #endif
  45436. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  45437. /*** Start of inlined file: juce_MouseInputSource.h ***/
  45438. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  45439. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  45440. class MouseInputSourceInternal;
  45441. /**
  45442. Represents a linear source of mouse events from a mouse device or individual finger
  45443. in a multi-touch environment.
  45444. Each MouseEvent object contains a reference to the MouseInputSource that generated
  45445. it. In an environment with a single mouse for input, all events will come from the
  45446. same source, but in a multi-touch system, there may be multiple MouseInputSource
  45447. obects active, each representing a stream of events coming from a particular finger.
  45448. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  45449. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  45450. the only events that can happen between a mouseDown and its corresponding mouseUp are
  45451. mouseDrags, etc.
  45452. When there are multiple touches arriving from multiple MouseInputSources, their
  45453. event streams may arrive in an interleaved order, so you should use the getIndex()
  45454. method to find out which finger each event came from.
  45455. @see MouseEvent
  45456. */
  45457. class JUCE_API MouseInputSource
  45458. {
  45459. public:
  45460. /** Creates a MouseInputSource.
  45461. You should never actually create a MouseInputSource in your own code - the
  45462. library takes care of managing these objects.
  45463. */
  45464. MouseInputSource (int index, bool isMouseDevice);
  45465. /** Destructor. */
  45466. ~MouseInputSource();
  45467. /** Returns true if this object represents a normal desk-based mouse device. */
  45468. bool isMouse() const;
  45469. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  45470. bool isTouch() const;
  45471. /** Returns true if this source has an on-screen pointer that can hover over
  45472. items without clicking them.
  45473. */
  45474. bool canHover() const;
  45475. /** Returns true if this source may have a scroll wheel. */
  45476. bool hasMouseWheel() const;
  45477. /** Returns this source's index in the global list of possible sources.
  45478. If the system only has a single mouse, there will only be a single MouseInputSource
  45479. with an index of 0.
  45480. If the system supports multi-touch input, then the index will represent a finger
  45481. number, starting from 0. When the first touch event begins, it will have finger
  45482. number 0, and then if a second touch happens while the first is still down, it
  45483. will have index 1, etc.
  45484. */
  45485. int getIndex() const;
  45486. /** Returns true if this device is currently being pressed. */
  45487. bool isDragging() const;
  45488. /** Returns the last-known screen position of this source. */
  45489. const Point<int> getScreenPosition() const;
  45490. /** Returns a set of modifiers that indicate which buttons are currently
  45491. held down on this device.
  45492. */
  45493. const ModifierKeys getCurrentModifiers() const;
  45494. /** Returns the component that was last known to be under this pointer. */
  45495. Component* getComponentUnderMouse() const;
  45496. /** Tells the device to dispatch a mouse-move or mouse-drag event.
  45497. This is asynchronous - the event will occur on the message thread.
  45498. */
  45499. void triggerFakeMove() const;
  45500. /** Returns the number of clicks that should be counted as belonging to the
  45501. current mouse event.
  45502. So the mouse is currently down and it's the second click of a double-click, this
  45503. will return 2.
  45504. */
  45505. int getNumberOfMultipleClicks() const throw();
  45506. /** Returns the time at which the last mouse-down occurred. */
  45507. const Time getLastMouseDownTime() const throw();
  45508. /** Returns the screen position at which the last mouse-down occurred. */
  45509. const Point<int> getLastMouseDownPosition() const throw();
  45510. /** Returns true if this mouse is currently down, and if it has been dragged more
  45511. than a couple of pixels from the place it was pressed.
  45512. */
  45513. bool hasMouseMovedSignificantlySincePressed() const throw();
  45514. /** Returns true if this input source uses a visible mouse cursor. */
  45515. bool hasMouseCursor() const throw();
  45516. /** Changes the mouse cursor, (if there is one). */
  45517. void showMouseCursor (const MouseCursor& cursor);
  45518. /** Hides the mouse cursor (if there is one). */
  45519. void hideCursor();
  45520. /** Un-hides the mouse cursor if it was hidden by hideCursor(). */
  45521. void revealCursor();
  45522. /** Forces an update of the mouse cursor for whatever component it's currently over. */
  45523. void forceMouseCursorUpdate();
  45524. /** Returns true if this mouse can be moved indefinitely in any direction without running out of space. */
  45525. bool canDoUnboundedMovement() const throw();
  45526. /** Allows the mouse to move beyond the edges of the screen.
  45527. Calling this method when the mouse button is currently pressed will remove the cursor
  45528. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  45529. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  45530. can be used for things like custom slider controls or dragging objects around, where
  45531. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  45532. The unbounded mode is automatically turned off when the mouse button is released, or
  45533. it can be turned off explicitly by calling this method again.
  45534. @param isEnabled whether to turn this mode on or off
  45535. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  45536. hidden; if true, it will only be hidden when it
  45537. is moved beyond the edge of the screen
  45538. */
  45539. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  45540. /** @internal */
  45541. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  45542. /** @internal */
  45543. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  45544. private:
  45545. friend class Desktop;
  45546. friend class ComponentPeer;
  45547. friend class MouseInputSourceInternal;
  45548. ScopedPointer<MouseInputSourceInternal> pimpl;
  45549. static const Point<int> getCurrentMousePosition();
  45550. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MouseInputSource);
  45551. };
  45552. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  45553. /*** End of inlined file: juce_MouseInputSource.h ***/
  45554. #endif
  45555. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  45556. #endif
  45557. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  45558. #endif
  45559. #ifndef __JUCE_MARKERLIST_JUCEHEADER__
  45560. #endif
  45561. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  45562. #endif
  45563. #ifndef __JUCE_RELATIVECOORDINATEPOSITIONER_JUCEHEADER__
  45564. #endif
  45565. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  45566. /*** Start of inlined file: juce_RelativeParallelogram.h ***/
  45567. #ifndef __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  45568. #define __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  45569. /**
  45570. A parallelogram defined by three RelativePoint positions.
  45571. @see RelativePoint, RelativeCoordinate
  45572. */
  45573. class JUCE_API RelativeParallelogram
  45574. {
  45575. public:
  45576. RelativeParallelogram();
  45577. RelativeParallelogram (const Rectangle<float>& simpleRectangle);
  45578. RelativeParallelogram (const RelativePoint& topLeft, const RelativePoint& topRight, const RelativePoint& bottomLeft);
  45579. RelativeParallelogram (const String& topLeft, const String& topRight, const String& bottomLeft);
  45580. ~RelativeParallelogram();
  45581. void resolveThreePoints (Point<float>* points, Expression::Scope* scope) const;
  45582. void resolveFourCorners (Point<float>* points, Expression::Scope* scope) const;
  45583. const Rectangle<float> getBounds (Expression::Scope* scope) const;
  45584. void getPath (Path& path, Expression::Scope* scope) const;
  45585. const AffineTransform resetToPerpendicular (Expression::Scope* scope);
  45586. bool isDynamic() const;
  45587. bool operator== (const RelativeParallelogram& other) const throw();
  45588. bool operator!= (const RelativeParallelogram& other) const throw();
  45589. static const Point<float> getInternalCoordForPoint (const Point<float>* parallelogramCorners, Point<float> point) throw();
  45590. static const Point<float> getPointForInternalCoord (const Point<float>* parallelogramCorners, const Point<float>& internalPoint) throw();
  45591. static const Rectangle<float> getBoundingBox (const Point<float>* parallelogramCorners) throw();
  45592. RelativePoint topLeft, topRight, bottomLeft;
  45593. };
  45594. #endif // __JUCE_RELATIVEPARALLELOGRAM_JUCEHEADER__
  45595. /*** End of inlined file: juce_RelativeParallelogram.h ***/
  45596. #endif
  45597. #ifndef __JUCE_RELATIVEPOINT_JUCEHEADER__
  45598. #endif
  45599. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  45600. /*** Start of inlined file: juce_RelativePointPath.h ***/
  45601. #ifndef __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  45602. #define __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  45603. class DrawablePath;
  45604. /**
  45605. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  45606. One of these paths can be converted into a Path object for drawing and manipulation, but
  45607. unlike a Path, its points can be dynamic instead of just fixed.
  45608. @see RelativePoint, RelativeCoordinate
  45609. */
  45610. class JUCE_API RelativePointPath
  45611. {
  45612. public:
  45613. RelativePointPath();
  45614. RelativePointPath (const RelativePointPath& other);
  45615. explicit RelativePointPath (const Path& path);
  45616. ~RelativePointPath();
  45617. bool operator== (const RelativePointPath& other) const throw();
  45618. bool operator!= (const RelativePointPath& other) const throw();
  45619. /** Resolves this points in this path and adds them to a normal Path object. */
  45620. void createPath (Path& path, Expression::Scope* scope) const;
  45621. /** Returns true if the path contains any non-fixed points. */
  45622. bool containsAnyDynamicPoints() const;
  45623. /** Quickly swaps the contents of this path with another. */
  45624. void swapWith (RelativePointPath& other) throw();
  45625. /** The types of element that may be contained in this path.
  45626. @see RelativePointPath::ElementBase
  45627. */
  45628. enum ElementType
  45629. {
  45630. nullElement,
  45631. startSubPathElement,
  45632. closeSubPathElement,
  45633. lineToElement,
  45634. quadraticToElement,
  45635. cubicToElement
  45636. };
  45637. /** Base class for the elements that make up a RelativePointPath.
  45638. */
  45639. class JUCE_API ElementBase
  45640. {
  45641. public:
  45642. ElementBase (ElementType type);
  45643. virtual ~ElementBase() {}
  45644. virtual const ValueTree createTree() const = 0;
  45645. virtual void addToPath (Path& path, Expression::Scope*) const = 0;
  45646. virtual RelativePoint* getControlPoints (int& numPoints) = 0;
  45647. virtual ElementBase* clone() const = 0;
  45648. bool isDynamic();
  45649. const ElementType type;
  45650. private:
  45651. JUCE_DECLARE_NON_COPYABLE (ElementBase);
  45652. };
  45653. class JUCE_API StartSubPath : public ElementBase
  45654. {
  45655. public:
  45656. StartSubPath (const RelativePoint& pos);
  45657. const ValueTree createTree() const;
  45658. void addToPath (Path& path, Expression::Scope*) const;
  45659. RelativePoint* getControlPoints (int& numPoints);
  45660. ElementBase* clone() const;
  45661. RelativePoint startPos;
  45662. private:
  45663. JUCE_DECLARE_NON_COPYABLE (StartSubPath);
  45664. };
  45665. class JUCE_API CloseSubPath : public ElementBase
  45666. {
  45667. public:
  45668. CloseSubPath();
  45669. const ValueTree createTree() const;
  45670. void addToPath (Path& path, Expression::Scope*) const;
  45671. RelativePoint* getControlPoints (int& numPoints);
  45672. ElementBase* clone() const;
  45673. private:
  45674. JUCE_DECLARE_NON_COPYABLE (CloseSubPath);
  45675. };
  45676. class JUCE_API LineTo : public ElementBase
  45677. {
  45678. public:
  45679. LineTo (const RelativePoint& endPoint);
  45680. const ValueTree createTree() const;
  45681. void addToPath (Path& path, Expression::Scope*) const;
  45682. RelativePoint* getControlPoints (int& numPoints);
  45683. ElementBase* clone() const;
  45684. RelativePoint endPoint;
  45685. private:
  45686. JUCE_DECLARE_NON_COPYABLE (LineTo);
  45687. };
  45688. class JUCE_API QuadraticTo : public ElementBase
  45689. {
  45690. public:
  45691. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  45692. const ValueTree createTree() const;
  45693. void addToPath (Path& path, Expression::Scope*) const;
  45694. RelativePoint* getControlPoints (int& numPoints);
  45695. ElementBase* clone() const;
  45696. RelativePoint controlPoints[2];
  45697. private:
  45698. JUCE_DECLARE_NON_COPYABLE (QuadraticTo);
  45699. };
  45700. class JUCE_API CubicTo : public ElementBase
  45701. {
  45702. public:
  45703. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  45704. const ValueTree createTree() const;
  45705. void addToPath (Path& path, Expression::Scope*) const;
  45706. RelativePoint* getControlPoints (int& numPoints);
  45707. ElementBase* clone() const;
  45708. RelativePoint controlPoints[3];
  45709. private:
  45710. JUCE_DECLARE_NON_COPYABLE (CubicTo);
  45711. };
  45712. void addElement (ElementBase* newElement);
  45713. OwnedArray <ElementBase> elements;
  45714. bool usesNonZeroWinding;
  45715. private:
  45716. class Positioner;
  45717. friend class Positioner;
  45718. bool containsDynamicPoints;
  45719. void applyTo (DrawablePath& path) const;
  45720. RelativePointPath& operator= (const RelativePointPath&);
  45721. JUCE_LEAK_DETECTOR (RelativePointPath);
  45722. };
  45723. #endif // __JUCE_RELATIVEPOINTPATH_JUCEHEADER__
  45724. /*** End of inlined file: juce_RelativePointPath.h ***/
  45725. #endif
  45726. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  45727. /*** Start of inlined file: juce_RelativeRectangle.h ***/
  45728. #ifndef __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  45729. #define __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  45730. class Component;
  45731. /**
  45732. An rectangle stored as a set of RelativeCoordinate values.
  45733. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  45734. @see RelativeCoordinate, RelativePoint
  45735. */
  45736. class JUCE_API RelativeRectangle
  45737. {
  45738. public:
  45739. /** Creates a zero-size rectangle at the origin. */
  45740. RelativeRectangle();
  45741. /** Creates an absolute rectangle, relative to the origin. */
  45742. explicit RelativeRectangle (const Rectangle<float>& rect);
  45743. /** Creates a rectangle from four coordinates. */
  45744. RelativeRectangle (const RelativeCoordinate& left, const RelativeCoordinate& right,
  45745. const RelativeCoordinate& top, const RelativeCoordinate& bottom);
  45746. /** Creates a rectangle from a stringified representation.
  45747. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  45748. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  45749. RelativeCoordinate class.
  45750. @see toString
  45751. */
  45752. explicit RelativeRectangle (const String& stringVersion);
  45753. bool operator== (const RelativeRectangle& other) const throw();
  45754. bool operator!= (const RelativeRectangle& other) const throw();
  45755. /** Calculates the absolute position of this rectangle.
  45756. You'll need to provide a suitable Expression::Scope for looking up any coordinates that may
  45757. be needed to calculate the result.
  45758. */
  45759. const Rectangle<float> resolve (const Expression::Scope* scope) const;
  45760. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  45761. Calling this will leave any anchor points unchanged, but will set any absolute
  45762. or relative positions to whatever values are necessary to make the resultant position
  45763. match the position that is provided.
  45764. */
  45765. void moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope);
  45766. /** Returns true if this rectangle depends on any external symbols for its position.
  45767. Coordinates that refer to symbols based on "this" are assumed not to be dynamic.
  45768. */
  45769. bool isDynamic() const;
  45770. /** Returns a string which represents this point.
  45771. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  45772. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  45773. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  45774. */
  45775. const String toString() const;
  45776. /** Renames a symbol if it is used by any of the coordinates.
  45777. This calls Expression::withRenamedSymbol() on the rectangle's coordinates.
  45778. */
  45779. void renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope);
  45780. /** Creates and sets an appropriate Component::Positioner object for the given component, which will
  45781. keep it positioned with this rectangle.
  45782. */
  45783. void applyToComponent (Component& component) const;
  45784. // The actual rectangle coords...
  45785. RelativeCoordinate left, right, top, bottom;
  45786. };
  45787. #endif // __JUCE_RELATIVERECTANGLE_JUCEHEADER__
  45788. /*** End of inlined file: juce_RelativeRectangle.h ***/
  45789. #endif
  45790. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  45791. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  45792. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  45793. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  45794. /**
  45795. A PropertyComponent that contains an on/off toggle button.
  45796. This type of property component can be used if you have a boolean value to
  45797. toggle on/off.
  45798. @see PropertyComponent
  45799. */
  45800. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  45801. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  45802. {
  45803. protected:
  45804. /** Creates a button component.
  45805. If you use this constructor, you must override the getState() and setState()
  45806. methods.
  45807. @param propertyName the property name to be passed to the PropertyComponent
  45808. @param buttonTextWhenTrue the text shown in the button when the value is true
  45809. @param buttonTextWhenFalse the text shown in the button when the value is false
  45810. */
  45811. BooleanPropertyComponent (const String& propertyName,
  45812. const String& buttonTextWhenTrue,
  45813. const String& buttonTextWhenFalse);
  45814. public:
  45815. /** Creates a button component.
  45816. @param valueToControl a Value object that this property should refer to.
  45817. @param propertyName the property name to be passed to the PropertyComponent
  45818. @param buttonText the text shown in the ToggleButton component
  45819. */
  45820. BooleanPropertyComponent (const Value& valueToControl,
  45821. const String& propertyName,
  45822. const String& buttonText);
  45823. /** Destructor. */
  45824. ~BooleanPropertyComponent();
  45825. /** Called to change the state of the boolean value. */
  45826. virtual void setState (bool newState);
  45827. /** Must return the current value of the property. */
  45828. virtual bool getState() const;
  45829. /** @internal */
  45830. void paint (Graphics& g);
  45831. /** @internal */
  45832. void refresh();
  45833. /** @internal */
  45834. void buttonClicked (Button*);
  45835. private:
  45836. ToggleButton button;
  45837. String onText, offText;
  45838. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BooleanPropertyComponent);
  45839. };
  45840. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  45841. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  45842. #endif
  45843. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  45844. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  45845. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  45846. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  45847. /**
  45848. A PropertyComponent that contains a button.
  45849. This type of property component can be used if you need a button to trigger some
  45850. kind of action.
  45851. @see PropertyComponent
  45852. */
  45853. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  45854. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  45855. {
  45856. public:
  45857. /** Creates a button component.
  45858. @param propertyName the property name to be passed to the PropertyComponent
  45859. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  45860. */
  45861. ButtonPropertyComponent (const String& propertyName,
  45862. bool triggerOnMouseDown);
  45863. /** Destructor. */
  45864. ~ButtonPropertyComponent();
  45865. /** Called when the user clicks the button.
  45866. */
  45867. virtual void buttonClicked() = 0;
  45868. /** Returns the string that should be displayed in the button.
  45869. If you need to change this string, call refresh() to update the component.
  45870. */
  45871. virtual const String getButtonText() const = 0;
  45872. /** @internal */
  45873. void refresh();
  45874. /** @internal */
  45875. void buttonClicked (Button*);
  45876. private:
  45877. TextButton button;
  45878. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonPropertyComponent);
  45879. };
  45880. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  45881. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  45882. #endif
  45883. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  45884. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  45885. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  45886. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  45887. /**
  45888. A PropertyComponent that shows its value as a combo box.
  45889. This type of property component contains a list of options and has a
  45890. combo box to choose one.
  45891. Your subclass's constructor must add some strings to the choices StringArray
  45892. and these are shown in the list.
  45893. The getIndex() method will be called to find out which option is the currently
  45894. selected one. If you call refresh() it will call getIndex() to check whether
  45895. the value has changed, and will update the combo box if needed.
  45896. If the user selects a different item from the list, setIndex() will be
  45897. called to let your class process this.
  45898. @see PropertyComponent, PropertyPanel
  45899. */
  45900. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  45901. private ComboBoxListener // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  45902. {
  45903. protected:
  45904. /** Creates the component.
  45905. Your subclass's constructor must add a list of options to the choices
  45906. member variable.
  45907. */
  45908. ChoicePropertyComponent (const String& propertyName);
  45909. public:
  45910. /** Creates the component.
  45911. @param valueToControl the value that the combo box will read and control
  45912. @param propertyName the name of the property
  45913. @param choices the list of possible values that the drop-down list will contain
  45914. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  45915. These are the values that will be read and written to the
  45916. valueToControl value. This array must contain the same number of items
  45917. as the choices array
  45918. */
  45919. ChoicePropertyComponent (const Value& valueToControl,
  45920. const String& propertyName,
  45921. const StringArray& choices,
  45922. const Array <var>& correspondingValues);
  45923. /** Destructor. */
  45924. ~ChoicePropertyComponent();
  45925. /** Called when the user selects an item from the combo box.
  45926. Your subclass must use this callback to update the value that this component
  45927. represents. The index is the index of the chosen item in the choices
  45928. StringArray.
  45929. */
  45930. virtual void setIndex (int newIndex);
  45931. /** Returns the index of the item that should currently be shown.
  45932. This is the index of the item in the choices StringArray that will be
  45933. shown.
  45934. */
  45935. virtual int getIndex() const;
  45936. /** Returns the list of options. */
  45937. const StringArray& getChoices() const;
  45938. /** @internal */
  45939. void refresh();
  45940. /** @internal */
  45941. void comboBoxChanged (ComboBox*);
  45942. protected:
  45943. /** The list of options that will be shown in the combo box.
  45944. Your subclass must populate this array in its constructor. If any empty
  45945. strings are added, these will be replaced with horizontal separators (see
  45946. ComboBox::addSeparator() for more info).
  45947. */
  45948. StringArray choices;
  45949. private:
  45950. ComboBox comboBox;
  45951. bool isCustomClass;
  45952. class RemapperValueSource;
  45953. void createComboBox();
  45954. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChoicePropertyComponent);
  45955. };
  45956. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  45957. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  45958. #endif
  45959. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  45960. #endif
  45961. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  45962. #endif
  45963. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  45964. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  45965. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  45966. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  45967. /**
  45968. A PropertyComponent that shows its value as a slider.
  45969. @see PropertyComponent, Slider
  45970. */
  45971. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  45972. private SliderListener // (can't use Slider::Listener due to idiotic VC2005 bug)
  45973. {
  45974. protected:
  45975. /** Creates the property component.
  45976. The ranges, interval and skew factor are passed to the Slider component.
  45977. If you need to customise the slider in other ways, your constructor can
  45978. access the slider member variable and change it directly.
  45979. */
  45980. SliderPropertyComponent (const String& propertyName,
  45981. double rangeMin,
  45982. double rangeMax,
  45983. double interval,
  45984. double skewFactor = 1.0);
  45985. public:
  45986. /** Creates the property component.
  45987. The ranges, interval and skew factor are passed to the Slider component.
  45988. If you need to customise the slider in other ways, your constructor can
  45989. access the slider member variable and change it directly.
  45990. */
  45991. SliderPropertyComponent (const Value& valueToControl,
  45992. const String& propertyName,
  45993. double rangeMin,
  45994. double rangeMax,
  45995. double interval,
  45996. double skewFactor = 1.0);
  45997. /** Destructor. */
  45998. ~SliderPropertyComponent();
  45999. /** Called when the user moves the slider to change its value.
  46000. Your subclass must use this method to update whatever item this property
  46001. represents.
  46002. */
  46003. virtual void setValue (double newValue);
  46004. /** Returns the value that the slider should show. */
  46005. virtual double getValue() const;
  46006. /** @internal */
  46007. void refresh();
  46008. /** @internal */
  46009. void sliderValueChanged (Slider*);
  46010. protected:
  46011. /** The slider component being used in this component.
  46012. Your subclass has access to this in case it needs to customise it in some way.
  46013. */
  46014. Slider slider;
  46015. private:
  46016. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPropertyComponent);
  46017. };
  46018. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  46019. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  46020. #endif
  46021. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  46022. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  46023. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  46024. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  46025. /**
  46026. A PropertyComponent that shows its value as editable text.
  46027. @see PropertyComponent
  46028. */
  46029. class JUCE_API TextPropertyComponent : public PropertyComponent
  46030. {
  46031. protected:
  46032. /** Creates a text property component.
  46033. The maxNumChars is used to set the length of string allowable, and isMultiLine
  46034. sets whether the text editor allows carriage returns.
  46035. @see TextEditor
  46036. */
  46037. TextPropertyComponent (const String& propertyName,
  46038. int maxNumChars,
  46039. bool isMultiLine);
  46040. public:
  46041. /** Creates a text property component.
  46042. The maxNumChars is used to set the length of string allowable, and isMultiLine
  46043. sets whether the text editor allows carriage returns.
  46044. @see TextEditor
  46045. */
  46046. TextPropertyComponent (const Value& valueToControl,
  46047. const String& propertyName,
  46048. int maxNumChars,
  46049. bool isMultiLine);
  46050. /** Destructor. */
  46051. ~TextPropertyComponent();
  46052. /** Called when the user edits the text.
  46053. Your subclass must use this callback to change the value of whatever item
  46054. this property component represents.
  46055. */
  46056. virtual void setText (const String& newText);
  46057. /** Returns the text that should be shown in the text editor.
  46058. */
  46059. virtual const String getText() const;
  46060. /** @internal */
  46061. void refresh();
  46062. /** @internal */
  46063. void textWasEdited();
  46064. private:
  46065. ScopedPointer<Label> textEditor;
  46066. void createEditor (int maxNumChars, bool isMultiLine);
  46067. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextPropertyComponent);
  46068. };
  46069. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  46070. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  46071. #endif
  46072. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  46073. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  46074. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  46075. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  46076. #if JUCE_WINDOWS || DOXYGEN
  46077. /**
  46078. A Windows-specific class that can create and embed an ActiveX control inside
  46079. itself.
  46080. To use it, create one of these, put it in place and make sure it's visible in a
  46081. window, then use createControl() to instantiate an ActiveX control. The control
  46082. will then be moved and resized to follow the movements of this component.
  46083. Of course, since the control is a heavyweight window, it'll obliterate any
  46084. juce components that may overlap this component, but that's life.
  46085. */
  46086. class JUCE_API ActiveXControlComponent : public Component
  46087. {
  46088. public:
  46089. /** Create an initially-empty container. */
  46090. ActiveXControlComponent();
  46091. /** Destructor. */
  46092. ~ActiveXControlComponent();
  46093. /** Tries to create an ActiveX control and embed it in this peer.
  46094. The peer controlIID is a pointer to an IID structure - it's treated
  46095. as a void* because when including the Juce headers, you might not always
  46096. have included windows.h first, in which case IID wouldn't be defined.
  46097. e.g. @code
  46098. const IID myIID = __uuidof (QTControl);
  46099. myControlComp->createControl (&myIID);
  46100. @endcode
  46101. */
  46102. bool createControl (const void* controlIID);
  46103. /** Deletes the ActiveX control, if one has been created.
  46104. */
  46105. void deleteControl();
  46106. /** Returns true if a control is currently in use. */
  46107. bool isControlOpen() const throw() { return control != 0; }
  46108. /** Does a QueryInterface call on the embedded control object.
  46109. This allows you to cast the control to whatever type of COM object you need.
  46110. The iid parameter is a pointer to an IID structure - it's treated
  46111. as a void* because when including the Juce headers, you might not always
  46112. have included windows.h first, in which case IID wouldn't be defined, but
  46113. you should just pass a pointer to an IID.
  46114. e.g. @code
  46115. const IID iid = __uuidof (IOleWindow);
  46116. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  46117. if (oleWindow != 0)
  46118. {
  46119. HWND hwnd;
  46120. oleWindow->GetWindow (&hwnd);
  46121. ...
  46122. oleWindow->Release();
  46123. }
  46124. @endcode
  46125. */
  46126. void* queryInterface (const void* iid) const;
  46127. /** Set this to false to stop mouse events being allowed through to the control.
  46128. */
  46129. void setMouseEventsAllowed (bool eventsCanReachControl);
  46130. /** Returns true if mouse events are allowed to get through to the control.
  46131. */
  46132. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  46133. /** @internal */
  46134. void paint (Graphics& g);
  46135. /** @internal */
  46136. void* originalWndProc;
  46137. private:
  46138. class Pimpl;
  46139. friend class Pimpl;
  46140. friend class ScopedPointer <Pimpl>;
  46141. ScopedPointer <Pimpl> control;
  46142. bool mouseEventsAllowed;
  46143. void setControlBounds (const Rectangle<int>& bounds) const;
  46144. void setControlVisible (bool b) const;
  46145. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ActiveXControlComponent);
  46146. };
  46147. #endif
  46148. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  46149. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  46150. #endif
  46151. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  46152. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  46153. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  46154. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  46155. /**
  46156. A component containing controls to let the user change the audio settings of
  46157. an AudioDeviceManager object.
  46158. Very easy to use - just create one of these and show it to the user.
  46159. @see AudioDeviceManager
  46160. */
  46161. class JUCE_API AudioDeviceSelectorComponent : public Component,
  46162. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  46163. public ButtonListener,
  46164. public ChangeListener
  46165. {
  46166. public:
  46167. /** Creates the component.
  46168. If your app needs only output channels, you might ask for a maximum of 0 input
  46169. channels, and the component won't display any options for choosing the input
  46170. channels. And likewise if you're doing an input-only app.
  46171. @param deviceManager the device manager that this component should control
  46172. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  46173. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  46174. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  46175. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  46176. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  46177. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  46178. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  46179. treated as a set of separate mono channels.
  46180. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  46181. are shown, with an "advanced" button that shows the rest of them
  46182. */
  46183. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  46184. const int minAudioInputChannels,
  46185. const int maxAudioInputChannels,
  46186. const int minAudioOutputChannels,
  46187. const int maxAudioOutputChannels,
  46188. const bool showMidiInputOptions,
  46189. const bool showMidiOutputSelector,
  46190. const bool showChannelsAsStereoPairs,
  46191. const bool hideAdvancedOptionsWithButton);
  46192. /** Destructor */
  46193. ~AudioDeviceSelectorComponent();
  46194. /** @internal */
  46195. void resized();
  46196. /** @internal */
  46197. void comboBoxChanged (ComboBox*);
  46198. /** @internal */
  46199. void buttonClicked (Button*);
  46200. /** @internal */
  46201. void changeListenerCallback (ChangeBroadcaster*);
  46202. /** @internal */
  46203. void childBoundsChanged (Component*);
  46204. private:
  46205. AudioDeviceManager& deviceManager;
  46206. ScopedPointer<ComboBox> deviceTypeDropDown;
  46207. ScopedPointer<Label> deviceTypeDropDownLabel;
  46208. ScopedPointer<Component> audioDeviceSettingsComp;
  46209. String audioDeviceSettingsCompType;
  46210. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  46211. const bool showChannelsAsStereoPairs;
  46212. const bool hideAdvancedOptionsWithButton;
  46213. class MidiInputSelectorComponentListBox;
  46214. friend class ScopedPointer<MidiInputSelectorComponentListBox>;
  46215. ScopedPointer<MidiInputSelectorComponentListBox> midiInputsList;
  46216. ScopedPointer<ComboBox> midiOutputSelector;
  46217. ScopedPointer<Label> midiInputsLabel, midiOutputLabel;
  46218. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceSelectorComponent);
  46219. };
  46220. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  46221. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  46222. #endif
  46223. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  46224. /*** Start of inlined file: juce_BubbleComponent.h ***/
  46225. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  46226. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  46227. /**
  46228. A component for showing a message or other graphics inside a speech-bubble-shaped
  46229. outline, pointing at a location on the screen.
  46230. This is a base class that just draws and positions the bubble shape, but leaves
  46231. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  46232. that draws a text message.
  46233. To use it, create your subclass, then either add it to a parent component or
  46234. put it on the desktop with addToDesktop (0), use setPosition() to
  46235. resize and position it, then make it visible.
  46236. @see BubbleMessageComponent
  46237. */
  46238. class JUCE_API BubbleComponent : public Component
  46239. {
  46240. protected:
  46241. /** Creates a BubbleComponent.
  46242. Your subclass will need to implement the getContentSize() and paintContent()
  46243. methods to draw the bubble's contents.
  46244. */
  46245. BubbleComponent();
  46246. public:
  46247. /** Destructor. */
  46248. ~BubbleComponent();
  46249. /** A list of permitted placements for the bubble, relative to the co-ordinates
  46250. at which it should be pointing.
  46251. @see setAllowedPlacement
  46252. */
  46253. enum BubblePlacement
  46254. {
  46255. above = 1,
  46256. below = 2,
  46257. left = 4,
  46258. right = 8
  46259. };
  46260. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  46261. point at which it's pointing.
  46262. By default when setPosition() is called, the bubble will place itself either
  46263. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  46264. the values in BubblePlacement to restrict this choice.
  46265. E.g. if you only want your bubble to appear above or below the target area,
  46266. use setAllowedPlacement (above | below);
  46267. @see BubblePlacement
  46268. */
  46269. void setAllowedPlacement (int newPlacement);
  46270. /** Moves and resizes the bubble to point at a given component.
  46271. This will resize the bubble to fit its content, then find a position for it
  46272. so that it's next to, but doesn't overlap the given component.
  46273. It'll put itself either above, below, or to the side of the component depending
  46274. on where there's the most space, honouring any restrictions that were set
  46275. with setAllowedPlacement().
  46276. */
  46277. void setPosition (Component* componentToPointTo);
  46278. /** Moves and resizes the bubble to point at a given point.
  46279. This will resize the bubble to fit its content, then position it
  46280. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  46281. are relative to either the bubble component's parent component if it has one, or
  46282. they are screen co-ordinates if not.
  46283. It'll put itself either above, below, or to the side of this point, depending
  46284. on where there's the most space, honouring any restrictions that were set
  46285. with setAllowedPlacement().
  46286. */
  46287. void setPosition (int arrowTipX,
  46288. int arrowTipY);
  46289. /** Moves and resizes the bubble to point at a given rectangle.
  46290. This will resize the bubble to fit its content, then find a position for it
  46291. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  46292. co-ordinates are relative to either the bubble component's parent component
  46293. if it has one, or they are screen co-ordinates if not.
  46294. It'll put itself either above, below, or to the side of the component depending
  46295. on where there's the most space, honouring any restrictions that were set
  46296. with setAllowedPlacement().
  46297. */
  46298. void setPosition (const Rectangle<int>& rectangleToPointTo);
  46299. protected:
  46300. /** Subclasses should override this to return the size of the content they
  46301. want to draw inside the bubble.
  46302. */
  46303. virtual void getContentSize (int& width, int& height) = 0;
  46304. /** Subclasses should override this to draw their bubble's contents.
  46305. The graphics object's clip region and the dimensions passed in here are
  46306. set up to paint just the rectangle inside the bubble.
  46307. */
  46308. virtual void paintContent (Graphics& g, int width, int height) = 0;
  46309. public:
  46310. /** @internal */
  46311. void paint (Graphics& g);
  46312. private:
  46313. Rectangle<int> content;
  46314. int side, allowablePlacements;
  46315. float arrowTipX, arrowTipY;
  46316. DropShadowEffect shadow;
  46317. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleComponent);
  46318. };
  46319. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  46320. /*** End of inlined file: juce_BubbleComponent.h ***/
  46321. #endif
  46322. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  46323. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  46324. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  46325. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  46326. /**
  46327. A speech-bubble component that displays a short message.
  46328. This can be used to show a message with the tail of the speech bubble
  46329. pointing to a particular component or location on the screen.
  46330. @see BubbleComponent
  46331. */
  46332. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  46333. private Timer
  46334. {
  46335. public:
  46336. /** Creates a bubble component.
  46337. After creating one a BubbleComponent, do the following:
  46338. - add it to an appropriate parent component, or put it on the
  46339. desktop with Component::addToDesktop (0).
  46340. - use the showAt() method to show a message.
  46341. - it will make itself invisible after it times-out (and can optionally
  46342. also delete itself), or you can reuse it somewhere else by calling
  46343. showAt() again.
  46344. */
  46345. BubbleMessageComponent (int fadeOutLengthMs = 150);
  46346. /** Destructor. */
  46347. ~BubbleMessageComponent();
  46348. /** Shows a message bubble at a particular position.
  46349. This shows the bubble with its stem pointing to the given location
  46350. (co-ordinates being relative to its parent component).
  46351. For details about exactly how it decides where to position itself, see
  46352. BubbleComponent::updatePosition().
  46353. @param x the x co-ordinate of end of the bubble's tail
  46354. @param y the y co-ordinate of end of the bubble's tail
  46355. @param message the text to display
  46356. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  46357. from its parent compnent. If this is 0 or less, it
  46358. will stay there until manually removed.
  46359. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  46360. mouse button is pressed (anywhere on the screen)
  46361. @param deleteSelfAfterUse if true, then the component will delete itself after
  46362. it becomes invisible
  46363. */
  46364. void showAt (int x, int y,
  46365. const String& message,
  46366. int numMillisecondsBeforeRemoving,
  46367. bool removeWhenMouseClicked = true,
  46368. bool deleteSelfAfterUse = false);
  46369. /** Shows a message bubble next to a particular component.
  46370. This shows the bubble with its stem pointing at the given component.
  46371. For details about exactly how it decides where to position itself, see
  46372. BubbleComponent::updatePosition().
  46373. @param component the component that you want to point at
  46374. @param message the text to display
  46375. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  46376. from its parent compnent. If this is 0 or less, it
  46377. will stay there until manually removed.
  46378. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  46379. mouse button is pressed (anywhere on the screen)
  46380. @param deleteSelfAfterUse if true, then the component will delete itself after
  46381. it becomes invisible
  46382. */
  46383. void showAt (Component* component,
  46384. const String& message,
  46385. int numMillisecondsBeforeRemoving,
  46386. bool removeWhenMouseClicked = true,
  46387. bool deleteSelfAfterUse = false);
  46388. /** @internal */
  46389. void getContentSize (int& w, int& h);
  46390. /** @internal */
  46391. void paintContent (Graphics& g, int w, int h);
  46392. /** @internal */
  46393. void timerCallback();
  46394. private:
  46395. int fadeOutLength, mouseClickCounter;
  46396. TextLayout textLayout;
  46397. int64 expiryTime;
  46398. bool deleteAfterUse;
  46399. void init (int numMillisecondsBeforeRemoving,
  46400. bool removeWhenMouseClicked,
  46401. bool deleteSelfAfterUse);
  46402. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BubbleMessageComponent);
  46403. };
  46404. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  46405. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  46406. #endif
  46407. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  46408. /*** Start of inlined file: juce_ColourSelector.h ***/
  46409. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  46410. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  46411. /**
  46412. A component that lets the user choose a colour.
  46413. This shows RGB sliders and a colourspace that the user can pick colours from.
  46414. This class is also a ChangeBroadcaster, so listeners can register to be told
  46415. when the colour changes.
  46416. */
  46417. class JUCE_API ColourSelector : public Component,
  46418. public ChangeBroadcaster,
  46419. protected SliderListener
  46420. {
  46421. public:
  46422. /** Options for the type of selector to show. These are passed into the constructor. */
  46423. enum ColourSelectorOptions
  46424. {
  46425. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  46426. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  46427. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  46428. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  46429. };
  46430. /** Creates a ColourSelector object.
  46431. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  46432. which of the selector's features should be visible.
  46433. The edgeGap value specifies the amount of space to leave around the edge.
  46434. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  46435. colourspace and hue selector components.
  46436. */
  46437. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  46438. int edgeGap = 4,
  46439. int gapAroundColourSpaceComponent = 7);
  46440. /** Destructor. */
  46441. ~ColourSelector();
  46442. /** Returns the colour that the user has currently selected.
  46443. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  46444. register to be told when the colour changes.
  46445. @see setCurrentColour
  46446. */
  46447. const Colour getCurrentColour() const;
  46448. /** Changes the colour that is currently being shown.
  46449. */
  46450. void setCurrentColour (const Colour& newColour);
  46451. /** Tells the selector how many preset colour swatches you want to have on the component.
  46452. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  46453. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  46454. their values.
  46455. */
  46456. virtual int getNumSwatches() const;
  46457. /** Called by the selector to find out the colour of one of the swatches.
  46458. Your subclass should return the colour of the swatch with the given index.
  46459. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  46460. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  46461. their values.
  46462. */
  46463. virtual const Colour getSwatchColour (int index) const;
  46464. /** Called by the selector when the user puts a new colour into one of the swatches.
  46465. Your subclass should change the colour of the swatch with the given index.
  46466. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  46467. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  46468. their values.
  46469. */
  46470. virtual void setSwatchColour (int index, const Colour& newColour) const;
  46471. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  46472. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  46473. methods.
  46474. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  46475. */
  46476. enum ColourIds
  46477. {
  46478. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  46479. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  46480. };
  46481. private:
  46482. class ColourSpaceView;
  46483. class HueSelectorComp;
  46484. class SwatchComponent;
  46485. friend class ColourSpaceView;
  46486. friend class ScopedPointer<ColourSpaceView>;
  46487. friend class HueSelectorComp;
  46488. friend class ScopedPointer<HueSelectorComp>;
  46489. Colour colour;
  46490. float h, s, v;
  46491. ScopedPointer<Slider> sliders[4];
  46492. ScopedPointer<ColourSpaceView> colourSpace;
  46493. ScopedPointer<HueSelectorComp> hueSelector;
  46494. OwnedArray <SwatchComponent> swatchComponents;
  46495. const int flags;
  46496. int edgeGap;
  46497. Rectangle<int> previewArea;
  46498. void setHue (float newH);
  46499. void setSV (float newS, float newV);
  46500. void updateHSV();
  46501. void update();
  46502. void sliderValueChanged (Slider*);
  46503. void paint (Graphics& g);
  46504. void resized();
  46505. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ColourSelector);
  46506. #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
  46507. // This constructor is here temporarily to prevent old code compiling, because the parameters
  46508. // have changed - if you get an error here, update your code to use the new constructor instead..
  46509. ColourSelector (bool);
  46510. #endif
  46511. };
  46512. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  46513. /*** End of inlined file: juce_ColourSelector.h ***/
  46514. #endif
  46515. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  46516. #endif
  46517. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  46518. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  46519. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  46520. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  46521. /**
  46522. A component that displays a piano keyboard, whose notes can be clicked on.
  46523. This component will mimic a physical midi keyboard, showing the current state of
  46524. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  46525. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  46526. Another feature is that the computer keyboard can also be used to play notes. By
  46527. default it maps the top two rows of a standard querty keyboard to the notes, but
  46528. these can be remapped if needed. It will only respond to keypresses when it has
  46529. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  46530. The component is also a ChangeBroadcaster, so if you want to be informed when the
  46531. keyboard is scrolled, you can register a ChangeListener for callbacks.
  46532. @see MidiKeyboardState
  46533. */
  46534. class JUCE_API MidiKeyboardComponent : public Component,
  46535. public MidiKeyboardStateListener,
  46536. public ChangeBroadcaster,
  46537. private Timer,
  46538. private AsyncUpdater
  46539. {
  46540. public:
  46541. /** The direction of the keyboard.
  46542. @see setOrientation
  46543. */
  46544. enum Orientation
  46545. {
  46546. horizontalKeyboard,
  46547. verticalKeyboardFacingLeft,
  46548. verticalKeyboardFacingRight,
  46549. };
  46550. /** Creates a MidiKeyboardComponent.
  46551. @param state the midi keyboard model that this component will represent
  46552. @param orientation whether the keyboard is horizonal or vertical
  46553. */
  46554. MidiKeyboardComponent (MidiKeyboardState& state,
  46555. Orientation orientation);
  46556. /** Destructor. */
  46557. ~MidiKeyboardComponent();
  46558. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  46559. on the component.
  46560. Values are 0 to 1.0, where 1.0 is the heaviest.
  46561. @see setMidiChannel
  46562. */
  46563. void setVelocity (float velocity, bool useMousePositionForVelocity);
  46564. /** Changes the midi channel number that will be used for events triggered by clicking
  46565. on the component.
  46566. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  46567. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  46568. Although this is the channel used for outgoing events, the component can display
  46569. incoming events from more than one channel - see setMidiChannelsToDisplay()
  46570. @see setVelocity
  46571. */
  46572. void setMidiChannel (int midiChannelNumber);
  46573. /** Returns the midi channel that the keyboard is using for midi messages.
  46574. @see setMidiChannel
  46575. */
  46576. int getMidiChannel() const throw() { return midiChannel; }
  46577. /** Sets a mask to indicate which incoming midi channels should be represented by
  46578. key movements.
  46579. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  46580. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  46581. in this mask, the on-screen keys will also go down.
  46582. By default, this mask is set to 0xffff (all channels displayed).
  46583. @see setMidiChannel
  46584. */
  46585. void setMidiChannelsToDisplay (int midiChannelMask);
  46586. /** Returns the current set of midi channels represented by the component.
  46587. This is the value that was set with setMidiChannelsToDisplay().
  46588. */
  46589. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  46590. /** Changes the width used to draw the white keys. */
  46591. void setKeyWidth (float widthInPixels);
  46592. /** Returns the width that was set by setKeyWidth(). */
  46593. float getKeyWidth() const throw() { return keyWidth; }
  46594. /** Changes the keyboard's current direction. */
  46595. void setOrientation (Orientation newOrientation);
  46596. /** Returns the keyboard's current direction. */
  46597. const Orientation getOrientation() const throw() { return orientation; }
  46598. /** Sets the range of midi notes that the keyboard will be limited to.
  46599. By default the range is 0 to 127 (inclusive), but you can limit this if you
  46600. only want a restricted set of the keys to be shown.
  46601. Note that the values here are inclusive and must be between 0 and 127.
  46602. */
  46603. void setAvailableRange (int lowestNote,
  46604. int highestNote);
  46605. /** Returns the first note in the available range.
  46606. @see setAvailableRange
  46607. */
  46608. int getRangeStart() const throw() { return rangeStart; }
  46609. /** Returns the last note in the available range.
  46610. @see setAvailableRange
  46611. */
  46612. int getRangeEnd() const throw() { return rangeEnd; }
  46613. /** If the keyboard extends beyond the size of the component, this will scroll
  46614. it to show the given key at the start.
  46615. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  46616. base class to send a callback to any ChangeListeners that have been registered.
  46617. */
  46618. void setLowestVisibleKey (int noteNumber);
  46619. /** Returns the number of the first key shown in the component.
  46620. @see setLowestVisibleKey
  46621. */
  46622. int getLowestVisibleKey() const throw() { return firstKey; }
  46623. /** Returns the length of the black notes.
  46624. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  46625. */
  46626. int getBlackNoteLength() const throw() { return blackNoteLength; }
  46627. /** If set to true, then scroll buttons will appear at either end of the keyboard
  46628. if there are too many notes to fit them all in the component at once.
  46629. */
  46630. void setScrollButtonsVisible (bool canScroll);
  46631. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  46632. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  46633. methods.
  46634. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  46635. */
  46636. enum ColourIds
  46637. {
  46638. whiteNoteColourId = 0x1005000,
  46639. blackNoteColourId = 0x1005001,
  46640. keySeparatorLineColourId = 0x1005002,
  46641. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  46642. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  46643. textLabelColourId = 0x1005005,
  46644. upDownButtonBackgroundColourId = 0x1005006,
  46645. upDownButtonArrowColourId = 0x1005007
  46646. };
  46647. /** Returns the position within the component of the left-hand edge of a key.
  46648. Depending on the keyboard's orientation, this may be a horizontal or vertical
  46649. distance, in either direction.
  46650. */
  46651. int getKeyStartPosition (const int midiNoteNumber) const;
  46652. /** Deletes all key-mappings.
  46653. @see setKeyPressForNote
  46654. */
  46655. void clearKeyMappings();
  46656. /** Maps a key-press to a given note.
  46657. @param key the key that should trigger the note
  46658. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  46659. be. The actual midi note that gets played will be
  46660. this value + (12 * the current base octave). To change
  46661. the base octave, see setKeyPressBaseOctave()
  46662. */
  46663. void setKeyPressForNote (const KeyPress& key,
  46664. int midiNoteOffsetFromC);
  46665. /** Removes any key-mappings for a given note.
  46666. For a description of what the note number means, see setKeyPressForNote().
  46667. */
  46668. void removeKeyPressForNote (int midiNoteOffsetFromC);
  46669. /** Changes the base note above which key-press-triggered notes are played.
  46670. The set of key-mappings that trigger notes can be moved up and down to cover
  46671. the entire scale using this method.
  46672. The value passed in is an octave number between 0 and 10 (inclusive), and
  46673. indicates which C is the base note to which the key-mapped notes are
  46674. relative.
  46675. */
  46676. void setKeyPressBaseOctave (int newOctaveNumber);
  46677. /** This sets the octave number which is shown as the octave number for middle C.
  46678. This affects only the default implementation of getWhiteNoteText(), which
  46679. passes this octave number to MidiMessage::getMidiNoteName() in order to
  46680. get the note text. See MidiMessage::getMidiNoteName() for more info about
  46681. the parameter.
  46682. By default this value is set to 3.
  46683. @see getOctaveForMiddleC
  46684. */
  46685. void setOctaveForMiddleC (int octaveNumForMiddleC);
  46686. /** This returns the value set by setOctaveForMiddleC().
  46687. @see setOctaveForMiddleC
  46688. */
  46689. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  46690. /** @internal */
  46691. void paint (Graphics& g);
  46692. /** @internal */
  46693. void resized();
  46694. /** @internal */
  46695. void mouseMove (const MouseEvent& e);
  46696. /** @internal */
  46697. void mouseDrag (const MouseEvent& e);
  46698. /** @internal */
  46699. void mouseDown (const MouseEvent& e);
  46700. /** @internal */
  46701. void mouseUp (const MouseEvent& e);
  46702. /** @internal */
  46703. void mouseEnter (const MouseEvent& e);
  46704. /** @internal */
  46705. void mouseExit (const MouseEvent& e);
  46706. /** @internal */
  46707. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  46708. /** @internal */
  46709. void timerCallback();
  46710. /** @internal */
  46711. bool keyStateChanged (bool isKeyDown);
  46712. /** @internal */
  46713. void focusLost (FocusChangeType cause);
  46714. /** @internal */
  46715. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  46716. /** @internal */
  46717. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  46718. /** @internal */
  46719. void handleAsyncUpdate();
  46720. /** @internal */
  46721. void colourChanged();
  46722. protected:
  46723. /** Draws a white note in the given rectangle.
  46724. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  46725. currently pressed down.
  46726. When doing this, be sure to note the keyboard's orientation.
  46727. */
  46728. virtual void drawWhiteNote (int midiNoteNumber,
  46729. Graphics& g,
  46730. int x, int y, int w, int h,
  46731. bool isDown, bool isOver,
  46732. const Colour& lineColour,
  46733. const Colour& textColour);
  46734. /** Draws a black note in the given rectangle.
  46735. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  46736. currently pressed down.
  46737. When doing this, be sure to note the keyboard's orientation.
  46738. */
  46739. virtual void drawBlackNote (int midiNoteNumber,
  46740. Graphics& g,
  46741. int x, int y, int w, int h,
  46742. bool isDown, bool isOver,
  46743. const Colour& noteFillColour);
  46744. /** Allows text to be drawn on the white notes.
  46745. By default this is used to label the C in each octave, but could be used for other things.
  46746. @see setOctaveForMiddleC
  46747. */
  46748. virtual const String getWhiteNoteText (const int midiNoteNumber);
  46749. /** Draws the up and down buttons that change the base note. */
  46750. virtual void drawUpDownButton (Graphics& g, int w, int h,
  46751. const bool isMouseOver,
  46752. const bool isButtonPressed,
  46753. const bool movesOctavesUp);
  46754. /** Callback when the mouse is clicked on a key.
  46755. You could use this to do things like handle right-clicks on keys, etc.
  46756. Return true if you want the click to trigger the note, or false if you
  46757. want to handle it yourself and not have the note played.
  46758. @see mouseDraggedToKey
  46759. */
  46760. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  46761. /** Callback when the mouse is dragged from one key onto another.
  46762. @see mouseDownOnKey
  46763. */
  46764. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  46765. /** Calculates the positon of a given midi-note.
  46766. This can be overridden to create layouts with custom key-widths.
  46767. @param midiNoteNumber the note to find
  46768. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  46769. @param x the x position of the left-hand edge of the key (this method
  46770. always works in terms of a horizontal keyboard)
  46771. @param w the width of the key
  46772. */
  46773. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  46774. int& x, int& w) const;
  46775. private:
  46776. friend class MidiKeyboardUpDownButton;
  46777. MidiKeyboardState& state;
  46778. int xOffset, blackNoteLength;
  46779. float keyWidth;
  46780. Orientation orientation;
  46781. int midiChannel, midiInChannelMask;
  46782. float velocity;
  46783. int noteUnderMouse, mouseDownNote;
  46784. BigInteger keysPressed, keysCurrentlyDrawnDown;
  46785. int rangeStart, rangeEnd, firstKey;
  46786. bool canScroll, mouseDragging, useMousePositionForVelocity;
  46787. ScopedPointer<Button> scrollDown, scrollUp;
  46788. Array <KeyPress> keyPresses;
  46789. Array <int> keyPressNotes;
  46790. int keyMappingOctave;
  46791. int octaveNumForMiddleC;
  46792. static const uint8 whiteNotes[];
  46793. static const uint8 blackNotes[];
  46794. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  46795. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  46796. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  46797. void resetAnyKeysInUse();
  46798. void updateNoteUnderMouse (const Point<int>& pos);
  46799. void repaintNote (const int midiNoteNumber);
  46800. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardComponent);
  46801. };
  46802. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  46803. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  46804. #endif
  46805. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  46806. /*** Start of inlined file: juce_NSViewComponent.h ***/
  46807. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  46808. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  46809. #if ! DOXYGEN
  46810. class NSViewComponentInternal;
  46811. #endif
  46812. #if JUCE_MAC || DOXYGEN
  46813. /**
  46814. A Mac-specific class that can create and embed an NSView inside itself.
  46815. To use it, create one of these, put it in place and make sure it's visible in a
  46816. window, then use setView() to assign an NSView to it. The view will then be
  46817. moved and resized to follow the movements of this component.
  46818. Of course, since the view is a native object, it'll obliterate any
  46819. juce components that may overlap this component, but that's life.
  46820. */
  46821. class JUCE_API NSViewComponent : public Component
  46822. {
  46823. public:
  46824. /** Create an initially-empty container. */
  46825. NSViewComponent();
  46826. /** Destructor. */
  46827. ~NSViewComponent();
  46828. /** Assigns an NSView to this peer.
  46829. The view will be retained and released by this component for as long as
  46830. it is needed. To remove the current view, just call setView (0).
  46831. Note: a void* is used here to avoid including the cocoa headers as
  46832. part of the juce.h, but the method expects an NSView*.
  46833. */
  46834. void setView (void* nsView);
  46835. /** Returns the current NSView.
  46836. Note: a void* is returned here to avoid including the cocoa headers as
  46837. a requirement of juce.h, so you should just cast the object to an NSView*.
  46838. */
  46839. void* getView() const;
  46840. /** Resizes this component to fit the view that it contains. */
  46841. void resizeToFitView();
  46842. /** @internal */
  46843. void paint (Graphics& g);
  46844. private:
  46845. friend class NSViewComponentInternal;
  46846. ScopedPointer <NSViewComponentInternal> info;
  46847. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponent);
  46848. };
  46849. #endif
  46850. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  46851. /*** End of inlined file: juce_NSViewComponent.h ***/
  46852. #endif
  46853. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  46854. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  46855. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  46856. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  46857. // this is used to disable OpenGL, and is defined in juce_Config.h
  46858. #if JUCE_OPENGL || DOXYGEN
  46859. /**
  46860. Represents the various properties of an OpenGL bitmap format.
  46861. @see OpenGLComponent::setPixelFormat
  46862. */
  46863. class JUCE_API OpenGLPixelFormat
  46864. {
  46865. public:
  46866. /** Creates an OpenGLPixelFormat.
  46867. The default constructor just initialises the object as a simple 8-bit
  46868. RGBA format.
  46869. */
  46870. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  46871. int alphaBits = 8,
  46872. int depthBufferBits = 16,
  46873. int stencilBufferBits = 0);
  46874. OpenGLPixelFormat (const OpenGLPixelFormat&);
  46875. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  46876. bool operator== (const OpenGLPixelFormat&) const;
  46877. int redBits; /**< The number of bits per pixel to use for the red channel. */
  46878. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  46879. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  46880. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  46881. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  46882. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  46883. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  46884. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  46885. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  46886. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  46887. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  46888. /** Returns a list of all the pixel formats that can be used in this system.
  46889. A reference component is needed in case there are multiple screens with different
  46890. capabilities - in which case, the one that the component is on will be used.
  46891. */
  46892. static void getAvailablePixelFormats (Component* component,
  46893. OwnedArray <OpenGLPixelFormat>& results);
  46894. private:
  46895. JUCE_LEAK_DETECTOR (OpenGLPixelFormat);
  46896. };
  46897. /**
  46898. A base class for types of OpenGL context.
  46899. An OpenGLComponent will supply its own context for drawing in its window.
  46900. */
  46901. class JUCE_API OpenGLContext
  46902. {
  46903. public:
  46904. /** Destructor. */
  46905. virtual ~OpenGLContext();
  46906. /** Makes this context the currently active one. */
  46907. virtual bool makeActive() const throw() = 0;
  46908. /** If this context is currently active, it is disactivated. */
  46909. virtual bool makeInactive() const throw() = 0;
  46910. /** Returns true if this context is currently active. */
  46911. virtual bool isActive() const throw() = 0;
  46912. /** Swaps the buffers (if the context can do this). */
  46913. virtual void swapBuffers() = 0;
  46914. /** Sets whether the context checks the vertical sync before swapping.
  46915. The value is the number of frames to allow between buffer-swapping. This is
  46916. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  46917. and greater numbers indicate that it should swap less often.
  46918. Returns true if it sets the value successfully.
  46919. */
  46920. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  46921. /** Returns the current swap-sync interval.
  46922. See setSwapInterval() for info about the value returned.
  46923. */
  46924. virtual int getSwapInterval() const = 0;
  46925. /** Returns the pixel format being used by this context. */
  46926. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  46927. /** For windowed contexts, this moves the context within the bounds of
  46928. its parent window.
  46929. */
  46930. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  46931. /** For windowed contexts, this triggers a repaint of the window.
  46932. (Not relevent on all platforms).
  46933. */
  46934. virtual void repaint() = 0;
  46935. /** Returns an OS-dependent handle to the raw GL context.
  46936. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  46937. a GLXContext.
  46938. */
  46939. virtual void* getRawContext() const throw() = 0;
  46940. /** Deletes the context.
  46941. This must only be called on the message thread, or will deadlock.
  46942. On background threads, call getCurrentContext()->deleteContext(), but be careful not
  46943. to call any other OpenGL function afterwards.
  46944. This doesn't touch other resources, such as window handles, etc.
  46945. You'll probably never have to call this method directly.
  46946. */
  46947. virtual void deleteContext() = 0;
  46948. /** Returns the context that's currently in active use by the calling thread.
  46949. Returns 0 if there isn't an active context.
  46950. */
  46951. static OpenGLContext* getCurrentContext();
  46952. protected:
  46953. OpenGLContext() throw();
  46954. private:
  46955. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLContext);
  46956. };
  46957. /**
  46958. A component that contains an OpenGL canvas.
  46959. Override this, add it to whatever component you want to, and use the renderOpenGL()
  46960. method to draw its contents.
  46961. */
  46962. class JUCE_API OpenGLComponent : public Component
  46963. {
  46964. public:
  46965. /** Used to select the type of openGL API to use, if more than one choice is available
  46966. on a particular platform.
  46967. */
  46968. enum OpenGLType
  46969. {
  46970. openGLDefault = 0,
  46971. #if JUCE_IOS
  46972. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  46973. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  46974. #endif
  46975. };
  46976. /** Creates an OpenGLComponent. */
  46977. OpenGLComponent (OpenGLType type = openGLDefault);
  46978. /** Destructor. */
  46979. ~OpenGLComponent();
  46980. /** Changes the pixel format used by this component.
  46981. @see OpenGLPixelFormat::getAvailablePixelFormats()
  46982. */
  46983. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  46984. /** Returns the pixel format that this component is currently using. */
  46985. const OpenGLPixelFormat getPixelFormat() const;
  46986. /** Specifies an OpenGL context which should be shared with the one that this
  46987. component is using.
  46988. This is an OpenGL feature that lets two contexts share their texture data.
  46989. Note that this pointer is stored by the component, and when the component
  46990. needs to recreate its internal context for some reason, the same context
  46991. will be used again to share lists. So if you pass a context in here,
  46992. don't delete the context while this component is still using it! You can
  46993. call shareWith (0) to stop this component from sharing with it.
  46994. */
  46995. void shareWith (OpenGLContext* contextToShareListsWith);
  46996. /** Returns the context that this component is sharing with.
  46997. @see shareWith
  46998. */
  46999. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  47000. /** Flips the openGL buffers over. */
  47001. void swapBuffers();
  47002. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  47003. When this is called, makeCurrentContextActive() will already have been called
  47004. for you, so you just need to draw.
  47005. */
  47006. virtual void renderOpenGL() = 0;
  47007. /** This method is called when the component creates a new OpenGL context.
  47008. A new context may be created when the component is first used, or when it
  47009. is moved to a different window, or when the window is hidden and re-shown,
  47010. etc.
  47011. You can use this callback as an opportunity to set up things like textures
  47012. that your context needs.
  47013. New contexts are created on-demand by the makeCurrentContextActive() method - so
  47014. if the context is deleted, e.g. by changing the pixel format or window, no context
  47015. will be created until the next call to makeCurrentContextActive(), which will
  47016. synchronously create one and call this method. This means that if you're using
  47017. a non-GUI thread for rendering, you can make sure this method is be called by
  47018. your renderer thread.
  47019. When this callback happens, the context will already have been made current
  47020. using the makeCurrentContextActive() method, so there's no need to call it
  47021. again in your code.
  47022. */
  47023. virtual void newOpenGLContextCreated() = 0;
  47024. /** Returns the context that will draw into this component.
  47025. This may return 0 if the component is currently invisible or hasn't currently
  47026. got a context. The context object can be deleted and a new one created during
  47027. the lifetime of this component, and there may be times when it doesn't have one.
  47028. @see newOpenGLContextCreated()
  47029. */
  47030. OpenGLContext* getCurrentContext() const throw() { return context; }
  47031. /** Makes this component the current openGL context.
  47032. You might want to use this in things like your resize() method, before calling
  47033. GL commands.
  47034. If this returns false, then the context isn't active, so you should avoid
  47035. making any calls.
  47036. This call may actually create a context if one isn't currently initialised. If
  47037. it does this, it will also synchronously call the newOpenGLContextCreated()
  47038. method to let you initialise it as necessary.
  47039. @see OpenGLContext::makeActive
  47040. */
  47041. bool makeCurrentContextActive();
  47042. /** Stops the current component being the active OpenGL context.
  47043. This is the opposite of makeCurrentContextActive()
  47044. @see OpenGLContext::makeInactive
  47045. */
  47046. void makeCurrentContextInactive();
  47047. /** Returns true if this component is the active openGL context for the
  47048. current thread.
  47049. @see OpenGLContext::isActive
  47050. */
  47051. bool isActiveContext() const throw();
  47052. /** Calls the rendering callback, and swaps the buffers afterwards.
  47053. This is called automatically by paint() when the component needs to be rendered.
  47054. It can be overridden if you need to decouple the rendering from the paint callback
  47055. and render with a custom thread.
  47056. Returns true if the operation succeeded.
  47057. */
  47058. virtual bool renderAndSwapBuffers();
  47059. /** This returns a critical section that can be used to lock the current context.
  47060. Because the context that is used by this component can change, e.g. when the
  47061. component is shown or hidden, then if you're rendering to it on a background
  47062. thread, this allows you to lock the context for the duration of your rendering
  47063. routine.
  47064. */
  47065. CriticalSection& getContextLock() throw() { return contextLock; }
  47066. /** Returns the native handle of an embedded heavyweight window, if there is one.
  47067. E.g. On windows, this will return the HWND of the sub-window containing
  47068. the opengl context, on the mac it'll be the NSOpenGLView.
  47069. */
  47070. void* getNativeWindowHandle() const;
  47071. /** Delete the context.
  47072. This can be called back on the same thread that created the context. */
  47073. void deleteContext();
  47074. /** @internal */
  47075. void paint (Graphics& g);
  47076. private:
  47077. const OpenGLType type;
  47078. class OpenGLComponentWatcher;
  47079. friend class OpenGLComponentWatcher;
  47080. friend class ScopedPointer <OpenGLComponentWatcher>;
  47081. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  47082. ScopedPointer <OpenGLContext> context;
  47083. OpenGLContext* contextToShareListsWith;
  47084. CriticalSection contextLock;
  47085. OpenGLPixelFormat preferredPixelFormat;
  47086. bool needToUpdateViewport;
  47087. OpenGLContext* createContext();
  47088. void updateContextPosition();
  47089. void internalRepaint (int x, int y, int w, int h);
  47090. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponent);
  47091. };
  47092. #endif
  47093. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  47094. /*** End of inlined file: juce_OpenGLComponent.h ***/
  47095. #endif
  47096. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  47097. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  47098. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  47099. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  47100. /**
  47101. A component with a set of buttons at the top for changing between pages of
  47102. preferences.
  47103. This is just a handy way of writing a Mac-style preferences panel where you
  47104. have a row of buttons along the top for the different preference categories,
  47105. each button having an icon above its name. Clicking these will show an
  47106. appropriate prefs page below it.
  47107. You can either put one of these inside your own component, or just use the
  47108. showInDialogBox() method to show it in a window and run it modally.
  47109. To use it, just add a set of named pages with the addSettingsPage() method,
  47110. and implement the createComponentForPage() method to create suitable components
  47111. for each of these pages.
  47112. */
  47113. class JUCE_API PreferencesPanel : public Component,
  47114. private ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  47115. {
  47116. public:
  47117. /** Creates an empty panel.
  47118. Use addSettingsPage() to add some pages to it in your constructor.
  47119. */
  47120. PreferencesPanel();
  47121. /** Destructor. */
  47122. ~PreferencesPanel();
  47123. /** Creates a page using a set of drawables to define the page's icon.
  47124. Note that the other version of this method is much easier if you're using
  47125. an image instead of a custom drawable.
  47126. @param pageTitle the name of this preferences page - you'll need to
  47127. make sure your createComponentForPage() method creates
  47128. a suitable component when it is passed this name
  47129. @param normalIcon the drawable to display in the page's button normally
  47130. @param overIcon the drawable to display in the page's button when the mouse is over
  47131. @param downIcon the drawable to display in the page's button when the button is down
  47132. @see DrawableButton
  47133. */
  47134. void addSettingsPage (const String& pageTitle,
  47135. const Drawable* normalIcon,
  47136. const Drawable* overIcon,
  47137. const Drawable* downIcon);
  47138. /** Creates a page using a set of drawables to define the page's icon.
  47139. The other version of this method gives you more control over the icon, but this
  47140. one is much easier if you're just loading it from a file.
  47141. @param pageTitle the name of this preferences page - you'll need to
  47142. make sure your createComponentForPage() method creates
  47143. a suitable component when it is passed this name
  47144. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  47145. For this to look good, you'll probably want to use a nice
  47146. transparent png file.
  47147. @param imageDataSize the size of the image data, in bytes
  47148. */
  47149. void addSettingsPage (const String& pageTitle,
  47150. const void* imageData,
  47151. int imageDataSize);
  47152. /** Utility method to display this panel in a DialogWindow.
  47153. Calling this will create a DialogWindow containing this panel with the
  47154. given size and title, and will run it modally, returning when the user
  47155. closes the dialog box.
  47156. */
  47157. void showInDialogBox (const String& dialogTitle,
  47158. int dialogWidth,
  47159. int dialogHeight,
  47160. const Colour& backgroundColour = Colours::white);
  47161. /** Subclasses must override this to return a component for each preferences page.
  47162. The subclass should return a pointer to a new component representing the named
  47163. page, which the panel will then display.
  47164. The panel will delete the component later when the user goes to another page
  47165. or deletes the panel.
  47166. */
  47167. virtual Component* createComponentForPage (const String& pageName) = 0;
  47168. /** Changes the current page being displayed. */
  47169. void setCurrentPage (const String& pageName);
  47170. /** @internal */
  47171. void resized();
  47172. /** @internal */
  47173. void paint (Graphics& g);
  47174. /** @internal */
  47175. void buttonClicked (Button* button);
  47176. private:
  47177. String currentPageName;
  47178. ScopedPointer <Component> currentPage;
  47179. OwnedArray<DrawableButton> buttons;
  47180. int buttonSize;
  47181. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PreferencesPanel);
  47182. };
  47183. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  47184. /*** End of inlined file: juce_PreferencesPanel.h ***/
  47185. #endif
  47186. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  47187. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  47188. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  47189. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  47190. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  47191. // amalgamated build)
  47192. #ifndef DOXYGEN
  47193. #if JUCE_WINDOWS
  47194. typedef ActiveXControlComponent QTCompBaseClass;
  47195. #elif JUCE_MAC
  47196. typedef NSViewComponent QTCompBaseClass;
  47197. #endif
  47198. #endif
  47199. // this is used to disable QuickTime, and is defined in juce_Config.h
  47200. #if JUCE_QUICKTIME || DOXYGEN
  47201. /**
  47202. A window that can play back a QuickTime movie.
  47203. */
  47204. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  47205. {
  47206. public:
  47207. /** Creates a QuickTimeMovieComponent, initially blank.
  47208. Use the loadMovie() method to load a movie once you've added the
  47209. component to a window, (or put it on the desktop as a heavyweight window).
  47210. Loading a movie when the component isn't visible can cause problems, as
  47211. QuickTime needs a window handle to initialise properly.
  47212. */
  47213. QuickTimeMovieComponent();
  47214. /** Destructor. */
  47215. ~QuickTimeMovieComponent();
  47216. /** Returns true if QT is installed and working on this machine.
  47217. */
  47218. static bool isQuickTimeAvailable() throw();
  47219. /** Tries to load a QuickTime movie from a file into the player.
  47220. It's best to call this function once you've added the component to a window,
  47221. (or put it on the desktop as a heavyweight window). Loading a movie when the
  47222. component isn't visible can cause problems, because QuickTime needs a window
  47223. handle to do its stuff.
  47224. @param movieFile the .mov file to open
  47225. @param isControllerVisible whether to show a controller bar at the bottom
  47226. @returns true if the movie opens successfully
  47227. */
  47228. bool loadMovie (const File& movieFile,
  47229. bool isControllerVisible);
  47230. /** Tries to load a QuickTime movie from a URL into the player.
  47231. It's best to call this function once you've added the component to a window,
  47232. (or put it on the desktop as a heavyweight window). Loading a movie when the
  47233. component isn't visible can cause problems, because QuickTime needs a window
  47234. handle to do its stuff.
  47235. @param movieURL the .mov file to open
  47236. @param isControllerVisible whether to show a controller bar at the bottom
  47237. @returns true if the movie opens successfully
  47238. */
  47239. bool loadMovie (const URL& movieURL,
  47240. bool isControllerVisible);
  47241. /** Tries to load a QuickTime movie from a stream into the player.
  47242. It's best to call this function once you've added the component to a window,
  47243. (or put it on the desktop as a heavyweight window). Loading a movie when the
  47244. component isn't visible can cause problems, because QuickTime needs a window
  47245. handle to do its stuff.
  47246. @param movieStream a stream containing a .mov file. The component may try
  47247. to read the whole stream before playing, rather than
  47248. streaming from it.
  47249. @param isControllerVisible whether to show a controller bar at the bottom
  47250. @returns true if the movie opens successfully
  47251. */
  47252. bool loadMovie (InputStream* movieStream,
  47253. bool isControllerVisible);
  47254. /** Closes the movie, if one is open. */
  47255. void closeMovie();
  47256. /** Returns the movie file that is currently open.
  47257. If there isn't one, this returns File::nonexistent
  47258. */
  47259. const File getCurrentMovieFile() const;
  47260. /** Returns true if there's currently a movie open. */
  47261. bool isMovieOpen() const;
  47262. /** Returns the length of the movie, in seconds. */
  47263. double getMovieDuration() const;
  47264. /** Returns the movie's natural size, in pixels.
  47265. You can use this to resize the component to show the movie at its preferred
  47266. scale.
  47267. If no movie is loaded, the size returned will be 0 x 0.
  47268. */
  47269. void getMovieNormalSize (int& width, int& height) const;
  47270. /** This will position the component within a given area, keeping its aspect
  47271. ratio correct according to the movie's normal size.
  47272. The component will be made as large as it can go within the space, and will
  47273. be aligned according to the justification value if this means there are gaps at
  47274. the top or sides.
  47275. */
  47276. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  47277. const RectanglePlacement& placement);
  47278. /** Starts the movie playing. */
  47279. void play();
  47280. /** Stops the movie playing. */
  47281. void stop();
  47282. /** Returns true if the movie is currently playing. */
  47283. bool isPlaying() const;
  47284. /** Moves the movie's position back to the start. */
  47285. void goToStart();
  47286. /** Sets the movie's position to a given time. */
  47287. void setPosition (double seconds);
  47288. /** Returns the current play position of the movie. */
  47289. double getPosition() const;
  47290. /** Changes the movie playback rate.
  47291. A value of 1 is normal speed, greater values play it proportionately faster,
  47292. smaller values play it slower.
  47293. */
  47294. void setSpeed (float newSpeed);
  47295. /** Changes the movie's playback volume.
  47296. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  47297. */
  47298. void setMovieVolume (float newVolume);
  47299. /** Returns the movie's playback volume.
  47300. @returns the volume in the range 0 (silent) to 1.0 (full)
  47301. */
  47302. float getMovieVolume() const;
  47303. /** Tells the movie whether it should loop. */
  47304. void setLooping (bool shouldLoop);
  47305. /** Returns true if the movie is currently looping.
  47306. @see setLooping
  47307. */
  47308. bool isLooping() const;
  47309. /** True if the native QuickTime controller bar is shown in the window.
  47310. @see loadMovie
  47311. */
  47312. bool isControllerVisible() const;
  47313. /** @internal */
  47314. void paint (Graphics& g);
  47315. private:
  47316. File movieFile;
  47317. bool movieLoaded, controllerVisible, looping;
  47318. #if JUCE_WINDOWS
  47319. void parentHierarchyChanged();
  47320. void visibilityChanged();
  47321. void createControlIfNeeded();
  47322. bool isControlCreated() const;
  47323. class Pimpl;
  47324. friend class ScopedPointer <Pimpl>;
  47325. ScopedPointer <Pimpl> pimpl;
  47326. #else
  47327. void* movie;
  47328. #endif
  47329. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QuickTimeMovieComponent);
  47330. };
  47331. #endif
  47332. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  47333. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  47334. #endif
  47335. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  47336. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  47337. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  47338. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  47339. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  47340. /**
  47341. On Windows only, this component sits in the taskbar tray as a small icon.
  47342. To use it, just create one of these components, but don't attempt to make it
  47343. visible, add it to a parent, or put it on the desktop.
  47344. You can then call setIconImage() to create an icon for it in the taskbar.
  47345. To change the icon's tooltip, you can use setIconTooltip().
  47346. To respond to mouse-events, you can override the normal mouseDown(),
  47347. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  47348. position will not be valid, you can use this to respond to clicks. Traditionally
  47349. you'd use a left-click to show your application's window, and a right-click
  47350. to show a pop-up menu.
  47351. */
  47352. class JUCE_API SystemTrayIconComponent : public Component
  47353. {
  47354. public:
  47355. SystemTrayIconComponent();
  47356. /** Destructor. */
  47357. ~SystemTrayIconComponent();
  47358. /** Changes the image shown in the taskbar.
  47359. */
  47360. void setIconImage (const Image& newImage);
  47361. /** Changes the tooltip that Windows shows above the icon. */
  47362. void setIconTooltip (const String& tooltip);
  47363. #if JUCE_LINUX
  47364. /** @internal */
  47365. void paint (Graphics& g);
  47366. #endif
  47367. private:
  47368. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SystemTrayIconComponent);
  47369. };
  47370. #endif
  47371. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  47372. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  47373. #endif
  47374. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  47375. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  47376. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  47377. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  47378. #if JUCE_WEB_BROWSER || DOXYGEN
  47379. #if ! DOXYGEN
  47380. class WebBrowserComponentInternal;
  47381. #endif
  47382. /**
  47383. A component that displays an embedded web browser.
  47384. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  47385. Windows, probably IE.
  47386. */
  47387. class JUCE_API WebBrowserComponent : public Component
  47388. {
  47389. public:
  47390. /** Creates a WebBrowserComponent.
  47391. Once it's created and visible, send the browser to a URL using goToURL().
  47392. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  47393. component is taken offscreen, it'll clear the current page
  47394. and replace it with a blank page - this can be handy to stop
  47395. the browser using resources in the background when it's not
  47396. actually being used.
  47397. */
  47398. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  47399. /** Destructor. */
  47400. ~WebBrowserComponent();
  47401. /** Sends the browser to a particular URL.
  47402. @param url the URL to go to.
  47403. @param headers an optional set of parameters to put in the HTTP header. If
  47404. you supply this, it should be a set of string in the form
  47405. "HeaderKey: HeaderValue"
  47406. @param postData an optional block of data that will be attached to the HTTP
  47407. POST request
  47408. */
  47409. void goToURL (const String& url,
  47410. const StringArray* headers = 0,
  47411. const MemoryBlock* postData = 0);
  47412. /** Stops the current page loading.
  47413. */
  47414. void stop();
  47415. /** Sends the browser back one page.
  47416. */
  47417. void goBack();
  47418. /** Sends the browser forward one page.
  47419. */
  47420. void goForward();
  47421. /** Refreshes the browser.
  47422. */
  47423. void refresh();
  47424. /** This callback is called when the browser is about to navigate
  47425. to a new location.
  47426. You can override this method to perform some action when the user
  47427. tries to go to a particular URL. To allow the operation to carry on,
  47428. return true, or return false to stop the navigation happening.
  47429. */
  47430. virtual bool pageAboutToLoad (const String& newURL);
  47431. /** @internal */
  47432. void paint (Graphics& g);
  47433. /** @internal */
  47434. void resized();
  47435. /** @internal */
  47436. void parentHierarchyChanged();
  47437. /** @internal */
  47438. void visibilityChanged();
  47439. private:
  47440. WebBrowserComponentInternal* browser;
  47441. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  47442. String lastURL;
  47443. StringArray lastHeaders;
  47444. MemoryBlock lastPostData;
  47445. void reloadLastURL();
  47446. void checkWindowAssociation();
  47447. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponent);
  47448. };
  47449. #endif
  47450. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  47451. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  47452. #endif
  47453. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  47454. #endif
  47455. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  47456. /*** Start of inlined file: juce_CallOutBox.h ***/
  47457. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  47458. #define __JUCE_CALLOUTBOX_JUCEHEADER__
  47459. /**
  47460. A box with a small arrow that can be used as a temporary pop-up window to show
  47461. extra controls when a button or other component is clicked.
  47462. Using one of these is similar to having a popup menu attached to a button or
  47463. other component - but it looks fancier, and has an arrow that can indicate the
  47464. object that it applies to.
  47465. Normally, you'd create one of these on the stack and run it modally, e.g.
  47466. @code
  47467. void mouseUp (const MouseEvent& e)
  47468. {
  47469. MyContentComponent content;
  47470. content.setSize (300, 300);
  47471. CallOutBox callOut (content, *this, 0);
  47472. callOut.runModalLoop();
  47473. }
  47474. @endcode
  47475. The call-out will resize and position itself when the content changes size.
  47476. */
  47477. class JUCE_API CallOutBox : public Component
  47478. {
  47479. public:
  47480. /** Creates a CallOutBox.
  47481. @param contentComponent the component to display inside the call-out. This should
  47482. already have a size set (although the call-out will also
  47483. update itself when the component's size is changed later).
  47484. Obviously this component must not be deleted until the
  47485. call-out box has been deleted.
  47486. @param componentToPointTo the component that the call-out's arrow should point towards
  47487. @param parentComponent if non-zero, this is the component to add the call-out to. If
  47488. this is zero, the call-out will be added to the desktop.
  47489. */
  47490. CallOutBox (Component& contentComponent,
  47491. Component& componentToPointTo,
  47492. Component* parentComponent);
  47493. /** Destructor. */
  47494. ~CallOutBox();
  47495. /** Changes the length of the arrow. */
  47496. void setArrowSize (float newSize);
  47497. /** Updates the position and size of the box.
  47498. You shouldn't normally need to call this, unless you need more precise control over the
  47499. layout.
  47500. @param newAreaToPointTo the rectangle to make the box's arrow point to
  47501. @param newAreaToFitIn the area within which the box's position should be constrained
  47502. */
  47503. void updatePosition (const Rectangle<int>& newAreaToPointTo,
  47504. const Rectangle<int>& newAreaToFitIn);
  47505. /** @internal */
  47506. void paint (Graphics& g);
  47507. /** @internal */
  47508. void resized();
  47509. /** @internal */
  47510. void moved();
  47511. /** @internal */
  47512. void childBoundsChanged (Component*);
  47513. /** @internal */
  47514. bool hitTest (int x, int y);
  47515. /** @internal */
  47516. void inputAttemptWhenModal();
  47517. /** @internal */
  47518. bool keyPressed (const KeyPress& key);
  47519. /** @internal */
  47520. void handleCommandMessage (int commandId);
  47521. private:
  47522. int borderSpace;
  47523. float arrowSize;
  47524. Component& content;
  47525. Path outline;
  47526. Point<float> targetPoint;
  47527. Rectangle<int> availableArea, targetArea;
  47528. Image background;
  47529. void refreshPath();
  47530. void drawCallOutBoxBackground (Graphics& g, const Path& outline, int width, int height);
  47531. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallOutBox);
  47532. };
  47533. #endif // __JUCE_CALLOUTBOX_JUCEHEADER__
  47534. /*** End of inlined file: juce_CallOutBox.h ***/
  47535. #endif
  47536. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  47537. /*** Start of inlined file: juce_ComponentPeer.h ***/
  47538. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  47539. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  47540. class ComponentBoundsConstrainer;
  47541. /**
  47542. The base class for window objects that wrap a component as a real operating
  47543. system object.
  47544. This is an abstract base class - the platform specific code contains default
  47545. implementations of it that create and manage windows.
  47546. @see Component::createNewPeer
  47547. */
  47548. class JUCE_API ComponentPeer
  47549. {
  47550. public:
  47551. /** A combination of these flags is passed to the ComponentPeer constructor. */
  47552. enum StyleFlags
  47553. {
  47554. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  47555. entry on the taskbar (ignored on MacOSX) */
  47556. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  47557. tooltip, etc. */
  47558. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  47559. through it (may not be possible on some platforms). */
  47560. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  47561. title bar and frame\. if not specified, the window will be
  47562. borderless. */
  47563. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  47564. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  47565. minimise button on it. */
  47566. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  47567. maximise button on it. */
  47568. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  47569. close button on it. */
  47570. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  47571. not be possible on all platforms). */
  47572. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  47573. do its own repainting, but only to repaint when the
  47574. performAnyPendingRepaintsNow() method is called. */
  47575. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  47576. be used for things like plugin windows, to stop them interfering
  47577. with the host's shortcut keys */
  47578. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  47579. };
  47580. /** Creates a peer.
  47581. The component is the one that we intend to represent, and the style flags are
  47582. a combination of the values in the StyleFlags enum
  47583. */
  47584. ComponentPeer (Component* component, int styleFlags);
  47585. /** Destructor. */
  47586. virtual ~ComponentPeer();
  47587. /** Returns the component being represented by this peer. */
  47588. Component* getComponent() const throw() { return component; }
  47589. /** Returns the set of style flags that were set when the window was created.
  47590. @see Component::addToDesktop
  47591. */
  47592. int getStyleFlags() const throw() { return styleFlags; }
  47593. /** Returns the raw handle to whatever kind of window is being used.
  47594. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  47595. but rememeber there's no guarantees what you'll get back.
  47596. */
  47597. virtual void* getNativeHandle() const = 0;
  47598. /** Shows or hides the window. */
  47599. virtual void setVisible (bool shouldBeVisible) = 0;
  47600. /** Changes the title of the window. */
  47601. virtual void setTitle (const String& title) = 0;
  47602. /** Moves the window without changing its size.
  47603. If the native window is contained in another window, then the co-ordinates are
  47604. relative to the parent window's origin, not the screen origin.
  47605. This should result in a callback to handleMovedOrResized().
  47606. */
  47607. virtual void setPosition (int x, int y) = 0;
  47608. /** Resizes the window without changing its position.
  47609. This should result in a callback to handleMovedOrResized().
  47610. */
  47611. virtual void setSize (int w, int h) = 0;
  47612. /** Moves and resizes the window.
  47613. If the native window is contained in another window, then the co-ordinates are
  47614. relative to the parent window's origin, not the screen origin.
  47615. This should result in a callback to handleMovedOrResized().
  47616. */
  47617. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  47618. /** Returns the current position and size of the window.
  47619. If the native window is contained in another window, then the co-ordinates are
  47620. relative to the parent window's origin, not the screen origin.
  47621. */
  47622. virtual const Rectangle<int> getBounds() const = 0;
  47623. /** Returns the x-position of this window, relative to the screen's origin. */
  47624. virtual const Point<int> getScreenPosition() const = 0;
  47625. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  47626. virtual const Point<int> localToGlobal (const Point<int>& relativePosition) = 0;
  47627. /** Converts a rectangle relative to the top-left of this component to screen co-ordinates. */
  47628. virtual const Rectangle<int> localToGlobal (const Rectangle<int>& relativePosition);
  47629. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  47630. virtual const Point<int> globalToLocal (const Point<int>& screenPosition) = 0;
  47631. /** Converts a screen area to a position relative to the top-left of this component. */
  47632. virtual const Rectangle<int> globalToLocal (const Rectangle<int>& screenPosition);
  47633. /** Minimises the window. */
  47634. virtual void setMinimised (bool shouldBeMinimised) = 0;
  47635. /** True if the window is currently minimised. */
  47636. virtual bool isMinimised() const = 0;
  47637. /** Enable/disable fullscreen mode for the window. */
  47638. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  47639. /** True if the window is currently full-screen. */
  47640. virtual bool isFullScreen() const = 0;
  47641. /** Sets the size to restore to if fullscreen mode is turned off. */
  47642. void setNonFullScreenBounds (const Rectangle<int>& newBounds) throw();
  47643. /** Returns the size to restore to if fullscreen mode is turned off. */
  47644. const Rectangle<int>& getNonFullScreenBounds() const throw();
  47645. /** Attempts to change the icon associated with this window.
  47646. */
  47647. virtual void setIcon (const Image& newIcon) = 0;
  47648. /** Sets a constrainer to use if the peer can resize itself.
  47649. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  47650. */
  47651. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) throw();
  47652. /** Returns the current constrainer, if one has been set. */
  47653. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  47654. /** Checks if a point is in the window.
  47655. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  47656. is false, then this returns false if the point is actually inside a child of this
  47657. window.
  47658. */
  47659. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  47660. /** Returns the size of the window frame that's around this window.
  47661. Whether or not the window has a normal window frame depends on the flags
  47662. that were set when the window was created by Component::addToDesktop()
  47663. */
  47664. virtual const BorderSize<int> getFrameSize() const = 0;
  47665. /** This is called when the window's bounds change.
  47666. A peer implementation must call this when the window is moved and resized, so that
  47667. this method can pass the message on to the component.
  47668. */
  47669. void handleMovedOrResized();
  47670. /** This is called if the screen resolution changes.
  47671. A peer implementation must call this if the monitor arrangement changes or the available
  47672. screen size changes.
  47673. */
  47674. void handleScreenSizeChange();
  47675. /** This is called to repaint the component into the given context. */
  47676. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  47677. /** Sets this window to either be always-on-top or normal.
  47678. Some kinds of window might not be able to do this, so should return false.
  47679. */
  47680. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  47681. /** Brings the window to the top, optionally also giving it focus. */
  47682. virtual void toFront (bool makeActive) = 0;
  47683. /** Moves the window to be just behind another one. */
  47684. virtual void toBehind (ComponentPeer* other) = 0;
  47685. /** Called when the window is brought to the front, either by the OS or by a call
  47686. to toFront().
  47687. */
  47688. void handleBroughtToFront();
  47689. /** True if the window has the keyboard focus. */
  47690. virtual bool isFocused() const = 0;
  47691. /** Tries to give the window keyboard focus. */
  47692. virtual void grabFocus() = 0;
  47693. /** Tells the window that text input may be required at the given position.
  47694. This may cause things like a virtual on-screen keyboard to appear, depending
  47695. on the OS.
  47696. */
  47697. virtual void textInputRequired (const Point<int>& position) = 0;
  47698. /** Called when the window gains keyboard focus. */
  47699. void handleFocusGain();
  47700. /** Called when the window loses keyboard focus. */
  47701. void handleFocusLoss();
  47702. Component* getLastFocusedSubcomponent() const throw();
  47703. /** Called when a key is pressed.
  47704. For keycode info, see the KeyPress class.
  47705. Returns true if the keystroke was used.
  47706. */
  47707. bool handleKeyPress (int keyCode, juce_wchar textCharacter);
  47708. /** Called whenever a key is pressed or released.
  47709. Returns true if the keystroke was used.
  47710. */
  47711. bool handleKeyUpOrDown (bool isKeyDown);
  47712. /** Called whenever a modifier key is pressed or released. */
  47713. void handleModifierKeysChange();
  47714. /** Returns the currently focused TextInputTarget, or null if none is found. */
  47715. TextInputTarget* findCurrentTextInputTarget();
  47716. /** Invalidates a region of the window to be repainted asynchronously. */
  47717. virtual void repaint (const Rectangle<int>& area) = 0;
  47718. /** This can be called (from the message thread) to cause the immediate redrawing
  47719. of any areas of this window that need repainting.
  47720. You shouldn't ever really need to use this, it's mainly for special purposes
  47721. like supporting audio plugins where the host's event loop is out of our control.
  47722. */
  47723. virtual void performAnyPendingRepaintsNow() = 0;
  47724. /** Changes the window's transparency. */
  47725. virtual void setAlpha (float newAlpha) = 0;
  47726. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  47727. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  47728. void handleUserClosingWindow();
  47729. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  47730. void handleFileDragExit (const StringArray& files);
  47731. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  47732. /** Resets the masking region.
  47733. The subclass should call this every time it's about to call the handlePaint
  47734. method.
  47735. @see addMaskedRegion
  47736. */
  47737. void clearMaskedRegion();
  47738. /** Adds a rectangle to the set of areas not to paint over.
  47739. A component can call this on its peer during its paint() method, to signal
  47740. that the painting code should ignore a given region. The reason
  47741. for this is to stop embedded windows (such as OpenGL) getting painted over.
  47742. The masked region is cleared each time before a paint happens, so a component
  47743. will have to make sure it calls this every time it's painted.
  47744. */
  47745. void addMaskedRegion (int x, int y, int w, int h);
  47746. /** Returns the number of currently-active peers.
  47747. @see getPeer
  47748. */
  47749. static int getNumPeers() throw();
  47750. /** Returns one of the currently-active peers.
  47751. @see getNumPeers
  47752. */
  47753. static ComponentPeer* getPeer (int index) throw();
  47754. /** Checks if this peer object is valid.
  47755. @see getNumPeers
  47756. */
  47757. static bool isValidPeer (const ComponentPeer* peer) throw();
  47758. virtual const StringArray getAvailableRenderingEngines();
  47759. virtual int getCurrentRenderingEngine() throw();
  47760. virtual void setCurrentRenderingEngine (int index);
  47761. protected:
  47762. Component* const component;
  47763. const int styleFlags;
  47764. RectangleList maskedRegion;
  47765. Rectangle<int> lastNonFullscreenBounds;
  47766. uint32 lastPaintTime;
  47767. ComponentBoundsConstrainer* constrainer;
  47768. static void updateCurrentModifiers() throw();
  47769. private:
  47770. WeakReference<Component> lastFocusedComponent, dragAndDropTargetComponent;
  47771. Component* lastDragAndDropCompUnderMouse;
  47772. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  47773. friend class Component;
  47774. friend class Desktop;
  47775. static ComponentPeer* getPeerFor (const Component* component) throw();
  47776. void setLastDragDropTarget (Component* comp);
  47777. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComponentPeer);
  47778. };
  47779. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  47780. /*** End of inlined file: juce_ComponentPeer.h ***/
  47781. #endif
  47782. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  47783. /*** Start of inlined file: juce_DialogWindow.h ***/
  47784. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  47785. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  47786. /**
  47787. A dialog-box style window.
  47788. This class is a convenient way of creating a DocumentWindow with a close button
  47789. that can be triggered by pressing the escape key.
  47790. Any of the methods available to a DocumentWindow or ResizableWindow are also
  47791. available to this, so it can be made resizable, have a menu bar, etc.
  47792. To add items to the box, see the ResizableWindow::setContentComponent() method.
  47793. Don't add components directly to this class - always put them in a content component!
  47794. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  47795. the user clicking the close button - for more info, see the DocumentWindow
  47796. help.
  47797. @see DocumentWindow, ResizableWindow
  47798. */
  47799. class JUCE_API DialogWindow : public DocumentWindow
  47800. {
  47801. public:
  47802. /** Creates a DialogWindow.
  47803. @param name the name to give the component - this is also
  47804. the title shown at the top of the window. To change
  47805. this later, use setName()
  47806. @param backgroundColour the colour to use for filling the window's background.
  47807. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  47808. close button to be triggered
  47809. @param addToDesktop if true, the window will be automatically added to the
  47810. desktop; if false, you can use it as a child component
  47811. */
  47812. DialogWindow (const String& name,
  47813. const Colour& backgroundColour,
  47814. bool escapeKeyTriggersCloseButton,
  47815. bool addToDesktop = true);
  47816. /** Destructor.
  47817. If a content component has been set with setContentComponent(), it
  47818. will be deleted.
  47819. */
  47820. ~DialogWindow();
  47821. /** Easy way of quickly showing a dialog box containing a given component.
  47822. This will open and display a DialogWindow containing a given component, returning
  47823. when the user clicks its close button.
  47824. It returns the value that was returned by the dialog box's runModalLoop() call.
  47825. To close the dialog programatically, you should call exitModalState (returnValue) on
  47826. the DialogWindow that is created. To find a pointer to this window from your
  47827. contentComponent, you can do something like this:
  47828. @code
  47829. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  47830. if (dw != 0)
  47831. dw->exitModalState (1234);
  47832. @endcode
  47833. @param dialogTitle the dialog box's title
  47834. @param contentComponent the content component for the dialog box. Make sure
  47835. that this has been set to the size you want it to
  47836. be before calling this method. The component won't
  47837. be deleted by this call, so you can re-use it or delete
  47838. it afterwards
  47839. @param componentToCentreAround if this is non-zero, it indicates a component that
  47840. you'd like to show this dialog box in front of. See the
  47841. DocumentWindow::centreAroundComponent() method for more
  47842. info on this parameter
  47843. @param backgroundColour a colour to use for the dialog box's background colour
  47844. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  47845. close button to be triggered
  47846. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  47847. a corner resizer
  47848. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  47849. to use a border or corner resizer component. See ResizableWindow::setResizable()
  47850. */
  47851. static int showModalDialog (const String& dialogTitle,
  47852. Component* contentComponent,
  47853. Component* componentToCentreAround,
  47854. const Colour& backgroundColour,
  47855. bool escapeKeyTriggersCloseButton,
  47856. bool shouldBeResizable = false,
  47857. bool useBottomRightCornerResizer = false);
  47858. protected:
  47859. /** @internal */
  47860. void resized();
  47861. private:
  47862. bool escapeKeyTriggersCloseButton;
  47863. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DialogWindow);
  47864. };
  47865. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  47866. /*** End of inlined file: juce_DialogWindow.h ***/
  47867. #endif
  47868. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  47869. #endif
  47870. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  47871. #endif
  47872. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  47873. /*** Start of inlined file: juce_SplashScreen.h ***/
  47874. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  47875. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  47876. /** A component for showing a splash screen while your app starts up.
  47877. This will automatically position itself, and delete itself when the app has
  47878. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  47879. this).
  47880. To use it, just create one of these in your JUCEApplication::initialise() method,
  47881. call its show() method and let the object delete itself later.
  47882. E.g. @code
  47883. void MyApp::initialise (const String& commandLine)
  47884. {
  47885. SplashScreen* splash = new SplashScreen();
  47886. splash->show ("welcome to my app",
  47887. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  47888. 4000, false);
  47889. .. no need to delete the splash screen - it'll do that itself.
  47890. }
  47891. @endcode
  47892. */
  47893. class JUCE_API SplashScreen : public Component,
  47894. public Timer,
  47895. private DeletedAtShutdown
  47896. {
  47897. public:
  47898. /** Creates a SplashScreen object.
  47899. After creating one of these (or your subclass of it), call one of the show()
  47900. methods to display it.
  47901. */
  47902. SplashScreen();
  47903. /** Destructor. */
  47904. ~SplashScreen();
  47905. /** Creates a SplashScreen object that will display an image.
  47906. As soon as this is called, the SplashScreen will be displayed in the centre of the
  47907. screen. This method will also dispatch any pending messages to make sure that when
  47908. it returns, the splash screen has been completely drawn, and your initialisation
  47909. code can carry on.
  47910. @param title the name to give the component
  47911. @param backgroundImage an image to draw on the component. The component's size
  47912. will be set to the size of this image, and if the image is
  47913. semi-transparent, the component will be made semi-transparent
  47914. too. This image will be deleted (or released from the ImageCache
  47915. if that's how it was created) by the splash screen object when
  47916. it is itself deleted.
  47917. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  47918. should stay visible for. If the initialisation takes longer than
  47919. this time, the splash screen will wait for it to finish before
  47920. disappearing, but if initialisation is very quick, this lets
  47921. you make sure that people get a good look at your splash.
  47922. @param useDropShadow if true, the window will have a drop shadow
  47923. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  47924. the mouse (anywhere)
  47925. */
  47926. void show (const String& title,
  47927. const Image& backgroundImage,
  47928. int minimumTimeToDisplayFor,
  47929. bool useDropShadow,
  47930. bool removeOnMouseClick = true);
  47931. /** Creates a SplashScreen object with a specified size.
  47932. For a custom splash screen, you can use this method to display it at a certain size
  47933. and then override the paint() method yourself to do whatever's necessary.
  47934. As soon as this is called, the SplashScreen will be displayed in the centre of the
  47935. screen. This method will also dispatch any pending messages to make sure that when
  47936. it returns, the splash screen has been completely drawn, and your initialisation
  47937. code can carry on.
  47938. @param title the name to give the component
  47939. @param width the width to use
  47940. @param height the height to use
  47941. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  47942. should stay visible for. If the initialisation takes longer than
  47943. this time, the splash screen will wait for it to finish before
  47944. disappearing, but if initialisation is very quick, this lets
  47945. you make sure that people get a good look at your splash.
  47946. @param useDropShadow if true, the window will have a drop shadow
  47947. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  47948. the mouse (anywhere)
  47949. */
  47950. void show (const String& title,
  47951. int width,
  47952. int height,
  47953. int minimumTimeToDisplayFor,
  47954. bool useDropShadow,
  47955. bool removeOnMouseClick = true);
  47956. /** @internal */
  47957. void paint (Graphics& g);
  47958. /** @internal */
  47959. void timerCallback();
  47960. private:
  47961. Image backgroundImage;
  47962. Time earliestTimeToDelete;
  47963. int originalClickCounter;
  47964. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SplashScreen);
  47965. };
  47966. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  47967. /*** End of inlined file: juce_SplashScreen.h ***/
  47968. #endif
  47969. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  47970. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  47971. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  47972. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  47973. /**
  47974. A thread that automatically pops up a modal dialog box with a progress bar
  47975. and cancel button while it's busy running.
  47976. These are handy for performing some sort of task while giving the user feedback
  47977. about how long there is to go, etc.
  47978. E.g. @code
  47979. class MyTask : public ThreadWithProgressWindow
  47980. {
  47981. public:
  47982. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  47983. {
  47984. }
  47985. ~MyTask()
  47986. {
  47987. }
  47988. void run()
  47989. {
  47990. for (int i = 0; i < thingsToDo; ++i)
  47991. {
  47992. // must check this as often as possible, because this is
  47993. // how we know if the user's pressed 'cancel'
  47994. if (threadShouldExit())
  47995. break;
  47996. // this will update the progress bar on the dialog box
  47997. setProgress (i / (double) thingsToDo);
  47998. // ... do the business here...
  47999. }
  48000. }
  48001. };
  48002. void doTheTask()
  48003. {
  48004. MyTask m;
  48005. if (m.runThread())
  48006. {
  48007. // thread finished normally..
  48008. }
  48009. else
  48010. {
  48011. // user pressed the cancel button..
  48012. }
  48013. }
  48014. @endcode
  48015. @see Thread, AlertWindow
  48016. */
  48017. class JUCE_API ThreadWithProgressWindow : public Thread,
  48018. private Timer
  48019. {
  48020. public:
  48021. /** Creates the thread.
  48022. Initially, the dialog box won't be visible, it'll only appear when the
  48023. runThread() method is called.
  48024. @param windowTitle the title to go at the top of the dialog box
  48025. @param hasProgressBar whether the dialog box should have a progress bar (see
  48026. setProgress() )
  48027. @param hasCancelButton whether the dialog box should have a cancel button
  48028. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  48029. the thread to stop before killing it forcibly (see
  48030. Thread::stopThread() )
  48031. @param cancelButtonText the text that should be shown in the cancel button
  48032. (if it has one)
  48033. */
  48034. ThreadWithProgressWindow (const String& windowTitle,
  48035. bool hasProgressBar,
  48036. bool hasCancelButton,
  48037. int timeOutMsWhenCancelling = 10000,
  48038. const String& cancelButtonText = "Cancel");
  48039. /** Destructor. */
  48040. ~ThreadWithProgressWindow();
  48041. /** Starts the thread and waits for it to finish.
  48042. This will start the thread, make the dialog box appear, and wait until either
  48043. the thread finishes normally, or until the cancel button is pressed.
  48044. Before returning, the dialog box will be hidden.
  48045. @param threadPriority the priority to use when starting the thread - see
  48046. Thread::startThread() for values
  48047. @returns true if the thread finished normally; false if the user pressed cancel
  48048. */
  48049. bool runThread (int threadPriority = 5);
  48050. /** The thread should call this periodically to update the position of the progress bar.
  48051. @param newProgress the progress, from 0.0 to 1.0
  48052. @see setStatusMessage
  48053. */
  48054. void setProgress (double newProgress);
  48055. /** The thread can call this to change the message that's displayed in the dialog box.
  48056. */
  48057. void setStatusMessage (const String& newStatusMessage);
  48058. /** Returns the AlertWindow that is being used.
  48059. */
  48060. AlertWindow* getAlertWindow() const throw() { return alertWindow; }
  48061. private:
  48062. void timerCallback();
  48063. double progress;
  48064. ScopedPointer <AlertWindow> alertWindow;
  48065. String message;
  48066. CriticalSection messageLock;
  48067. const int timeOutMsWhenCancelling;
  48068. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadWithProgressWindow);
  48069. };
  48070. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  48071. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  48072. #endif
  48073. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  48074. #endif
  48075. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  48076. #endif
  48077. #ifndef __JUCE_COLOUR_JUCEHEADER__
  48078. #endif
  48079. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  48080. #endif
  48081. #ifndef __JUCE_COLOURS_JUCEHEADER__
  48082. #endif
  48083. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  48084. #endif
  48085. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  48086. /*** Start of inlined file: juce_EdgeTable.h ***/
  48087. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  48088. #define __JUCE_EDGETABLE_JUCEHEADER__
  48089. class Path;
  48090. class Image;
  48091. /**
  48092. A table of horizontal scan-line segments - used for rasterising Paths.
  48093. @see Path, Graphics
  48094. */
  48095. class JUCE_API EdgeTable
  48096. {
  48097. public:
  48098. /** Creates an edge table containing a path.
  48099. A table is created with a fixed vertical range, and only sections of the path
  48100. which lie within this range will be added to the table.
  48101. @param clipLimits only the region of the path that lies within this area will be added
  48102. @param pathToAdd the path to add to the table
  48103. @param transform a transform to apply to the path being added
  48104. */
  48105. EdgeTable (const Rectangle<int>& clipLimits,
  48106. const Path& pathToAdd,
  48107. const AffineTransform& transform);
  48108. /** Creates an edge table containing a rectangle.
  48109. */
  48110. EdgeTable (const Rectangle<int>& rectangleToAdd);
  48111. /** Creates an edge table containing a rectangle list.
  48112. */
  48113. EdgeTable (const RectangleList& rectanglesToAdd);
  48114. /** Creates an edge table containing a rectangle.
  48115. */
  48116. EdgeTable (const Rectangle<float>& rectangleToAdd);
  48117. /** Creates a copy of another edge table. */
  48118. EdgeTable (const EdgeTable& other);
  48119. /** Copies from another edge table. */
  48120. EdgeTable& operator= (const EdgeTable& other);
  48121. /** Destructor. */
  48122. ~EdgeTable();
  48123. void clipToRectangle (const Rectangle<int>& r);
  48124. void excludeRectangle (const Rectangle<int>& r);
  48125. void clipToEdgeTable (const EdgeTable& other);
  48126. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels);
  48127. bool isEmpty() throw();
  48128. const Rectangle<int>& getMaximumBounds() const throw() { return bounds; }
  48129. void translate (float dx, int dy) throw();
  48130. /** Reduces the amount of space the table has allocated.
  48131. This will shrink the table down to use as little memory as possible - useful for
  48132. read-only tables that get stored and re-used for rendering.
  48133. */
  48134. void optimiseTable();
  48135. /** Iterates the lines in the table, for rendering.
  48136. This function will iterate each line in the table, and call a user-defined class
  48137. to render each pixel or continuous line of pixels that the table contains.
  48138. @param iterationCallback this templated class must contain the following methods:
  48139. @code
  48140. inline void setEdgeTableYPos (int y);
  48141. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  48142. inline void handleEdgeTablePixelFull (int x) const;
  48143. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  48144. inline void handleEdgeTableLineFull (int x, int width) const;
  48145. @endcode
  48146. (these don't necessarily have to be 'const', but it might help it go faster)
  48147. */
  48148. template <class EdgeTableIterationCallback>
  48149. void iterate (EdgeTableIterationCallback& iterationCallback) const throw()
  48150. {
  48151. const int* lineStart = table;
  48152. for (int y = 0; y < bounds.getHeight(); ++y)
  48153. {
  48154. const int* line = lineStart;
  48155. lineStart += lineStrideElements;
  48156. int numPoints = line[0];
  48157. if (--numPoints > 0)
  48158. {
  48159. int x = *++line;
  48160. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  48161. int levelAccumulator = 0;
  48162. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  48163. while (--numPoints >= 0)
  48164. {
  48165. const int level = *++line;
  48166. jassert (isPositiveAndBelow (level, (int) 256));
  48167. const int endX = *++line;
  48168. jassert (endX >= x);
  48169. const int endOfRun = (endX >> 8);
  48170. if (endOfRun == (x >> 8))
  48171. {
  48172. // small segment within the same pixel, so just save it for the next
  48173. // time round..
  48174. levelAccumulator += (endX - x) * level;
  48175. }
  48176. else
  48177. {
  48178. // plot the fist pixel of this segment, including any accumulated
  48179. // levels from smaller segments that haven't been drawn yet
  48180. levelAccumulator += (0x100 - (x & 0xff)) * level;
  48181. levelAccumulator >>= 8;
  48182. x >>= 8;
  48183. if (levelAccumulator > 0)
  48184. {
  48185. if (levelAccumulator >= 255)
  48186. iterationCallback.handleEdgeTablePixelFull (x);
  48187. else
  48188. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  48189. }
  48190. // if there's a run of similar pixels, do it all in one go..
  48191. if (level > 0)
  48192. {
  48193. jassert (endOfRun <= bounds.getRight());
  48194. const int numPix = endOfRun - ++x;
  48195. if (numPix > 0)
  48196. iterationCallback.handleEdgeTableLine (x, numPix, level);
  48197. }
  48198. // save the bit at the end to be drawn next time round the loop.
  48199. levelAccumulator = (endX & 0xff) * level;
  48200. }
  48201. x = endX;
  48202. }
  48203. levelAccumulator >>= 8;
  48204. if (levelAccumulator > 0)
  48205. {
  48206. x >>= 8;
  48207. jassert (x >= bounds.getX() && x < bounds.getRight());
  48208. if (levelAccumulator >= 255)
  48209. iterationCallback.handleEdgeTablePixelFull (x);
  48210. else
  48211. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  48212. }
  48213. }
  48214. }
  48215. }
  48216. private:
  48217. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  48218. HeapBlock<int> table;
  48219. Rectangle<int> bounds;
  48220. int maxEdgesPerLine, lineStrideElements;
  48221. bool needToCheckEmptinesss;
  48222. void addEdgePoint (int x, int y, int winding);
  48223. void remapTableForNumEdges (int newNumEdgesPerLine);
  48224. void intersectWithEdgeTableLine (int y, const int* otherLine);
  48225. void clipEdgeTableLineToRange (int* line, int x1, int x2) throw();
  48226. void sanitiseLevels (bool useNonZeroWinding) throw();
  48227. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) throw();
  48228. JUCE_LEAK_DETECTOR (EdgeTable);
  48229. };
  48230. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  48231. /*** End of inlined file: juce_EdgeTable.h ***/
  48232. #endif
  48233. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  48234. /*** Start of inlined file: juce_FillType.h ***/
  48235. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  48236. #define __JUCE_FILLTYPE_JUCEHEADER__
  48237. /**
  48238. Represents a colour or fill pattern to use for rendering paths.
  48239. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  48240. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  48241. @see Graphics::setFillType, DrawablePath::setFill
  48242. */
  48243. class JUCE_API FillType
  48244. {
  48245. public:
  48246. /** Creates a default fill type, of solid black. */
  48247. FillType() throw();
  48248. /** Creates a fill type of a solid colour.
  48249. @see setColour
  48250. */
  48251. FillType (const Colour& colour) throw();
  48252. /** Creates a gradient fill type.
  48253. @see setGradient
  48254. */
  48255. FillType (const ColourGradient& gradient);
  48256. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  48257. and rotation of the pattern.
  48258. @see setTiledImage
  48259. */
  48260. FillType (const Image& image, const AffineTransform& transform) throw();
  48261. /** Creates a copy of another FillType. */
  48262. FillType (const FillType& other);
  48263. /** Makes a copy of another FillType. */
  48264. FillType& operator= (const FillType& other);
  48265. /** Destructor. */
  48266. ~FillType() throw();
  48267. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  48268. bool isColour() const throw() { return gradient == 0 && image.isNull(); }
  48269. /** Returns true if this is a gradient fill. */
  48270. bool isGradient() const throw() { return gradient != 0; }
  48271. /** Returns true if this is a tiled image pattern fill. */
  48272. bool isTiledImage() const throw() { return image.isValid(); }
  48273. /** Turns this object into a solid colour fill.
  48274. If the object was an image or gradient, those fields will no longer be valid. */
  48275. void setColour (const Colour& newColour) throw();
  48276. /** Turns this object into a gradient fill. */
  48277. void setGradient (const ColourGradient& newGradient);
  48278. /** Turns this object into a tiled image fill type. The transform allows you to set
  48279. the scaling, offset and rotation of the pattern.
  48280. */
  48281. void setTiledImage (const Image& image, const AffineTransform& transform) throw();
  48282. /** Changes the opacity that should be used.
  48283. If the fill is a solid colour, this just changes the opacity of that colour. For
  48284. gradients and image tiles, it changes the opacity that will be used for them.
  48285. */
  48286. void setOpacity (float newOpacity) throw();
  48287. /** Returns the current opacity to be applied to the colour, gradient, or image.
  48288. @see setOpacity
  48289. */
  48290. float getOpacity() const throw() { return colour.getFloatAlpha(); }
  48291. /** Returns true if this fill type is completely transparent. */
  48292. bool isInvisible() const throw();
  48293. bool operator== (const FillType& other) const;
  48294. bool operator!= (const FillType& other) const;
  48295. /** The solid colour being used.
  48296. If the fill type is not a solid colour, the alpha channel of this colour indicates
  48297. the opacity that should be used for the fill, and the RGB channels are ignored.
  48298. */
  48299. Colour colour;
  48300. /** Returns the gradient that should be used for filling.
  48301. This will be zero if the object is some other type of fill.
  48302. If a gradient is active, the overall opacity with which it should be applied
  48303. is indicated by the alpha channel of the colour variable.
  48304. */
  48305. ScopedPointer <ColourGradient> gradient;
  48306. /** The image that should be used for tiling.
  48307. If an image fill is active, the overall opacity with which it should be applied
  48308. is indicated by the alpha channel of the colour variable.
  48309. */
  48310. Image image;
  48311. /** The transform that should be applied to the image or gradient that's being drawn.
  48312. */
  48313. AffineTransform transform;
  48314. private:
  48315. JUCE_LEAK_DETECTOR (FillType);
  48316. };
  48317. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  48318. /*** End of inlined file: juce_FillType.h ***/
  48319. #endif
  48320. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  48321. #endif
  48322. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  48323. #endif
  48324. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  48325. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  48326. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  48327. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  48328. /**
  48329. Interface class for graphics context objects, used internally by the Graphics class.
  48330. Users are not supposed to create instances of this class directly - do your drawing
  48331. via the Graphics object instead.
  48332. It's a base class for different types of graphics context, that may perform software-based
  48333. or OS-accelerated rendering.
  48334. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  48335. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  48336. context.
  48337. */
  48338. class JUCE_API LowLevelGraphicsContext
  48339. {
  48340. protected:
  48341. LowLevelGraphicsContext();
  48342. public:
  48343. virtual ~LowLevelGraphicsContext();
  48344. /** Returns true if this device is vector-based, e.g. a printer. */
  48345. virtual bool isVectorDevice() const = 0;
  48346. /** Moves the origin to a new position.
  48347. The co-ords are relative to the current origin, and indicate the new position
  48348. of (0, 0).
  48349. */
  48350. virtual void setOrigin (int x, int y) = 0;
  48351. virtual void addTransform (const AffineTransform& transform) = 0;
  48352. virtual float getScaleFactor() = 0;
  48353. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  48354. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  48355. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  48356. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  48357. virtual void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform) = 0;
  48358. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  48359. virtual const Rectangle<int> getClipBounds() const = 0;
  48360. virtual bool isClipEmpty() const = 0;
  48361. virtual void saveState() = 0;
  48362. virtual void restoreState() = 0;
  48363. virtual void beginTransparencyLayer (float opacity) = 0;
  48364. virtual void endTransparencyLayer() = 0;
  48365. virtual void setFill (const FillType& fillType) = 0;
  48366. virtual void setOpacity (float newOpacity) = 0;
  48367. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  48368. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  48369. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  48370. virtual void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  48371. virtual void drawLine (const Line <float>& line) = 0;
  48372. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  48373. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  48374. virtual void setFont (const Font& newFont) = 0;
  48375. virtual const Font getFont() = 0;
  48376. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  48377. };
  48378. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  48379. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  48380. #endif
  48381. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  48382. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  48383. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  48384. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  48385. /**
  48386. An implementation of LowLevelGraphicsContext that turns the drawing operations
  48387. into a PostScript document.
  48388. */
  48389. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  48390. {
  48391. public:
  48392. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  48393. const String& documentTitle,
  48394. int totalWidth,
  48395. int totalHeight);
  48396. ~LowLevelGraphicsPostScriptRenderer();
  48397. bool isVectorDevice() const;
  48398. void setOrigin (int x, int y);
  48399. void addTransform (const AffineTransform& transform);
  48400. float getScaleFactor();
  48401. bool clipToRectangle (const Rectangle<int>& r);
  48402. bool clipToRectangleList (const RectangleList& clipRegion);
  48403. void excludeClipRectangle (const Rectangle<int>& r);
  48404. void clipToPath (const Path& path, const AffineTransform& transform);
  48405. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  48406. void saveState();
  48407. void restoreState();
  48408. void beginTransparencyLayer (float opacity);
  48409. void endTransparencyLayer();
  48410. bool clipRegionIntersects (const Rectangle<int>& r);
  48411. const Rectangle<int> getClipBounds() const;
  48412. bool isClipEmpty() const;
  48413. void setFill (const FillType& fillType);
  48414. void setOpacity (float opacity);
  48415. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  48416. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  48417. void fillPath (const Path& path, const AffineTransform& transform);
  48418. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  48419. void drawLine (const Line <float>& line);
  48420. void drawVerticalLine (int x, float top, float bottom);
  48421. void drawHorizontalLine (int x, float top, float bottom);
  48422. const Font getFont();
  48423. void setFont (const Font& newFont);
  48424. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  48425. protected:
  48426. OutputStream& out;
  48427. int totalWidth, totalHeight;
  48428. bool needToClip;
  48429. Colour lastColour;
  48430. struct SavedState
  48431. {
  48432. SavedState();
  48433. ~SavedState();
  48434. RectangleList clip;
  48435. int xOffset, yOffset;
  48436. FillType fillType;
  48437. Font font;
  48438. private:
  48439. SavedState& operator= (const SavedState&);
  48440. };
  48441. OwnedArray <SavedState> stateStack;
  48442. void writeClip();
  48443. void writeColour (const Colour& colour);
  48444. void writePath (const Path& path) const;
  48445. void writeXY (float x, float y) const;
  48446. void writeTransform (const AffineTransform& trans) const;
  48447. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  48448. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsPostScriptRenderer);
  48449. };
  48450. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  48451. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  48452. #endif
  48453. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  48454. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  48455. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  48456. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  48457. /**
  48458. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  48459. its rendering in memory.
  48460. User code is not supposed to create instances of this class directly - do all your
  48461. rendering via the Graphics class instead.
  48462. */
  48463. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  48464. {
  48465. public:
  48466. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn);
  48467. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  48468. ~LowLevelGraphicsSoftwareRenderer();
  48469. bool isVectorDevice() const;
  48470. void setOrigin (int x, int y);
  48471. void addTransform (const AffineTransform& transform);
  48472. float getScaleFactor();
  48473. bool clipToRectangle (const Rectangle<int>& r);
  48474. bool clipToRectangleList (const RectangleList& clipRegion);
  48475. void excludeClipRectangle (const Rectangle<int>& r);
  48476. void clipToPath (const Path& path, const AffineTransform& transform);
  48477. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform);
  48478. bool clipRegionIntersects (const Rectangle<int>& r);
  48479. const Rectangle<int> getClipBounds() const;
  48480. bool isClipEmpty() const;
  48481. void saveState();
  48482. void restoreState();
  48483. void beginTransparencyLayer (float opacity);
  48484. void endTransparencyLayer();
  48485. void setFill (const FillType& fillType);
  48486. void setOpacity (float opacity);
  48487. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  48488. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  48489. void fillPath (const Path& path, const AffineTransform& transform);
  48490. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles);
  48491. void drawLine (const Line <float>& line);
  48492. void drawVerticalLine (int x, float top, float bottom);
  48493. void drawHorizontalLine (int x, float top, float bottom);
  48494. void setFont (const Font& newFont);
  48495. const Font getFont();
  48496. void drawGlyph (int glyphNumber, float x, float y);
  48497. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  48498. protected:
  48499. Image image;
  48500. class GlyphCache;
  48501. class CachedGlyph;
  48502. class SavedState;
  48503. friend class ScopedPointer <SavedState>;
  48504. friend class OwnedArray <SavedState>;
  48505. friend class OwnedArray <CachedGlyph>;
  48506. ScopedPointer <SavedState> currentState;
  48507. OwnedArray <SavedState> stateStack;
  48508. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsSoftwareRenderer);
  48509. };
  48510. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  48511. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  48512. #endif
  48513. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  48514. #endif
  48515. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  48516. #endif
  48517. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  48518. /*** Start of inlined file: juce_DrawableComposite.h ***/
  48519. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  48520. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  48521. /**
  48522. A drawable object which acts as a container for a set of other Drawables.
  48523. @see Drawable
  48524. */
  48525. class JUCE_API DrawableComposite : public Drawable
  48526. {
  48527. public:
  48528. /** Creates a composite Drawable. */
  48529. DrawableComposite();
  48530. /** Creates a copy of a DrawableComposite. */
  48531. DrawableComposite (const DrawableComposite& other);
  48532. /** Destructor. */
  48533. ~DrawableComposite();
  48534. /** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  48535. @see setContentArea
  48536. */
  48537. void setBoundingBox (const RelativeParallelogram& newBoundingBox);
  48538. /** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  48539. @see setBoundingBox
  48540. */
  48541. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  48542. /** Changes the bounding box transform to match the content area, so that any sub-items will
  48543. be drawn at their untransformed positions.
  48544. */
  48545. void resetBoundingBoxToContentArea();
  48546. /** Returns the main content rectangle.
  48547. The content area is actually defined by the markers named "left", "right", "top" and
  48548. "bottom", but this method is a shortcut that returns them all at once.
  48549. @see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  48550. */
  48551. const RelativeRectangle getContentArea() const;
  48552. /** Changes the main content area.
  48553. The content area is actually defined by the markers named "left", "right", "top" and
  48554. "bottom", but this method is a shortcut that sets them all at once.
  48555. @see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  48556. */
  48557. void setContentArea (const RelativeRectangle& newArea);
  48558. /** Resets the content area and the bounding transform to fit around the area occupied
  48559. by the child components (ignoring any markers).
  48560. */
  48561. void resetContentAreaAndBoundingBoxToFitChildren();
  48562. /** The name of the marker that defines the left edge of the content area. */
  48563. static const char* const contentLeftMarkerName;
  48564. /** The name of the marker that defines the right edge of the content area. */
  48565. static const char* const contentRightMarkerName;
  48566. /** The name of the marker that defines the top edge of the content area. */
  48567. static const char* const contentTopMarkerName;
  48568. /** The name of the marker that defines the bottom edge of the content area. */
  48569. static const char* const contentBottomMarkerName;
  48570. /** @internal */
  48571. Drawable* createCopy() const;
  48572. /** @internal */
  48573. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  48574. /** @internal */
  48575. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  48576. /** @internal */
  48577. static const Identifier valueTreeType;
  48578. /** @internal */
  48579. const Rectangle<float> getDrawableBounds() const;
  48580. /** @internal */
  48581. void childBoundsChanged (Component*);
  48582. /** @internal */
  48583. void childrenChanged();
  48584. /** @internal */
  48585. void parentHierarchyChanged();
  48586. /** @internal */
  48587. MarkerList* getMarkers (bool xAxis);
  48588. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  48589. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  48590. {
  48591. public:
  48592. ValueTreeWrapper (const ValueTree& state);
  48593. ValueTree getChildList() const;
  48594. ValueTree getChildListCreating (UndoManager* undoManager);
  48595. const RelativeParallelogram getBoundingBox() const;
  48596. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  48597. void resetBoundingBoxToContentArea (UndoManager* undoManager);
  48598. const RelativeRectangle getContentArea() const;
  48599. void setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager);
  48600. MarkerList::ValueTreeWrapper getMarkerList (bool xAxis) const;
  48601. MarkerList::ValueTreeWrapper getMarkerListCreating (bool xAxis, UndoManager* undoManager);
  48602. static const Identifier topLeft, topRight, bottomLeft;
  48603. private:
  48604. static const Identifier childGroupTag, markerGroupTagX, markerGroupTagY;
  48605. };
  48606. private:
  48607. RelativeParallelogram bounds;
  48608. MarkerList markersX, markersY;
  48609. bool updateBoundsReentrant;
  48610. friend class Drawable::Positioner<DrawableComposite>;
  48611. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  48612. void recalculateCoordinates (Expression::Scope*);
  48613. void updateBoundsToFitChildren();
  48614. DrawableComposite& operator= (const DrawableComposite&);
  48615. JUCE_LEAK_DETECTOR (DrawableComposite);
  48616. };
  48617. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  48618. /*** End of inlined file: juce_DrawableComposite.h ***/
  48619. #endif
  48620. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  48621. /*** Start of inlined file: juce_DrawableImage.h ***/
  48622. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  48623. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  48624. /**
  48625. A drawable object which is a bitmap image.
  48626. @see Drawable
  48627. */
  48628. class JUCE_API DrawableImage : public Drawable
  48629. {
  48630. public:
  48631. DrawableImage();
  48632. DrawableImage (const DrawableImage& other);
  48633. /** Destructor. */
  48634. ~DrawableImage();
  48635. /** Sets the image that this drawable will render. */
  48636. void setImage (const Image& imageToUse);
  48637. /** Returns the current image. */
  48638. const Image getImage() const { return image; }
  48639. /** Sets the opacity to use when drawing the image. */
  48640. void setOpacity (float newOpacity);
  48641. /** Returns the image's opacity. */
  48642. float getOpacity() const throw() { return opacity; }
  48643. /** Sets a colour to draw over the image's alpha channel.
  48644. By default this is transparent so isn't drawn, but if you set a non-transparent
  48645. colour here, then it will be overlaid on the image, using the image's alpha
  48646. channel as a mask.
  48647. This is handy for doing things like darkening or lightening an image by overlaying
  48648. it with semi-transparent black or white.
  48649. */
  48650. void setOverlayColour (const Colour& newOverlayColour);
  48651. /** Returns the overlay colour. */
  48652. const Colour& getOverlayColour() const throw() { return overlayColour; }
  48653. /** Sets the bounding box within which the image should be displayed. */
  48654. void setBoundingBox (const RelativeParallelogram& newBounds);
  48655. /** Returns the position to which the image's top-left corner should be remapped in the target
  48656. coordinate space when rendering this object.
  48657. @see setTransform
  48658. */
  48659. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  48660. /** @internal */
  48661. void paint (Graphics& g);
  48662. /** @internal */
  48663. bool hitTest (int x, int y) const;
  48664. /** @internal */
  48665. Drawable* createCopy() const;
  48666. /** @internal */
  48667. const Rectangle<float> getDrawableBounds() const;
  48668. /** @internal */
  48669. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  48670. /** @internal */
  48671. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  48672. /** @internal */
  48673. static const Identifier valueTreeType;
  48674. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  48675. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  48676. {
  48677. public:
  48678. ValueTreeWrapper (const ValueTree& state);
  48679. const var getImageIdentifier() const;
  48680. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  48681. Value getImageIdentifierValue (UndoManager* undoManager);
  48682. float getOpacity() const;
  48683. void setOpacity (float newOpacity, UndoManager* undoManager);
  48684. Value getOpacityValue (UndoManager* undoManager);
  48685. const Colour getOverlayColour() const;
  48686. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  48687. Value getOverlayColourValue (UndoManager* undoManager);
  48688. const RelativeParallelogram getBoundingBox() const;
  48689. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  48690. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  48691. };
  48692. private:
  48693. Image image;
  48694. float opacity;
  48695. Colour overlayColour;
  48696. RelativeParallelogram bounds;
  48697. friend class Drawable::Positioner<DrawableImage>;
  48698. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  48699. void recalculateCoordinates (Expression::Scope*);
  48700. DrawableImage& operator= (const DrawableImage&);
  48701. JUCE_LEAK_DETECTOR (DrawableImage);
  48702. };
  48703. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  48704. /*** End of inlined file: juce_DrawableImage.h ***/
  48705. #endif
  48706. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  48707. /*** Start of inlined file: juce_DrawablePath.h ***/
  48708. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  48709. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  48710. /*** Start of inlined file: juce_DrawableShape.h ***/
  48711. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  48712. #define __JUCE_DRAWABLESHAPE_JUCEHEADER__
  48713. /**
  48714. A base class implementing common functionality for Drawable classes which
  48715. consist of some kind of filled and stroked outline.
  48716. @see DrawablePath, DrawableRectangle
  48717. */
  48718. class JUCE_API DrawableShape : public Drawable
  48719. {
  48720. protected:
  48721. DrawableShape();
  48722. DrawableShape (const DrawableShape&);
  48723. public:
  48724. /** Destructor. */
  48725. ~DrawableShape();
  48726. /** A FillType wrapper that allows the gradient coordinates to be implemented using RelativePoint.
  48727. */
  48728. class RelativeFillType
  48729. {
  48730. public:
  48731. RelativeFillType();
  48732. RelativeFillType (const FillType& fill);
  48733. RelativeFillType (const RelativeFillType&);
  48734. RelativeFillType& operator= (const RelativeFillType&);
  48735. bool operator== (const RelativeFillType&) const;
  48736. bool operator!= (const RelativeFillType&) const;
  48737. bool isDynamic() const;
  48738. bool recalculateCoords (Expression::Scope* scope);
  48739. void writeTo (ValueTree& v, ComponentBuilder::ImageProvider*, UndoManager*) const;
  48740. bool readFrom (const ValueTree& v, ComponentBuilder::ImageProvider*);
  48741. FillType fill;
  48742. RelativePoint gradientPoint1, gradientPoint2, gradientPoint3;
  48743. };
  48744. /** Sets a fill type for the path.
  48745. This colour is used to fill the path - if you don't want the path to be
  48746. filled (e.g. if you're just drawing an outline), set this to a transparent
  48747. colour.
  48748. @see setPath, setStrokeFill
  48749. */
  48750. void setFill (const FillType& newFill);
  48751. /** Sets a fill type for the path.
  48752. This colour is used to fill the path - if you don't want the path to be
  48753. filled (e.g. if you're just drawing an outline), set this to a transparent
  48754. colour.
  48755. @see setPath, setStrokeFill
  48756. */
  48757. void setFill (const RelativeFillType& newFill);
  48758. /** Returns the current fill type.
  48759. @see setFill
  48760. */
  48761. const RelativeFillType& getFill() const throw() { return mainFill; }
  48762. /** Sets the fill type with which the outline will be drawn.
  48763. @see setFill
  48764. */
  48765. void setStrokeFill (const FillType& newStrokeFill);
  48766. /** Sets the fill type with which the outline will be drawn.
  48767. @see setFill
  48768. */
  48769. void setStrokeFill (const RelativeFillType& newStrokeFill);
  48770. /** Returns the current stroke fill.
  48771. @see setStrokeFill
  48772. */
  48773. const RelativeFillType& getStrokeFill() const throw() { return strokeFill; }
  48774. /** Changes the properties of the outline that will be drawn around the path.
  48775. If the stroke has 0 thickness, no stroke will be drawn.
  48776. @see setStrokeThickness, setStrokeColour
  48777. */
  48778. void setStrokeType (const PathStrokeType& newStrokeType);
  48779. /** Changes the stroke thickness.
  48780. This is a shortcut for calling setStrokeType.
  48781. */
  48782. void setStrokeThickness (float newThickness);
  48783. /** Returns the current outline style. */
  48784. const PathStrokeType& getStrokeType() const throw() { return strokeType; }
  48785. /** @internal */
  48786. class FillAndStrokeState : public Drawable::ValueTreeWrapperBase
  48787. {
  48788. public:
  48789. FillAndStrokeState (const ValueTree& state);
  48790. ValueTree getFillState (const Identifier& fillOrStrokeType);
  48791. const RelativeFillType getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider*) const;
  48792. void setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  48793. ComponentBuilder::ImageProvider*, UndoManager*);
  48794. const PathStrokeType getStrokeType() const;
  48795. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager*);
  48796. static const Identifier type, colour, colours, fill, stroke, path, jointStyle, capStyle, strokeWidth,
  48797. gradientPoint1, gradientPoint2, gradientPoint3, radial, imageId, imageOpacity;
  48798. };
  48799. /** @internal */
  48800. const Rectangle<float> getDrawableBounds() const;
  48801. /** @internal */
  48802. void paint (Graphics& g);
  48803. /** @internal */
  48804. bool hitTest (int x, int y);
  48805. protected:
  48806. /** Called when the cached path should be updated. */
  48807. void pathChanged();
  48808. /** Called when the cached stroke should be updated. */
  48809. void strokeChanged();
  48810. /** True if there's a stroke with a non-zero thickness and non-transparent colour. */
  48811. bool isStrokeVisible() const throw();
  48812. /** Updates the details from a FillAndStrokeState object, returning true if something changed. */
  48813. void refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider*);
  48814. /** Writes the stroke and fill details to a FillAndStrokeState object. */
  48815. void writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider*, UndoManager*) const;
  48816. PathStrokeType strokeType;
  48817. Path path, strokePath;
  48818. private:
  48819. class RelativePositioner;
  48820. RelativeFillType mainFill, strokeFill;
  48821. ScopedPointer<RelativeCoordinatePositionerBase> mainFillPositioner, strokeFillPositioner;
  48822. void setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  48823. ScopedPointer<RelativeCoordinatePositionerBase>& positioner);
  48824. DrawableShape& operator= (const DrawableShape&);
  48825. };
  48826. #endif // __JUCE_DRAWABLESHAPE_JUCEHEADER__
  48827. /*** End of inlined file: juce_DrawableShape.h ***/
  48828. /**
  48829. A drawable object which renders a filled or outlined shape.
  48830. For details on how to change the fill and stroke, see the DrawableShape class.
  48831. @see Drawable, DrawableShape
  48832. */
  48833. class JUCE_API DrawablePath : public DrawableShape
  48834. {
  48835. public:
  48836. /** Creates a DrawablePath. */
  48837. DrawablePath();
  48838. DrawablePath (const DrawablePath& other);
  48839. /** Destructor. */
  48840. ~DrawablePath();
  48841. /** Changes the path that will be drawn.
  48842. @see setFillColour, setStrokeType
  48843. */
  48844. void setPath (const Path& newPath);
  48845. /** Sets the path using a RelativePointPath.
  48846. Calling this will set up a Component::Positioner to automatically update the path
  48847. if any of the points in the source path are dynamic.
  48848. */
  48849. void setPath (const RelativePointPath& newPath);
  48850. /** Returns the current path. */
  48851. const Path& getPath() const;
  48852. /** Returns the current path for the outline. */
  48853. const Path& getStrokePath() const;
  48854. /** @internal */
  48855. Drawable* createCopy() const;
  48856. /** @internal */
  48857. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  48858. /** @internal */
  48859. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  48860. /** @internal */
  48861. static const Identifier valueTreeType;
  48862. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  48863. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  48864. {
  48865. public:
  48866. ValueTreeWrapper (const ValueTree& state);
  48867. bool usesNonZeroWinding() const;
  48868. void setUsesNonZeroWinding (bool b, UndoManager* undoManager);
  48869. class Element
  48870. {
  48871. public:
  48872. explicit Element (const ValueTree& state);
  48873. ~Element();
  48874. const Identifier getType() const throw() { return state.getType(); }
  48875. int getNumControlPoints() const throw();
  48876. const RelativePoint getControlPoint (int index) const;
  48877. Value getControlPointValue (int index, UndoManager*) const;
  48878. const RelativePoint getStartPoint() const;
  48879. const RelativePoint getEndPoint() const;
  48880. void setControlPoint (int index, const RelativePoint& point, UndoManager*);
  48881. float getLength (Expression::Scope*) const;
  48882. ValueTreeWrapper getParent() const;
  48883. Element getPreviousElement() const;
  48884. const String getModeOfEndPoint() const;
  48885. void setModeOfEndPoint (const String& newMode, UndoManager*);
  48886. void convertToLine (UndoManager*);
  48887. void convertToCubic (Expression::Scope*, UndoManager*);
  48888. void convertToPathBreak (UndoManager* undoManager);
  48889. ValueTree insertPoint (const Point<float>& targetPoint, Expression::Scope*, UndoManager*);
  48890. void removePoint (UndoManager* undoManager);
  48891. float findProportionAlongLine (const Point<float>& targetPoint, Expression::Scope*) const;
  48892. static const Identifier mode, startSubPathElement, closeSubPathElement,
  48893. lineToElement, quadraticToElement, cubicToElement;
  48894. static const char* cornerMode;
  48895. static const char* roundedMode;
  48896. static const char* symmetricMode;
  48897. ValueTree state;
  48898. };
  48899. ValueTree getPathState();
  48900. void readFrom (const RelativePointPath& path, UndoManager* undoManager);
  48901. void writeTo (RelativePointPath& path) const;
  48902. static const Identifier nonZeroWinding, point1, point2, point3;
  48903. };
  48904. private:
  48905. ScopedPointer<RelativePointPath> relativePath;
  48906. class RelativePositioner;
  48907. friend class RelativePositioner;
  48908. void applyRelativePath (const RelativePointPath&, Expression::Scope*);
  48909. DrawablePath& operator= (const DrawablePath&);
  48910. JUCE_LEAK_DETECTOR (DrawablePath);
  48911. };
  48912. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  48913. /*** End of inlined file: juce_DrawablePath.h ***/
  48914. #endif
  48915. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  48916. /*** Start of inlined file: juce_DrawableRectangle.h ***/
  48917. #ifndef __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  48918. #define __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  48919. /**
  48920. A Drawable object which draws a rectangle.
  48921. For details on how to change the fill and stroke, see the DrawableShape class.
  48922. @see Drawable, DrawableShape
  48923. */
  48924. class JUCE_API DrawableRectangle : public DrawableShape
  48925. {
  48926. public:
  48927. DrawableRectangle();
  48928. DrawableRectangle (const DrawableRectangle& other);
  48929. /** Destructor. */
  48930. ~DrawableRectangle();
  48931. /** Sets the rectangle's bounds. */
  48932. void setRectangle (const RelativeParallelogram& newBounds);
  48933. /** Returns the rectangle's bounds. */
  48934. const RelativeParallelogram& getRectangle() const throw() { return bounds; }
  48935. /** Returns the corner size to be used. */
  48936. const RelativePoint getCornerSize() const { return cornerSize; }
  48937. /** Sets a new corner size for the rectangle */
  48938. void setCornerSize (const RelativePoint& newSize);
  48939. /** @internal */
  48940. Drawable* createCopy() const;
  48941. /** @internal */
  48942. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  48943. /** @internal */
  48944. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  48945. /** @internal */
  48946. static const Identifier valueTreeType;
  48947. /** Internally-used class for wrapping a DrawableRectangle's state into a ValueTree. */
  48948. class ValueTreeWrapper : public DrawableShape::FillAndStrokeState
  48949. {
  48950. public:
  48951. ValueTreeWrapper (const ValueTree& state);
  48952. const RelativeParallelogram getRectangle() const;
  48953. void setRectangle (const RelativeParallelogram& newBounds, UndoManager*);
  48954. void setCornerSize (const RelativePoint& cornerSize, UndoManager*);
  48955. const RelativePoint getCornerSize() const;
  48956. Value getCornerSizeValue (UndoManager*) const;
  48957. static const Identifier topLeft, topRight, bottomLeft, cornerSize;
  48958. };
  48959. private:
  48960. friend class Drawable::Positioner<DrawableRectangle>;
  48961. RelativeParallelogram bounds;
  48962. RelativePoint cornerSize;
  48963. void rebuildPath();
  48964. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  48965. void recalculateCoordinates (Expression::Scope*);
  48966. DrawableRectangle& operator= (const DrawableRectangle&);
  48967. JUCE_LEAK_DETECTOR (DrawableRectangle);
  48968. };
  48969. #endif // __JUCE_DRAWABLERECTANGLE_JUCEHEADER__
  48970. /*** End of inlined file: juce_DrawableRectangle.h ***/
  48971. #endif
  48972. #ifndef __JUCE_DRAWABLESHAPE_JUCEHEADER__
  48973. #endif
  48974. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  48975. /*** Start of inlined file: juce_DrawableText.h ***/
  48976. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  48977. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  48978. /**
  48979. A drawable object which renders a line of text.
  48980. @see Drawable
  48981. */
  48982. class JUCE_API DrawableText : public Drawable
  48983. {
  48984. public:
  48985. /** Creates a DrawableText object. */
  48986. DrawableText();
  48987. DrawableText (const DrawableText& other);
  48988. /** Destructor. */
  48989. ~DrawableText();
  48990. /** Sets the text to display.*/
  48991. void setText (const String& newText);
  48992. /** Sets the colour of the text. */
  48993. void setColour (const Colour& newColour);
  48994. /** Returns the current text colour. */
  48995. const Colour& getColour() const throw() { return colour; }
  48996. /** Sets the font to use.
  48997. Note that the font height and horizontal scale are actually based upon the position
  48998. of the fontSizeAndScaleAnchor parameter to setBounds(). If applySizeAndScale is true, then
  48999. the height and scale control point will be moved to match the dimensions of the font supplied;
  49000. if it is false, then the new font's height and scale are ignored.
  49001. */
  49002. void setFont (const Font& newFont, bool applySizeAndScale);
  49003. /** Changes the justification of the text within the bounding box. */
  49004. void setJustification (const Justification& newJustification);
  49005. /** Returns the parallelogram that defines the text bounding box. */
  49006. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  49007. /** Sets the bounding box that contains the text. */
  49008. void setBoundingBox (const RelativeParallelogram& newBounds);
  49009. /** Returns the point within the bounds that defines the font's size and scale. */
  49010. const RelativePoint& getFontSizeControlPoint() const throw() { return fontSizeControlPoint; }
  49011. /** Sets the control point that defines the font's height and horizontal scale.
  49012. This position is a point within the bounding box parallelogram, whose Y position (relative
  49013. to the parallelogram's origin and possibly distorted shape) specifies the font's height,
  49014. and its X defines the font's horizontal scale.
  49015. */
  49016. void setFontSizeControlPoint (const RelativePoint& newPoint);
  49017. /** @internal */
  49018. void paint (Graphics& g);
  49019. /** @internal */
  49020. Drawable* createCopy() const;
  49021. /** @internal */
  49022. void refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder);
  49023. /** @internal */
  49024. const ValueTree createValueTree (ComponentBuilder::ImageProvider* imageProvider) const;
  49025. /** @internal */
  49026. static const Identifier valueTreeType;
  49027. /** @internal */
  49028. const Rectangle<float> getDrawableBounds() const;
  49029. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  49030. class ValueTreeWrapper : public Drawable::ValueTreeWrapperBase
  49031. {
  49032. public:
  49033. ValueTreeWrapper (const ValueTree& state);
  49034. const String getText() const;
  49035. void setText (const String& newText, UndoManager* undoManager);
  49036. Value getTextValue (UndoManager* undoManager);
  49037. const Colour getColour() const;
  49038. void setColour (const Colour& newColour, UndoManager* undoManager);
  49039. const Justification getJustification() const;
  49040. void setJustification (const Justification& newJustification, UndoManager* undoManager);
  49041. const Font getFont() const;
  49042. void setFont (const Font& newFont, UndoManager* undoManager);
  49043. Value getFontValue (UndoManager* undoManager);
  49044. const RelativeParallelogram getBoundingBox() const;
  49045. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  49046. const RelativePoint getFontSizeControlPoint() const;
  49047. void setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager);
  49048. static const Identifier text, colour, font, justification, topLeft, topRight, bottomLeft, fontSizeAnchor;
  49049. };
  49050. private:
  49051. RelativeParallelogram bounds;
  49052. RelativePoint fontSizeControlPoint;
  49053. Point<float> resolvedPoints[3];
  49054. Font font, scaledFont;
  49055. String text;
  49056. Colour colour;
  49057. Justification justification;
  49058. friend class Drawable::Positioner<DrawableText>;
  49059. bool registerCoordinates (RelativeCoordinatePositionerBase&);
  49060. void recalculateCoordinates (Expression::Scope*);
  49061. void refreshBounds();
  49062. const AffineTransform getArrangementAndTransform (GlyphArrangement& glyphs) const;
  49063. DrawableText& operator= (const DrawableText&);
  49064. JUCE_LEAK_DETECTOR (DrawableText);
  49065. };
  49066. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  49067. /*** End of inlined file: juce_DrawableText.h ***/
  49068. #endif
  49069. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  49070. #endif
  49071. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  49072. /*** Start of inlined file: juce_GlowEffect.h ***/
  49073. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  49074. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  49075. /**
  49076. A component effect that adds a coloured blur around the component's contents.
  49077. (This will only work on non-opaque components).
  49078. @see Component::setComponentEffect, DropShadowEffect
  49079. */
  49080. class JUCE_API GlowEffect : public ImageEffectFilter
  49081. {
  49082. public:
  49083. /** Creates a default 'glow' effect.
  49084. To customise its appearance, use the setGlowProperties() method.
  49085. */
  49086. GlowEffect();
  49087. /** Destructor. */
  49088. ~GlowEffect();
  49089. /** Sets the glow's radius and colour.
  49090. The radius is how large the blur should be, and the colour is
  49091. used to render it (for a less intense glow, lower the colour's
  49092. opacity).
  49093. */
  49094. void setGlowProperties (float newRadius,
  49095. const Colour& newColour);
  49096. /** @internal */
  49097. void applyEffect (Image& sourceImage, Graphics& destContext, float alpha);
  49098. private:
  49099. float radius;
  49100. Colour colour;
  49101. JUCE_LEAK_DETECTOR (GlowEffect);
  49102. };
  49103. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  49104. /*** End of inlined file: juce_GlowEffect.h ***/
  49105. #endif
  49106. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  49107. #endif
  49108. #ifndef __JUCE_FONT_JUCEHEADER__
  49109. #endif
  49110. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  49111. #endif
  49112. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  49113. #endif
  49114. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  49115. #endif
  49116. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  49117. #endif
  49118. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  49119. #endif
  49120. #ifndef __JUCE_LINE_JUCEHEADER__
  49121. #endif
  49122. #ifndef __JUCE_PATH_JUCEHEADER__
  49123. #endif
  49124. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  49125. /*** Start of inlined file: juce_PathIterator.h ***/
  49126. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  49127. #define __JUCE_PATHITERATOR_JUCEHEADER__
  49128. /**
  49129. Flattens a Path object into a series of straight-line sections.
  49130. Use one of these to iterate through a Path object, and it will convert
  49131. all the curves into line sections so it's easy to render or perform
  49132. geometric operations on.
  49133. @see Path
  49134. */
  49135. class JUCE_API PathFlatteningIterator
  49136. {
  49137. public:
  49138. /** Creates a PathFlatteningIterator.
  49139. After creation, use the next() method to initialise the fields in the
  49140. object with the first line's position.
  49141. @param path the path to iterate along
  49142. @param transform a transform to apply to each point in the path being iterated
  49143. @param tolerance the amount by which the curves are allowed to deviate from the lines
  49144. into which they are being broken down - a higher tolerance contains
  49145. less lines, so can be generated faster, but will be less smooth.
  49146. */
  49147. PathFlatteningIterator (const Path& path,
  49148. const AffineTransform& transform = AffineTransform::identity,
  49149. float tolerance = defaultTolerance);
  49150. /** Destructor. */
  49151. ~PathFlatteningIterator();
  49152. /** Fetches the next line segment from the path.
  49153. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  49154. so that they describe the new line segment.
  49155. @returns false when there are no more lines to fetch.
  49156. */
  49157. bool next();
  49158. float x1; /**< The x position of the start of the current line segment. */
  49159. float y1; /**< The y position of the start of the current line segment. */
  49160. float x2; /**< The x position of the end of the current line segment. */
  49161. float y2; /**< The y position of the end of the current line segment. */
  49162. /** Indicates whether the current line segment is closing a sub-path.
  49163. If the current line is the one that connects the end of a sub-path
  49164. back to the start again, this will be true.
  49165. */
  49166. bool closesSubPath;
  49167. /** The index of the current line within the current sub-path.
  49168. E.g. you can use this to see whether the line is the first one in the
  49169. subpath by seeing if it's 0.
  49170. */
  49171. int subPathIndex;
  49172. /** Returns true if the current segment is the last in the current sub-path. */
  49173. bool isLastInSubpath() const throw() { return stackPos == stackBase.getData()
  49174. && (index >= path.numElements || points [index] == Path::moveMarker); }
  49175. /** This is the default value that should be used for the tolerance value (see the constructor parameters). */
  49176. static const float defaultTolerance;
  49177. private:
  49178. const Path& path;
  49179. const AffineTransform transform;
  49180. float* points;
  49181. const float toleranceSquared;
  49182. float subPathCloseX, subPathCloseY;
  49183. const bool isIdentityTransform;
  49184. HeapBlock <float> stackBase;
  49185. float* stackPos;
  49186. size_t index, stackSize;
  49187. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PathFlatteningIterator);
  49188. };
  49189. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  49190. /*** End of inlined file: juce_PathIterator.h ***/
  49191. #endif
  49192. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  49193. #endif
  49194. #ifndef __JUCE_POINT_JUCEHEADER__
  49195. #endif
  49196. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  49197. #endif
  49198. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  49199. #endif
  49200. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  49201. /*** Start of inlined file: juce_CameraDevice.h ***/
  49202. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  49203. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  49204. #if JUCE_USE_CAMERA || DOXYGEN
  49205. /**
  49206. Controls any video capture devices that might be available.
  49207. Use getAvailableDevices() to list the devices that are attached to the
  49208. system, then call openDevice to open one for use. Once you have a CameraDevice
  49209. object, you can get a viewer component from it, and use its methods to
  49210. stream to a file or capture still-frames.
  49211. */
  49212. class JUCE_API CameraDevice
  49213. {
  49214. public:
  49215. /** Destructor. */
  49216. virtual ~CameraDevice();
  49217. /** Returns a list of the available cameras on this machine.
  49218. You can open one of these devices by calling openDevice().
  49219. */
  49220. static const StringArray getAvailableDevices();
  49221. /** Opens a camera device.
  49222. The index parameter indicates which of the items returned by getAvailableDevices()
  49223. to open.
  49224. The size constraints allow the method to choose between different resolutions if
  49225. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  49226. then these will be ignored.
  49227. */
  49228. static CameraDevice* openDevice (int deviceIndex,
  49229. int minWidth = 128, int minHeight = 64,
  49230. int maxWidth = 1024, int maxHeight = 768);
  49231. /** Returns the name of this device */
  49232. const String getName() const { return name; }
  49233. /** Creates a component that can be used to display a preview of the
  49234. video from this camera.
  49235. */
  49236. Component* createViewerComponent();
  49237. /** Starts recording video to the specified file.
  49238. You should use getFileExtension() to find out the correct extension to
  49239. use for your filename.
  49240. If the file exists, it will be deleted before the recording starts.
  49241. This method may not start recording instantly, so if you need to know the
  49242. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  49243. after the recording has finished.
  49244. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  49245. or may not be used, depending on the driver.
  49246. */
  49247. void startRecordingToFile (const File& file, int quality = 2);
  49248. /** Stops recording, after a call to startRecordingToFile().
  49249. */
  49250. void stopRecording();
  49251. /** Returns the file extension that should be used for the files
  49252. that you pass to startRecordingToFile().
  49253. This may be platform-specific, e.g. ".mov" or ".avi".
  49254. */
  49255. static const String getFileExtension();
  49256. /** After calling stopRecording(), this method can be called to return the timestamp
  49257. of the first frame that was written to the file.
  49258. */
  49259. const Time getTimeOfFirstRecordedFrame() const;
  49260. /**
  49261. Receives callbacks with images from a CameraDevice.
  49262. @see CameraDevice::addListener
  49263. */
  49264. class JUCE_API Listener
  49265. {
  49266. public:
  49267. Listener() {}
  49268. virtual ~Listener() {}
  49269. /** This method is called when a new image arrives.
  49270. This may be called by any thread, so be careful about thread-safety,
  49271. and make sure that you process the data as quickly as possible to
  49272. avoid glitching!
  49273. */
  49274. virtual void imageReceived (const Image& image) = 0;
  49275. };
  49276. /** Adds a listener to receive images from the camera.
  49277. Be very careful not to delete the listener without first removing it by calling
  49278. removeListener().
  49279. */
  49280. void addListener (Listener* listenerToAdd);
  49281. /** Removes a listener that was previously added with addListener().
  49282. */
  49283. void removeListener (Listener* listenerToRemove);
  49284. protected:
  49285. /** @internal */
  49286. CameraDevice (const String& name, int index);
  49287. private:
  49288. void* internal;
  49289. bool isRecording;
  49290. String name;
  49291. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CameraDevice);
  49292. };
  49293. /** This typedef is just for compatibility with old code - newer code should use the CameraDevice::Listener class directly. */
  49294. typedef CameraDevice::Listener CameraImageListener;
  49295. #endif
  49296. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  49297. /*** End of inlined file: juce_CameraDevice.h ***/
  49298. #endif
  49299. #ifndef __JUCE_IMAGE_JUCEHEADER__
  49300. #endif
  49301. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  49302. /*** Start of inlined file: juce_ImageCache.h ***/
  49303. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  49304. #define __JUCE_IMAGECACHE_JUCEHEADER__
  49305. /**
  49306. A global cache of images that have been loaded from files or memory.
  49307. If you're loading an image and may need to use the image in more than one
  49308. place, this is used to allow the same image to be shared rather than loading
  49309. multiple copies into memory.
  49310. Another advantage is that after images are released, they will be kept in
  49311. memory for a few seconds before it is actually deleted, so if you're repeatedly
  49312. loading/deleting the same image, it'll reduce the chances of having to reload it
  49313. each time.
  49314. @see Image, ImageFileFormat
  49315. */
  49316. class JUCE_API ImageCache
  49317. {
  49318. public:
  49319. /** Loads an image from a file, (or just returns the image if it's already cached).
  49320. If the cache already contains an image that was loaded from this file,
  49321. that image will be returned. Otherwise, this method will try to load the
  49322. file, add it to the cache, and return it.
  49323. Remember that the image returned is shared, so drawing into it might
  49324. affect other things that are using it! If you want to draw on it, first
  49325. call Image::duplicateIfShared()
  49326. @param file the file to try to load
  49327. @returns the image, or null if it there was an error loading it
  49328. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  49329. */
  49330. static const Image getFromFile (const File& file);
  49331. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  49332. If the cache already contains an image that was loaded from this block of memory,
  49333. that image will be returned. Otherwise, this method will try to load the
  49334. file, add it to the cache, and return it.
  49335. Remember that the image returned is shared, so drawing into it might
  49336. affect other things that are using it! If you want to draw on it, first
  49337. call Image::duplicateIfShared()
  49338. @param imageData the block of memory containing the image data
  49339. @param dataSize the data size in bytes
  49340. @returns the image, or an invalid image if it there was an error loading it
  49341. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  49342. */
  49343. static const Image getFromMemory (const void* imageData, int dataSize);
  49344. /** Checks the cache for an image with a particular hashcode.
  49345. If there's an image in the cache with this hashcode, it will be returned,
  49346. otherwise it will return an invalid image.
  49347. @param hashCode the hash code that was associated with the image by addImageToCache()
  49348. @see addImageToCache
  49349. */
  49350. static const Image getFromHashCode (int64 hashCode);
  49351. /** Adds an image to the cache with a user-defined hash-code.
  49352. The image passed-in will be referenced (not copied) by the cache, so it's probably
  49353. a good idea not to draw into it after adding it, otherwise this will affect all
  49354. instances of it that may be in use.
  49355. @param image the image to add
  49356. @param hashCode the hash-code to associate with it
  49357. @see getFromHashCode
  49358. */
  49359. static void addImageToCache (const Image& image, int64 hashCode);
  49360. /** Changes the amount of time before an unused image will be removed from the cache.
  49361. By default this is about 5 seconds.
  49362. */
  49363. static void setCacheTimeout (int millisecs);
  49364. private:
  49365. class Pimpl;
  49366. friend class Pimpl;
  49367. ImageCache();
  49368. ~ImageCache();
  49369. JUCE_DECLARE_NON_COPYABLE (ImageCache);
  49370. };
  49371. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  49372. /*** End of inlined file: juce_ImageCache.h ***/
  49373. #endif
  49374. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  49375. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  49376. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  49377. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  49378. /**
  49379. Represents a filter kernel to use in convoluting an image.
  49380. @see Image::applyConvolution
  49381. */
  49382. class JUCE_API ImageConvolutionKernel
  49383. {
  49384. public:
  49385. /** Creates an empty convulution kernel.
  49386. @param size the length of each dimension of the kernel, so e.g. if the size
  49387. is 5, it will create a 5x5 kernel
  49388. */
  49389. ImageConvolutionKernel (int size);
  49390. /** Destructor. */
  49391. ~ImageConvolutionKernel();
  49392. /** Resets all values in the kernel to zero. */
  49393. void clear();
  49394. /** Returns one of the kernel values. */
  49395. float getKernelValue (int x, int y) const throw();
  49396. /** Sets the value of a specific cell in the kernel.
  49397. The x and y parameters must be in the range 0 < x < getKernelSize().
  49398. @see setOverallSum
  49399. */
  49400. void setKernelValue (int x, int y, float value) throw();
  49401. /** Rescales all values in the kernel to make the total add up to a fixed value.
  49402. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  49403. */
  49404. void setOverallSum (float desiredTotalSum);
  49405. /** Multiplies all values in the kernel by a value. */
  49406. void rescaleAllValues (float multiplier);
  49407. /** Intialises the kernel for a gaussian blur.
  49408. @param blurRadius this may be larger or smaller than the kernel's actual
  49409. size but this will obviously be wasteful or clip at the
  49410. edges. Ideally the kernel should be just larger than
  49411. (blurRadius * 2).
  49412. */
  49413. void createGaussianBlur (float blurRadius);
  49414. /** Returns the size of the kernel.
  49415. E.g. if it's a 3x3 kernel, this returns 3.
  49416. */
  49417. int getKernelSize() const { return size; }
  49418. /** Applies the kernel to an image.
  49419. @param destImage the image that will receive the resultant convoluted pixels.
  49420. @param sourceImage the source image to read from - this can be the same image as
  49421. the destination, but if different, it must be exactly the same
  49422. size and format.
  49423. @param destinationArea the region of the image to apply the filter to
  49424. */
  49425. void applyToImage (Image& destImage,
  49426. const Image& sourceImage,
  49427. const Rectangle<int>& destinationArea) const;
  49428. private:
  49429. HeapBlock <float> values;
  49430. const int size;
  49431. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImageConvolutionKernel);
  49432. };
  49433. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  49434. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  49435. #endif
  49436. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  49437. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  49438. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  49439. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  49440. /**
  49441. Base-class for codecs that can read and write image file formats such
  49442. as PNG, JPEG, etc.
  49443. This class also contains static methods to make it easy to load images
  49444. from files, streams or from memory.
  49445. @see Image, ImageCache
  49446. */
  49447. class JUCE_API ImageFileFormat
  49448. {
  49449. protected:
  49450. /** Creates an ImageFormat. */
  49451. ImageFileFormat() {}
  49452. public:
  49453. /** Destructor. */
  49454. virtual ~ImageFileFormat() {}
  49455. /** Returns a description of this file format.
  49456. E.g. "JPEG", "PNG"
  49457. */
  49458. virtual const String getFormatName() = 0;
  49459. /** Returns true if the given stream seems to contain data that this format
  49460. understands.
  49461. The format class should only read the first few bytes of the stream and sniff
  49462. for header bytes that it understands.
  49463. @see decodeImage
  49464. */
  49465. virtual bool canUnderstand (InputStream& input) = 0;
  49466. /** Tries to decode and return an image from the given stream.
  49467. This will be called for an image format after calling its canUnderStand() method
  49468. to see if it can handle the stream.
  49469. @param input the stream to read the data from. The stream will be positioned
  49470. at the start of the image data (but this may not necessarily
  49471. be position 0)
  49472. @returns the image that was decoded, or an invalid image if it fails.
  49473. @see loadFrom
  49474. */
  49475. virtual const Image decodeImage (InputStream& input) = 0;
  49476. /** Attempts to write an image to a stream.
  49477. To specify extra information like encoding quality, there will be appropriate parameters
  49478. in the subclasses of the specific file types.
  49479. @returns true if it nothing went wrong.
  49480. */
  49481. virtual bool writeImageToStream (const Image& sourceImage,
  49482. OutputStream& destStream) = 0;
  49483. /** Tries the built-in decoders to see if it can find one to read this stream.
  49484. There are currently built-in decoders for PNG, JPEG and GIF formats.
  49485. The object that is returned should not be deleted by the caller.
  49486. @see canUnderstand, decodeImage, loadFrom
  49487. */
  49488. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  49489. /** Tries to load an image from a stream.
  49490. This will use the findImageFormatForStream() method to locate a suitable
  49491. codec, and use that to load the image.
  49492. @returns the image that was decoded, or an invalid image if it fails.
  49493. */
  49494. static const Image loadFrom (InputStream& input);
  49495. /** Tries to load an image from a file.
  49496. This will use the findImageFormatForStream() method to locate a suitable
  49497. codec, and use that to load the image.
  49498. @returns the image that was decoded, or an invalid image if it fails.
  49499. */
  49500. static const Image loadFrom (const File& file);
  49501. /** Tries to load an image from a block of raw image data.
  49502. This will use the findImageFormatForStream() method to locate a suitable
  49503. codec, and use that to load the image.
  49504. @returns the image that was decoded, or an invalid image if it fails.
  49505. */
  49506. static const Image loadFrom (const void* rawData,
  49507. const int numBytesOfData);
  49508. };
  49509. /**
  49510. A subclass of ImageFileFormat for reading and writing PNG files.
  49511. @see ImageFileFormat, JPEGImageFormat
  49512. */
  49513. class JUCE_API PNGImageFormat : public ImageFileFormat
  49514. {
  49515. public:
  49516. PNGImageFormat();
  49517. ~PNGImageFormat();
  49518. const String getFormatName();
  49519. bool canUnderstand (InputStream& input);
  49520. const Image decodeImage (InputStream& input);
  49521. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  49522. };
  49523. /**
  49524. A subclass of ImageFileFormat for reading and writing JPEG files.
  49525. @see ImageFileFormat, PNGImageFormat
  49526. */
  49527. class JUCE_API JPEGImageFormat : public ImageFileFormat
  49528. {
  49529. public:
  49530. JPEGImageFormat();
  49531. ~JPEGImageFormat();
  49532. /** Specifies the quality to be used when writing a JPEG file.
  49533. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  49534. any negative value is "default" quality
  49535. */
  49536. void setQuality (float newQuality);
  49537. const String getFormatName();
  49538. bool canUnderstand (InputStream& input);
  49539. const Image decodeImage (InputStream& input);
  49540. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  49541. private:
  49542. float quality;
  49543. };
  49544. /**
  49545. A subclass of ImageFileFormat for reading GIF files.
  49546. @see ImageFileFormat, PNGImageFormat, JPEGImageFormat
  49547. */
  49548. class JUCE_API GIFImageFormat : public ImageFileFormat
  49549. {
  49550. public:
  49551. GIFImageFormat();
  49552. ~GIFImageFormat();
  49553. const String getFormatName();
  49554. bool canUnderstand (InputStream& input);
  49555. const Image decodeImage (InputStream& input);
  49556. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  49557. };
  49558. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  49559. /*** End of inlined file: juce_ImageFileFormat.h ***/
  49560. #endif
  49561. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  49562. #endif
  49563. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  49564. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  49565. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  49566. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  49567. /**
  49568. A class to take care of the logic involved with the loading/saving of some kind
  49569. of document.
  49570. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  49571. functions you need for documents that get saved to a file, so this class attempts
  49572. to abstract most of the boring stuff.
  49573. Your subclass should just implement all the pure virtual methods, and you can
  49574. then use the higher-level public methods to do the load/save dialogs, to warn the user
  49575. about overwriting files, etc.
  49576. The document object keeps track of whether it has changed since it was last saved or
  49577. loaded, so when you change something, call its changed() method. This will set a
  49578. flag so it knows it needs saving, and will also broadcast a change message using the
  49579. ChangeBroadcaster base class.
  49580. @see ChangeBroadcaster
  49581. */
  49582. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  49583. {
  49584. public:
  49585. /** Creates a FileBasedDocument.
  49586. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  49587. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  49588. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  49589. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  49590. */
  49591. FileBasedDocument (const String& fileExtension,
  49592. const String& fileWildCard,
  49593. const String& openFileDialogTitle,
  49594. const String& saveFileDialogTitle);
  49595. /** Destructor. */
  49596. virtual ~FileBasedDocument();
  49597. /** Returns true if the changed() method has been called since the file was
  49598. last saved or loaded.
  49599. @see resetChangedFlag, changed
  49600. */
  49601. bool hasChangedSinceSaved() const { return changedSinceSave; }
  49602. /** Called to indicate that the document has changed and needs saving.
  49603. This method will also trigger a change message to be sent out using the
  49604. ChangeBroadcaster base class.
  49605. After calling the method, the hasChangedSinceSaved() method will return true, until
  49606. it is reset either by saving to a file or using the resetChangedFlag() method.
  49607. @see hasChangedSinceSaved, resetChangedFlag
  49608. */
  49609. virtual void changed();
  49610. /** Sets the state of the 'changed' flag.
  49611. The 'changed' flag is set to true when the changed() method is called - use this method
  49612. to reset it or to set it without also broadcasting a change message.
  49613. @see changed, hasChangedSinceSaved
  49614. */
  49615. void setChangedFlag (bool hasChanged);
  49616. /** Tries to open a file.
  49617. If the file opens correctly, the document's file (see the getFile() method) is set
  49618. to this new one; if it fails, the document's file is left unchanged, and optionally
  49619. a message box is shown telling the user there was an error.
  49620. @returns true if the new file loaded successfully
  49621. @see loadDocument, loadFromUserSpecifiedFile
  49622. */
  49623. bool loadFrom (const File& fileToLoadFrom,
  49624. bool showMessageOnFailure);
  49625. /** Asks the user for a file and tries to load it.
  49626. This will pop up a dialog box using the title, file extension and
  49627. wildcard specified in the document's constructor, and asks the user
  49628. for a file. If they pick one, the loadFrom() method is used to
  49629. try to load it, optionally showing a message if it fails.
  49630. @returns true if a file was loaded; false if the user cancelled or if they
  49631. picked a file which failed to load correctly
  49632. @see loadFrom
  49633. */
  49634. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  49635. /** A set of possible outcomes of one of the save() methods
  49636. */
  49637. enum SaveResult
  49638. {
  49639. savedOk = 0, /**< indicates that a file was saved successfully. */
  49640. userCancelledSave, /**< indicates that the user aborted the save operation. */
  49641. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  49642. };
  49643. /** Tries to save the document to the last file it was saved or loaded from.
  49644. This will always try to write to the file, even if the document isn't flagged as
  49645. having changed.
  49646. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  49647. true, it will prompt the user to pick a file, as if
  49648. saveAsInteractive() was called.
  49649. @param showMessageOnFailure if true it will show a warning message when if the
  49650. save operation fails
  49651. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  49652. */
  49653. SaveResult save (bool askUserForFileIfNotSpecified,
  49654. bool showMessageOnFailure);
  49655. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  49656. it if they say yes.
  49657. If you've got a document open and want to close it (e.g. to quit the app), this is the
  49658. method to call.
  49659. If the document doesn't need saving it'll return the value savedOk so
  49660. you can go ahead and delete the document.
  49661. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  49662. return savedOk, so again, you can safely delete the document.
  49663. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  49664. close-document operation.
  49665. And if they click "save changes", it'll try to save and either return savedOk, or
  49666. failedToWriteToFile if there was a problem.
  49667. @see save, saveAs, saveAsInteractive
  49668. */
  49669. SaveResult saveIfNeededAndUserAgrees();
  49670. /** Tries to save the document to a specified file.
  49671. If this succeeds, it'll also change the document's internal file (as returned by
  49672. the getFile() method). If it fails, the file will be left unchanged.
  49673. @param newFile the file to try to write to
  49674. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  49675. the user first if they want to overwrite it
  49676. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  49677. use the saveAsInteractive() method to ask the user for a
  49678. filename
  49679. @param showMessageOnFailure if true and the write operation fails, it'll show
  49680. a message box to warn the user
  49681. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  49682. */
  49683. SaveResult saveAs (const File& newFile,
  49684. bool warnAboutOverwritingExistingFiles,
  49685. bool askUserForFileIfNotSpecified,
  49686. bool showMessageOnFailure);
  49687. /** Prompts the user for a filename and tries to save to it.
  49688. This will pop up a dialog box using the title, file extension and
  49689. wildcard specified in the document's constructor, and asks the user
  49690. for a file. If they pick one, the saveAs() method is used to try to save
  49691. to this file.
  49692. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  49693. the user first if they want to overwrite it
  49694. @see saveIfNeededAndUserAgrees, save, saveAs
  49695. */
  49696. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  49697. /** Returns the file that this document was last successfully saved or loaded from.
  49698. When the document object is created, this will be set to File::nonexistent.
  49699. It is changed when one of the load or save methods is used, or when setFile()
  49700. is used to explicitly set it.
  49701. */
  49702. const File getFile() const { return documentFile; }
  49703. /** Sets the file that this document thinks it was loaded from.
  49704. This won't actually load anything - it just changes the file stored internally.
  49705. @see getFile
  49706. */
  49707. void setFile (const File& newFile);
  49708. protected:
  49709. /** Overload this to return the title of the document.
  49710. This is used in message boxes, filenames and file choosers, so it should be
  49711. something sensible.
  49712. */
  49713. virtual const String getDocumentTitle() = 0;
  49714. /** This method should try to load your document from the given file.
  49715. If it fails, it should return an error message. If it succeeds, it should return
  49716. an empty string.
  49717. */
  49718. virtual const String loadDocument (const File& file) = 0;
  49719. /** This method should try to write your document to the given file.
  49720. If it fails, it should return an error message. If it succeeds, it should return
  49721. an empty string.
  49722. */
  49723. virtual const String saveDocument (const File& file) = 0;
  49724. /** This is used for dialog boxes to make them open at the last folder you
  49725. were using.
  49726. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  49727. the last document that was used - you might want to store this value
  49728. in a static variable, or even in your application's properties. It should
  49729. be a global setting rather than a property of this object.
  49730. This method works very well in conjunction with a RecentlyOpenedFilesList
  49731. object to manage your recent-files list.
  49732. As a default value, it's ok to return File::nonexistent, and the document
  49733. object will use a sensible one instead.
  49734. @see RecentlyOpenedFilesList
  49735. */
  49736. virtual const File getLastDocumentOpened() = 0;
  49737. /** This is used for dialog boxes to make them open at the last folder you
  49738. were using.
  49739. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  49740. the last document that was used - you might want to store this value
  49741. in a static variable, or even in your application's properties. It should
  49742. be a global setting rather than a property of this object.
  49743. This method works very well in conjunction with a RecentlyOpenedFilesList
  49744. object to manage your recent-files list.
  49745. @see RecentlyOpenedFilesList
  49746. */
  49747. virtual void setLastDocumentOpened (const File& file) = 0;
  49748. private:
  49749. File documentFile;
  49750. bool changedSinceSave;
  49751. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  49752. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileBasedDocument);
  49753. };
  49754. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  49755. /*** End of inlined file: juce_FileBasedDocument.h ***/
  49756. #endif
  49757. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  49758. #endif
  49759. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  49760. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  49761. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  49762. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  49763. /**
  49764. Manages a set of files for use as a list of recently-opened documents.
  49765. This is a handy class for holding your list of recently-opened documents, with
  49766. helpful methods for things like purging any non-existent files, automatically
  49767. adding them to a menu, and making persistence easy.
  49768. @see File, FileBasedDocument
  49769. */
  49770. class JUCE_API RecentlyOpenedFilesList
  49771. {
  49772. public:
  49773. /** Creates an empty list.
  49774. */
  49775. RecentlyOpenedFilesList();
  49776. /** Destructor. */
  49777. ~RecentlyOpenedFilesList();
  49778. /** Sets a limit for the number of files that will be stored in the list.
  49779. When addFile() is called, then if there is no more space in the list, the
  49780. least-recently added file will be dropped.
  49781. @see getMaxNumberOfItems
  49782. */
  49783. void setMaxNumberOfItems (int newMaxNumber);
  49784. /** Returns the number of items that this list will store.
  49785. @see setMaxNumberOfItems
  49786. */
  49787. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  49788. /** Returns the number of files in the list.
  49789. The most recently added file is always at index 0.
  49790. */
  49791. int getNumFiles() const;
  49792. /** Returns one of the files in the list.
  49793. The most recently added file is always at index 0.
  49794. */
  49795. const File getFile (int index) const;
  49796. /** Returns an array of all the absolute pathnames in the list.
  49797. */
  49798. const StringArray& getAllFilenames() const throw() { return files; }
  49799. /** Clears all the files from the list. */
  49800. void clear();
  49801. /** Adds a file to the list.
  49802. The file will be added at index 0. If this file is already in the list, it will
  49803. be moved up to index 0, but a file can only appear once in the list.
  49804. If the list already contains the maximum number of items that is permitted, the
  49805. least-recently added file will be dropped from the end.
  49806. */
  49807. void addFile (const File& file);
  49808. /** Checks each of the files in the list, removing any that don't exist.
  49809. You might want to call this after reloading a list of files, or before putting them
  49810. on a menu.
  49811. */
  49812. void removeNonExistentFiles();
  49813. /** Adds entries to a menu, representing each of the files in the list.
  49814. This is handy for creating an "open recent file..." menu in your app. The
  49815. menu items are numbered consecutively starting with the baseItemId value,
  49816. and can either be added as complete pathnames, or just the last part of the
  49817. filename.
  49818. If dontAddNonExistentFiles is true, then each file will be checked and only those
  49819. that exist will be added.
  49820. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  49821. pointers to file objects. Any files that appear in this list will not be added to the
  49822. menu - the reason for this is that you might have a number of files already open, so
  49823. might not want these to be shown in the menu.
  49824. It returns the number of items that were added.
  49825. */
  49826. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  49827. int baseItemId,
  49828. bool showFullPaths,
  49829. bool dontAddNonExistentFiles,
  49830. const File** filesToAvoid = 0);
  49831. /** Returns a string that encapsulates all the files in the list.
  49832. The string that is returned can later be passed into restoreFromString() in
  49833. order to recreate the list. This is handy for persisting your list, e.g. in
  49834. a PropertiesFile object.
  49835. @see restoreFromString
  49836. */
  49837. const String toString() const;
  49838. /** Restores the list from a previously stringified version of the list.
  49839. Pass in a stringified version created with toString() in order to persist/restore
  49840. your list.
  49841. @see toString
  49842. */
  49843. void restoreFromString (const String& stringifiedVersion);
  49844. private:
  49845. StringArray files;
  49846. int maxNumberOfItems;
  49847. JUCE_LEAK_DETECTOR (RecentlyOpenedFilesList);
  49848. };
  49849. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  49850. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  49851. #endif
  49852. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  49853. #endif
  49854. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  49855. /*** Start of inlined file: juce_SystemClipboard.h ***/
  49856. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  49857. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  49858. /**
  49859. Handles reading/writing to the system's clipboard.
  49860. */
  49861. class JUCE_API SystemClipboard
  49862. {
  49863. public:
  49864. /** Copies a string of text onto the clipboard */
  49865. static void copyTextToClipboard (const String& text);
  49866. /** Gets the current clipboard's contents.
  49867. Obviously this might have come from another app, so could contain
  49868. anything..
  49869. */
  49870. static const String getTextFromClipboard();
  49871. };
  49872. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  49873. /*** End of inlined file: juce_SystemClipboard.h ***/
  49874. #endif
  49875. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  49876. #endif
  49877. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  49878. #endif
  49879. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  49880. /*** Start of inlined file: juce_UnitTest.h ***/
  49881. #ifndef __JUCE_UNITTEST_JUCEHEADER__
  49882. #define __JUCE_UNITTEST_JUCEHEADER__
  49883. class UnitTestRunner;
  49884. /**
  49885. This is a base class for classes that perform a unit test.
  49886. To write a test using this class, your code should look something like this:
  49887. @code
  49888. class MyTest : public UnitTest
  49889. {
  49890. public:
  49891. MyTest() : UnitTest ("Foobar testing") {}
  49892. void runTest()
  49893. {
  49894. beginTest ("Part 1");
  49895. expect (myFoobar.doesSomething());
  49896. expect (myFoobar.doesSomethingElse());
  49897. beginTest ("Part 2");
  49898. expect (myOtherFoobar.doesSomething());
  49899. expect (myOtherFoobar.doesSomethingElse());
  49900. ...etc..
  49901. }
  49902. };
  49903. // Creating a static instance will automatically add the instance to the array
  49904. // returned by UnitTest::getAllTests(), so the test will be included when you call
  49905. // UnitTestRunner::runAllTests()
  49906. static MyTest test;
  49907. @endcode
  49908. To run a test, use the UnitTestRunner class.
  49909. @see UnitTestRunner
  49910. */
  49911. class JUCE_API UnitTest
  49912. {
  49913. public:
  49914. /** Creates a test with the given name. */
  49915. explicit UnitTest (const String& name);
  49916. /** Destructor. */
  49917. virtual ~UnitTest();
  49918. /** Returns the name of the test. */
  49919. const String getName() const throw() { return name; }
  49920. /** Runs the test, using the specified UnitTestRunner.
  49921. You shouldn't need to call this method directly - use
  49922. UnitTestRunner::runTests() instead.
  49923. */
  49924. void performTest (UnitTestRunner* runner);
  49925. /** Returns the set of all UnitTest objects that currently exist. */
  49926. static Array<UnitTest*>& getAllTests();
  49927. /** You can optionally implement this method to set up your test.
  49928. This method will be called before runTest().
  49929. */
  49930. virtual void initialise();
  49931. /** You can optionally implement this method to clear up after your test has been run.
  49932. This method will be called after runTest() has returned.
  49933. */
  49934. virtual void shutdown();
  49935. /** Implement this method in your subclass to actually run your tests.
  49936. The content of your implementation should call beginTest() and expect()
  49937. to perform the tests.
  49938. */
  49939. virtual void runTest() = 0;
  49940. /** Tells the system that a new subsection of tests is beginning.
  49941. This should be called from your runTest() method, and may be called
  49942. as many times as you like, to demarcate different sets of tests.
  49943. */
  49944. void beginTest (const String& testName);
  49945. /** Checks that the result of a test is true, and logs this result.
  49946. In your runTest() method, you should call this method for each condition that
  49947. you want to check, e.g.
  49948. @code
  49949. void runTest()
  49950. {
  49951. beginTest ("basic tests");
  49952. expect (x + y == 2);
  49953. expect (getThing() == someThing);
  49954. ...etc...
  49955. }
  49956. @endcode
  49957. If testResult is true, a pass is logged; if it's false, a failure is logged.
  49958. If the failure message is specified, it will be written to the log if the test fails.
  49959. */
  49960. void expect (bool testResult, const String& failureMessage = String::empty);
  49961. /** Compares two values, and if they don't match, prints out a message containing the
  49962. expected and actual result values.
  49963. */
  49964. template <class ValueType>
  49965. void expectEquals (ValueType actual, ValueType expected, String failureMessage = String::empty)
  49966. {
  49967. const bool result = (actual == expected);
  49968. if (! result)
  49969. {
  49970. if (failureMessage.isNotEmpty())
  49971. failureMessage << " -- ";
  49972. failureMessage << "Expected value: " << expected << ", Actual value: " << actual;
  49973. }
  49974. expect (result, failureMessage);
  49975. }
  49976. /** Writes a message to the test log.
  49977. This can only be called from within your runTest() method.
  49978. */
  49979. void logMessage (const String& message);
  49980. private:
  49981. const String name;
  49982. UnitTestRunner* runner;
  49983. JUCE_DECLARE_NON_COPYABLE (UnitTest);
  49984. };
  49985. /**
  49986. Runs a set of unit tests.
  49987. You can instantiate one of these objects and use it to invoke tests on a set of
  49988. UnitTest objects.
  49989. By using a subclass of UnitTestRunner, you can intercept logging messages and
  49990. perform custom behaviour when each test completes.
  49991. @see UnitTest
  49992. */
  49993. class JUCE_API UnitTestRunner
  49994. {
  49995. public:
  49996. /** */
  49997. UnitTestRunner();
  49998. /** Destructor. */
  49999. virtual ~UnitTestRunner();
  50000. /** Runs a set of tests.
  50001. The tests are performed in order, and the results are logged. To run all the
  50002. registered UnitTest objects that exist, use runAllTests().
  50003. */
  50004. void runTests (const Array<UnitTest*>& tests, bool assertOnFailure);
  50005. /** Runs all the UnitTest objects that currently exist.
  50006. This calls runTests() for all the objects listed in UnitTest::getAllTests().
  50007. */
  50008. void runAllTests (bool assertOnFailure);
  50009. /** Contains the results of a test.
  50010. One of these objects is instantiated each time UnitTest::beginTest() is called, and
  50011. it contains details of the number of subsequent UnitTest::expect() calls that are
  50012. made.
  50013. */
  50014. struct TestResult
  50015. {
  50016. /** The main name of this test (i.e. the name of the UnitTest object being run). */
  50017. String unitTestName;
  50018. /** The name of the current subcategory (i.e. the name that was set when UnitTest::beginTest() was called). */
  50019. String subcategoryName;
  50020. /** The number of UnitTest::expect() calls that succeeded. */
  50021. int passes;
  50022. /** The number of UnitTest::expect() calls that failed. */
  50023. int failures;
  50024. /** A list of messages describing the failed tests. */
  50025. StringArray messages;
  50026. };
  50027. /** Returns the number of TestResult objects that have been performed.
  50028. @see getResult
  50029. */
  50030. int getNumResults() const throw();
  50031. /** Returns one of the TestResult objects that describes a test that has been run.
  50032. @see getNumResults
  50033. */
  50034. const TestResult* getResult (int index) const throw();
  50035. protected:
  50036. /** Called when the list of results changes.
  50037. You can override this to perform some sort of behaviour when results are added.
  50038. */
  50039. virtual void resultsUpdated();
  50040. /** Logs a message about the current test progress.
  50041. By default this just writes the message to the Logger class, but you could override
  50042. this to do something else with the data.
  50043. */
  50044. virtual void logMessage (const String& message);
  50045. private:
  50046. friend class UnitTest;
  50047. UnitTest* currentTest;
  50048. String currentSubCategory;
  50049. OwnedArray <TestResult, CriticalSection> results;
  50050. bool assertOnFailure;
  50051. void beginNewTest (UnitTest* test, const String& subCategory);
  50052. void endTest();
  50053. void addPass();
  50054. void addFail (const String& failureMessage);
  50055. JUCE_DECLARE_NON_COPYABLE (UnitTestRunner);
  50056. };
  50057. #endif // __JUCE_UNITTEST_JUCEHEADER__
  50058. /*** End of inlined file: juce_UnitTest.h ***/
  50059. #endif
  50060. #endif
  50061. /*** End of inlined file: juce_app_includes.h ***/
  50062. #endif
  50063. #if JUCE_MSVC
  50064. #pragma warning (pop)
  50065. #pragma pack (pop)
  50066. #endif
  50067. #ifdef JUCE_DLL
  50068. #undef JUCE_LEAK_DETECTOR(OwnerClass)
  50069. #define JUCE_LEAK_DETECTOR(OwnerClass)
  50070. #endif
  50071. END_JUCE_NAMESPACE
  50072. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  50073. #ifdef JUCE_NAMESPACE
  50074. // this will obviously save a lot of typing, but can be disabled by
  50075. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  50076. using namespace JUCE_NAMESPACE;
  50077. /* On the Mac, these symbols are defined in the Mac libraries, so
  50078. these macros make it easier to reference them without writing out
  50079. the namespace every time.
  50080. If you run into difficulties where these macros interfere with the contents
  50081. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  50082. the comments in that file for more information.
  50083. */
  50084. #if (JUCE_MAC || JUCE_IOS) && ! JUCE_DONT_DEFINE_MACROS
  50085. #define Component JUCE_NAMESPACE::Component
  50086. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  50087. #define Point JUCE_NAMESPACE::Point
  50088. #define Button JUCE_NAMESPACE::Button
  50089. #endif
  50090. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  50091. it easier to use the juce version explicitly.
  50092. If you run into difficulties where this macro interferes with other 3rd party header
  50093. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  50094. file for more information.
  50095. */
  50096. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  50097. #define Rectangle JUCE_NAMESPACE::Rectangle
  50098. #endif
  50099. #endif
  50100. #endif
  50101. /* Easy autolinking to the right JUCE libraries under win32.
  50102. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  50103. including this header file.
  50104. */
  50105. #if JUCE_MSVC
  50106. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  50107. /** If you want your application to link to Juce as a DLL instead of
  50108. a static library (on win32), just define the JUCE_DLL macro before
  50109. including juce.h
  50110. */
  50111. #ifdef JUCE_DLL
  50112. #if JUCE_DEBUG
  50113. #define AUTOLINKEDLIB "JUCE_debug.lib"
  50114. #else
  50115. #define AUTOLINKEDLIB "JUCE.lib"
  50116. #endif
  50117. #else
  50118. #if JUCE_DEBUG
  50119. #ifdef _WIN64
  50120. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  50121. #else
  50122. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  50123. #endif
  50124. #else
  50125. #ifdef _WIN64
  50126. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  50127. #else
  50128. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  50129. #endif
  50130. #endif
  50131. #endif
  50132. #pragma comment(lib, AUTOLINKEDLIB)
  50133. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  50134. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  50135. #endif
  50136. // Auto-link the other win32 libs that are needed by library calls..
  50137. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  50138. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  50139. // Auto-links to various win32 libs that are needed by library calls..
  50140. #pragma comment(lib, "kernel32.lib")
  50141. #pragma comment(lib, "user32.lib")
  50142. #pragma comment(lib, "shell32.lib")
  50143. #pragma comment(lib, "gdi32.lib")
  50144. #pragma comment(lib, "vfw32.lib")
  50145. #pragma comment(lib, "comdlg32.lib")
  50146. #pragma comment(lib, "winmm.lib")
  50147. #pragma comment(lib, "wininet.lib")
  50148. #pragma comment(lib, "ole32.lib")
  50149. #pragma comment(lib, "oleaut32.lib")
  50150. #pragma comment(lib, "advapi32.lib")
  50151. #pragma comment(lib, "ws2_32.lib")
  50152. #pragma comment(lib, "version.lib")
  50153. #pragma comment(lib, "shlwapi.lib")
  50154. #ifdef _NATIVE_WCHAR_T_DEFINED
  50155. #ifdef _DEBUG
  50156. #pragma comment(lib, "comsuppwd.lib")
  50157. #else
  50158. #pragma comment(lib, "comsuppw.lib")
  50159. #endif
  50160. #else
  50161. #ifdef _DEBUG
  50162. #pragma comment(lib, "comsuppd.lib")
  50163. #else
  50164. #pragma comment(lib, "comsupp.lib")
  50165. #endif
  50166. #endif
  50167. #if JUCE_OPENGL
  50168. #pragma comment(lib, "OpenGL32.Lib")
  50169. #pragma comment(lib, "GlU32.Lib")
  50170. #endif
  50171. #if JUCE_QUICKTIME
  50172. #pragma comment (lib, "QTMLClient.lib")
  50173. #endif
  50174. #if JUCE_USE_CAMERA
  50175. #pragma comment (lib, "Strmiids.lib")
  50176. #pragma comment (lib, "wmvcore.lib")
  50177. #endif
  50178. #if JUCE_DIRECT2D
  50179. #pragma comment (lib, "Dwrite.lib")
  50180. #pragma comment (lib, "D2d1.lib")
  50181. #endif
  50182. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  50183. #endif
  50184. #endif
  50185. #endif
  50186. #endif // __JUCE_JUCEHEADER__
  50187. /*** End of inlined file: juce.h ***/
  50188. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__